Skip to content

The 80B Qwen3-Coder-Next on a 16 GB Mac, about 13 tok/s, fully offline. A mixture-of-experts inference engine for Apple silicon.

Rust

0.5.4 candidate: Qwen sampling defaults (top-k 20, min-p 0), repeat penalty off, per-pile split off by default; long-chat fixes, GPU top-k word pick, faster prompt-reading linear attention

Picassoai00130bfa9f51
diff --git a/Cargo.lock b/Cargo.lock
index 5020edb..675632a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -289,7 +289,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "coachwhip"
-version = "0.5.3"
+version = "0.5.4"
dependencies = [
"anyhow",
"candle-core",
@@ -302,7 +302,7 @@ dependencies = [
[[package]]
name = "coachwhip-engine"
-version = "0.5.3"
+version = "0.5.4"
dependencies = [
"candle-core",
"candle-metal-kernels",
@@ -316,7 +316,7 @@ dependencies = [
[[package]]
name = "coachwhip-prepare"
-version = "0.5.3"
+version = "0.5.4"
dependencies = [
"anyhow",
"byteorder",
@@ -326,7 +326,7 @@ dependencies = [
[[package]]
name = "coachwhip-server"
-version = "0.5.3"
+version = "0.5.4"
dependencies = [
"anyhow",
"candle-core",
diff --git a/Cargo.toml b/Cargo.toml
index 00680d0..1ffaa6b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ members = ["crates/engine", "crates/server", "crates/cli", "crates/prepare"]
resolver = "2"
[workspace.package]
-version = "0.5.3"
+version = "0.5.4"
edition = "2021"
license = "Apache-2.0"
publish = false
diff --git a/crates/engine/src/experts.rs b/crates/engine/src/experts.rs
index 9cfa86d..0d609bf 100644
--- a/crates/engine/src/experts.rs
+++ b/crates/engine/src/experts.rs
@@ -2222,9 +2222,15 @@ impl CustomOp2 for MoeMatvec {
if tokens > 8 && crate::fuse_kernel::group3_on() {
drop(encoder);
let (pb, hb) = crate::fuse_kernel::piles(&device, ids.buffer(), il.start_offset() * 4, tokens * nei0, nei0, self.slots)?;
+ let min_cnt = crate::mv_id::pile_min();
let encoder = device.command_encoder()?;
- if crate::mv_id::matmul_id_piles(device.device(), &encoder, device.kernels(), dt, (self.n, self.k, self.slots, self.bytes), self.bank.buffer(), x.buffer(), xl.start_offset() * 4, (ne11, nb11, nb12), &pb, &hb, (self.slots, tokens, nei0), &dst).map_err(candle::MetalError::from)? {
+ if crate::mv_id::matmul_id_piles(device.device(), &encoder, device.kernels(), dt, (self.n, self.k, self.slots, self.bytes), self.bank.buffer(), x.buffer(), xl.start_offset() * 4, (ne11, nb11, nb12), &pb, &hb, (self.slots, tokens, nei0), &dst, min_cnt).map_err(candle::MetalError::from)? {
drop(encoder);
+ if min_cnt > 1 {
+ let (sp, sn) = crate::fuse_kernel::small_pairs(&device, &pb, &hb, tokens * nei0, self.slots, min_cnt)?;
+ let encoder = device.command_encoder()?;
+ crate::mv_id::matvec_id_list(device.device(), &encoder, dt, (self.n, self.k, self.slots, self.bytes), self.bank.buffer(), x.buffer(), xl.start_offset() * 4, (ne11, nb11, nb12), ids.buffer(), il.start_offset() * 4, (nei0, tokens), &sp, &sn, tokens * nei0, &dst).map_err(candle::MetalError::from)?;
+ }
return Ok((MetalStorage::new(dst, device.clone(), elems, DType::F32), Shape::from((tokens, nei0, self.n))));
}
candle::bail!("grouped expert multiply: unsupported type {dt:?}")
@@ -2260,7 +2266,7 @@ impl CustomOp2 for MoeMatvec {
let pb = device.new_buffer_with_data(&piles)?;
let hb = device.new_buffer_with_data(&heads)?;
let encoder = device.command_encoder()?;
- if crate::mv_id::matmul_id_piles(device.device(), &encoder, device.kernels(), dt, (self.n, self.k, self.slots, self.bytes), self.bank.buffer(), x.buffer(), xl.start_offset() * 4, (ne11, nb11, nb12), &pb, &hb, (used, most, nei0), &dst).map_err(candle::MetalError::from)? {
+ if crate::mv_id::matmul_id_piles(device.device(), &encoder, device.kernels(), dt, (self.n, self.k, self.slots, self.bytes), self.bank.buffer(), x.buffer(), xl.start_offset() * 4, (ne11, nb11, nb12), &pb, &hb, (used, most, nei0), &dst, 0).map_err(candle::MetalError::from)? {
drop(encoder);
return Ok((MetalStorage::new(dst, device.clone(), elems, DType::F32), Shape::from((tokens, nei0, self.n))));
}
diff --git a/crates/engine/src/fuse_kernel.rs b/crates/engine/src/fuse_kernel.rs
index 53fe03e..ed3ca10 100644
--- a/crates/engine/src/fuse_kernel.rs
+++ b/crates/engine/src/fuse_kernel.rs
@@ -201,6 +201,27 @@ kernel void cw_pile(
for (uint i = 0; i < n_ids; i++) if (ids[i] == e) { piles[w] = ushort2(i % nei0, i / nei0); w++; }
}
+// The small piles' words: thread e copies its pile when it has fewer than min_cnt words.
+kernel void cw_small(
+ device const ushort2* piles [[buffer(0)]],
+ device const uint* heads [[buffer(1)]],
+ device ushort2* outp [[buffer(2)]],
+ device uint* npairs [[buffer(3)]],
+ constant uint& experts [[buffer(4)]],
+ constant uint& min_cnt [[buffer(5)]],
+ uint e [[thread_position_in_threadgroup]])
+{
+ threadgroup uint counts[256];
+ uint c = 0, first = 0;
+ if (e < experts) { c = heads[3 * e + 2]; first = heads[3 * e + 1]; if (c >= min_cnt) c = 0; }
+ counts[e] = c;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ uint off = 0;
+ for (uint j = 0; j < e; j++) off += counts[j];
+ for (uint i = 0; i < c; i++) outp[off + i] = piles[first + i];
+ if (e == 255) { uint tot = off + c; npairs[0] = tot; }
+}
+
// Top-k, one pass: group g takes elements [g*4096, (g+1)*4096), 256 threads x 16 values in registers,
// and writes its k best (value, index) in order. has_ids: the input carries its own indices (pass 2).
kernel void cw_topk(
@@ -603,3 +624,20 @@ pub fn topk(logits: &Tensor, k: usize) -> Result<(Vec<f32>, Vec<u32>)> {
let vals = out[..k].iter().map(|b| f32::from_bits(*b)).collect();
Ok((vals, out[k..].to_vec()))
}
+
+/// From the piles: the list of words in piles smaller than `min_cnt`, and its length (on the GPU).
+pub fn small_pairs(dev: &candle::MetalDevice, piles: &candle_metal_kernels::metal::Buffer, heads: &candle_metal_kernels::metal::Buffer, n_pairs: usize, experts: usize, min_cnt: u32)
+ -> Result<(Arc<candle_metal_kernels::metal::Buffer>, Arc<candle_metal_kernels::metal::Buffer>)> {
+ let ob = dev.new_buffer_builder().with_size_for(n_pairs.max(1), DType::U32).with_label("cw-small").build()?;
+ let nb = dev.new_buffer_builder().with_size_for(1, DType::U32).with_label("cw-small-n").build()?;
+ let p = pipe(dev, "cw_small")?;
+ {
+ let enc = dev.command_encoder()?;
+ let enc = enc.as_ref();
+ enc.set_compute_pipeline_state(&p);
+ let (e_u, m_u) = (experts as u32, min_cnt);
+ set_params!(enc, ((piles, 0usize), (heads, 0usize), Output::with_offset(&ob, 0), Output::with_offset(&nb, 0), e_u, m_u));
+ enc.dispatch_thread_groups(MTLSize { width: 1, height: 1, depth: 1 }, MTLSize { width: 256, height: 1, depth: 1 });
+ }
+ Ok((ob, nb))
+}
diff --git a/crates/engine/src/ggml_mv_plain.metal b/crates/engine/src/ggml_mv_plain.metal
index 26eed2c..3338008 100644
--- a/crates/engine/src/ggml_mv_plain.metal
+++ b/crates/engine/src/ggml_mv_plain.metal
@@ -7554,3 +7554,44 @@ template [[host_name("kernel_mul_mv_id_iq2_s_f32")]] kernel kernel_mul_mv_id_t
template [[host_name("kernel_mul_mv_id_iq4_nl_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_nl_f32_impl <N_R0_IQ4_NL>>>;
template [[host_name("kernel_mul_mv_id_iq4_xs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_xs_f32_impl <N_R0_IQ4_XS>>>;
template [[host_name("kernel_mul_mv_id_tq2_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_tq2_0_f32_impl <N_R0_TQ2_0>>>;
+
+
+// Coachwhip: the one-word expert multiply over a LIST of (slot, word) pairs (the small piles' words).
+template<mul_mv_disp_fn_t disp_fn>
+kernel void kernel_mul_mv_idl(
+ constant ggml_metal_kargs_mul_mv_id & args,
+ device const char * src0s,
+ device const char * src1,
+ device char * dst,
+ device const char * ids,
+ device const ushort2 * pairs,
+ device const uint * npairs,
+ threadgroup char * shmem [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ ushort tiitg[[thread_index_in_threadgroup]],
+ ushort tiisg[[thread_index_in_simdgroup]],
+ ushort sgitg[[simdgroup_index_in_threadgroup]]) {
+ if (tgpig.z >= npairs[0]) return;
+ const ushort2 pr = pairs[tgpig.z];
+ const int iid1 = pr.y;
+ const int idx = pr.x;
+ tgpig.z = 0;
+ const int32_t i02 = ((device const int32_t *) (ids + iid1*args.nbi1))[idx];
+ const int64_t i11 = idx % args.ne11;
+ const int64_t i12 = iid1;
+ const int64_t i1 = idx;
+ const int64_t i2 = i12;
+ device const char * src0_cur = src0s + i02*args.nb02;
+ device const char * src1_cur = src1 + i11*args.nb11 + i12*args.nb12;
+ device char * dst_cur = dst + (i1*args.ne0 + i2*args.ne1*args.ne0)*sizeof(float);
+ ggml_metal_kargs_mul_mv args0 = {
+ args.ne00, args.ne01, 1, args.nb00, args.nb01, args.nb02, args.nb02,
+ args.ne10, 1, 1, args.nb10, args.nb11, args.nb12, args.nb12,
+ args.ne0, 1, args.nr0, 1, 1,
+ };
+ disp_fn(args0, src0_cur, src1_cur, dst_cur, shmem, tgpig, tiitg, tiisg, sgitg);
+}
+typedef decltype(kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>) kernel_mul_mv_idl_t;
+template [[host_name("kernel_mul_mv_idl_iq2_xxs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq2_xxs_f32_disp<ggml_metal_kargs_mul_mv>>>;
+template [[host_name("kernel_mul_mv_idl_iq3_xxs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq3_xxs_f32_disp<ggml_metal_kargs_mul_mv>>>;
+template [[host_name("kernel_mul_mv_idl_iq4_xs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq4_xs_f32_impl <N_R0_IQ4_XS>>>;
diff --git a/crates/engine/src/ggml_mv_split.metal b/crates/engine/src/ggml_mv_split.metal
index 03a98b0..df12a80 100644
--- a/crates/engine/src/ggml_mv_split.metal
+++ b/crates/engine/src/ggml_mv_split.metal
@@ -7554,3 +7554,43 @@ template [[host_name("kernel_mul_mv_id_iq2_s_f32")]] kernel kernel_mul_mv_id_t
template [[host_name("kernel_mul_mv_id_iq4_nl_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_nl_f32_impl <N_R0_IQ4_NL>>>;
template [[host_name("kernel_mul_mv_id_iq4_xs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_xs_f32_impl <N_R0_IQ4_XS>>>;
template [[host_name("kernel_mul_mv_id_tq2_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_tq2_0_f32_impl <N_R0_TQ2_0>>>;
+
+// Coachwhip: the one-word expert multiply over a LIST of (slot, word) pairs (the small piles' words).
+template<mul_mv_disp_fn_t disp_fn>
+kernel void kernel_mul_mv_idl(
+ constant ggml_metal_kargs_mul_mv_id & args,
+ device const char * src0s,
+ device const char * src1,
+ device char * dst,
+ device const char * ids,
+ device const ushort2 * pairs,
+ device const uint * npairs,
+ threadgroup char * shmem [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ ushort tiitg[[thread_index_in_threadgroup]],
+ ushort tiisg[[thread_index_in_simdgroup]],
+ ushort sgitg[[simdgroup_index_in_threadgroup]]) {
+ if (tgpig.z >= npairs[0]) return;
+ const ushort2 pr = pairs[tgpig.z];
+ const int iid1 = pr.y;
+ const int idx = pr.x;
+ tgpig.z = 0;
+ const int32_t i02 = ((device const int32_t *) (ids + iid1*args.nbi1))[idx];
+ const int64_t i11 = idx % args.ne11;
+ const int64_t i12 = iid1;
+ const int64_t i1 = idx;
+ const int64_t i2 = i12;
+ device const char * src0_cur = src0s + i02*args.nb02;
+ device const char * src1_cur = src1 + i11*args.nb11 + i12*args.nb12;
+ device char * dst_cur = dst + (i1*args.ne0 + i2*args.ne1*args.ne0)*sizeof(float);
+ ggml_metal_kargs_mul_mv args0 = {
+ args.ne00, args.ne01, 1, args.nb00, args.nb01, args.nb02, args.nb02,
+ args.ne10, 1, 1, args.nb10, args.nb11, args.nb12, args.nb12,
+ args.ne0, 1, args.nr0, 1, 1,
+ };
+ disp_fn(args0, src0_cur, src1_cur, dst_cur, shmem, tgpig, tiitg, tiisg, sgitg);
+}
+typedef decltype(kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>) kernel_mul_mv_idl_t;
+template [[host_name("kernel_mul_mv_idl_iq2_xxs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq2_xxs_f32_disp<ggml_metal_kargs_mul_mv>>>;
+template [[host_name("kernel_mul_mv_idl_iq3_xxs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq3_xxs_f32_disp<ggml_metal_kargs_mul_mv>>>;
+template [[host_name("kernel_mul_mv_idl_iq4_xs_f32")]] kernel kernel_mul_mv_idl_t kernel_mul_mv_idl<mmv_fn<kernel_mul_mv_iq4_xs_f32_impl <N_R0_IQ4_XS>>>;
diff --git a/crates/engine/src/mv_id.rs b/crates/engine/src/mv_id.rs
index cf2da99..ebd633e 100644
--- a/crates/engine/src/mv_id.rs
+++ b/crates/engine/src/mv_id.rs
@@ -293,6 +293,7 @@ pub fn matmul_id_piles(
heads: &Buffer,
(used, most, nei0): (usize, usize, usize),
dst: &Buffer,
+ min_cnt: u32,
) -> Result<bool, MetalKernelError> {
let (name, block) = match dtype {
GgmlDType::Iq2Xxs => ("kernel_mul_mm_idg_iq2_xxs_f32", 66usize),
@@ -322,9 +323,67 @@ pub fn matmul_id_piles(
let ne1 = nei0 as i64;
set_params!(
encoder,
- (src0s, (src1, src1_offset), Output::with_offset(dst, 0), piles, heads, ne00, ne02_, nb01, nb02_, ne11_, ne12, nb10, nb11_, nb12_, ne0, ne1)
+ (src0s, (src1, src1_offset), Output::with_offset(dst, 0), piles, heads, ne00, ne02_, nb01, nb02_, ne11_, ne12, nb10, nb11_, nb12_, ne0, ne1, min_cnt)
);
let groups = MTLSize { width: most.div_ceil(32), height: n.div_ceil(64), depth: used };
encoder.dispatch_thread_groups(groups, MTLSize { width: 128, height: 1, depth: 1 });
Ok(true)
}
+
+
+/// The one-word expert multiply over a list of (slot, word) pairs; `npairs` holds the list length.
+#[allow(clippy::too_many_arguments)]
+pub fn matvec_id_list(
+ device: &Device,
+ ep: impl EncoderProvider,
+ dtype: GgmlDType,
+ (n, k, ne02, nb02): (usize, usize, usize, usize),
+ src0s: &Buffer,
+ src1: &Buffer,
+ src1_offset: usize,
+ (ne11, nb11, nb12): (usize, usize, usize),
+ ids: &Buffer,
+ ids_offset: usize,
+ (nei0, nei1): (usize, usize),
+ pairs: &Buffer,
+ npairs: &Buffer,
+ max_pairs: usize,
+ dst: &Buffer,
+) -> Result<bool, MetalKernelError> {
+ let nb32 = k / 32;
+ let short_row = nb32 < 32 && 32 % nb32 == 0;
+ let (name, block, nr0, split, smem) = match dtype {
+ GgmlDType::Iq2Xxs => ("kernel_mul_mv_idl_iq2_xxs_f32", 66usize, if short_row { 8 } else { 4 }, short_row, 256 * 8 + 128),
+ GgmlDType::Iq3Xxs => ("kernel_mul_mv_idl_iq3_xxs_f32", 98, if short_row { 8 } else { 4 }, short_row, 256 * 4 + 128),
+ GgmlDType::Iq4Xs => ("kernel_mul_mv_idl_iq4_xs_f32", 136, 2, false, 32 * 4),
+ _ => return Ok(false),
+ };
+ let nsg = 2usize;
+ let pipeline = new_pipe(device, name, split)?;
+ let encoder = ep.encoder();
+ let encoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ encoder.set_threadgroup_memory_length(0, smem);
+ let args = KargsMvId {
+ nei0: nei0 as i32, nei1: nei1 as i32, nbi1: (nei0 * 4) as u64,
+ ne00: k as i32, ne01: n as i32, ne02: ne02 as i32,
+ nb00: block as u64, nb01: (k / 256 * block) as u64, nb02: nb02 as u64,
+ ne10: k as i32, ne11: ne11 as i32, ne12: nei1 as i32, ne13: 1,
+ nb10: 4, nb11: nb11 as u64, nb12: nb12 as u64,
+ ne0: n as i32, ne1: nei0 as i32, nb1: (n * 4) as u64, nr0: nr0 as i32,
+ };
+ encoder.set_bytes(0, &args);
+ encoder.set_input_buffer(1, Some(src0s), 0);
+ encoder.set_input_buffer(2, Some(src1), src1_offset);
+ encoder.set_output_buffer(3, Some(dst), 0);
+ encoder.set_input_buffer(4, Some(ids), ids_offset);
+ encoder.set_input_buffer(5, Some(pairs), 0);
+ encoder.set_input_buffer(6, Some(npairs), 0);
+ encoder.dispatch_thread_groups(MTLSize { width: n.div_ceil(nr0 * nsg), height: 1, depth: max_pairs }, MTLSize { width: 32, height: nsg, depth: 1 });
+ Ok(true)
+}
+
+pub fn pile_min() -> u32 {
+ static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+ *N.get_or_init(|| std::env::var("COACHWHIP_PILE_MIN").ok().and_then(|v| v.parse().ok()).unwrap_or(0))
+}
diff --git a/crates/server/src/chat.rs b/crates/server/src/chat.rs
index dc50c93..216be1b 100644
--- a/crates/server/src/chat.rs
+++ b/crates/server/src/chat.rs
@@ -232,8 +232,8 @@ static SAMPLER_EXTRA: std::sync::Mutex<(Option<usize>, Option<f64>)> = std::sync
static REPEAT_REQ: std::sync::Mutex<Option<f64>> = std::sync::Mutex::new(None);
fn default_repeat_penalty() -> f64 { std::env::var("COACHWHIP_REPEAT_PENALTY").ok().and_then(|v| v.parse().ok()).unwrap_or(1.0) }
fn repeat_last_n() -> usize { std::env::var("COACHWHIP_REPEAT_LAST_N").ok().and_then(|v| v.parse().ok()).unwrap_or(64) }
-fn default_top_k() -> usize { std::env::var("COACHWHIP_TOP_K").ok().and_then(|v| v.parse().ok()).unwrap_or(40) }
-fn default_min_p() -> f64 { std::env::var("COACHWHIP_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.05) }
+fn default_top_k() -> usize { std::env::var("COACHWHIP_TOP_K").ok().and_then(|v| v.parse().ok()).unwrap_or(20) }
+fn default_min_p() -> f64 { std::env::var("COACHWHIP_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0) }
/// The word pick: argmax at temperature 0, else top-k -> top-p -> min-p -> temperature -> draw.
struct Picker { s: Sampling, k: usize, min_p: f64, rng: u64, penalty: f64, hist: std::collections::VecDeque<u32> }
diff --git a/vendor/candle-metal-kernels/src/metal_src/quantized.metal b/vendor/candle-metal-kernels/src/metal_src/quantized.metal
index c31f7fa..6156cfa 100644
--- a/vendor/candle-metal-kernels/src/metal_src/quantized.metal
+++ b/vendor/candle-metal-kernels/src/metal_src/quantized.metal
@@ -7885,6 +7885,7 @@ kernel void kernel_mul_mm_idg(
constant uint64_t & nb12,
constant int64_t & ne0,
constant int64_t & ne1,
+ constant uint & min_cnt,
threadgroup uchar * shared_memory [[threadgroup(0)]],
uint3 tgpig[[threadgroup_position_in_grid]],
uint tiitg[[thread_index_in_threadgroup]],
@@ -7894,7 +7895,7 @@ kernel void kernel_mul_mm_idg(
const uint first = heads[3 * z + 1];
const uint cnt = heads[3 * z + 2];
tgpig.z = 0;
- if (tgpig.x * 32 >= cnt) return;
+ if (cnt < min_cnt || tgpig.x * 32 >= cnt) return;
device const uchar * src0 = src0s + e * nb02;
threadgroup ushort2 * rowids = (threadgroup ushort2 *)(shared_memory + 8192);
for (uint i = tiitg; i < cnt; i += 128) rowids[i] = piles[first + i];