diff --git a/metal/kernels/dense_mm.metal b/metal/kernels/dense_mm.metal new file mode 100644 index 00000000..4f50b9ee --- /dev/null +++ b/metal/kernels/dense_mm.metal @@ -0,0 +1,65 @@ +// metal/kernels/dense_mm.metal - dense projections for a PROMPT chunk (after quant/units/mma.metal): +// act_f16 X[t][k] -> half (the matrix units' operand) +// dq_f16 a quantized matrix -> half rows (ref_quant's values rounded to fp16), once per chunk +// gemm_f16 Y[t][n] = Xh[t] . Wh[n] (fp32) by MetalPerformancePrimitives matmul2d, TM x TN tiles, K dynamic; +// rows of Y past n_out / t past n_tok are not written (the tensors carry the extents) +#include +using namespace mpp::tensor_ops; + +kernel void act_f16(device const float* x [[buffer(0)]], device half* xh [[buffer(1)]], constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + if (gid < n) xh[gid] = half(x[gid]); +} + +struct DqArgs { + uint n_in; // values per row + uint n_out; // rows + uint row_bytes; +}; + +// one thread per unit: grid (units per row / 64, n_out), 64 threads +template +kernel void dq_f16(device const uchar* W [[buffer(0)]], device half* Wh [[buffer(1)]], constant DqArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, H = UNIT / 2; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, 64); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int u = int(tg.x) * 64 + tid, r = int(tg.y); + if (u * UNIT >= int(a.n_in)) return; + // the unit's chunk origin: a 128-wide chunk holds whole units of every format + const int k0 = (u * UNIT) / 128 * 128; + float w[UNIT]; + int p0, p1; + DW::run(W + ulong(r) * a.row_bytes, u, k0, w, p0, p1, tab); + device half* o = Wh + ulong(r) * a.n_in + k0; + for (int j = 0; j < H; ++j) { + o[p0 + j] = half(w[j]); + o[p1 + j] = half(w[H + j]); + } +} + +struct GemmArgs { int M, N, K; int pad; }; // Y is M rows of N floats + +template +kernel void gemm_f16(device half* A [[buffer(0)]], device half* B [[buffer(1)]], device float* Y [[buffer(2)]], + constant GemmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]]) { + tensor, tensor_inline> tA(A, dextents(a.K, a.M)); + tensor, tensor_inline> tB(B, dextents(a.K, a.N)); + tensor, tensor_inline> tY(Y, dextents(a.N, a.M)); + constexpr auto desc = matmul2d_descriptor(TM, TN, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tA.slice(0, int(tg.y) * TM); + auto mB = tB.slice(0, int(tg.x) * TN); + auto mY = tY.slice(int(tg.x) * TN, int(tg.y) * TM); + op.run(mA, mB, mY); +} + +#define DQ(F) template [[host_name("dq_f16_" #F)]] kernel decltype(dq_f16) dq_f16; +#define DQ_(F) DQ(F) +DQ_(T_BF16) DQ_(T_Q8_0) DQ_(T_Q4_0) DQ_(T_Q5_0) DQ_(T_IQ4_NL) DQ_(T_IQ4_XS) DQ_(T_Q2_0) DQ_(T_IQ3_S) DQ_(T_Q3_K) +DQ_(T_Q4_K) DQ_(T_Q5_K) DQ_(T_Q6_K) +template [[host_name("gemm_f16_64_64_4")]] kernel decltype(gemm_f16<64, 64, 4>) gemm_f16<64, 64, 4>; +template [[host_name("gemm_f16_128_64_4")]] kernel decltype(gemm_f16<128, 64, 4>) gemm_f16<128, 64, 4>; +template [[host_name("gemm_f16_64_128_4")]] kernel decltype(gemm_f16<64, 128, 4>) gemm_f16<64, 128, 4>; +template [[host_name("gemm_f16_64_32_4")]] kernel decltype(gemm_f16<64, 32, 4>) gemm_f16<64, 32, 4>; diff --git a/metal/kernels/mm_bench.metal b/metal/kernels/mm_bench.metal new file mode 100644 index 00000000..71dd8076 --- /dev/null +++ b/metal/kernels/mm_bench.metal @@ -0,0 +1,51 @@ +// metal/kernels/mm_bench.metal - matrix throughput probes (mm_bench.cpp): C[M][N] = A[M][K] . B[N][K]^T, fp32 out. +// mpp_mm Metal 4 MetalPerformancePrimitives matmul2d (the M5's neural accelerators), a TM x TN +// tile of C per threadgroup, K dynamic, A and B straight from device memory +// sg_mm simdgroup_matrix 8x8, a 32 x 32 tile per simdgroup (4 x 4 accumulators), 4 simdgroups +#include +using namespace mpp::tensor_ops; + +struct MmArgs { int M, N, K; }; + +template +kernel void mpp_mm(device T* A [[buffer(0)]], device T* B [[buffer(1)]], device float* C [[buffer(2)]], + constant MmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]]) { + // extents are (inner, outer): A is M rows of K, B is N rows of K, C is M rows of N + tensor, tensor_inline> tA(A, dextents(a.K, a.M)); + tensor, tensor_inline> tB(B, dextents(a.K, a.N)); + tensor, tensor_inline> tC(C, dextents(a.N, a.M)); + constexpr auto desc = matmul2d_descriptor(TM, TN, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tA.slice(0, int(tg.y) * TM); + auto mB = tB.slice(0, int(tg.x) * TN); + auto mC = tC.slice(int(tg.x) * TN, int(tg.y) * TM); + op.run(mA, mB, mC); +} + +#define MPP(T, M, N, S) template [[host_name("mpp_mm_" #T "_" #M "_" #N "_" #S)]] kernel decltype(mpp_mm) mpp_mm; +MPP(half, 64, 32, 4) MPP(half, 64, 64, 4) MPP(half, 128, 64, 4) MPP(half, 32, 64, 4) MPP(half, 64, 128, 4) +MPP(half, 16, 64, 2) MPP(half, 128, 128, 4) +MPP(float, 64, 32, 4) MPP(float, 64, 64, 4) MPP(float, 128, 64, 4) +MPP(bfloat, 64, 64, 4) MPP(bfloat, 128, 64, 4) + +// simdgroup_matrix: threadgroup tile 64 x 64 (4 simdgroups x 32 x 32), K in steps of 8, operands from device memory +template +kernel void sg_mm(device const T* A [[buffer(0)]], device const T* B [[buffer(1)]], device float* C [[buffer(2)]], + constant MmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const int m0 = int(tg.y) * 64 + (sg >> 1) * 32, n0 = int(tg.x) * 64 + (sg & 1) * 32; + simdgroup_matrix acc[4][4]; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) acc[i][j] = make_filled_simdgroup_matrix(0.0f); + for (int k = 0; k < a.K; k += 8) { + simdgroup_matrix ma[4], mb[4]; + for (int i = 0; i < 4; ++i) simdgroup_load(ma[i], A + (m0 + 8 * i) * a.K + k, a.K); + for (int j = 0; j < 4; ++j) simdgroup_load(mb[j], B + (n0 + 8 * j) * a.K + k, a.K, ulong2(0, 0), true); + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) simdgroup_multiply_accumulate(acc[i][j], ma[i], mb[j], acc[i][j]); + } + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) simdgroup_store(acc[i][j], C + (m0 + 8 * i) * a.N + n0 + 8 * j, a.N); +} +template [[host_name("sg_mm_half")]] kernel decltype(sg_mm) sg_mm; +template [[host_name("sg_mm_float")]] kernel decltype(sg_mm) sg_mm; diff --git a/metal/kernels/moe_mm.metal b/metal/kernels/moe_mm.metal new file mode 100644 index 00000000..599a0099 --- /dev/null +++ b/metal/kernels/moe_mm.metal @@ -0,0 +1,351 @@ +// metal/kernels/moe_mm.metal - routed experts for a PROMPT chunk (after quant/units/mma.metal): a grouped GEMM on +// the matrix units through Metal 4's MetalPerformancePrimitives matmul2d (on the M5 its neural accelerators). +// +// Plan (deterministic, three passes): the chunk's T x topk (token, expert) entries are sorted by expert, then by +// entry index; each expert's run is padded to a multiple of TM rows; tile i = (expert, first padded row). +// mm_hist per block of 1024 entries: a histogram of experts -> bcnt[block][expert] +// mm_scan one threadgroup (thread = expert): block offsets, the padded expert offsets, the tile list +// mm_place per block: an entry's padded row = expert offset + earlier blocks' count + rank in its block; +// srt_tok[row] = token (-1 on padding), srt_w[row] = weight, pos[entry] = row +// GEMMs: a threadgroup takes a tile (TM rows of one expert) and TN output rows; per K chunk of TK it converts the +// tile's activations to fp16 and dequantizes TN x TK weights (ref_quant's arithmetic, then rounded to fp16) into +// threadgroup memory, and matmul2d multiplies them, fp32 accumulation. +// mm_gu H[row][f] = silu(x . gate_f) * (x . up_f), fp32, for the n_ff rows +// mm_down YE[row][d] = h . down_d, fp32 +// mm_combine y[t][d] = sum_k w(t, k) * YE[pos(t, k)][d], k in order +// +// The idea of feeding matmul2d tiles of dequantized weights from threadgroup memory follows yibie/strata-mlx's +// tile_matmul (MIT); the code is our own. +#include +using namespace mpp::tensor_ops; + +struct MmPlanArgs { + uint n_ent; // T * topk + uint topk; + uint n_expert; + uint tm; // the tile height (rows of one expert) + uint n_blocks; // ceil(n_ent / 1024) +}; + +// counts per block: bcnt[block * n_expert + e] +kernel void mm_hist(device const int* ids [[buffer(0)]], device uint* bcnt [[buffer(1)]], + constant MmPlanArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup atomic_uint h[1024]; + for (uint e = tid; e < a.n_expert; e += 1024) atomic_store_explicit(&h[e], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint i = tg.x * 1024 + tid; + if (i < a.n_ent) atomic_fetch_add_explicit(&h[ids[i]], 1u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = tid; e < a.n_expert; e += 1024) + bcnt[tg.x * a.n_expert + e] = atomic_load_explicit(&h[e], memory_order_relaxed); +} + +// one threadgroup of n_expert (<= 1024) threads. boff[block][e] = expert e's rows before this block (within e); +// eoff[e] = expert e's first padded row; tiles[i] = (expert, row0); meta[0] = n_tiles, meta[1] = padded rows, +// meta[2..4] = an indirect grid (gx, n_tiles, 1) for the GEMMs, gx given in meta[2] by the host. +kernel void mm_scan(device const uint* bcnt [[buffer(0)]], device uint* boff [[buffer(1)]], + device uint* eoff [[buffer(2)]], device int2* tiles [[buffer(3)]], device uint* meta [[buffer(4)]], + constant MmPlanArgs& a [[buffer(5)]], + ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup uint s_rows[32], s_tiles[32]; + const uint e = tid; + uint tot = 0; + if (e < a.n_expert) + for (uint b = 0; b < a.n_blocks; ++b) { + boff[b * a.n_expert + e] = tot; + tot += bcnt[b * a.n_expert + e]; + } + const uint nt = (tot + a.tm - 1) / a.tm, rows = nt * a.tm; + const uint pr = simd_prefix_exclusive_sum(rows), pt = simd_prefix_exclusive_sum(nt); + if (lane == 31) { s_rows[sg] = pr + rows; s_tiles[sg] = pt + nt; } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint orow = 0, otile = 0, all_rows = 0, all_tiles = 0; + for (int i = 0; i < 32; ++i) { + if (i < int(sg)) { orow += s_rows[i]; otile += s_tiles[i]; } + all_rows += s_rows[i]; + all_tiles += s_tiles[i]; + } + if (e < a.n_expert) { + const uint r0 = orow + pr, t0 = otile + pt; + eoff[e] = r0; + for (uint k = 0; k < nt; ++k) tiles[t0 + k] = int2(int(e), int(r0 + k * a.tm)); + } + if (tid == 0) { + meta[0] = all_tiles; + meta[1] = all_rows; + meta[3] = all_tiles; + meta[4] = 1; + } +} + +// grid (n_blocks), 1024 threads. srt_* must be cleared to the padding value (-1 / 0) beforehand by mm_clear. +kernel void mm_place(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]], + device const uint* boff [[buffer(2)]], device const uint* eoff [[buffer(3)]], + device int* srt_tok [[buffer(4)]], device float* srt_w [[buffer(5)]], device int* pos [[buffer(6)]], + constant MmPlanArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup int s_id[1024]; + const uint i = tg.x * 1024 + tid; + const int e = i < a.n_ent ? ids[i] : -1; + s_id[tid] = e; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (i >= a.n_ent) return; + uint rank = 0; + for (uint j = 0; j < tid; ++j) rank += s_id[j] == e; + const uint row = eoff[e] + boff[tg.x * a.n_expert + e] + rank; + srt_tok[row] = int(i / a.topk); + srt_w[row] = w[i]; + pos[i] = int(row); +} + +kernel void mm_clear(device int* srt_tok [[buffer(0)]], constant uint& n [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + if (gid < n) srt_tok[gid] = -1; +} + +// ---- the GEMMs ----------------------------------------------------------------------------------------------------- +// weights of one expert: gate at W + gate_off + e * gu_stride (+ up_off for up), down at W + down_off + e * d_stride +struct MmArgs { + ulong gate_off; + ulong up_off; + ulong down_off; + ulong gu_stride; + ulong d_stride; + uint gu_row; // bytes per gate/up row (n_embd values) + uint d_row; // bytes per down row (n_ff values) + uint n_embd; + uint n_ff; +}; + +// TN x TK weights of `nrow`-strided rows into threadgroup half: thread-strided units of the format +template +static inline void stage_w(device const uchar* w0, uint row_bytes, int k0, threadgroup half* dst, + threadgroup const uint* tab, ushort tid, ushort nth) { + constexpr int UNIT = fmt::UNIT, UPC = TK / UNIT, H = UNIT / 2; + static_assert(TK % UNIT == 0, "the K chunk must hold whole units of the format"); + for (int it = tid; it < TN * UPC; it += nth) { + const int r = it / UPC, uu = it - r * UPC; + float wv[UNIT]; + int p0, p1; + DW::run(w0 + ulong(r) * row_bytes, k0 / UNIT + uu, k0, wv, p0, p1, tab); + for (int j = 0; j < H; ++j) { + dst[r * TK + p0 + j] = half(wv[j]); + dst[r * TK + p1 + j] = half(wv[H + j]); + } + } +} + +template +kernel void mm_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]], + device float* H [[buffer(2)]], device const int* srt_tok [[buffer(3)]], + device const int2* tiles [[buffer(4)]], constant MmArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half xa[TM * TK]; + threadgroup half wg[TN * TK]; + threadgroup half wu[TN * TK]; + threadgroup uint tab[fmt::TAB]; + threadgroup int tok[TM]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN; + for (int m = tid; m < TM; m += NTH) tok[m] = srt_tok[row0 + m]; + device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false); + matmul2d> op; + tensor, tensor_inline> tA(xa, dextents(TK, TM)); + tensor, tensor_inline> tG(wg, dextents(TK, TN)); + tensor, tensor_inline> tU(wu, dextents(TK, TN)); + auto accg = op.template get_destination_cooperative_tensor(); + auto accu = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + for (int it = tid; it < TM * TK; it += NTH) { + const int m = it / TK, k = it - m * TK; + xa[it] = tok[m] >= 0 ? half(x[ulong(tok[m]) * a.n_embd + k0 + k]) : half(0.0f); + } + stage_w(g0, a.gu_row, k0, wg, tab, tid, NTH); + stage_w(u0, a.gu_row, k0, wu, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + auto pg = op.template get_destination_cooperative_tensor(); + auto pu = op.template get_destination_cooperative_tensor(); + op.run(tA, tG, pg); + op.run(tA, tU, pu); + for (uint16_t i = 0; i < pg.get_capacity(); ++i) + if (pg.is_valid_element(i)) { accg[i] += pg[i]; accu[i] += pu[i]; } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tH(H, dextents(a.n_ff, 1 << 30)); + accg.store(tH.slice(f0, row0)); +} + +template +kernel void mm_down(device const uchar* W [[buffer(0)]], device const float* H [[buffer(1)]], + device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], + constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half ha[TM * TK]; + threadgroup half wd[TN * TK]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN; + device const uchar* w0 = W + a.down_off + ulong(e) * a.d_stride + ulong(d0) * a.d_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false); + matmul2d> op; + tensor, tensor_inline> tA(ha, dextents(TK, TM)); + tensor, tensor_inline> tW(wd, dextents(TK, TN)); + auto acc = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) { + for (int it = tid; it < TM * TK; it += NTH) { + const int m = it / TK, k = it - m * TK; + ha[it] = half(H[ulong(row0 + m) * a.n_ff + k0 + k]); + } + stage_w(w0, a.d_row, k0, wd, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + auto p = op.template get_destination_cooperative_tensor(); + op.run(tA, tW, p); + for (uint16_t i = 0; i < p.get_capacity(); ++i) + if (p.is_valid_element(i)) acc[i] += p[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + tensor, tensor_inline> tY(YE, dextents(a.n_embd, 1 << 30)); + acc.store(tY.slice(d0, row0)); +} + +// grid (T * n_embd / 256), 256 threads +kernel void mm_combine(device const float* YE [[buffer(0)]], device const int* pos [[buffer(1)]], + device const float* srt_w [[buffer(2)]], device float* y [[buffer(3)]], + constant uint4& a [[buffer(4)]], // (T, n_embd, topk, -) + uint gid [[thread_position_in_grid]]) { + const uint t = gid / a.y, d = gid % a.y; + if (t >= a.x) return; + float s = 0.0f; + for (uint k = 0; k < a.z; ++k) { + const int r = pos[t * a.z + k]; + s = fma(srt_w[r], YE[ulong(r) * a.y + d], s); + } + y[gid] = s; +} + +#define MMGU_(F, M, N, K, S) template [[host_name("mm_gu_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu) mm_gu; +#define MMDN_(F, M, N, K, S) template [[host_name("mm_down_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down) mm_down; +#define MMGU(F, M, N, K, S) MMGU_(F, M, N, K, S) +#define MMDN(F, M, N, K, S) MMDN_(F, M, N, K, S) +#define MM_GU_SET(F) MMGU(F, 32, 64, 64, 4) MMGU(F, 64, 64, 64, 4) MMGU(F, 16, 64, 64, 2) MMGU(F, 32, 32, 64, 2) +#define MM_DN_SET(F) MMDN(F, 32, 64, 64, 4) MMDN(F, 64, 64, 64, 4) MMDN(F, 16, 64, 64, 2) MMDN(F, 32, 32, 64, 2) +MM_GU_SET(T_Q2_0) MM_GU_SET(T_IQ3_XXS) MM_GU_SET(T_IQ2_XXS) MM_GU_SET(T_IQ2_XS) MM_GU_SET(T_IQ2_S) MM_GU_SET(T_IQ3_S) +MM_DN_SET(T_Q2_0) MM_DN_SET(T_IQ4_NL) + +// ---- v2: activations gathered once per layer as fp16 rows, read by matmul2d from device memory --------------------- +// mm_gather: XS[row][k] = half(x[srt_tok[row]][k]) (0 on padding rows). grid (rows), 256 threads. +kernel void mm_gather(device const float* x [[buffer(0)]], device const int* srt_tok [[buffer(1)]], + device half* XS [[buffer(2)]], constant uint& n [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + const int t = srt_tok[tg.x]; + device half* o = XS + ulong(tg.x) * n; + for (uint k = tid; k < n; k += 256) o[k] = t >= 0 ? half(x[ulong(t) * n + k]) : half(0.0f); +} + +template +kernel void mm_gu2(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], + device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half wg[TN * TK]; + threadgroup half wu[TN * TK]; + threadgroup float ot[TM * TN]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN; + device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d> op; + tensor, tensor_inline> tX((device half*)XS, dextents(a.n_embd, 1 << 30)); + tensor, tensor_inline> tG(wg, dextents(TK, TN)); + tensor, tensor_inline> tU(wu, dextents(TK, TN)); + auto tA = tX.template slice(0, row0); + auto accg = op.template get_destination_cooperative_tensor(); + auto accu = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + stage_w(g0, a.gu_row, k0, wg, tab, tid, NTH); + stage_w(u0, a.gu_row, k0, wu, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + tA = tX.template slice(k0, row0); + op.run(tA, tG, accg); + op.run(tA, tU, accu); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tO(ot, dextents(TN, TM)); + accg.store(tO); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int it = tid; it < TM * TN; it += NTH) { + const int m = it / TN, f = it - m * TN; + HS[ulong(row0 + m) * a.n_ff + f0 + f] = half(ot[it]); + } +} + +template +kernel void mm_down2(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]], + device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], + constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half wd[TN * TK]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN; + device const uchar* w0 = W + a.down_off + ulong(e) * a.d_stride + ulong(d0) * a.d_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d> op; + tensor, tensor_inline> tH((device half*)HS, dextents(a.n_ff, 1 << 30)); + tensor, tensor_inline> tW(wd, dextents(TK, TN)); + auto tA = tH.template slice(0, row0); + auto acc = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) { + stage_w(w0, a.d_row, k0, wd, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + tA = tH.template slice(k0, row0); + op.run(tA, tW, acc); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + tensor, tensor_inline> tY(YE, dextents(a.n_embd, 1 << 30)); + acc.store(tY.slice(d0, row0)); +} + +#define MMGU2_(F, M, N, K, S) template [[host_name("mm_gu2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu2) mm_gu2; +#define MMDN2_(F, M, N, K, S) template [[host_name("mm_down2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down2) mm_down2; +#define MMGU2(F, M, N, K, S) MMGU2_(F, M, N, K, S) +#define MMDN2(F, M, N, K, S) MMDN2_(F, M, N, K, S) +#define MM_GU2_SET(F) MMGU2(F, 32, 64, 32, 2) MMGU2(F, 32, 32, 32, 2) MMGU2(F, 32, 64, 16, 2) MMGU2(F, 64, 32, 16, 2) MMGU2(F, 16, 32, 32, 2) MMGU2(F, 16, 64, 16, 2) MMGU2(F, 16, 128, 32, 4) MMGU2(F, 32, 64, 16, 4) MMGU2(F, 16, 32, 32, 1) MMGU2(F, 16, 64, 32, 4) MMGU2(F, 16, 64, 64, 2) MMGU2(F, 32, 64, 64, 4) MMGU2(F, 64, 64, 64, 4) MMGU2(F, 16, 32, 64, 2) MMGU2(F, 32, 64, 32, 4) MMGU2(F, 64, 64, 32, 4) MMGU2(F, 16, 64, 32, 2) +#define MM_DN2_SET(F) MMDN2(F, 32, 64, 32, 2) MMDN2(F, 32, 32, 32, 2) MMDN2(F, 32, 64, 16, 2) MMDN2(F, 64, 32, 16, 2) MMDN2(F, 16, 32, 32, 2) MMDN2(F, 16, 64, 16, 2) MMDN2(F, 16, 128, 32, 4) MMDN2(F, 32, 64, 16, 4) MMDN2(F, 16, 32, 32, 1) MMDN2(F, 16, 64, 32, 4) MMDN2(F, 16, 64, 64, 2) MMDN2(F, 32, 64, 64, 4) MMDN2(F, 64, 64, 64, 4) MMDN2(F, 16, 32, 64, 2) MMDN2(F, 32, 64, 32, 4) MMDN2(F, 64, 64, 32, 4) MMDN2(F, 16, 64, 32, 2) +MM_GU2_SET(T_Q2_0) MM_GU2_SET(T_IQ3_XXS) MM_GU2_SET(T_IQ2_XXS) MM_GU2_SET(T_IQ2_XS) MM_GU2_SET(T_IQ2_S) MM_GU2_SET(T_IQ3_S) +MM_DN2_SET(T_Q2_0) +MMDN2(T_IQ4_NL, 16, 64, 32, 2) MMDN2(T_IQ4_NL, 16, 64, 64, 2) MMDN2(T_IQ4_NL, 16, 32, 32, 2) MMDN2(T_IQ4_NL, 32, 32, 32, 2) MMDN2(T_IQ4_NL, 16, 128, 32, 4) diff --git a/metal/tests/dense_mm_parity.cpp b/metal/tests/dense_mm_parity.cpp new file mode 100644 index 00000000..b333e060 --- /dev/null +++ b/metal/tests/dense_mm_parity.cpp @@ -0,0 +1,139 @@ +// metal/tests/dense_mm_parity.cpp - dense prompt projections (dense_mm.metal): dequantize to fp16 once, then the +// MPP GEMM. Parity vs a reference with the same fp16 operands (and the exact float one), every dense format and +// awkward row counts; then the speed on the packs' shapes for a 2048-token chunk. +// dense_mm_parity parity +// dense_mm_parity --bench speed +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct DqArgs { uint32_t n_in, n_out, row_bytes; }; +struct GemmArgs { int M, N, K, pad; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); } +int unit_of(int t) { + switch (t) { + case ref::Q2_0: case ref::IQ3_S: case ref::BF16: return 16; + default: return 32; + } +} +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + mtl::Pipeline pact = cx.pipeline(lib, "act_f16"); + auto run_all = [&](int ty, const mtl::Buffer& W, size_t woff, int n_in, int n_out, int T, const mtl::Buffer& x, + const mtl::Buffer& xh, const mtl::Buffer& wh, const mtl::Buffer& y, const std::string& gk, + std::vector& ds, int which) { + static std::vector keep; + mtl::Pipeline* pdq = new mtl::Pipeline(cx.pipeline(lib, "dq_f16_" + std::to_string(ty))); + mtl::Pipeline* pg = new mtl::Pipeline(cx.pipeline(lib, gk)); + keep.push_back(pdq); + keep.push_back(pg); + int tm = 64, tn = 64; + std::sscanf(gk.c_str(), "gemm_f16_%d_%d", &tm, &tn); + if (which & 1) { + const uint32_t n = (uint32_t)T * n_in; + mtl::Dispatch d; d.p = &pact; d.args = {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(n)}; + d.grid[0] = (n + 255) / 256; d.tg[0] = 256; ds.push_back(d); + } + if (which & 2) { + DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ref::row_bytes(ty, n_in)}; + mtl::Dispatch d; d.p = pdq; d.args = {mtl::Arg::B(W, woff), mtl::Arg::B(wh), mtl::Arg::V(a)}; + d.grid[0] = (n_in / unit_of(ty) + 63) / 64; d.grid[1] = n_out; d.tg[0] = 64; ds.push_back(d); + } + if (which & 4) { + GemmArgs g{T, n_out, n_in, 0}; + mtl::Dispatch d; d.p = pg; d.args = {mtl::Arg::B(xh), mtl::Arg::B(wh), mtl::Arg::B(y), mtl::Arg::V(g)}; + d.grid[0] = (n_out + tn - 1) / tn; d.grid[1] = (T + tm - 1) / tm; d.tg[0] = 128; ds.push_back(d); + } + }; + const std::vector types = {ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0, + ref::IQ3_S, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K}; + if (!bench) { + int fails = 0; + for (int ty : types) + for (int n_in : {2560, 640, 6144}) { + if (n_in % 256 && ref::block_elems(ty) == 256) continue; + for (int n_out : {100, 48}) { + const int T = 72; + const size_t rb = ref::row_bytes(ty, n_in); + mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * (size_t)T * n_in), xh = cx.alloc(2 * (size_t)T * n_in), + wh = cx.alloc(2 * (size_t)n_out * n_in), y = cx.alloc(4 * (size_t)T * n_out); + ref::random_blocks(ty, W.as(), n_out, n_in, 5 + ty + n_in, 0.02f); + ref::Rng r(3); + for (size_t i = 0; i < (size_t)T * n_in; ++i) x.as()[i] = r.sym(); + std::vector ds; + run_all(ty, W, 0, n_in, n_out, T, x, xh, wh, y, "gemm_f16_64_64_4", ds, 7); + cx.run(ds); + std::vector wf((size_t)n_in * n_out); + ref::dequant(ty, W.ptr, wf.data(), wf.size()); + double se16 = 0, se = 0, sr = 0; + for (int t = 0; t < T; ++t) + for (int o = 0; o < n_out; ++o) { + double a16 = 0, ae = 0; + for (int k = 0; k < n_in; ++k) { + const float xv = x.as()[(size_t)t * n_in + k], wv = wf[(size_t)o * n_in + k]; + a16 += (double)h16(xv) * h16(wv); + ae += (double)xv * wv; + } + const double g = y.as()[(size_t)t * n_out + o]; + se16 += (g - a16) * (g - a16); + se += (g - ae) * (g - ae); + sr += ae * ae; + } + const double r16 = std::sqrt(se16 / sr), re = std::sqrt(se / sr); + const bool ok = r16 < 1e-5; + fails += !ok; + std::printf("dense mm %-7s %5d -> %4d, T %d: vs fp16 operands %.2e, vs exact %.2e %s\n", + ref::type_name(ty), n_in, n_out, T, r16, re, ok ? "PASS" : "FAIL"); + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + struct Shape { const char* name; int type, n_in, n_out; }; + const std::vector shapes = {{"gdn qkv", ref::IQ4_XS, 2560, 10240}, {"gdn qkv", ref::Q3_K, 2560, 10240}, + {"gdn gate", ref::Q4_K, 2560, 6144}, {"gdn out", ref::Q6_K, 6144, 2560}, + {"qsa q", ref::Q2_0, 2560, 12288}, {"hc down", ref::BF16, 10240, 324}, + {"hc up", ref::BF16, 320, 10240}, {"router", ref::BF16, 2560, 512}, + {"alpha", ref::BF16, 2560, 48}}; + const int T = 2048; + for (const Shape& s : shapes) { + if (s.n_in % 128) { std::printf("%-9s %-6s: n_in %d not a multiple of 128 (needs the 32-chunk path)\n", s.name, ref::type_name(s.type), s.n_in); continue; } + const size_t rb = ref::row_bytes(s.type, s.n_in); + mtl::Buffer W = cx.alloc(rb * s.n_out), x = cx.alloc(4 * (size_t)T * s.n_in), xh = cx.alloc(2 * (size_t)T * s.n_in), + wh = cx.alloc(2 * (size_t)s.n_out * s.n_in), y = cx.alloc(4 * (size_t)T * s.n_out); + ref::random_blocks(s.type, W.as(), s.n_out, s.n_in, 3, 0.02f); + auto timeit = [&](int which, const std::string& gk) { + std::vector ds; + for (int i = 0; i < 4; ++i) run_all(s.type, W, 0, s.n_in, s.n_out, T, x, xh, wh, y, gk, ds, which); + cx.warm(ds, 0.2); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 4); + return median(t); + }; + const double tdq = timeit(2, "gemm_f16_64_64_4"), tact = timeit(1, "gemm_f16_64_64_4"); + double best = 1e9; + std::string bk; + for (const char* gk : {"gemm_f16_64_64_4", "gemm_f16_128_64_4", "gemm_f16_64_128_4", "gemm_f16_64_32_4"}) { + const double tg = timeit(4, gk); + if (tg < best) { best = tg; bk = gk; } + } + const double fl = 2.0 * T * s.n_in * s.n_out; + std::printf("%-9s %-6s %5d -> %5d, T %d: dequant %7.1f us, act %6.1f us, GEMM %7.1f us (%5.1f TFLOP/s, %s) -> %.2f us a token\n", + s.name, ref::type_name(s.type), s.n_in, s.n_out, T, tdq * 1e6, tact * 1e6, best * 1e6, fl / best / 1e12, + bk.c_str(), (tdq + best) / T * 1e6); + } + return 0; +} diff --git a/metal/tests/mm_bench.cpp b/metal/tests/mm_bench.cpp new file mode 100644 index 00000000..95087299 --- /dev/null +++ b/metal/tests/mm_bench.cpp @@ -0,0 +1,103 @@ +// metal/tests/mm_bench.cpp - matrix throughput (TFLOP/s) of MPP matmul2d and simdgroup_matrix, fp16/bf16/fp32 +// operands, fp32 results, on a square 4096^3 and on prompt-expert shapes; checks one product against the CPU. +// mm_bench +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct MmArgs { int M, N, K; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +} // namespace + +int main() { + mtl::Context cx; + std::printf("device %s, metal4 %d\n", cx.device_name().c_str(), cx.supports_metal4()); + const int lib = cx.compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + const int MAX = 4096; + mtl::Buffer A = cx.alloc((size_t)MAX * MAX * 4), B = cx.alloc((size_t)MAX * MAX * 4), C = cx.alloc((size_t)MAX * MAX * 4); + ref::Rng r(1); + // fill as half and float views of the same random values (each kernel reads its own type) + auto fill = [&](int elem) { + for (size_t i = 0; i < (size_t)MAX * MAX; ++i) { + const float v = r.sym(); + if (elem == 4) { A.as()[i] = v; B.as()[i] = r.sym(); } + else if (elem == 2) { A.as()[i] = ref::f32_to_f16(v); B.as()[i] = ref::f32_to_f16(r.sym()); } + else { A.as()[i] = ref::f32_to_bf16(v); B.as()[i] = ref::f32_to_bf16(r.sym()); } + } + }; + struct K { std::string name; int elem; int tm, tn, sg; bool mpp; }; + const std::vector ks = { + {"mpp_mm_half_64_32_4", 2, 64, 32, 4, true}, {"mpp_mm_half_64_64_4", 2, 64, 64, 4, true}, + {"mpp_mm_half_128_64_4", 2, 128, 64, 4, true}, {"mpp_mm_half_32_64_4", 2, 32, 64, 4, true}, + {"mpp_mm_half_64_128_4", 2, 64, 128, 4, true}, {"mpp_mm_half_128_128_4", 2, 128, 128, 4, true}, + {"mpp_mm_half_16_64_2", 2, 16, 64, 2, true}, {"mpp_mm_bfloat_64_64_4", 3, 64, 64, 4, true}, + {"mpp_mm_bfloat_128_64_4", 3, 128, 64, 4, true}, {"mpp_mm_float_64_32_4", 4, 64, 32, 4, true}, + {"mpp_mm_float_64_64_4", 4, 64, 64, 4, true}, {"mpp_mm_float_128_64_4", 4, 128, 64, 4, true}, + {"sg_mm_half", 2, 64, 64, 4, false}, {"sg_mm_float", 4, 64, 64, 4, false}}; + struct Shape { const char* name; int M, N, K; }; + const std::vector shapes = {{"square 4096^3", 4096, 4096, 4096}, + {"expert gu 128 tok x 1280 x 2560", 128, 1280, 2560}, + {"expert down 128 tok x 2560 x 640", 128, 2560, 640}, + {"dense qkv 2048 tok x 10240 x 2560", 2048, 4096, 2560}, + {"expert gu 16 tok x 1280 x 2560", 16, 1280, 2560}}; + int filled = 0; + for (const K& k : ks) { + if (filled != k.elem) { fill(k.elem); filled = k.elem; } + mtl::Pipeline p = cx.pipeline(lib, k.name); + // correctness on a small product (M = tm*2, N = tn*2, K = 256) against the CPU + { + const int M = k.tm * 2, N = k.tn * 2, KK = 256; + MmArgs a{M, N, KK}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(C), mtl::Arg::V(a)}; + d.grid[0] = N / k.tn; + d.grid[1] = M / k.tm; + d.tg[0] = 32 * k.sg; + cx.run({d}); + double se = 0, sr = 0; + for (int i = 0; i < M; ++i) + for (int j = 0; j < N; ++j) { + double ref = 0; + for (int q = 0; q < KK; ++q) { + auto val = [&](const mtl::Buffer& X, size_t idx) -> double { + if (k.elem == 4) return X.as()[idx]; + if (k.elem == 2) return ref::f16_to_f32(X.as()[idx]); + return ref::bf16_to_f32(X.as()[idx]); + }; + ref += val(A, (size_t)i * KK + q) * val(B, (size_t)j * KK + q); + } + const double e = C.as()[i * N + j] - ref; + se += e * e; + sr += ref * ref; + } + std::printf("%-26s check rel L2 %.2e\n", k.name.c_str(), std::sqrt(se / sr)); + } + for (const Shape& s : shapes) { + if (s.M % k.tm || s.N % k.tn) continue; + MmArgs a{s.M, s.N, s.K}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(C), mtl::Arg::V(a)}; + d.grid[0] = s.N / k.tn; + d.grid[1] = s.M / k.tm; + d.tg[0] = 32 * k.sg; + const int reps = std::max(1, (int)(2e10 / (2.0 * s.M * s.N * s.K))); + std::vector ds(std::min(reps, 200), d); + cx.warm(ds, 0.2); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / ds.size()); + const double m = median(t); + std::printf("%-26s %-36s %8.1f us %6.2f TFLOP/s\n", k.name.c_str(), s.name, m * 1e6, + 2.0 * s.M * s.N * s.K / m / 1e12); + } + } + return 0; +} diff --git a/metal/tests/moe_mm_parity.cpp b/metal/tests/moe_mm_parity.cpp new file mode 100644 index 00000000..31b23dc5 --- /dev/null +++ b/metal/tests/moe_mm_parity.cpp @@ -0,0 +1,225 @@ +// metal/tests/moe_mm_parity.cpp - the prompt-chunk routed experts (moe_mm.metal): plan, gate/up GEMM, down GEMM, +// combine, against a CPU reference that rounds the activations and weights to fp16 as the kernels do (the matrix +// units' operands) - and against the exact float reference for the size of that rounding; then the speed. +// +// moe_mm_parity [--gu Q2_0] [--dn Q2_0] [--T 256] [--tile 32,64,64,4] parity (64 experts) +// moe_mm_parity --bench [--gu ..] [--dn ..] [--T 2048] [--tile ..] per-layer time, 512 experts +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int N_EMBD = 2560, N_FF = 640, TOPK = 10; +struct MmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; }; +struct MmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +int type_of(const std::string& s) { + for (int t : {ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL}) + if (s == ref::type_name(t)) return t; + std::exit(2); +} +float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); } +} // namespace + +int main(int argc, char** argv) { + int gu = ref::Q2_0, dn = ref::Q2_0, T = 256, TM = 16, TN = 64, TK = 16, SG = 2, DTN = -1, DTK = -1, DSG = -1; + bool bench = false, v2 = false; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--gu") gu = type_of(argv[++i]); + else if (a == "--dn") dn = type_of(argv[++i]); + else if (a == "--T") T = std::atoi(argv[++i]); + else if (a == "--tile") std::sscanf(argv[++i], "%d,%d,%d,%d", &TM, &TN, &TK, &SG); + else if (a == "--dtile") std::sscanf(argv[++i], "%d,%d,%d", &DTN, &DTK, &DSG); // the down kernel's TN,TK,SG + else if (a == "--bench") bench = true; + else if (a == "--v2") v2 = true; + } + if (bench && T == 256) T = 2048; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "moe_mm.metal"}); + const int NE = bench ? 512 : 64, LAYERS = bench ? 4 : 1; + const size_t gu_row = ref::row_bytes(gu, N_EMBD), d_row = ref::row_bytes(dn, N_FF); + const size_t up_off = (size_t)N_FF * gu_row, down_off = 2 * up_off, blob = down_off + (size_t)N_EMBD * d_row; + std::printf("device %s; %s/%s, T %d, %d experts, tile TM %d TN %d TK %d SG %d\n", cx.device_name().c_str(), + ref::type_name(gu), ref::type_name(dn), T, NE, TM, TN, TK, SG); + mtl::Buffer W = cx.alloc(blob * NE * LAYERS); + { + std::vector tmp(blob * 16); + for (int e = 0; e < 16; ++e) { + ref::random_blocks(gu, tmp.data() + e * blob, 2 * N_FF, N_EMBD, 100 + e, 0.02f); + ref::random_blocks(dn, tmp.data() + e * blob + down_off, N_EMBD, N_FF, 200 + e, 0.02f); + } + for (size_t e = 0; e < (size_t)NE * LAYERS; ++e) std::memcpy(W.as() + e * blob, tmp.data() + (e % 16) * blob, blob); + } + const int nent = T * TOPK, nblk = (nent + 1023) / 1024; + const int maxrows = nent + NE * TM; + mtl::Buffer x = cx.alloc(4 * (size_t)T * N_EMBD), ids = cx.alloc(4 * nent), w = cx.alloc(4 * nent), + bcnt = cx.alloc(4 * (size_t)nblk * NE), boff = cx.alloc(4 * (size_t)nblk * NE), eoff = cx.alloc(4 * NE), + tiles = cx.alloc(8 * (size_t)(maxrows / TM + 1)), meta = cx.alloc(64), stok = cx.alloc(4 * (size_t)maxrows), + sw = cx.alloc(4 * (size_t)maxrows), pos = cx.alloc(4 * nent), H = cx.alloc(4 * (size_t)maxrows * N_FF), + YE = cx.alloc(4 * (size_t)maxrows * N_EMBD), y = cx.alloc(4 * (size_t)T * N_EMBD), + XS = cx.alloc(2 * (size_t)maxrows * N_EMBD), HS = cx.alloc(2 * (size_t)maxrows * N_FF); + ref::Rng r(7); + for (size_t i = 0; i < (size_t)T * N_EMBD; ++i) x.as()[i] = r.sym(); + for (int t = 0; t < T; ++t) { + std::set used; + float s = 0; + for (int k = 0; k < TOPK; ++k) { + int e; + do e = (int)(r.next() % NE); while (used.count(e)); + used.insert(e); + ids.as()[t * TOPK + k] = e; + s += (w.as()[t * TOPK + k] = 0.2f + r.uni()); + } + for (int k = 0; k < TOPK; ++k) w.as()[t * TOPK + k] /= s; + } + mtl::Pipeline phist = cx.pipeline(lib, "mm_hist"), pscan = cx.pipeline(lib, "mm_scan"), pplace = cx.pipeline(lib, "mm_place"), + pclear = cx.pipeline(lib, "mm_clear"), pcomb = cx.pipeline(lib, "mm_combine"); + if (DTN < 0) { DTN = TN; DTK = TK; DSG = SG; } + if (dn == ref::IQ4_NL && DTK < 32) DTK = 32; + const std::string tl = std::to_string(TM) + "_" + std::to_string(TN) + "_" + std::to_string(TK) + "_" + std::to_string(SG); + const std::string dtl = std::to_string(TM) + "_" + std::to_string(DTN) + "_" + std::to_string(DTK) + "_" + std::to_string(DSG); + mtl::Pipeline pgu = cx.pipeline(lib, (v2 ? "mm_gu2_" : "mm_gu_") + std::to_string(gu) + "_" + tl), + pdn = cx.pipeline(lib, (v2 ? "mm_down2_" : "mm_down_") + std::to_string(dn) + "_" + (v2 ? dtl : tl)), + pgat = cx.pipeline(lib, "mm_gather"); + MmPlanArgs pa{(uint32_t)nent, TOPK, (uint32_t)NE, (uint32_t)TM, (uint32_t)nblk}; + auto encode = [&](int layer, std::vector& ds, bool plan, bool gemm) { + if (plan) { + const uint32_t nclr = maxrows; + mtl::Dispatch c; c.p = &pclear; c.args = {mtl::Arg::B(stok), mtl::Arg::V(nclr)}; c.grid[0] = (maxrows + 255) / 256; c.tg[0] = 256; ds.push_back(c); + mtl::Dispatch h; h.p = &phist; h.args = {mtl::Arg::B(ids), mtl::Arg::B(bcnt), mtl::Arg::V(pa)}; h.grid[0] = nblk; h.tg[0] = 1024; ds.push_back(h); + meta.as()[2] = N_FF / TN; + mtl::Dispatch sc; sc.p = &pscan; sc.args = {mtl::Arg::B(bcnt), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(tiles), mtl::Arg::B(meta), mtl::Arg::V(pa)}; sc.tg[0] = NE; ds.push_back(sc); + mtl::Dispatch pl; pl.p = &pplace; pl.args = {mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(stok), mtl::Arg::B(sw), mtl::Arg::B(pos), mtl::Arg::V(pa)}; pl.grid[0] = nblk; pl.tg[0] = 1024; ds.push_back(pl); + } + if (gemm) { + MmArgs ma{(uint64_t)layer * NE * blob, (uint64_t)layer * NE * blob + up_off, (uint64_t)layer * NE * blob + down_off, + blob, blob, (uint32_t)gu_row, (uint32_t)d_row, N_EMBD, N_FF}; + if (v2) { + const uint32_t ne = N_EMBD; + mtl::Dispatch ga; ga.p = &pgat; ga.args = {mtl::Arg::B(x), mtl::Arg::B(stok), mtl::Arg::B(XS), mtl::Arg::V(ne)}; + ga.grid[0] = meta.as()[1]; ga.tg[0] = 256; ds.push_back(ga); + } + mtl::Dispatch g; g.p = &pgu; + if (v2) g.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + else g.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(H), mtl::Arg::B(stok), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + g.grid[0] = N_FF / TN; g.grid[1] = meta.as()[0]; g.tg[0] = 32 * SG; ds.push_back(g); + mtl::Dispatch d; d.p = &pdn; d.args = {mtl::Arg::B(W), mtl::Arg::B(v2 ? HS : H), mtl::Arg::B(YE), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + d.grid[0] = N_EMBD / (v2 ? DTN : TN); d.grid[1] = meta.as()[0]; d.tg[0] = 32 * (v2 ? DSG : SG); ds.push_back(d); + const uint32_t ca[4] = {(uint32_t)T, N_EMBD, TOPK, 0}; + mtl::Dispatch cb; cb.p = &pcomb; cb.args = {mtl::Arg::B(YE), mtl::Arg::B(pos), mtl::Arg::B(sw), mtl::Arg::B(y), mtl::Arg::V(ca)}; + cb.grid[0] = (T * N_EMBD + 255) / 256; cb.tg[0] = 256; ds.push_back(cb); + } + }; + { + std::vector ds; + encode(0, ds, true, false); + cx.run(ds); // the plan first: the GEMMs' grid is the tile count + } + const uint32_t ntiles = meta.as()[0]; + std::printf("plan: %u tiles of %d, %u padded rows for %d entries\n", ntiles, TM, meta.as()[1], nent); + if (!bench) { + // the plan: every entry placed once, rows of an expert contiguous and in entry order + bool ok_plan = true; + std::vector seen(maxrows, 0); + for (int i = 0; i < nent; ++i) { + const int row = pos.as()[i]; + if (row < 0 || row >= (int)meta.as()[1] || stok.as()[row] != i / TOPK) ok_plan = false; + else seen[row]++; + } + for (int i = 0; i < maxrows; ++i) if (seen[i] > 1) ok_plan = false; + std::vector ds; + encode(0, ds, false, true); + cx.run(ds); + // reference: fp16 operands (x, weights, h), fp32+ accumulation; and the exact one + double se16 = 0, se = 0, sr = 0; + std::vector wg((size_t)N_FF * N_EMBD), wu(wg.size()), wd((size_t)N_EMBD * N_FF); + std::vector yr16((size_t)T * N_EMBD, 0.0), yr((size_t)T * N_EMBD, 0.0); + for (int e = 0; e < NE; ++e) { + const uint8_t* b = W.as() + e * blob; + bool any = false; + for (int i = 0; i < nent && !any; ++i) any = ids.as()[i] == e; + if (!any) continue; + ref::dequant(gu, b, wg.data(), wg.size()); + ref::dequant(gu, b + up_off, wu.data(), wu.size()); + ref::dequant(dn, b + down_off, wd.data(), wd.size()); + for (int i = 0; i < nent; ++i) { + if (ids.as()[i] != e) continue; + const int t = i / TOPK; + const float* xt = x.as() + (size_t)t * N_EMBD; + std::vector h16v(N_FF), hv(N_FF); + for (int f = 0; f < N_FF; ++f) { + double g = 0, u = 0, g16 = 0, u16 = 0; + for (int k = 0; k < N_EMBD; ++k) { + const float xk = xt[k], xh = h16(xk); + g += (double)wg[(size_t)f * N_EMBD + k] * xk; + u += (double)wu[(size_t)f * N_EMBD + k] * xk; + g16 += (double)h16(wg[(size_t)f * N_EMBD + k]) * xh; + u16 += (double)h16(wu[(size_t)f * N_EMBD + k]) * xh; + } + hv[f] = g / (1 + std::exp(-g)) * u; + h16v[f] = h16((float)(g16 / (1 + std::exp(-g16)) * u16)); + } + const double wt = w.as()[i]; + for (int d = 0; d < N_EMBD; ++d) { + double s = 0, s16 = 0; + for (int f = 0; f < N_FF; ++f) { + s += (double)wd[(size_t)d * N_FF + f] * hv[f]; + s16 += (double)h16(wd[(size_t)d * N_FF + f]) * h16v[f]; + } + yr[(size_t)t * N_EMBD + d] += wt * s; + yr16[(size_t)t * N_EMBD + d] += wt * s16; + } + } + } + for (size_t i = 0; i < yr.size(); ++i) { + const double g = y.as()[i]; + se16 += (g - yr16[i]) * (g - yr16[i]); + se += (g - yr[i]) * (g - yr[i]); + sr += yr[i] * yr[i]; + } + const double rel16 = std::sqrt(se16 / sr), rel = std::sqrt(se / sr); + const bool ok = ok_plan && rel16 < 2e-4; + std::printf("parity: plan %s; y vs fp16-operand reference rel L2 %.2e, vs exact float reference %.2e %s\n", + ok_plan ? "ok" : "WRONG", rel16, rel, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; + } + // bench: the plan, the two GEMMs and the combine, LAYERS distinct weight sets rotated + double flops = 0; + { + const double rows = meta.as()[1]; + flops = 2.0 * nent * (2.0 * N_FF * N_EMBD + (double)N_EMBD * N_FF); + std::printf("useful GFLOP per layer %.1f (padded rows %.0f = %.2fx entries)\n", flops / 1e9, rows, rows / nent); + } + auto timeit = [&](bool plan, bool gemm, int part) { + std::vector ds; + for (int l = 0; l < 8; ++l) { + std::vector one; + encode(l % LAYERS, one, plan, gemm); + if (part >= 0 && gemm) { ds.push_back(one[part]); continue; } + for (auto& d : one) ds.push_back(d); + } + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 8); + return median(t); + }; + const int o = v2 ? 1 : 0; + const double tp = timeit(true, false, -1), tg = timeit(false, true, o), td = timeit(false, true, o + 1), + tc = timeit(false, true, o + 2), ta = timeit(false, true, -1); + if (v2) std::printf("gather %.1f us\n", timeit(false, true, 0) * 1e6); + const double fgu = 2.0 * nent * 2.0 * N_FF * N_EMBD, fdn = 2.0 * nent * N_EMBD * N_FF; + std::printf("per layer: plan %.1f us, gate/up %.1f us (%.1f TFLOP/s useful), down %.1f us (%.1f TFLOP/s), combine %.1f us;" + " GEMMs + combine %.1f us = %.1f TFLOP/s; %.1f us per token per layer -> 48 layers: %.0f tok/s (experts only)\n", + tp * 1e6, tg * 1e6, fgu / tg / 1e12, td * 1e6, fdn / td / 1e12, tc * 1e6, ta * 1e6, flops / ta / 1e12, + (ta + tp) / T * 1e6, T / (48 * (ta + tp))); + return 0; +}