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

lab: GPU shrink (Q2_K kernels Q3K/Q4K/Q5K), two kinds of slot, dense shrink at load, probability-rule prefetch, shaped fit, measurement switches — all off by default, nothing public

Picassoai3fed3273fea3
diff --git a/Cargo.lock b/Cargo.lock
index 164d596..c13c5a0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -187,7 +187,6 @@ dependencies = [
[[package]]
name = "candle-metal-kernels"
version = "0.11.0"
-source = "git+https://github.com/huggingface/candle?rev=5ba5d5b468b5b1df40e82dd3d556987bedeea041#5ba5d5b468b5b1df40e82dd3d556987bedeea041"
dependencies = [
"block2",
"half",
@@ -291,7 +290,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "coachwhip"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"anyhow",
"candle-core",
@@ -304,19 +303,30 @@ dependencies = [
[[package]]
name = "coachwhip-engine"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"candle-core",
"candle-metal-kernels",
"candle-nn",
"candle-transformers",
+ "libc",
+ "objc2",
"objc2-metal",
"rayon",
]
+[[package]]
+name = "coachwhip-prepare"
+version = "0.4.0"
+dependencies = [
+ "anyhow",
+ "byteorder",
+ "candle-core",
+]
+
[[package]]
name = "coachwhip-server"
-version = "0.3.0"
+version = "0.4.0"
dependencies = [
"anyhow",
"candle-core",
diff --git a/Cargo.toml b/Cargo.toml
index 28fb46f..cef0c0a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,9 +1,9 @@
[workspace]
-members = ["crates/engine", "crates/server", "crates/cli"]
+members = ["crates/engine", "crates/server", "crates/cli", "crates/prepare"]
resolver = "2"
[workspace.package]
-version = "0.3.0"
+version = "0.4.0"
edition = "2021"
license = "Apache-2.0"
publish = false
@@ -14,6 +14,7 @@ candle-nn = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5
candle-transformers = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041", features = ["metal"] }
candle-metal-kernels = { git = "https://github.com/huggingface/candle", rev = "5ba5d5b468b5b1df40e82dd3d556987bedeea041" }
objc2-metal = "0.3.1"
+objc2 = "0.6"
tokenizers = { version = "0.23.1", default-features = false, features = ["fancy-regex"] }
clap = { version = "4.2.4", features = ["derive"] }
anyhow = "1"
@@ -24,3 +25,6 @@ coachwhip-server = { path = "crates/server" }
[profile.release]
debug = false
+
+[patch."https://github.com/huggingface/candle"]
+candle-metal-kernels = { path = "vendor/candle-metal-kernels" }
diff --git a/coachwhip.sh b/coachwhip.sh
index 1b64c3c..c1d1ce5 100755
--- a/coachwhip.sh
+++ b/coachwhip.sh
@@ -1,6 +1,6 @@
#!/bin/bash
# Start the Coachwhip chat and open it in the browser.
-# ./coachwhip.sh <model.gguf> <tokenizer.json> [bank] [port]
+# ./coachwhip.sh <model.gguf> <tokenizer.json> [bank] [port] [more coachwhip options...]
set -euo pipefail
[ $# -ge 2 ] || { echo "usage: $0 <model.gguf> <tokenizer.json> [bank] [port]" >&2; exit 1; }
# Paths are made absolute before moving to the Coachwhip folder, so relative ones work too.
@@ -10,7 +10,7 @@ TOKENIZER="$(abs "$2")"
BANK="${3:-44}"
PORT="${4:-8090}"
cd "$(dirname "$0")"
-./target/release/coachwhip --model "$MODEL" --tokenizer "$TOKENIZER" --bank "$BANK" --chat "$PORT" &
+./target/release/coachwhip --model "$MODEL" --tokenizer "$TOKENIZER" --bank "$BANK" --chat "$PORT" "${@:5}" &
pid=$!
trap 'kill $pid 2>/dev/null' INT TERM EXIT
until curl -s -o /dev/null "http://127.0.0.1:$PORT/"; do
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 7346ceb..3ea84f6 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -76,10 +76,41 @@ struct Args {
/// Print where each word's time went after every answer.
#[arg(long)]
profile: bool,
+
+ /// Ask the router for this many experts per word instead of the model's own number (Qwen3.5-122B:
+ /// 4 instead of 8). Fewer experts means fewer bytes per word and faster writing; the answers
+ /// change, so check them for your use.
+ #[arg(long)]
+ experts: Option<usize>,
+
+ /// The parallel path: the GPU waits on a shared event for its experts instead of the CPU
+ /// re-queuing each layer. Faster on big models; the answers do not change.
+ #[arg(long)]
+ parallel: bool,
+
+ /// The register: learns, as it runs, what each expert adds to the running state, and guesses
+ /// the next layers' experts from the state it predicts. Fewer reads; the answers do not change.
+ #[arg(long)]
+ register: bool,
}
fn main() -> Result<()> {
let args = Args::parse();
+ // The engine reads these as switches; the flags are their front door.
+ if let Some(k) = args.experts {
+ std::env::set_var("COACHWHIP_TOPK", k.to_string());
+ }
+ if args.parallel {
+ std::env::set_var("COACHWHIP_PARALLEL", "1");
+ }
+ // The parallel path commits GPU work itself, layer by layer, once the CPU has written what
+ // that work reads; Candle must not commit on its own count in between.
+ if coachwhip_engine::experts::parallel() && std::env::var("CANDLE_METAL_COMPUTE_PER_BUFFER").is_err() {
+ std::env::set_var("CANDLE_METAL_COMPUTE_PER_BUFFER", "1000000");
+ }
+ if args.register {
+ std::env::set_var("COACHWHIP_REGISTER", "1");
+ }
let device = Device::new_metal(0)?;
// A hot path belongs to one model: its routes live in a folder named after the model file.
let model_name = args.model.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "model".into());
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index c1e9276..6879aa6 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -12,4 +12,6 @@ candle-nn.workspace = true
candle-transformers.workspace = true
candle-metal-kernels.workspace = true
objc2-metal.workspace = true
+objc2.workspace = true
rayon.workspace = true
+libc = "0.2"
diff --git a/crates/engine/src/experts.rs b/crates/engine/src/experts.rs
index d11c898..5583878 100644
--- a/crates/engine/src/experts.rs
+++ b/crates/engine/src/experts.rs
@@ -44,11 +44,39 @@ struct BankMat {
k: usize,
}
+/// Two kinds of slot (`COACHWHIP_SHARP=<n>`, Captain's design): the experts the model leans on
+/// keep the file's own bytes in `n` sharp slots per layer; the rest go through the GPU shrink
+/// into the small (Q2) bank. A sharp slot's index carries `SHARP_FLAG`.
+pub const SHARP_FLAG: usize = 1 << 30;
+
+struct SharpBank {
+ mats: [BankMat; 3],
+ slots: Slots,
+ ready: Vec<Arc<AtomicBool>>,
+}
+
struct Bank {
mats: [BankMat; 3],
slots: Slots,
+ sharp: Option<SharpBank>,
/// False while the prefetch thread is still reading an expert into the slot.
ready: Vec<Arc<AtomicBool>>,
+ /// The GPU's own copy of which slot holds which expert, and which slots are ready (S4).
+ gpu: Arc<crate::gpu_sync::GpuBank>,
+ /// S4: slots the GPU is about to read for the word in flight; a prefetch may not take them.
+ pinned: Vec<AtomicBool>,
+}
+
+impl Bank {
+ /// Rewrite the GPU's table from the CPU's: every expert's slot, or none.
+ fn sync_table(&self) {
+ for e in 0..self.gpu.experts as u32 {
+ match self.slots.slot_of.get(&e) {
+ Some(&s) => self.gpu.set_slot(e, s),
+ None => self.gpu.clear(e),
+ }
+ }
+ }
}
/// A bank's bookkeeping, apart from the GPU memory it describes: which expert sits in which
@@ -120,6 +148,17 @@ impl Slots {
Some(plan)
}
+ /// The toaster: once a layer has used these experts, their slots go to the front of the
+ /// eviction line, so the next reads take them first instead of the longest-unused slots.
+ pub fn pop(&mut self, used: &[u32]) {
+ for &e in used {
+ if let Some(&slot) = self.slot_of.get(&e) {
+ self.lru.retain(|&x| x != slot);
+ self.lru.push_front(slot);
+ }
+ }
+ }
+
/// Reserve slots for the predicted experts not already held, best first, as far as free slots
/// go; never evicts another predicted expert or a slot still being filled.
pub fn reserve(&mut self, predicted: &[u32], ready: impl Fn(usize) -> bool) -> Vec<(u32, usize)> {
@@ -247,6 +286,26 @@ struct Trail {
lines: Vec<String>,
/// Finished forward passes, waiting to be saved.
blocks: Vec<String>,
+ /// The words of the forward pass in progress, for the block's T line.
+ tokens: Vec<u32>,
+}
+
+/// Our register: per layer, what each expert adds to the running vector (`d`), what the layer adds
+/// regardless (`d0`), and the last prediction waiting to be checked against the truth.
+struct Register {
+ d: Vec<Tensor>,
+ d0: Vec<Tensor>,
+ lr: f32,
+ lr0: f32,
+ last: Option<(usize, Tensor, Tensor, Tensor)>,
+ /// The input the last prediction was made from (measurement only).
+ last_x: Tensor,
+}
+
+impl Default for Register {
+ fn default() -> Self {
+ Self { d: Vec::new(), d0: Vec::new(), lr: 1.0, lr0: 0.05, last: None, last_x: Tensor::zeros(1, DType::F32, &Device::Cpu).unwrap() }
+ }
}
#[derive(Default)]
@@ -272,6 +331,32 @@ struct Stats {
expert_seconds: f64,
load_phase_seconds: f64,
maths_seconds: f64,
+ /// S6 measurement: how often a bank-only route (experts already resident) would have picked
+ /// the same experts as the real route. Layers seen, summed agreement fraction, layers fully
+ /// agreeing, words where every layer agreed, and whether the current word has agreed so far.
+ draft_layers: u64,
+ draft_agree: f64,
+ draft_layers_full: u64,
+ draft_words_full: u64,
+ draft_word_ok: bool,
+ /// S6 measurement: drafts run, words drafted, words the plain path agreed with.
+ spec_passes: u64,
+ spec_drafted: u64,
+ spec_accepted: u64,
+ /// Register measurement: relative error of its predicted state against the truth, summed per
+ /// layer step, and the same for the plain carry-over (x alone) as the yardstick.
+ /// Where the CPU time around the loads goes, per layer step (profile mode, plain path):
+ /// waiting for the GPU to hand the picks back, placing the experts in the bank (no reads),
+ /// the reads themselves, the bookkeeping (learn, log, guess, prefetch requests), and the encode.
+ t_readback: f64,
+ t_place: f64,
+ t_books: f64,
+ t_encode: f64,
+ reg_steps: u64,
+ reg_err: f64,
+ reg_err_plain: f64,
+ reg_err_by_layer: Vec<f64>,
+ reg_plain_by_layer: Vec<f64>,
}
static PROFILE: AtomicBool = AtomicBool::new(false);
@@ -280,6 +365,61 @@ fn profiling() -> bool {
PROFILE.load(Ordering::Relaxed)
}
+fn toaster() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_TOASTER").is_ok())
+}
+
+/// Lab (`COACHWHIP_STAGE=1`): file reads land in ordinary memory and are copied into the bank.
+fn staged() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_STAGE").map(|v| v == "1").unwrap_or(false))
+}
+
+/// Lab (`COACHWHIP_QRULE=<p>`): prefetch every early-guess candidate whose router probability is
+/// at least `p`, instead of a flat `prefetch` per layer. `COACHWHIP_QCAP` caps the width (16).
+fn q_rule() -> Option<f32> {
+ static V: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();
+ *V.get_or_init(|| std::env::var("COACHWHIP_QRULE").ok().and_then(|v| v.parse().ok()))
+}
+
+fn q_cap() -> usize {
+ static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+ *V.get_or_init(|| std::env::var("COACHWHIP_QCAP").ok().and_then(|v| v.parse().ok()).unwrap_or(16))
+}
+
+/// Lab (`COACHWHIP_SPLIT=1`): a layer's maths starts on the resident experts while its misses
+/// are read, then finishes with the misses. Same sum, two halves.
+fn split_maths() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_SPLIT").map(|v| v == "1").unwrap_or(false))
+}
+
+/// The GPU shrink (`COACHWHIP_GPUQ2=1`): the bank holds Q2_K copies, shrunk on arrival.
+pub fn gpuq2() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_GPUQ2").map(|v| v == "1").unwrap_or(false))
+}
+
+/// The shaped shrink (`COACHWHIP_SHAPE=1`): the shrink's fit is weighted by the token's shape.
+pub fn shaped() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_SHAPE").map(|v| v == "1").unwrap_or(false))
+}
+
+/// With the GPU shrink on, squeeze the down matrix too (`COACHWHIP_Q2_DOWN=1`). Off by default:
+/// down is the fat, sensitive one, and the Q2 file that read well last night kept it sharp.
+fn shrink_down() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_Q2_DOWN").map(|v| v == "1").unwrap_or(false))
+}
+
+/// S4: the GPU never stops for the CPU (`COACHWHIP_PARALLEL=1`).
+pub fn parallel() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("COACHWHIP_PARALLEL").is_ok())
+}
+
pub struct ExpertStore {
file: std::fs::File,
device: Device,
@@ -299,6 +439,54 @@ pub struct ExpertStore {
/// The word being written (one-word steps only) and the layer it has reached.
word: AtomicU64,
now_layer: AtomicUsize,
+ /// S6: routing confined to the bank, nothing read or learned.
+ draft: AtomicBool,
+ /// Foresight: the draft pass also tells the bank what the real pass of this word will need.
+ foresee: AtomicBool,
+ /// Which word ahead the foresight draft is on (0 = the word about to be written).
+ foresee_step: AtomicU64,
+ foresight_lists: Mutex<Vec<(usize, Tensor)>>,
+ /// Lab (`COACHWHIP_DUMP=file`): every layer's MoE input and router scores, one record per
+ /// layer per word, to fit the expert predictor from.
+ dump: Mutex<Option<std::io::BufWriter<std::fs::File>>>,
+ /// Our register (`COACHWHIP_REGISTER=1`): what each expert adds to the running vector, per
+ /// layer, learned on the GPU as the words go by; the early guess reads the state it predicts.
+ register: Mutex<Option<Register>>,
+ /// S4: the resolve-and-wait kernel, when the parallel path is on (`COACHWHIP_PARALLEL=1`).
+ /// The parallel path (S4), when `COACHWHIP_PARALLEL` is set.
+ s4: Option<S4>,
+ /// The GPU shrink (`COACHWHIP_GPUQ2=1`): arriving experts are shrunk to Q2_K on the GPU on
+ /// their way into the bank, which holds Q2 copies and so parks more of them.
+ requant: Option<crate::requant::Requant>,
+ /// Staging buffers for the shrink, by size, reused across reads.
+ staging: Mutex<HashMap<usize, Vec<Arc<candle_metal_kernels::metal::Buffer>>>>,
+ /// Sharp slots per layer (0 = one kind of slot) and the hot experts per layer that get them,
+ /// from the route logs at load: the most-used experts of each layer.
+ sharp_n: usize,
+ hot: Vec<Vec<u32>>,
+ /// The token's shape per layer (`COACHWHIP_SHAPE=1`): running mean of x² over the hidden
+ /// size (for gate and up) and of the expert's hidden² over the intermediate size (for down),
+ /// in shared buffers the shaped shrink reads. Count of updates alongside.
+ shape: Mutex<HashMap<usize, (Arc<candle_metal_kernels::metal::Buffer>, Arc<candle_metal_kernels::metal::Buffer>, u64)>>,
+}
+
+/// The parallel path's fixed parts: the two kernels, the shared event, the sequence of waits and
+/// the service thread's queue.
+struct S4 {
+ pipes: crate::gpu_sync::Pipelines,
+ event: crate::gpu_sync::GpuEvent,
+ seq: AtomicU64,
+ tx: Mutex<Option<mpsc::Sender<S4Job>>>,
+}
+
+/// One layer's picks for the service thread: read them, place the experts, signal the GPU.
+struct S4Job {
+ layer: usize,
+ seq: u64,
+ n_ids: usize,
+ n_guess: usize,
+ prefetch_k: usize,
+ ahead: usize,
}
/// Expert ids ordered by a router's scores, best first. Equal scores keep expert order, so the
@@ -312,7 +500,7 @@ pub fn rank(scores: &[f32]) -> Vec<u32> {
/// A guessed read is stale once its word is over, or the word has reached its layer: from then
/// on that layer reads its own misses, and a late guess would only evict experts still to be used.
pub fn is_stale(job_layer: usize, job_word: u64, now_layer: usize, now_word: u64) -> bool {
- job_word != now_word || job_layer <= now_layer
+ job_word < now_word || (job_word == now_word && job_layer <= now_layer)
}
impl ExpertStore {
@@ -347,6 +535,13 @@ impl ExpertStore {
slices.push(per_expert);
}
let file = std::fs::File::open(path)?;
+ // Lab (`COACHWHIP_NOCACHE=1`): read experts straight from the flash, bypassing the page
+ // cache. On a 16 GB box the cache has nothing to give back and costs a copy per read.
+ if std::env::var("COACHWHIP_NOCACHE").map(|v| v == "1").unwrap_or(false) {
+ use std::os::unix::io::AsRawFd;
+ let r = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_NOCACHE, 1) };
+ eprintln!("coachwhip: page cache bypassed for expert reads (fcntl F_NOCACHE -> {r})");
+ }
let experts = slices[0].len();
let per_expert_mb = slices[0][0].iter().map(|s| s.bytes).sum::<usize>() as f64 / 1e6;
eprintln!(
@@ -356,6 +551,18 @@ impl ExpertStore {
let dirs: Vec<&Path> = settings.routes.iter().chain(settings.learned.iter()).map(|p| p.as_path()).collect();
let routes = load_routes(&dirs, layers);
eprintln!("coachwhip: route table for {} (layer, expert) pairs", routes.len());
+ let sharp_n: usize = std::env::var("COACHWHIP_SHARP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
+ let hot: Vec<Vec<u32>> = (0..layers)
+ .map(|l| {
+ let mut use_count: Vec<(u32, u64)> = (0..slices[l].len() as u32).map(|e| (e, routes.get(&(l, e)).map_or(0, |row| row.values().sum()))).collect();
+ use_count.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+ use_count.into_iter().take(sharp_n).filter(|(_, n)| *n > 0).map(|(e, _)| e).collect()
+ })
+ .collect();
+ if sharp_n > 0 {
+ let known: usize = hot.iter().map(|h| h.len()).sum();
+ eprintln!("coachwhip: two kinds of slot: {sharp_n} sharp per layer for the hot experts ({known} known from the route logs), {per_layer} small");
+ }
let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let store = Arc::new(Self {
file,
@@ -374,7 +581,39 @@ impl ExpertStore {
prefetch_tx: Mutex::new(None),
word: AtomicU64::new(0),
now_layer: AtomicUsize::new(0),
+ draft: AtomicBool::new(false),
+ foresee: AtomicBool::new(false),
+ foresee_step: AtomicU64::new(0),
+ foresight_lists: Mutex::new(Vec::new()),
+ dump: Mutex::new(std::env::var("COACHWHIP_DUMP").ok().and_then(|p| std::fs::File::create(p).ok()).map(std::io::BufWriter::new)),
+ register: Mutex::new(if std::env::var("COACHWHIP_REGISTER").map(|v| v == "1").unwrap_or(false) { Some(Register::default()) } else { None }),
+ s4: if parallel() {
+ Some(S4 { pipes: crate::gpu_sync::pipelines(metal.device())?, event: crate::gpu_sync::GpuEvent::new(metal.device())?, seq: AtomicU64::new(0), tx: Mutex::new(None) })
+ } else {
+ None
+ },
+ requant: if gpuq2() { Some(crate::requant::Requant::new(metal)?) } else { None },
+ staging: Mutex::new(HashMap::new()),
+ shape: Mutex::new(HashMap::new()),
+ sharp_n,
+ hot,
});
+ if gpuq2() {
+ let q2_mb = store.slices[0][0].iter().enumerate().map(|(i, s)| if i < 2 || shrink_down() { s.dims.iter().product::<usize>() / crate::requant::QK_K * crate::requant::Q2K_BLOCK_BYTES } else { s.bytes }).sum::<usize>() as f64 / 1e6;
+ eprintln!("coachwhip: GPU shrink on: experts are shrunk to Q2_K on arrival, {q2_mb:.1} MB each in the bank ({:.2} GB)", per_layer as f64 * layers as f64 * q2_mb / 1e3);
+ }
+ if let Some(s4) = &store.s4 {
+ eprintln!("coachwhip: parallel path on: the GPU waits on a shared event for its experts; the CPU never waits for the GPU inside a word");
+ let (tx, rx) = mpsc::channel::<S4Job>();
+ *s4.tx.lock().unwrap() = Some(tx);
+ let weak: Weak<Self> = Arc::downgrade(&store);
+ std::thread::spawn(move || {
+ for job in rx {
+ let Some(st) = weak.upgrade() else { break };
+ st.s4_service(job);
+ }
+ });
+ }
// The prefetch threads read guessed experts into free slots while the GPU works on the
// current layer. They hold only a weak handle, so the store still shuts down with the model.
let (tx, rx) = mpsc::channel::<(usize, u64, Vec<u32>)>();
@@ -416,18 +655,132 @@ impl ExpertStore {
scores
.into_iter()
.map(|(e, _)| e)
- .filter(|e| present.map_or(true, |b| !b.slots.slot_of.contains_key(e)))
+ .filter(|e| present.map_or(true, |b| !b.slots.slot_of.contains_key(e) && !b.sharp.as_ref().map_or(false, |sb| sb.slots.slot_of.contains_key(e))))
.take(k)
.collect()
}
+ pub fn register_on(&self) -> bool {
+ self.register.lock().unwrap().is_some()
+ }
+
+ /// One step of the register at `layer`: learn from the layer before (its prediction against
+ /// this layer's real input), then predict this layer's output state from the experts it chose.
+ /// `xs` is (1, h), `ids` the chosen experts, `top_w` their weights (1, k). Returns x̂ (1, h).
+ fn register_step(&self, layer: usize, xs: &Tensor, ids: &[u32], top_w: &Tensor) -> Result<Tensor> {
+ let mut guard = self.register.lock().unwrap();
+ let Some(reg) = guard.as_mut() else { return Ok(xs.clone()) };
+ let h = xs.dim(1)?;
+ let experts = self.slices[layer].len();
+ let device = xs.device();
+ if reg.d.is_empty() {
+ for l in 0..self.layers {
+ reg.d.push(Tensor::zeros((experts, h), DType::F32, device)?);
+ reg.d0.push(Tensor::zeros(h, DType::F32, device)?);
+ }
+ reg.lr = std::env::var("COACHWHIP_REGISTER_LR").ok().and_then(|v| v.parse().ok()).unwrap_or(1.0);
+ reg.lr0 = std::env::var("COACHWHIP_REGISTER_LR0").ok().and_then(|v| v.parse().ok()).unwrap_or(0.05);
+ eprintln!("coachwhip: register on: {} layers x {experts} experts x {h}, lr {} / {}", self.layers, reg.lr, reg.lr0);
+ }
+ // Learn: the layer before predicted x̂; this layer's input is the truth.
+ if let Some((l, x_hat, ids_t, w_t)) = reg.last.take() {
+ if l + 1 == layer {
+ let err = (xs - &x_hat)?; // (1, h)
+ if profiling() {
+ let truth = xs.sqr()?.sum_all()?.to_scalar::<f32>()?.sqrt().max(1e-6);
+ let e = err.sqr()?.sum_all()?.to_scalar::<f32>()?.sqrt();
+ let plain = (xs - &reg.last_x)?.sqr()?.sum_all()?.to_scalar::<f32>()?.sqrt();
+ let mut st = self.stats.lock().unwrap();
+ if st.reg_err_by_layer.len() < self.layers {
+ st.reg_err_by_layer = vec![0.0; self.layers];
+ st.reg_plain_by_layer = vec![0.0; self.layers];
+ }
+ st.reg_steps += 1;
+ st.reg_err += (e / truth) as f64;
+ st.reg_err_plain += (plain / truth) as f64;
+ st.reg_err_by_layer[layer] += (e / truth) as f64;
+ st.reg_plain_by_layer[layer] += (plain / truth) as f64;
+ }
+ let delta = w_t.broadcast_mul(&err)?.affine(reg.lr as f64, 0.0)?; // (k, h)
+ reg.d[l] = reg.d[l].index_add(&ids_t, &delta, 0)?;
+ reg.d0[l] = (&reg.d0[l] + err.squeeze(0)?.affine(reg.lr0 as f64, 0.0)?)?;
+ }
+ }
+ // Predict: x̂ = x + d0 + Σ w_e d[e].
+ let ids_t = Tensor::new(ids, device)?;
+ let w_t = top_w.reshape((ids.len(), 1))?.to_dtype(DType::F32)?;
+ let adds = reg.d[layer].index_select(&ids_t, 0)?; // (k, h)
+ let x_hat = (xs.broadcast_add(&reg.d0[layer])? + w_t.broadcast_mul(&adds)?.sum_keepdim(0)?)?;
+ reg.last = Some((layer, x_hat.clone(), ids_t, w_t));
+ reg.last_x = xs.clone();
+ Ok(x_hat)
+ }
+
+ /// The register step with the picks still on the GPU (the parallel path never reads them
+ /// back): `top_ids` (1, k) u32, `top_w` (1, k). Learns from the layer before, predicts x̂.
+ fn register_step_gpu(&self, layer: usize, xs: &Tensor, top_ids: &Tensor, top_w: &Tensor) -> Result<Tensor> {
+ let mut guard = self.register.lock().unwrap();
+ let Some(reg) = guard.as_mut() else { return Ok(xs.clone()) };
+ let h = xs.dim(1)?;
+ let k = top_ids.elem_count();
+ let experts = self.slices[layer].len();
+ let device = xs.device();
+ if reg.d.is_empty() {
+ for _ in 0..self.layers {
+ reg.d.push(Tensor::zeros((experts, h), DType::F32, device)?);
+ reg.d0.push(Tensor::zeros(h, DType::F32, device)?);
+ }
+ reg.lr = std::env::var("COACHWHIP_REGISTER_LR").ok().and_then(|v| v.parse().ok()).unwrap_or(1.0);
+ reg.lr0 = std::env::var("COACHWHIP_REGISTER_LR0").ok().and_then(|v| v.parse().ok()).unwrap_or(0.05);
+ eprintln!("coachwhip: register on (GPU): {} layers x {experts} experts x {h}, lr {} / {}", self.layers, reg.lr, reg.lr0);
+ }
+ if let Some((l, x_hat, ids_t, w_t)) = reg.last.take() {
+ if l + 1 == layer {
+ let err = (xs - &x_hat)?;
+ let delta = w_t.broadcast_mul(&err)?.affine(reg.lr as f64, 0.0)?;
+ reg.d[l] = reg.d[l].index_add(&ids_t, &delta, 0)?;
+ reg.d0[l] = (&reg.d0[l] + err.squeeze(0)?.affine(reg.lr0 as f64, 0.0)?)?;
+ }
+ }
+ let ids_t = top_ids.flatten_all()?.contiguous()?;
+ let w_t = top_w.reshape((k, 1))?.to_dtype(DType::F32)?;
+ let adds = reg.d[layer].index_select(&ids_t, 0)?;
+ let x_hat = (xs.broadcast_add(&reg.d0[layer])? + w_t.broadcast_mul(&adds)?.sum_keepdim(0)?)?;
+ reg.last = Some((layer, x_hat.clone(), ids_t, w_t));
+ Ok(x_hat)
+ }
+
+ /// Chain one more layer on the GPU: route x̂ with `gate` (the next layer's router), then add
+ /// what those experts typically add. No read-back.
+ fn register_chain(&self, layer: usize, x_hat: &Tensor, gate: &Linear, k: usize) -> Result<Tensor> {
+ let guard = self.register.lock().unwrap();
+ let Some(reg) = guard.as_ref() else { return Ok(x_hat.clone()) };
+ if reg.d.is_empty() || layer >= reg.d.len() {
+ return Ok(x_hat.clone());
+ }
+ let scores = gate.forward(x_hat)?; // (1, e)
+ let top = scores.arg_sort_last_dim(false)?.narrow(D::Minus1, 0, k)?.contiguous()?; // (1, k)
+ let p = candle_nn::ops::softmax_last_dim(&scores.gather(&top, D::Minus1)?)?; // (1, k)
+ let adds = reg.d[layer].index_select(&top.flatten_all()?, 0)?; // (k, h)
+ Ok((x_hat.broadcast_add(&reg.d0[layer])? + p.reshape((k, 1))?.broadcast_mul(&adds)?.sum_keepdim(0)?)?)
+ }
+
+ /// Lab: how many experts beyond the top k the foresight peek fetches per layer
+ /// (`COACHWHIP_FORESIGHT_EXTRA`, default 0).
+ fn foresight_extra() -> usize {
+ static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+ *V.get_or_init(|| std::env::var("COACHWHIP_FORESIGHT_EXTRA").ok().and_then(|v| v.parse().ok()).unwrap_or(0))
+ }
+
/// Hand a layer's guessed experts to the prefetch threads.
fn request_prefetch(&self, layer: usize, predicted: Vec<u32>) {
if predicted.is_empty() {
return;
}
if let Some(tx) = self.prefetch_tx.lock().unwrap().as_ref() {
- let _ = tx.send((layer, self.word.load(Ordering::Acquire), predicted));
+ // A draft pass runs ahead of the real pass of the same word: its reads belong to that word.
+ let word = self.word.load(Ordering::Acquire) + if self.drafting() { 1 + self.foresee_step.load(Ordering::Acquire) } else { 0 };
+ let _ = tx.send((layer, word, predicted));
}
}
@@ -437,7 +790,7 @@ impl ExpertStore {
let missing: Vec<u32> = {
let banks = self.banks.lock().unwrap();
let present = banks.get(&layer);
- guess.iter().take(k).copied().filter(|e| present.map_or(true, |b| !b.slots.slot_of.contains_key(e))).collect()
+ guess.iter().take(k).copied().filter(|e| present.map_or(true, |b| !b.slots.slot_of.contains_key(e) && !b.sharp.as_ref().map_or(false, |sb| sb.slots.slot_of.contains_key(e)))).collect()
};
for pair in missing.chunks(2) {
self.request_prefetch(layer, pair.to_vec());
@@ -454,35 +807,190 @@ impl ExpertStore {
/// Prefetch thread: reserve free slots for the predicted experts, then read them in with the
/// bank unlocked, so the main thread is never held up by a read it did not ask for.
- fn prefetch(&self, layer: usize, predicted: &[u32]) -> Result<()> {
- let mut jobs: Vec<(u32, [(usize, usize); 3], Arc<AtomicBool>)> = Vec::new();
+ fn prefetch(&self, layer: usize, predicted_all: &[u32]) -> Result<()> {
+ // Two kinds: hot predictions go to the sharp bank, read plain.
+ let (hot, cold): (Vec<u32>, Vec<u32>) = predicted_all.iter().partition(|&&e| self.is_hot(layer, e));
+ if !hot.is_empty() {
+ let mut sjobs: Vec<(u32, usize, [(usize, usize); 3], Arc<AtomicBool>)> = Vec::new();
+ {
+ let mut banks = self.banks.lock().unwrap();
+ if let Some(bank) = banks.get_mut(&layer) {
+ if let Some(sb) = bank.sharp.as_mut() {
+ let ready = &sb.ready;
+ let reserved = sb.slots.reserve(&hot, |s| ready[s].load(Ordering::Acquire));
+ for &(_, slot) in &reserved {
+ ready[slot].store(false, Ordering::Release);
+ }
+ for (e, slot) in reserved {
+ let ptrs = [0, 1, 2].map(|i| (sb.mats[i].base + slot * sb.mats[i].bytes, sb.mats[i].bytes));
+ sjobs.push((e, slot, ptrs, ready[slot].clone()));
+ }
+ }
+ }
+ }
+ for (e, _slot, ptrs, ready) in sjobs {
+ for (i, s) in self.slices[layer][e as usize].iter().enumerate() {
+ let dst = unsafe { std::slice::from_raw_parts_mut(ptrs[i].0 as *mut u8, s.bytes) };
+ self.file.read_exact_at(dst, s.offset)?;
+ }
+ ready.store(true, Ordering::Release);
+ self.stats.lock().unwrap().prefetch_copies += 1;
+ }
+ }
+ let predicted: &[u32] = &cold;
+ if predicted.is_empty() {
+ return Ok(());
+ }
+ let mut jobs: Vec<(u32, usize, [(usize, usize); 3], Arc<AtomicBool>, Arc<crate::gpu_sync::GpuBank>)> = Vec::new();
{
let mut banks = self.banks.lock().unwrap();
let Some(bank) = banks.get_mut(&layer) else { return Ok(()) };
let ready = &bank.ready;
- for (e, slot) in bank.slots.reserve(predicted, |s| ready[s].load(Ordering::Acquire)) {
+ let pinned = &bank.pinned;
+ let reserved = bank.slots.reserve(predicted, |s| ready[s].load(Ordering::Acquire) && !pinned[s].load(Ordering::Acquire));
+ for &(_, slot) in &reserved {
ready[slot].store(false, Ordering::Release);
+ bank.gpu.set_ready(slot, false);
+ }
+ // The GPU's table follows the CPU's: evicted experts gone, new ones present but not ready.
+ bank.sync_table();
+ let gpu = bank.gpu.clone();
+ for (e, slot) in reserved {
let ptrs = [0, 1, 2].map(|i| (bank.mats[i].base + slot * bank.mats[i].bytes, bank.mats[i].bytes));
- jobs.push((e, ptrs, ready[slot].clone()));
+ jobs.push((e, slot, ptrs, ready[slot].clone(), gpu.clone()));
}
}
- for (e, ptrs, ready) in jobs {
+ if self.requant.is_some() {
+ let mats: [(Arc<QMetalStorage>, usize); 3] = {
+ let banks = self.banks.lock().unwrap();
+ let bank = &banks[&layer];
+ [0, 1, 2].map(|i| (bank.mats[i].storage.clone(), bank.mats[i].bytes))
+ };
+ for (e, slot, _ptrs, ready, gpu) in jobs {
+ self.shrink_into(layer, e, slot, &mats)?;
+ ready.store(true, Ordering::Release);
+ gpu.set_ready(slot, true);
+ self.stats.lock().unwrap().prefetch_copies += 1;
+ }
+ return Ok(());
+ }
+ for (e, slot, ptrs, ready, gpu) in jobs {
for (i, s) in self.slices[layer][e as usize].iter().enumerate() {
let dst = unsafe { std::slice::from_raw_parts_mut(ptrs[i].0 as *mut u8, s.bytes) };
- self.file.read_exact_at(dst, s.offset)?;
+ if staged() {
+ let mut tmp = vec![0u8; s.bytes];
+ self.file.read_exact_at(&mut tmp, s.offset)?;
+ dst.copy_from_slice(&tmp);
+ } else {
+ self.file.read_exact_at(dst, s.offset)?;
+ }
}
ready.store(true, Ordering::Release);
+ gpu.set_ready(slot, true);
self.stats.lock().unwrap().prefetch_copies += 1;
}
Ok(())
}
+ fn take_staging(&self, bytes: usize) -> Result<Arc<candle_metal_kernels::metal::Buffer>> {
+ if let Some(b) = self.staging.lock().unwrap().entry(bytes).or_default().pop() {
+ return Ok(b);
+ }
+ Ok(self.metal.new_buffer_builder().with_size(bytes).with_label("shrink_staging").build()?)
+ }
+
+ fn put_staging(&self, bytes: usize, b: Arc<candle_metal_kernels::metal::Buffer>) {
+ self.staging.lock().unwrap().entry(bytes).or_default().push(b);
+ }
+
+ /// Read one expert of `layer` from the file and shrink it on the GPU straight into `slot`
+ /// of the bank's three matrices (`mats`: storage and bytes per slot). Returns when the slot
+ /// holds the shrunk bytes.
+ fn shrink_into(&self, layer: usize, e: u32, slot: usize, mats: &[(Arc<QMetalStorage>, usize); 3]) -> Result<()> {
+ let Some(rq) = self.requant.as_ref() else { candle::bail!("shrink_into without the GPU shrink") };
+ for (i, sl) in self.slices[layer][e as usize].iter().enumerate() {
+ if i == 2 && !shrink_down() {
+ // The down matrix keeps the file's bytes: read it straight into its slot.
+ let dst = unsafe { std::slice::from_raw_parts_mut((mats[i].0.buffer().contents() as usize + slot * mats[i].1) as *mut u8, sl.bytes) };
+ self.file.read_exact_at(dst, sl.offset)?;
+ continue;
+ }
+ let Some(kind) = crate::requant::SrcKind::of(sl.dtype) else {
+ candle::bail!("the GPU shrink takes Q3_K, Q4_K or Q5_K experts, this file has {:?}", sl.dtype)
+ };
+ let staging = self.take_staging(sl.bytes)?;
+ let dst = unsafe { std::slice::from_raw_parts_mut(staging.contents() as *mut u8, sl.bytes) };
+ self.file.read_exact_at(dst, sl.offset)?;
+ let n_blocks = sl.dims.iter().product::<usize>() / crate::requant::QK_K;
+ let shape_buf = if shaped() {
+ let shapes = self.shape.lock().unwrap();
+ shapes.get(&layer).filter(|(_, _, n)| *n >= 32).map(|(xs, hs, _)| if i == 2 { hs.clone() } else { xs.clone() })
+ } else {
+ None
+ };
+ match shape_buf {
+ Some(sh) => rq.run_shaped(kind, &staging, 0, mats[i].0.buffer(), slot * mats[i].1, n_blocks, &sh, sl.dims[1], )?,
+ None => rq.run(kind, &staging, 0, mats[i].0.buffer(), slot * mats[i].1, n_blocks)?,
+ }
+ self.put_staging(sl.bytes, staging);
+ }
+ Ok(())
+ }
+
+ /// Fold one token's shape into `layer`'s running shape: x² over the hidden size, hidden² over
+ /// the intermediate size (averaged over the experts the token used). CPU side, ~20k floats.
+ fn note_shape(&self, layer: usize, xs: &Tensor, hidden: &Tensor) -> Result<()> {
+ let x: Vec<f32> = xs.flatten_all()?.to_dtype(DType::F32)?.to_vec1()?;
+ let h2: Vec<Vec<f32>> = hidden.to_dtype(DType::F32)?.to_vec2()?;
+ let inter = h2.first().map_or(0, |r| r.len());
+ let mut shapes = self.shape.lock().unwrap();
+ let entry = match shapes.get(&layer) {
+ Some(_) => shapes.get_mut(&layer).unwrap(),
+ None => {
+ let xb = self.metal.new_buffer_builder().with_size(x.len() * 4).with_label("shape_x").build()?;
+ let hb = self.metal.new_buffer_builder().with_size(inter * 4).with_label("shape_h").build()?;
+ unsafe {
+ std::ptr::write_bytes(xb.contents() as *mut u8, 0, x.len() * 4);
+ std::ptr::write_bytes(hb.contents() as *mut u8, 0, inter * 4);
+ }
+ shapes.insert(layer, (xb, hb, 0));
+ shapes.get_mut(&layer).unwrap()
+ }
+ };
+ let n = entry.2 as f32;
+ let a = 1.0 / (n + 1.0);
+ let xp = entry.0.contents() as *mut f32;
+ let hp = entry.1.contents() as *mut f32;
+ unsafe {
+ for (i, v) in x.iter().enumerate() {
+ let old = *xp.add(i);
+ *xp.add(i) = old + a * (v * v - old);
+ }
+ for (i, row) in h2.iter().enumerate() {
+ let w = 1.0 / h2.len() as f32;
+ for (j, v) in row.iter().enumerate() {
+ let old = *hp.add(j);
+ let target = v * v;
+ // average over the experts used this token, then fold into the running mean
+ *hp.add(j) = old + a * w * (target - old) * if i == 0 { 1.0 } else { 1.0 };
+ }
+ }
+ }
+ entry.2 += 1;
+ Ok(())
+ }
+
/// A layer's bank: three shared buffers, each `per_layer` expert slots of one matrix.
fn make_bank(&self, layer: usize) -> Result<Bank> {
let mut mats = Vec::with_capacity(3);
- for s in self.slices[layer][0].iter() {
+ for (i, s) in self.slices[layer][0].iter().enumerate() {
let elems: usize = s.dims.iter().product();
- let storage = QMetalStorage::zeros(&self.metal, elems * self.per_layer, s.dtype)?;
+ let (dtype, bytes) = if self.requant.is_some() && (i < 2 || shrink_down()) {
+ (GgmlDType::Q2K, elems / crate::requant::QK_K * crate::requant::Q2K_BLOCK_BYTES)
+ } else {
+ (s.dtype, s.bytes)
+ };
+ let storage = QMetalStorage::zeros(&self.metal, elems * self.per_layer, dtype)?;
let base = storage.buffer().contents() as usize;
if base == 0 {
candle::bail!("Metal gave a buffer the CPU cannot write to");
@@ -490,8 +998,8 @@ impl ExpertStore {
mats.push(BankMat {
storage: Arc::new(storage),
base,
- bytes: s.bytes,
- dtype: s.dtype,
+ bytes,
+ dtype,
n: s.dims[0],
k: s.dims[1],
});
@@ -502,10 +1010,34 @@ impl ExpertStore {
};
// `zeros` queues a GPU fill; let it run now, or it would wipe the experts written in afterwards.
self.device.synchronize()?;
+ let gpu = Arc::new(crate::gpu_sync::GpuBank::new(&self.metal, self.slices[layer].len(), self.per_layer, 8 * 16 + 32)?);
+ let sharp = if self.sharp_n > 0 {
+ let mut smats = Vec::with_capacity(3);
+ for s in self.slices[layer][0].iter() {
+ let elems: usize = s.dims.iter().product();
+ let storage = QMetalStorage::zeros(&self.metal, elems * self.sharp_n, s.dtype)?;
+ let base = storage.buffer().contents() as usize;
+ if base == 0 {
+ candle::bail!("Metal gave a buffer the CPU cannot write to");
+ }
+ smats.push(BankMat { storage: Arc::new(storage), base, bytes: s.bytes, dtype: s.dtype, n: s.dims[0], k: s.dims[1] });
+ }
+ let smats: [BankMat; 3] = match smats.try_into() {
+ Ok(m) => m,
+ Err(_) => candle::bail!("a bank has three matrices"),
+ };
+ self.device.synchronize()?;
+ Some(SharpBank { mats: smats, slots: Slots::new(self.sharp_n), ready: (0..self.sharp_n).map(|_| Arc::new(AtomicBool::new(true))).collect() })
+ } else {
+ None
+ };
Ok(Bank {
mats,
slots: Slots::new(self.per_layer),
+ sharp,
ready: (0..self.per_layer).map(|_| Arc::new(AtomicBool::new(true))).collect(),
+ gpu,
+ pinned: (0..self.per_layer).map(|_| AtomicBool::new(false)).collect(),
})
}
@@ -555,15 +1087,75 @@ impl ExpertStore {
/// Makes sure every needed expert of one layer sits in the bank; returns expert -> slot.
/// None when the bank is too small for this forward.
- fn ensure(&self, layer: usize, needed: &[u32]) -> Result<Option<HashMap<u32, usize>>> {
- if needed.len() > self.per_layer {
+ fn is_hot(&self, layer: usize, e: u32) -> bool {
+ self.sharp_n > 0 && self.hot[layer].contains(&e)
+ }
+
+ /// The sharp bank's half of a forward: give the hot experts sharp slots, read the missing
+ /// ones straight from the file (no shrink). Returns expert -> slot | SHARP_FLAG, or None when
+ /// the sharp bank cannot hold them (the caller then treats them as cold).
+ fn ensure_sharp(&self, layer: usize, bank: &mut Bank, hot: &[u32]) -> Result<Option<HashMap<u32, usize>>> {
+ let Some(sb) = bank.sharp.as_mut() else { return Ok(None) };
+ if hot.is_empty() {
+ return Ok(Some(HashMap::new()));
+ }
+ if hot.len() > self.sharp_n {
return Ok(None);
}
+ let ready = &sb.ready;
+ let Some(plan) = sb.slots.assign(hot, |s| ready[s].load(Ordering::Acquire)) else { return Ok(None) };
+ for &(_, slot) in &plan.hits {
+ while !sb.ready[slot].load(Ordering::Acquire) {
+ std::thread::yield_now();
+ }
+ }
+ self.stats.lock().unwrap().hits += plan.hits.len() as u64;
+ if !plan.misses.is_empty() {
+ let places: [(usize, usize); 3] = [0, 1, 2].map(|i| (sb.mats[i].base, sb.mats[i].bytes));
+ let reads: Vec<(usize, usize, u64)> = plan
+ .misses
+ .iter()
+ .flat_map(|&(e, slot)| self.slices[layer][e as usize].iter().enumerate().map(move |(i, s)| (places[i].0 + slot * places[i].1, s.bytes, s.offset)).collect::<Vec<_>>())
+ .collect();
+ let started = Instant::now();
+ reads.par_iter().try_for_each(|&(dst, len, offset)| {
+ let dst = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, len) };
+ self.file.read_exact_at(dst, offset)
+ })?;
+ let mut st = self.stats.lock().unwrap();
+ st.loads += plan.misses.len() as u64;
+ st.bytes_loaded += reads.iter().map(|r| r.1 as u64).sum::<u64>();
+ st.load_seconds += started.elapsed().as_secs_f64();
+ }
+ Ok(Some(hot.iter().map(|&e| (e, sb.slots.slot_of[&e] | SHARP_FLAG)).collect()))
+ }
+
+ fn ensure(&self, layer: usize, needed_all: &[u32]) -> Result<Option<HashMap<u32, usize>>> {
let mut banks = self.banks.lock().unwrap();
if !banks.contains_key(&layer) {
banks.insert(layer, self.make_bank(layer)?);
}
let bank = banks.get_mut(&layer).unwrap();
+ // Two kinds: the hot experts go to the sharp bank; what it cannot take is cold.
+ let (hot, mut cold): (Vec<u32>, Vec<u32>) = needed_all.iter().partition(|&&e| self.is_hot(layer, e));
+ let sharp_map = if self.sharp_n > 0 {
+ match self.ensure_sharp(layer, bank, &hot)? {
+ Some(m) => m,
+ None => {
+ cold.extend(hot.iter().copied());
+ HashMap::new()
+ }
+ }
+ } else {
+ HashMap::new()
+ };
+ let needed: &[u32] = &cold;
+ if needed.len() > self.per_layer {
+ return Ok(None);
+ }
+ if needed.is_empty() {
+ return Ok(Some(sharp_map));
+ }
// A slot still being filled by a prefetch cannot be taken; if too few are free for this
// layer's misses, read them fresh instead, before the bank is touched.
let ready = &bank.ready;
@@ -571,6 +1163,16 @@ impl ExpertStore {
self.stats.lock().unwrap().crowded += 1;
return Ok(None);
};
+ // S4: the GPU reads these slots later than now; keep the prefetch readers off them until
+ // this layer is placed again for the next word.
+ if self.s4.is_some() {
+ for p in &bank.pinned {
+ p.store(false, Ordering::Release);
+ }
+ for &(_, slot) in plan.hits.iter().chain(plan.misses.iter()) {
+ bank.pinned[slot].store(true, Ordering::Release);
+ }
+ }
// A prefetch may still be reading a hit in; wait for it rather than read it twice.
let mut waited = 0.0;
for &(_, slot) in &plan.hits {
@@ -589,7 +1191,20 @@ impl ExpertStore {
st.prefetch_wait_seconds += waited;
}
let misses = plan.misses;
- if !misses.is_empty() {
+ // The GPU's table follows: misses are placed but not ready until their bytes land.
+ for &(_, slot) in &misses {
+ bank.gpu.set_ready(slot, false);
+ }
+ bank.sync_table();
+ if !misses.is_empty() && self.requant.is_some() {
+ let mats: [(Arc<QMetalStorage>, usize); 3] = [0, 1, 2].map(|i| (bank.mats[i].storage.clone(), bank.mats[i].bytes));
+ let started = Instant::now();
+ misses.par_iter().try_for_each(|&(e, slot)| self.shrink_into(layer, e, slot, &mats))?;
+ let mut st = self.stats.lock().unwrap();
+ st.loads += misses.len() as u64;
+ st.bytes_loaded += misses.len() as u64 * self.slices[layer][0].iter().map(|s| s.bytes as u64).sum::<u64>();
+ st.load_seconds += started.elapsed().as_secs_f64();
+ } else if !misses.is_empty() {
// All of this layer's misses go to the SSD at once: it serves several requests in
// parallel far faster than one after another. Each matrix of each expert is one read.
let places: [(usize, usize); 3] = [0, 1, 2].map(|i| (bank.mats[i].base, bank.mats[i].bytes));
@@ -607,14 +1222,334 @@ impl ExpertStore {
reads.par_iter().try_for_each(|&(dst, len, offset)| {
// Each read fills its own slot of a shared buffer that no GPU work in flight uses.
let dst = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, len) };
- self.file.read_exact_at(dst, offset)
+ if staged() {
+ // Lab: read into ordinary memory first, then copy; the shared buffer may be
+ // slower to write straight from the file.
+ let mut tmp = vec![0u8; len];
+ self.file.read_exact_at(&mut tmp, offset)?;
+ dst.copy_from_slice(&tmp);
+ Ok(())
+ } else {
+ self.file.read_exact_at(dst, offset)
+ }
})?;
let mut st = self.stats.lock().unwrap();
st.loads += misses.len() as u64;
st.bytes_loaded += reads.iter().map(|r| r.1 as u64).sum::<u64>();
st.load_seconds += started.elapsed().as_secs_f64();
}
- Ok(Some(bank.slots.slot_of.clone()))
+ for &(_, slot) in &misses {
+ bank.gpu.set_ready(slot, true);
+ }
+ let mut map = bank.slots.slot_of.clone();
+ map.extend(sharp_map);
+ Ok(Some(map))
+ }
+
+ /// Like `ensure`, but hands the miss reads back instead of doing them, so the caller can
+ /// start the GPU on the hits first. Returns expert -> slot, the misses, and their reads
+ /// (destination, length, file offset); None when the bank is too small or crowded.
+ fn ensure_split(&self, layer: usize, needed: &[u32]) -> Result<Option<(HashMap<u32, usize>, Vec<(u32, usize)>, Vec<(usize, usize, u64)>)>> {
+ if needed.len() > self.per_layer {
+ return Ok(None);
+ }
+ let mut banks = self.banks.lock().unwrap();
+ if !banks.contains_key(&layer) {
+ banks.insert(layer, self.make_bank(layer)?);
+ }
+ let bank = banks.get_mut(&layer).unwrap();
+ let ready = &bank.ready;
+ let Some(plan) = bank.slots.assign(needed, |s| ready[s].load(Ordering::Acquire)) else {
+ self.stats.lock().unwrap().crowded += 1;
+ return Ok(None);
+ };
+ let mut waited = 0.0;
+ for &(_, slot) in &plan.hits {
+ if !bank.ready[slot].load(Ordering::Acquire) {
+ let wait = Instant::now();
+ while !bank.ready[slot].load(Ordering::Acquire) {
+ std::thread::yield_now();
+ }
+ waited += wait.elapsed().as_secs_f64();
+ }
+ }
+ {
+ let mut st = self.stats.lock().unwrap();
+ st.hits += plan.hits.len() as u64;
+ st.prefetch_hits += plan.prefetch_hits;
+ st.prefetch_wait_seconds += waited;
+ }
+ let misses = plan.misses;
+ for &(_, slot) in &misses {
+ bank.gpu.set_ready(slot, false);
+ // The prefetchers must not take a slot whose bytes are still to come.
+ bank.ready[slot].store(false, Ordering::Release);
+ }
+ bank.sync_table();
+ let places: [(usize, usize); 3] = [0, 1, 2].map(|i| (bank.mats[i].base, bank.mats[i].bytes));
+ let reads: Vec<(usize, usize, u64)> = misses
+ .iter()
+ .flat_map(|&(e, slot)| {
+ self.slices[layer][e as usize]
+ .iter()
+ .enumerate()
+ .map(move |(i, s)| (places[i].0 + slot * places[i].1, s.bytes, s.offset))
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ Ok(Some((bank.slots.slot_of.clone(), misses, reads)))
+ }
+
+ /// The second half of `ensure_split`: read the misses in, then mark their slots ready.
+ fn read_misses(&self, layer: usize, misses: &[(u32, usize)], reads: &[(usize, usize, u64)]) -> Result<()> {
+ if misses.is_empty() {
+ return Ok(());
+ }
+ let started = Instant::now();
+ reads.par_iter().try_for_each(|&(dst, len, offset)| {
+ let dst = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, len) };
+ self.file.read_exact_at(dst, offset)
+ })?;
+ {
+ let mut st = self.stats.lock().unwrap();
+ st.loads += misses.len() as u64;
+ st.bytes_loaded += reads.iter().map(|r| r.1 as u64).sum::<u64>();
+ st.load_seconds += started.elapsed().as_secs_f64();
+ }
+ let banks = self.banks.lock().unwrap();
+ if let Some(bank) = banks.get(&layer) {
+ for &(_, slot) in misses {
+ bank.ready[slot].store(true, Ordering::Release);
+ bank.gpu.set_ready(slot, true);
+ }
+ }
+ Ok(())
+ }
+
+ /// S4: the GPU's view of `layer`'s bank, making the bank if the layer has none yet.
+ fn gpu_bank(&self, layer: usize) -> Result<Arc<crate::gpu_sync::GpuBank>> {
+ let mut banks = self.banks.lock().unwrap();
+ if !banks.contains_key(&layer) {
+ banks.insert(layer, self.make_bank(layer)?);
+ }
+ Ok(banks[&layer].gpu.clone())
+ }
+
+ /// S4: every layer's bank must exist before a word starts, so none is made mid-word while the
+ /// GPU queue is waiting on the service thread. Called at layer 0; cheap once they exist.
+ fn ensure_all_banks(&self) -> Result<()> {
+ let mut banks = self.banks.lock().unwrap();
+ if banks.len() >= self.layers {
+ return Ok(());
+ }
+ for layer in 0..self.layers {
+ if !banks.contains_key(&layer) {
+ let bank = self.make_bank(layer)?;
+ banks.insert(layer, bank);
+ }
+ }
+ Ok(())
+ }
+
+ /// S4 service: wait for the GPU to publish a layer's picks, place and read its experts, hand
+ /// the early guess to the readers, then let the GPU go on. Never touches the GPU queue.
+ fn s4_service(&self, job: S4Job) {
+ let Some(s4) = &self.s4 else { return };
+ let dbg = std::env::var("COACHWHIP_S4_DEBUG").is_ok();
+ let Ok(gpu) = self.gpu_bank(job.layer) else { return };
+ let started = Instant::now();
+ if dbg {
+ eprintln!("s4: job layer {} seq {} received", job.layer, job.seq);
+ }
+ let mut picks: Option<Vec<u32>> = None;
+ while picks.is_none() {
+ let flag = gpu.flag();
+ if flag != 0 {
+ picks = gpu.picks_checked(job.n_ids + job.n_guess, flag);
+ }
+ if picks.is_none() && started.elapsed().as_secs() > 15 {
+ eprintln!("coachwhip: parallel: layer {} never published its picks; releasing the GPU", job.layer);
+ break;
+ }
+ std::hint::spin_loop();
+ }
+ if let Some(picks) = picks {
+ if dbg {
+ eprintln!("s4: layer {} flag seen after {:.1} ms", job.layer, started.elapsed().as_secs_f64() * 1e3);
+ }
+ self.reached(job.layer);
+ let ids = vec![picks[..job.n_ids].to_vec()];
+ self.learn(job.layer, &ids);
+ let mut needed: Vec<u32> = ids[0].clone();
+ needed.sort_unstable();
+ needed.dedup();
+ let placed = Instant::now();
+ loop {
+ match self.ensure(job.layer, &needed) {
+ Ok(Some(_)) => break,
+ Ok(None) => {
+ if placed.elapsed().as_secs() > 15 {
+ eprintln!("coachwhip: parallel: layer {} found no free slots; releasing the GPU", job.layer);
+ break;
+ }
+ std::thread::yield_now();
+ }
+ Err(e) => {
+ eprintln!("coachwhip: parallel: layer {}: {e}", job.layer);
+ break;
+ }
+ }
+ }
+ if dbg {
+ // Every needed expert must sit ready in a slot the GPU's table knows about.
+ let banks = self.banks.lock().unwrap();
+ if let Some(bank) = banks.get(&job.layer) {
+ for e in &needed {
+ match bank.slots.slot_of.get(e) {
+ Some(&slot) if bank.ready[slot].load(Ordering::Acquire) => {}
+ Some(&slot) => eprintln!("s4: MISSING layer {} expert {e}: slot {slot} not ready", job.layer),
+ None => eprintln!("s4: MISSING layer {} expert {e}: no slot", job.layer),
+ }
+ }
+ }
+ }
+ if job.n_guess > 0 && job.layer + job.ahead < self.layers {
+ self.prefetch_guess(job.layer + job.ahead, &picks[job.n_ids..], job.prefetch_k);
+ }
+ let mut st = self.stats.lock().unwrap();
+ st.load_phase_seconds += started.elapsed().as_secs_f64();
+ }
+ s4.event.signal(job.seq);
+ if dbg {
+ eprintln!("s4: layer {} signalled seq {} after {:.1} ms", job.layer, job.seq, started.elapsed().as_secs_f64() * 1e3);
+ }
+ if job.layer + 1 == self.layers {
+ let missing: u32 = (0..self.layers).filter_map(|l| self.banks.lock().unwrap().get(&l).map(|b| b.gpu.missing())).sum();
+ if missing > 0 {
+ eprintln!("coachwhip: parallel: {missing} expert picks so far had no slot when the GPU looked them up");
+ }
+ }
+ }
+
+ /// S6 measurement bookkeeping: one draft of `k` words, `accepted` of them matched the plain path.
+ pub fn note_speculation(&self, k: usize, accepted: usize) {
+ let mut st = self.stats.lock().unwrap();
+ st.spec_passes += 1;
+ st.spec_drafted += k as u64;
+ st.spec_accepted += accepted as u64;
+ }
+
+ /// S6 draft mode: route only among experts already in the bank, read nothing, learn nothing.
+ pub fn set_draft(&self, on: bool) {
+ self.draft.store(on, Ordering::Release);
+ }
+
+ pub fn drafting(&self) -> bool {
+ self.draft.load(Ordering::Acquire)
+ }
+
+ /// Foresight (`COACHWHIP_FORESIGHT=1`): during the draft pass, each layer's unrestricted route
+ /// is handed to the readers a whole word before the real pass asks for it.
+ pub fn set_foresee(&self, on: bool, step: u64) {
+ self.foresee.store(on, Ordering::Release);
+ self.foresee_step.store(step, Ordering::Release);
+ }
+
+ pub fn foreseeing(&self) -> bool {
+ self.foresee.load(Ordering::Acquire)
+ }
+
+ /// The bank's map for the GPU: a mask that shuts out every expert not sitting ready in a slot
+ /// (0 / -1e30, one per expert) and the slot each expert sits in (u32, one per expert).
+ fn peek_tables(&self, layer: usize, top_k: usize, device: &Device) -> Result<(Tensor, Tensor)> {
+ let (mask, table) = {
+ let banks = self.banks.lock().unwrap();
+ let Some(bank) = banks.get(&layer) else { candle::bail!("draft: layer {layer} has no bank yet") };
+ let experts = self.slices[layer].len();
+ let mut mask = vec![-1e30f32; experts];
+ let mut table = vec![0u32; experts];
+ let mut ready = 0;
+ for (&e, &s) in bank.slots.slot_of.iter() {
+ if bank.ready[s].load(Ordering::Acquire) {
+ mask[e as usize] = 0.0;
+ table[e as usize] = s as u32;
+ ready += 1;
+ }
+ }
+ if ready < top_k {
+ candle::bail!("draft: layer {layer} holds only {ready} ready experts")
+ }
+ (mask, table)
+ };
+ let n = mask.len();
+ Ok((Tensor::from_vec(mask, n, device)?, Tensor::from_vec(table, n, device)?))
+ }
+
+ /// A layer's foresight list, kept on the GPU until `flush_foresight`.
+ fn keep_foresight(&self, layer: usize, list: Tensor) {
+ self.foresight_lists.lock().unwrap().push((layer, list));
+ }
+
+ /// After a peek pass: read every layer's foresight list back (one wait) and start the reads.
+ pub fn flush_foresight(&self, top_k: usize) -> Result<()> {
+ let lists: Vec<(usize, Tensor)> = std::mem::take(&mut *self.foresight_lists.lock().unwrap());
+ for (layer, list) in lists {
+ let ids: Vec<u32> = list.to_vec1()?;
+ self.prefetch_guess(layer, &ids, top_k + ExpertStore::foresight_extra());
+ }
+ Ok(())
+ }
+
+ /// The experts of `layer` sitting in a ready slot right now, expert -> slot; None before the
+ /// layer has a bank at all.
+ pub fn resident_ready(&self, layer: usize) -> Option<HashMap<u32, usize>> {
+ let banks = self.banks.lock().unwrap();
+ let bank = banks.get(&layer)?;
+ Some(bank.slots.slot_of.iter().filter(|(_, &s)| bank.ready[s].load(Ordering::Acquire)).map(|(&e, &s)| (e, s)).collect())
+ }
+
+ /// The toaster (`COACHWHIP_TOASTER=1`): after a layer has computed, its experts' slots become
+ /// the first to be evicted.
+ fn pop_used(&self, layer: usize, used: &[u32]) {
+ if let Some(bank) = self.banks.lock().unwrap().get_mut(&layer) {
+ bank.slots.pop(used);
+ }
+ }
+
+ /// The experts of `layer` in the bank right now, before this layer's loads.
+ fn resident(&self, layer: usize) -> Vec<u32> {
+ let banks = self.banks.lock().unwrap();
+ banks.get(&layer).map(|b| b.slots.slot_of.keys().copied().collect()).unwrap_or_default()
+ }
+
+ /// S6 measurement: compare the real route with the route a draft confined to the bank would
+ /// take, and keep the score.
+ fn measure_draft(&self, layer: usize, scores: &[f32], real: &[u32], top_k: usize) {
+ let mut resident = self.resident(layer);
+ resident.sort_by(|a, b| scores[*b as usize].partial_cmp(&scores[*a as usize]).unwrap_or(std::cmp::Ordering::Equal));
+ let draft: Vec<u32> = resident.into_iter().take(top_k).collect();
+ let agree = real.iter().filter(|e| draft.contains(e)).count();
+ let mut st = self.stats.lock().unwrap();
+ if layer == 0 {
+ st.draft_word_ok = true;
+ }
+ st.draft_layers += 1;
+ st.draft_agree += agree as f64 / top_k as f64;
+ if agree == top_k {
+ st.draft_layers_full += 1;
+ } else {
+ st.draft_word_ok = false;
+ }
+ if layer + 1 == self.slices.len() && st.draft_word_ok {
+ st.draft_words_full += 1;
+ }
+ }
+
+ /// One `mul_mv_id` dispatch over the sharp bank's matrix.
+ fn bank_op_sharp(&self, layer: usize, which: usize, nei0: usize, rows_per_expert: bool) -> MoeMatvec {
+ let banks = self.banks.lock().unwrap();
+ let m = &banks[&layer].sharp.as_ref().expect("a sharp bank").mats[which];
+ MoeMatvec { bank: m.storage.clone(), dtype: m.dtype, n: m.n, k: m.k, slots: self.sharp_n, bytes: m.bytes, nei0, rows_per_expert }
}
/// One `mul_mv_id` dispatch over a bank matrix.
@@ -635,6 +1570,25 @@ impl ExpertStore {
/// Learn from one layer's picks: add the step from the layer before to the route table at once,
/// and keep the line for the log.
+ /// Lab: append one record (layer, the MoE input, the router's scores) to the dump file.
+ fn dump_record(&self, layer: usize, xs: &[f32], scores: &[f32]) {
+ use std::io::Write;
+ let mut d = self.dump.lock().unwrap();
+ if let Some(f) = d.as_mut() {
+ let mut buf = Vec::with_capacity(4 + 4 * (xs.len() + scores.len()));
+ buf.extend_from_slice(&(layer as u32).to_le_bytes());
+ for v in xs.iter().chain(scores.iter()) {
+ buf.extend_from_slice(&v.to_le_bytes());
+ }
+ let _ = f.write_all(&buf);
+ }
+ }
+
+ /// The words a forward pass is about to route, so the log's T line can name them.
+ pub fn note_tokens(&self, tokens: Vec<u32>) {
+ self.trail.lock().unwrap().tokens = tokens;
+ }
+
fn learn(&self, layer: usize, ids: &[Vec<u32>]) {
let mut trail = self.trail.lock().unwrap();
if layer == 0 {
@@ -647,7 +1601,11 @@ impl ExpertStore {
let line = ids.iter().map(|t| t.iter().map(|e| e.to_string()).collect::<Vec<_>>().join(" ")).collect::<Vec<_>>().join(",");
trail.lines.push(line);
if layer + 1 == self.layers {
- let block = format!("T -\n{}\n", trail.lines.join("\n"));
+ let words = if trail.tokens.is_empty() { "-".to_string() } else { trail.tokens.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" ") };
+ let block = format!("T {words}
+{}
+", trail.lines.join("
+"));
trail.blocks.push(block);
trail.lines.clear();
} else {
@@ -708,8 +1666,45 @@ impl ExpertStore {
s.fresh, s.fresh_read_seconds, s.fresh_build_seconds
);
}
+ if s.spec_passes > 0 {
+ eprintln!(
+ "coachwhip S6: {} drafts of {} words: {} of {} drafted words accepted ({:.1}%), {:.2} accepted per draft",
+ s.spec_passes,
+ s.spec_drafted / s.spec_passes,
+ s.spec_accepted,
+ s.spec_drafted,
+ 100.0 * s.spec_accepted as f64 / s.spec_drafted.max(1) as f64,
+ s.spec_accepted as f64 / s.spec_passes as f64
+ );
+ }
+ if profiling() && s.draft_layers > 0 {
+ eprintln!(
+ "coachwhip S6: bank-only route agrees with the real route on {:.1}% of experts; {:.1}% of layers fully; {} of {} words fully",
+ 100.0 * s.draft_agree / s.draft_layers as f64,
+ 100.0 * s.draft_layers_full as f64 / s.draft_layers as f64,
+ s.draft_words_full,
+ s.words
+ );
+ }
+ if profiling() && s.reg_steps > 0 {
+ let n = s.reg_steps as f64;
+ eprintln!(
+ "coachwhip register: predicted state is {:.1}% off the truth on average (carrying the input unchanged: {:.1}% off); by layer:",
+ 100.0 * s.reg_err / n,
+ 100.0 * s.reg_err_plain / n
+ );
+ let per = n / s.reg_err_by_layer.len().max(1) as f64;
+ let line: Vec<String> = s.reg_err_by_layer.iter().zip(s.reg_plain_by_layer.iter()).enumerate().filter(|(l, _)| *l > 0).map(|(l, (e, p))| format!("{l}:{:.0}/{:.0}", 100.0 * e / per, 100.0 * p / per)).collect();
+ eprintln!("coachwhip register by layer (register/plain, % off): {}", line.join(" "));
+ }
if profiling() && s.words > 2 {
let words = (s.words - 1) as f64;
+ eprintln!(
+ "coachwhip cpu split per word: readback {:.1} ms, placing {:.1} ms, bookkeeping {:.1} ms (the rest of router+loads is the reads and the encode)",
+ 1000.0 * s.t_readback / words,
+ 1000.0 * s.t_place / words,
+ 1000.0 * s.t_books / words
+ );
eprintln!(
"coachwhip profile: {} written words after the first, {:.1} ms per word in total, {:.1} ms in the expert layers: router+loads {:.1} (of which file reads {:.1}), expert maths {:.1}",
s.words - 1,
@@ -795,6 +1790,15 @@ impl CustomOp2 for MoeMatvec {
}
}
+/// Router scores with every expert not `allowed` pushed far below the rest, so `route` picks
+/// only among the allowed ones (S6 draft: the experts already in the bank).
+pub fn restrict(logits: &Tensor, allowed: impl Fn(u32) -> bool) -> Result<Tensor> {
+ let n = logits.dim(D::Minus1)?;
+ let mask: Vec<f32> = (0..n as u32).map(|e| if allowed(e) { 0.0 } else { -1e30 }).collect();
+ let mask = Tensor::from_vec(mask, n, logits.device())?.to_dtype(logits.dtype())?;
+ logits.broadcast_add(&mask)
+}
+
/// The router's choice for each token: the `top_k` likeliest experts from the router's scores,
/// best first, and their weights, rescaled to sum to 1 when `norm`.
pub fn route(logits: &Tensor, top_k: usize, norm: bool) -> Result<(Tensor, Tensor)> {
@@ -814,6 +1818,8 @@ pub struct StreamedMoe {
/// A later layer's router (`ahead` layers on), run early on this layer's input to guess
/// that layer's experts while there is still time to read them in.
pub next_gate: Option<Linear>,
+ /// The very next layer's router, for the register to chain through when `ahead` is 2.
+ pub gate1: Option<Linear>,
pub ahead: usize,
pub store: Arc<ExpertStore>,
pub top_k: usize,
@@ -861,8 +1867,8 @@ impl StreamedMoe {
pub fn forward(&self, xs: &Tensor) -> Result<Tensor> {
let (b, s, h) = xs.dims3()?;
- let prof = profiling() && b * s == 1;
- if prof && self.layer == 0 {
+ let prof = profiling() && b * s == 1 && self.store.s4.is_none();
+ if prof && self.layer == 0 && !self.store.drafting() {
self.store.device.synchronize()?;
let mut st = self.store.stats.lock().unwrap();
if let Some(t) = st.word_started {
@@ -876,29 +1882,184 @@ impl StreamedMoe {
let started = Instant::now();
let dtype = xs.dtype();
let n = b * s;
- if n == 1 {
+ if n == 1 && !self.store.drafting() && self.store.s4.is_none() {
self.store.reached(self.layer);
}
let xs = xs.reshape((n, h))?.to_dtype(DType::F32)?.contiguous()?;
- let (top_ids, top_w) = route(&self.gate.forward(&xs)?, self.top_k, self.norm_topk_prob)?;
+ // S6 draft: the bank as it stands is the whole model for this word. No reads, no learning,
+ // no prefetch, no bookkeeping; the LRU order is left alone too.
+ if self.store.drafting() {
+ if n != 1 {
+ candle::bail!("draft: one word at a time")
+ }
+ // No round trip to the CPU: the bank's map goes up to the GPU as two small tensors, the
+ // GPU picks among the resident experts and looks their slots up itself. The foresight
+ // list (the unrestricted route) is kept on the GPU and read back once, after the pass.
+ let device = xs.device();
+ let logits = self.gate.forward(&xs)?;
+ let (mask, table) = self.store.peek_tables(self.layer, self.top_k, device)?;
+ if self.store.foreseeing() {
+ let want = (self.top_k + ExpertStore::foresight_extra()).min(logits.dim(D::Minus1)?);
+ let list = logits.arg_sort_last_dim(false)?.narrow(D::Minus1, 0, want)?.flatten_all()?.contiguous()?;
+ self.store.keep_foresight(self.layer, list);
+ }
+ let (top_ids, top_w) = route(&logits.broadcast_add(&mask)?, self.top_k, self.norm_topk_prob)?;
+ let slots = table.gather(&top_ids.flatten_all()?, 0)?.reshape((n, self.top_k))?;
+ let gate = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 0, self.top_k, false))?;
+ let up = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 1, self.top_k, false))?;
+ let inter = gate.dim(2)?;
+ let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((n * self.top_k, inter))?;
+ let down = hidden.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 2, self.top_k, true))?;
+ let out = down.broadcast_mul(&top_w.unsqueeze(2)?)?.sum(1)?;
+ return out.reshape((b, s, h))?.to_dtype(dtype);
+ }
+
+ let logits = self.gate.forward(&xs)?;
+ let (top_ids, top_w) = route(&logits, self.top_k, self.norm_topk_prob)?;
+
+ // S4, the parallel path: nothing here waits for the GPU. The picks stay on the GPU; a tiny
+ // kernel publishes them for the service thread, the maths is queued behind a wait on the
+ // shared event, and a second kernel looks the slots up once the service thread has placed
+ // the experts and signalled. The CPU moves straight on to the next layer.
+ if n == 1 && self.store.s4.is_some() {
+ let s4 = self.store.s4.as_ref().unwrap();
+ if self.layer == 0 {
+ self.store.ensure_all_banks()?;
+ }
+ let device = xs.device();
+ let (guess, n_guess) = match &self.next_gate {
+ Some(g) if self.prefetch_k > 0 => {
+ // With the register on, guess from the state it predicts, all on the GPU.
+ let x_in = if self.store.register_on() {
+ let mut x_hat = self.store.register_step_gpu(self.layer, &xs, &top_ids, &top_w)?;
+ if self.ahead >= 2 {
+ if let Some(g1) = &self.gate1 {
+ x_hat = self.store.register_chain(self.layer + 1, &x_hat, g1, self.top_k)?;
+ }
+ }
+ x_hat
+ } else {
+ xs.clone()
+ };
+ let scores = g.forward(&x_in)?;
+ let n_guess = 32.min(scores.dim(D::Minus1)?);
+ (scores.arg_sort_last_dim(false)?.narrow(D::Minus1, 0, n_guess)?.flatten_all()?.contiguous()?, n_guess)
+ }
+ _ => (Tensor::zeros(1, DType::U32, device)?, 0),
+ };
+ // Metal's rule: a command buffer must be committed after the CPU writes the data it
+ // reads. The buffer holding the layer before's maths is committed by this layer's flush,
+ // so wait here until the service thread has placed and written that layer's experts.
+ // The GPU keeps its queue; only the CPU's run-ahead is capped at one layer.
+ let last = s4.seq.load(Ordering::Acquire);
+ let held = Instant::now();
+ while s4.event.value() < last {
+ if held.elapsed().as_secs() > 20 {
+ candle::bail!("parallel: layer {} waited too long for the layer before", self.layer)
+ }
+ std::hint::spin_loop();
+ }
+ let gpu = self.store.gpu_bank(self.layer)?;
+ gpu.reset_flag();
+ if std::env::var("COACHWHIP_S4_DEBUG").is_ok() {
+ eprintln!("s4: encode layer {}", self.layer);
+ }
+ let publish = crate::gpu_sync::Publish { bank: gpu.clone(), pipeline: s4.pipes.publish.clone(), n_guess };
+ let _published = top_ids.apply_op2_no_bwd(&guess, &publish)?;
+ crate::gpu_sync::flush()?;
+ let seq = s4.seq.fetch_add(1, Ordering::AcqRel) + 1;
+ s4.event.gpu_wait(seq)?;
+ let resolve = crate::gpu_sync::Resolve { bank: gpu.clone(), pipeline: s4.pipes.resolve.clone() };
+ let slots = top_ids.apply_op1_no_bwd(&resolve)?;
+ let gate = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 0, self.top_k, false))?;
+ let up = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 1, self.top_k, false))?;
+ let inter = gate.dim(2)?;
+ let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((n * self.top_k, inter))?;
+ let down = hidden.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 2, self.top_k, true))?;
+ let out = down.broadcast_mul(&top_w.unsqueeze(2)?)?.sum(1)?;
+ if let Some(tx) = s4.tx.lock().unwrap().as_ref() {
+ let _ = tx.send(S4Job { layer: self.layer, seq, n_ids: self.top_k, n_guess, prefetch_k: self.prefetch_k, ahead: self.ahead });
+ }
+ return out.reshape((b, s, h))?.to_dtype(dtype);
+ }
+ // S6 measurement (profile mode, one word at a time): what a bank-only draft would pick.
+ let draft_scores: Option<Vec<f32>> = if prof { Some(logits.flatten_all()?.to_dtype(DType::F32)?.to_vec1()?) } else { None };
+ if n == 1 && self.store.dump.lock().unwrap().is_some() {
+ let x: Vec<f32> = xs.flatten_all()?.to_vec1()?;
+ let s: Vec<f32> = logits.flatten_all()?.to_dtype(DType::F32)?.to_vec1()?;
+ self.store.dump_record(self.layer, &x, &s);
+ }
// The guess for a later layer is queued before the read-back below, so it costs no wait.
+ let register = n == 1 && self.store.register_on();
let early = match &self.next_gate {
- Some(g) if n == 1 && self.prefetch_k > 0 => Some(g.forward(&xs)?),
+ Some(g) if n == 1 && self.prefetch_k > 0 && !register => Some(g.forward(&xs)?),
_ => None,
};
// Reading the picks back waits for the GPU to finish everything queued so far, so no
// kernel is still reading a bank slot when `ensure` and the prefetchers overwrite it.
// Keep this wait if this code ever changes.
+ let t_rb = Instant::now();
let ids: Vec<Vec<u32>> = top_ids.to_vec2()?;
+ let t_rb = t_rb.elapsed().as_secs_f64();
+ let t_bk = Instant::now();
+ if let Some(scores) = &draft_scores {
+ self.store.measure_draft(self.layer, scores, &ids[0], self.top_k);
+ }
self.store.learn(self.layer, &ids);
let mut needed: Vec<u32> = ids.iter().flatten().copied().collect();
needed.sort_unstable();
needed.dedup();
- let slot_of = self.store.ensure(self.layer, &needed)?;
+ let books_a = t_bk.elapsed().as_secs_f64();
+ let loads_before = if prof { self.store.stats.lock().unwrap().load_seconds } else { 0.0 };
+ let t_pl = Instant::now();
+ // Split path: assign now, read the misses after the hits' maths has been queued.
+ let split = n == 1 && split_maths();
+ let mut pending: Option<(Vec<(u32, usize)>, Vec<(usize, usize, u64)>)> = None;
+ let slot_of = if split {
+ match self.store.ensure_split(self.layer, &needed)? {
+ Some((slot_of, misses, reads)) => {
+ pending = Some((misses, reads));
+ Some(slot_of)
+ }
+ None => None,
+ }
+ } else {
+ self.store.ensure(self.layer, &needed)?
+ };
+ let t_pl = t_pl.elapsed().as_secs_f64();
+ let loads_in = if prof { self.store.stats.lock().unwrap().load_seconds - loads_before } else { 0.0 };
+ let t_bk2 = Instant::now();
+ // Our register: predict the state this layer hands on, chain to the layer before the
+ // target if need be, and run the target layer's router on the predicted state.
+ let early = match (&self.next_gate, register) {
+ (Some(g), true) if self.prefetch_k > 0 => {
+ let mut x_hat = self.store.register_step(self.layer, &xs, &ids[0], &top_w)?;
+ if self.ahead >= 2 {
+ if let Some(g1) = &self.gate1 {
+ x_hat = self.store.register_chain(self.layer + 1, &x_hat, g1, self.top_k)?;
+ }
+ }
+ Some(g.forward(&x_hat)?)
+ }
+ _ => early,
+ };
if let Some(logits) = early {
let scores: Vec<f32> = logits.flatten_all()?.to_dtype(DType::F32)?.to_vec1()?;
- self.store.prefetch_guess(self.layer + self.ahead, &rank(&scores), self.prefetch_k);
+ if let Some(p_min) = q_rule() {
+ // The probability rule: a candidate is read iff its router probability, calibrated
+ // on the route dumps, says it is more likely needed than its bytes cost. On the
+ // 122B that line sits at a router probability of about 1%.
+ let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
+ let ex: Vec<f32> = scores.iter().map(|&z| (z - m).exp()).collect();
+ let sum: f32 = ex.iter().sum();
+ let ranked = rank(&scores);
+ let cands: Vec<u32> = ranked.iter().copied().take_while(|&e| ex[e as usize] / sum >= p_min).take(q_cap()).collect();
+ let k = cands.len().max(1);
+ self.store.prefetch_guess(self.layer + self.ahead, &cands, k);
+ } else {
+ self.store.prefetch_guess(self.layer + self.ahead, &rank(&scores), self.prefetch_k);
+ }
} else if n == 1 && self.prefetch_k > 0 {
for ahead in 1..=self.store.ahead {
if self.layer + ahead < self.store.slices.len() {
@@ -907,17 +2068,81 @@ impl StreamedMoe {
}
}
}
+ let books_b = t_bk2.elapsed().as_secs_f64();
if prof {
self.store.device.synchronize()?;
let mut st = self.store.stats.lock().unwrap();
if st.words > 1 {
st.load_phase_seconds += started.elapsed().as_secs_f64();
+ st.t_readback += t_rb;
+ st.t_place += (t_pl - loads_in).max(0.0);
+ st.t_books += books_a + books_b;
}
}
let maths_started = Instant::now();
let device = xs.device();
- let out = if let Some(slot_of) = slot_of {
+ let out = if let (Some(slot_of), Some((misses, reads))) = (&slot_of, pending.take()) {
+ // The resident experts first, queued and flushed so the GPU works while the CPU reads.
+ let miss_set: HashSet<u32> = misses.iter().map(|&(e, _)| e).collect();
+ let row = &ids[0];
+ let part = |positions: &[usize]| -> Result<Option<Tensor>> {
+ if positions.is_empty() {
+ return Ok(None);
+ }
+ let k = positions.len();
+ let slots: Vec<u32> = positions.iter().map(|&p| slot_of[&row[p]] as u32).collect();
+ let slots = Tensor::from_vec(slots, (1, k), device)?;
+ let idx = Tensor::new(positions.iter().map(|&p| p as u32).collect::<Vec<_>>(), device)?;
+ let w = top_w.index_select(&idx, 1)?; // (1, k)
+ let gate = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 0, k, false))?;
+ let up = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 1, k, false))?;
+ let inter = gate.dim(2)?;
+ let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((k, inter))?;
+ let down = hidden.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 2, k, true))?;
+ Ok(Some(down.broadcast_mul(&w.unsqueeze(2)?)?.sum(1)?))
+ };
+ let hit_pos: Vec<usize> = (0..row.len()).filter(|&p| !miss_set.contains(&row[p])).collect();
+ let miss_pos: Vec<usize> = (0..row.len()).filter(|&p| miss_set.contains(&row[p])).collect();
+ let hits_out = part(&hit_pos)?;
+ if hits_out.is_some() && !misses.is_empty() {
+ crate::gpu_sync::flush()?;
+ }
+ self.store.read_misses(self.layer, &misses, &reads)?;
+ let miss_out = part(&miss_pos)?;
+ match (hits_out, miss_out) {
+ (Some(a), Some(b)) => (a + b)?,
+ (Some(a), None) | (None, Some(a)) => a,
+ (None, None) => xs.zeros_like()?,
+ }
+ } else if let (Some(slot_of), true) = (&slot_of, n == 1 && self.store.sharp_n > 0) {
+ // Two kinds of slot: the sharp experts and the small ones each get their dispatches; the sums add.
+ let row = &ids[0];
+ let part = |positions: &[usize], sharp: bool| -> Result<Option<Tensor>> {
+ if positions.is_empty() {
+ return Ok(None);
+ }
+ let k = positions.len();
+ let slots: Vec<u32> = positions.iter().map(|&p| (slot_of[&row[p]] & !SHARP_FLAG) as u32).collect();
+ let slots = Tensor::from_vec(slots, (1, k), device)?;
+ let idx = Tensor::new(positions.iter().map(|&p| p as u32).collect::<Vec<_>>(), device)?;
+ let w = top_w.index_select(&idx, 1)?;
+ let op = |which: usize, nei0: usize, rpe: bool| if sharp { self.store.bank_op_sharp(self.layer, which, nei0, rpe) } else { self.store.bank_op(self.layer, which, nei0, rpe) };
+ let gate = xs.apply_op2_no_bwd(&slots, &op(0, k, false))?;
+ let up = xs.apply_op2_no_bwd(&slots, &op(1, k, false))?;
+ let inter = gate.dim(2)?;
+ let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((k, inter))?;
+ let down = hidden.apply_op2_no_bwd(&slots, &op(2, k, true))?;
+ Ok(Some(down.broadcast_mul(&w.unsqueeze(2)?)?.sum(1)?))
+ };
+ let sharp_pos: Vec<usize> = (0..row.len()).filter(|&p| slot_of[&row[p]] & SHARP_FLAG != 0).collect();
+ let small_pos: Vec<usize> = (0..row.len()).filter(|&p| slot_of[&row[p]] & SHARP_FLAG == 0).collect();
+ match (part(&sharp_pos, true)?, part(&small_pos, false)?) {
+ (Some(a), Some(b)) => (a + b)?,
+ (Some(a), None) | (None, Some(a)) => a,
+ (None, None) => xs.zeros_like()?,
+ }
+ } else if let Some(slot_of) = slot_of {
let slots: Vec<u32> = ids.iter().flatten().map(|e| slot_of[e] as u32).collect();
let slots = Tensor::from_vec(slots, (n, self.top_k), device)?;
let gate = xs.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 0, self.top_k, false))?; // (n, k, inter)
@@ -925,10 +2150,16 @@ impl StreamedMoe {
let inter = gate.dim(2)?;
let hidden = (candle_nn::ops::silu(&gate)? * &up)?.reshape((n * self.top_k, inter))?;
let down = hidden.apply_op2_no_bwd(&slots, &self.store.bank_op(self.layer, 2, self.top_k, true))?; // (n, k, h)
+ if n == 1 && shaped() && self.store.requant.is_some() {
+ self.store.note_shape(self.layer, &xs, &hidden)?;
+ }
down.broadcast_mul(&top_w.unsqueeze(2)?)?.sum(1)?
} else {
self.reference(&xs, &ids, &top_w)?
};
+ if n == 1 && toaster() {
+ self.store.pop_used(self.layer, &needed);
+ }
if prof {
self.store.device.synchronize()?;
let mut st = self.store.stats.lock().unwrap();
diff --git a/crates/engine/src/gpu_sync.rs b/crates/engine/src/gpu_sync.rs
new file mode 100644
index 0000000..8d21788
--- /dev/null
+++ b/crates/engine/src/gpu_sync.rs
@@ -0,0 +1,281 @@
+//! The parallel path (S4): the GPU never drains for the CPU inside a word.
+//!
+//! Per layer, a tiny kernel copies the router's picks (and the early guess) into memory the CPU
+//! can read, and its command buffer is committed at once so it completes the moment the GPU
+//! reaches it. The expert maths is queued behind a wait on a shared event. A service thread sees
+//! the picks, places and reads the experts, updates the GPU's expert-to-slot table and signals
+//! the event; a second kernel then looks the slots up on the GPU and the maths runs. The CPU
+//! never waits for the queue inside a word; the GPU waits only for bytes.
+
+use candle::backend::BackendStorage;
+use candle::{CustomOp1, CustomOp2, DType, Layout, MetalStorage, Result, Shape};
+use candle_metal_kernels::metal::{Buffer, Commands, ComputePipeline, Device};
+use candle_metal_kernels::{set_params, Output};
+use objc2::rc::Retained;
+use objc2::runtime::ProtocolObject;
+use objc2_metal::{MTLDevice, MTLEvent, MTLSharedEvent, MTLSize};
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::Arc;
+
+pub const NO_SLOT: u32 = u32::MAX;
+
+const SOURCE: &str = r#"
+#include <metal_stdlib>
+using namespace metal;
+
+kernel void coachwhip_publish(
+ device const uint* ids [[buffer(0)]],
+ device const uint* guess [[buffer(1)]],
+ device uint* picks [[buffer(2)]],
+ device atomic_uint* flag [[buffer(3)]],
+ device uint* out [[buffer(4)]],
+ constant uint& n_ids [[buffer(5)]],
+ constant uint& n_guess [[buffer(6)]],
+ uint tid [[thread_position_in_grid]],
+ uint tgs [[threads_per_threadgroup]])
+{
+ for (uint i = tid; i < n_ids; i += tgs) picks[i] = ids[i];
+ for (uint i = tid; i < n_guess; i += tgs) picks[n_ids + i] = guess[i];
+ threadgroup_barrier(mem_flags::mem_device);
+ if (tid == 0) {
+ // The flag is 1 + the sum of the picks: the CPU reads picks until they add up to it.
+ uint sum = 0;
+ for (uint i = 0; i < n_ids + n_guess; ++i) sum += picks[i];
+ atomic_store_explicit(flag, 1u + sum, memory_order_relaxed);
+ out[0] = 1u;
+ }
+}
+
+kernel void coachwhip_resolve(
+ device const uint* ids [[buffer(0)]],
+ device const uint* table [[buffer(1)]],
+ device uint* slots [[buffer(2)]],
+ device atomic_uint* missing [[buffer(3)]],
+ constant uint& n_ids [[buffer(4)]],
+ uint tid [[thread_position_in_grid]],
+ uint tgs [[threads_per_threadgroup]])
+{
+ for (uint i = tid; i < n_ids; i += tgs) {
+ uint s = table[ids[i]];
+ if (s == 0xFFFFFFFFu) {
+ atomic_fetch_add_explicit(missing, 1u, memory_order_relaxed);
+ s = 0u;
+ }
+ slots[i] = s;
+ }
+}
+"#;
+
+/// The GPU's view of one layer's bank, in memory both sides can touch.
+pub struct GpuBank {
+ table: Arc<Buffer>,
+ ready: Arc<Buffer>,
+ picks: Arc<Buffer>,
+ flag: Arc<Buffer>,
+ /// How many picks the resolve kernel found no slot for (should stay 0).
+ missing: Arc<Buffer>,
+ pub experts: usize,
+ pub slots: usize,
+ pub max_picks: usize,
+}
+
+fn atom(buffer: &Buffer, i: usize) -> &AtomicU32 {
+ unsafe { AtomicU32::from_ptr((buffer.contents() as *mut u32).add(i)) }
+}
+
+impl GpuBank {
+ pub fn new(metal: &candle::MetalDevice, experts: usize, slots: usize, max_picks: usize) -> Result<Self> {
+ // Plain shared buffers, zeroed from the CPU: no GPU work queued, so making a bank never
+ // has to wait for the queue (which, mid-word, may be waiting on us).
+ let make = |n: usize, label: &str| -> Result<Arc<Buffer>> {
+ let buf = metal.new_buffer_builder().with_size_for(n, DType::U32).with_label(label).build()?;
+ unsafe { std::ptr::write_bytes(buf.contents() as *mut u8, 0, n * 4) };
+ Ok(buf)
+ };
+ let table = make(experts, "s4_table")?;
+ let ready = make(slots, "s4_ready")?;
+ let picks = make(max_picks, "s4_picks")?;
+ let flag = make(1, "s4_flag")?;
+ let missing = make(1, "s4_missing")?;
+ let bank = Self { table, ready, picks, flag, missing, experts, slots, max_picks };
+ for e in 0..experts {
+ bank.clear(e as u32);
+ }
+ for s in 0..slots {
+ bank.set_ready(s, false);
+ }
+ Ok(bank)
+ }
+
+ pub fn set_slot(&self, expert: u32, slot: usize) {
+ atom(&self.table, expert as usize).store(slot as u32, Ordering::Release);
+ }
+
+ pub fn clear(&self, expert: u32) {
+ atom(&self.table, expert as usize).store(NO_SLOT, Ordering::Release);
+ }
+
+ pub fn set_ready(&self, slot: usize, ready: bool) {
+ atom(&self.ready, slot).store(ready as u32, Ordering::Release);
+ }
+
+ pub fn reset_flag(&self) {
+ atom(&self.flag, 0).store(0, Ordering::Release);
+ }
+
+ /// 0 = the picks are not out yet; otherwise 1 + the sum of the picks.
+ pub fn flag(&self) -> u32 {
+ atom(&self.flag, 0).load(Ordering::SeqCst)
+ }
+
+ pub fn picks(&self, n: usize) -> Vec<u32> {
+ (0..n).map(|i| atom(&self.picks, i).load(Ordering::SeqCst)).collect()
+ }
+
+ /// The picks once they are complete: read until they add up to the flag's checksum.
+ pub fn picks_checked(&self, n: usize, flag: u32) -> Option<Vec<u32>> {
+ let picks = self.picks(n);
+ let sum = picks.iter().fold(0u32, |a, &b| a.wrapping_add(b));
+ if sum.wrapping_add(1) == flag { Some(picks) } else { None }
+ }
+
+ /// Picks the resolve kernel found no slot for so far.
+ pub fn missing(&self) -> u32 {
+ atom(&self.missing, 0).load(Ordering::SeqCst)
+ }
+}
+
+/// The two kernels, compiled once per device.
+pub struct Pipelines {
+ pub publish: Arc<ComputePipeline>,
+ pub resolve: Arc<ComputePipeline>,
+}
+
+pub fn pipelines(device: &Device) -> Result<Pipelines> {
+ let lib = device.new_library_with_source(SOURCE, None).map_err(candle::MetalError::from)?;
+ let mut get = |name: &str| -> Result<Arc<ComputePipeline>> {
+ let f = lib.get_function(name, None).map_err(candle::MetalError::from)?;
+ Ok(Arc::new(device.new_compute_pipeline_state_with_function(&f).map_err(candle::MetalError::from)?))
+ };
+ Ok(Pipelines { publish: get("coachwhip_publish")?, resolve: get("coachwhip_resolve")? })
+}
+
+/// A Metal shared event: the CPU signals values, the GPU queue waits for them.
+pub struct GpuEvent(Retained<ProtocolObject<dyn MTLSharedEvent>>);
+unsafe impl Send for GpuEvent {}
+unsafe impl Sync for GpuEvent {}
+
+impl GpuEvent {
+ pub fn new(device: &Device) -> Result<Self> {
+ let e = device.as_ref().newSharedEvent().ok_or_else(|| candle::Error::Msg("Metal gave no shared event".into()))?;
+ Ok(Self(e))
+ }
+
+ pub fn signal(&self, value: u64) {
+ self.0.setSignaledValue(value);
+ }
+
+ pub fn value(&self) -> u64 {
+ self.0.signaledValue()
+ }
+
+ /// Queue a wait: everything encoded after this runs only once the CPU has signalled `value`.
+ pub fn gpu_wait(&self, value: u64) -> Result<()> {
+ let commands = Commands::current().ok_or_else(|| candle::Error::Msg("no Metal command queue in use yet".into()))?;
+ let event: &ProtocolObject<dyn MTLEvent> = ProtocolObject::from_ref(&*self.0);
+ commands.encode_wait_for_event(event, value).map_err(candle::MetalError::from)?;
+ Ok(())
+ }
+}
+
+/// Commit the work encoded so far, so it runs and completes without waiting for anything later.
+pub fn flush() -> Result<()> {
+ let commands = Commands::current().ok_or_else(|| candle::Error::Msg("no Metal command queue in use yet".into()))?;
+ commands.flush().map_err(candle::MetalError::from)?;
+ Ok(())
+}
+
+/// `ids (1, k) u32, guess (n_guess,) u32`: copies both into the bank's shared picks buffer and
+/// raises the flag. The output is a one-element dummy.
+pub struct Publish {
+ pub bank: Arc<GpuBank>,
+ pub pipeline: Arc<ComputePipeline>,
+ pub n_guess: usize,
+}
+
+impl CustomOp2 for Publish {
+ fn name(&self) -> &'static str {
+ "coachwhip-publish"
+ }
+
+ fn cpu_fwd(&self, _: &candle::CpuStorage, _: &Layout, _: &candle::CpuStorage, _: &Layout) -> Result<(candle::CpuStorage, Shape)> {
+ candle::bail!("coachwhip-publish runs on Metal only")
+ }
+
+ fn metal_fwd(&self, ids: &MetalStorage, il: &Layout, guess: &MetalStorage, gl: &Layout) -> Result<(MetalStorage, Shape)> {
+ if ids.dtype() != DType::U32 || guess.dtype() != DType::U32 {
+ candle::bail!("coachwhip-publish: ids and guess must be u32")
+ }
+ let n_ids = il.shape().elem_count();
+ if n_ids + self.n_guess > self.bank.max_picks {
+ candle::bail!("coachwhip-publish: {} picks, room for {}", n_ids + self.n_guess, self.bank.max_picks)
+ }
+ let device = ids.device().clone();
+ let dst = device.new_buffer_builder().with_size_for(1, DType::U32).with_label("publish").build()?;
+ {
+ let encoder = device.command_encoder()?;
+ let encoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&self.pipeline);
+ let n_ids_u = n_ids as u32;
+ let n_guess_u = self.n_guess as u32;
+ set_params!(
+ encoder,
+ (
+ (ids.buffer(), il.start_offset() * 4),
+ (guess.buffer(), gl.start_offset() * 4),
+ self.bank.picks.as_ref(),
+ self.bank.flag.as_ref(),
+ Output::with_offset(&dst, 0),
+ n_ids_u,
+ n_guess_u
+ )
+ );
+ encoder.dispatch_thread_groups(MTLSize { width: 1, height: 1, depth: 1 }, MTLSize { width: 64, height: 1, depth: 1 });
+ }
+ Ok((MetalStorage::new(dst, device, 1, DType::U32), Shape::from(1)))
+ }
+}
+
+/// `ids (1, k) u32` -> `slots (1, k) u32`, looked up in the bank's expert-to-slot table on the GPU.
+pub struct Resolve {
+ pub bank: Arc<GpuBank>,
+ pub pipeline: Arc<ComputePipeline>,
+}
+
+impl CustomOp1 for Resolve {
+ fn name(&self) -> &'static str {
+ "coachwhip-resolve"
+ }
+
+ fn cpu_fwd(&self, _: &candle::CpuStorage, _: &Layout) -> Result<(candle::CpuStorage, Shape)> {
+ candle::bail!("coachwhip-resolve runs on Metal only")
+ }
+
+ fn metal_fwd(&self, ids: &MetalStorage, il: &Layout) -> Result<(MetalStorage, Shape)> {
+ if ids.dtype() != DType::U32 {
+ candle::bail!("coachwhip-resolve: ids must be u32")
+ }
+ let n_ids = il.shape().elem_count();
+ let device = ids.device().clone();
+ let dst = device.new_buffer_builder().with_size_for(n_ids, DType::U32).with_label("resolve").build()?;
+ {
+ let encoder = device.command_encoder()?;
+ let encoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&self.pipeline);
+ let n_ids_u = n_ids as u32;
+ set_params!(encoder, ((ids.buffer(), il.start_offset() * 4), self.bank.table.as_ref(), Output::with_offset(&dst, 0), self.bank.missing.as_ref(), n_ids_u));
+ encoder.dispatch_thread_groups(MTLSize { width: 1, height: 1, depth: 1 }, MTLSize { width: 64, height: 1, depth: 1 });
+ }
+ Ok((MetalStorage::new(dst, device, n_ids, DType::U32), il.shape().clone()))
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f36dfc0..096ea41 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -2,6 +2,8 @@
//! The experts stream from the SSD into a small bank on the GPU; the model families sit on top.
pub mod experts;
+pub mod gpu_sync;
+pub mod requant;
pub mod model;
pub mod model_next;
mod mv_id;
diff --git a/crates/engine/src/model.rs b/crates/engine/src/model.rs
index b18cdb6..b80ccb3 100644
--- a/crates/engine/src/model.rs
+++ b/crates/engine/src/model.rs
@@ -171,6 +171,7 @@ impl Qwen3Moe {
layer,
gate: Linear::new(gate, None),
next_gate: None,
+ gate1: None,
ahead: settings.ahead.max(1),
store: store.clone(),
top_k,
@@ -295,6 +296,30 @@ impl Model {
self.think().thinks()
}
+ /// S6 measurement (Qwen3-Next family only): see `Qwen3Next::speculate_measure`.
+ pub fn speculate_measure(&mut self, last: u32, offset: usize, k: usize) -> Result<Option<(Vec<u32>, usize)>> {
+ match self {
+ Self::Qwen3Moe(_) => Ok(None),
+ Self::Qwen3Next(m) => m.speculate_measure(last, offset, k).map(Some),
+ }
+ }
+
+ /// Foresight (Qwen3-Next family only): see `Qwen3Next::foresee`.
+ pub fn foresee(&mut self, last: u32, offset: usize, steps: usize) -> Result<bool> {
+ match self {
+ Self::Qwen3Moe(_) => Ok(false),
+ Self::Qwen3Next(m) => m.foresee(last, offset, steps),
+ }
+ }
+
+ /// S6 (Qwen3-Next family only): see `Qwen3Next::speculate`.
+ pub fn speculate(&mut self, last: u32, offset: usize, k: usize) -> Result<Option<Vec<u32>>> {
+ match self {
+ Self::Qwen3Moe(_) => Ok(None),
+ Self::Qwen3Next(m) => m.speculate(last, offset, k),
+ }
+ }
+
/// The text that opens the assistant's turn, with thinking on or off.
pub fn assistant_open(&self, think: bool) -> &'static str {
let t = self.think();
diff --git a/crates/engine/src/model_next.rs b/crates/engine/src/model_next.rs
index 5960214..9db8dfe 100644
--- a/crates/engine/src/model_next.rs
+++ b/crates/engine/src/model_next.rs
@@ -6,9 +6,94 @@
//! Follows llama.cpp's qwen3next graph for the tensor layout and the maths.
use crate::experts::{ExpertStore, Settings, StreamedMoe};
-use candle::quantized::gguf_file;
+use candle::quantized::{ggml_file::qtensor_from_ggml, gguf_file, GgmlDType, QTensor};
use candle::{DType, Device, Module, Result, Tensor, D};
-use candle_nn::kv_cache::KvCache;
+/// Inputs this long or shorter run the delta rule word by word (exact); longer ones block-wise.
+pub const DELTA_STEPS_MAX: usize = 8;
+
+/// The delta rule one word at a time over the first `upto` positions: the memory decays, is
+/// corrected by each key and value, and is read out with the query. Returns the outputs
+/// `(upto, n_v, dv)` and the memory after them.
+pub fn delta_steps(qc: &Tensor, kc: &Tensor, vc: &Tensor, beta: &Tensor, log_decay: &Tensor, mut s: Tensor, upto: usize) -> Result<(Tensor, Tensor)> {
+ let n_v = kc.dim(1)?;
+ let decay = log_decay.exp()?;
+ let mut outs = Vec::with_capacity(upto);
+ for t in 0..upto {
+ let kt = kc.get(t)?.unsqueeze(1)?.contiguous()?; // (n_v, 1, dk)
+ let qt = qc.get(t)?.unsqueeze(1)?.contiguous()?;
+ let vt = vc.get(t)?.unsqueeze(1)?; // (n_v, 1, dv)
+ let bt = beta.get(t)?.reshape((n_v, 1, 1))?;
+ let gt = decay.get(t)?.reshape((n_v, 1, 1))?;
+ s = s.broadcast_mul(&gt)?;
+ let sk = kt.matmul(&s)?; // (n_v, 1, dv)
+ let d = (vt - sk)?.broadcast_mul(&bt)?;
+ s = (s + kt.transpose(1, 2)?.contiguous()?.matmul(&d)?)?;
+ outs.push(qt.matmul(&s)?.squeeze(1)?); // (n_v, dv)
+ }
+ Ok((Tensor::stack(&outs, 0)?, s))
+}
+
+/// What a recorded forward leaves behind, so the layer's memory can be rewound to any prefix of
+/// it: the memory before, the convolution window before, and every word's inputs.
+struct Trail {
+ s0: Tensor,
+ conv_before: Tensor,
+ padded: Tensor,
+ qc: Tensor,
+ kc: Tensor,
+ vc: Tensor,
+ beta: Tensor,
+ log_decay: Tensor,
+}
+
+/// Keys and values kept between words, like candle's KvCache, plus `truncate` so a speculative
+/// draft can be taken back.
+struct KvBuf {
+ k: Option<Tensor>,
+ v: Option<Tensor>,
+ len: usize,
+ cap: usize,
+}
+
+impl KvBuf {
+ fn new(cap: usize) -> Self {
+ Self { k: None, v: None, len: 0, cap }
+ }
+
+ /// Appends along the sequence axis (dim 2) and returns everything kept so far.
+ fn append(&mut self, k: &Tensor, v: &Tensor) -> Result<(Tensor, Tensor)> {
+ let l = k.dim(2)?;
+ if self.k.is_none() || self.len + l > self.cap {
+ let (b, h, _, d) = k.dims4()?;
+ let cap = (self.len + l).max(self.cap) + 1024;
+ let len = self.len;
+ let grow = |old: &Option<Tensor>, t: &Tensor| -> Result<Tensor> {
+ let fresh = Tensor::zeros((b, h, cap, d), t.dtype(), t.device())?;
+ if let (Some(o), true) = (old, len > 0) {
+ fresh.slice_set(&o.narrow(2, 0, len)?, 2, 0)?;
+ }
+ Ok(fresh)
+ };
+ self.k = Some(grow(&self.k, k)?);
+ self.v = Some(grow(&self.v, v)?);
+ self.cap = cap;
+ }
+ let kb = self.k.as_ref().unwrap();
+ let vb = self.v.as_ref().unwrap();
+ kb.slice_set(k, 2, self.len)?;
+ vb.slice_set(v, 2, self.len)?;
+ self.len += l;
+ Ok((kb.narrow(2, 0, self.len)?, vb.narrow(2, 0, self.len)?))
+ }
+
+ fn truncate(&mut self, len: usize) {
+ self.len = self.len.min(len);
+ }
+
+ fn reset(&mut self) {
+ self.len = 0;
+ }
+}
use candle_nn::{Embedding, Linear};
use candle_transformers::models::quantized_qwen3::Gguf;
use candle_transformers::models::with_tracing::QMatMul;
@@ -28,7 +113,33 @@ fn wire_lookahead(layers: &mut [Layer], ahead: usize) {
let ahead = ahead.max(1);
for i in ahead..layers.len() {
layers[i - ahead].moe.next_gate = Some(layers[i].moe.gate.clone());
+ if ahead >= 2 {
+ layers[i - ahead].moe.gate1 = Some(layers[i - ahead + 1].moe.gate.clone());
+ }
+ }
+}
+
+/// Lab (`COACHWHIP_PREDICTOR=file`): fitted expert predictors in place of the borrowed routers.
+/// File: u32 layers, hidden, experts, ahead; then per layer L in 0..layers-ahead: f32 W[experts x
+/// hidden] (row-major), f32 b[experts]. W maps layer L's MoE input to layer L+ahead's scores.
+fn load_predictor(layers: &mut [Layer], path: &str, ahead: usize, device: &Device) -> Result<()> {
+ let bytes = std::fs::read(path).map_err(|e| candle::Error::Msg(format!("predictor {path}: {e}")))?;
+ let u32_at = |i: usize| u32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()) as usize;
+ let (n_layers, hidden, experts, f_ahead) = (u32_at(0), u32_at(4), u32_at(8), u32_at(12));
+ if n_layers != layers.len() || f_ahead != ahead {
+ candle::bail!("predictor {path}: {n_layers} layers, ahead {f_ahead}; model has {} layers, ahead {ahead}", layers.len())
+ }
+ let mut pos = 16;
+ let floats = |pos: usize, n: usize| -> Vec<f32> { bytes[pos..pos + 4 * n].chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect() };
+ for l in 0..n_layers - ahead {
+ let w = Tensor::from_vec(floats(pos, experts * hidden), (experts, hidden), device)?;
+ pos += 4 * experts * hidden;
+ let b = Tensor::from_vec(floats(pos, experts), experts, device)?;
+ pos += 4 * experts;
+ layers[l].moe.next_gate = Some(Linear::new(w, Some(b)));
}
+ eprintln!("coachwhip: fitted expert predictor loaded from {path} ({} layers, {ahead} ahead)", n_layers - ahead);
+ Ok(())
}
fn softplus(x: &Tensor) -> Result<Tensor> {
@@ -164,6 +275,9 @@ mod proj_tests {
eps: 1e-6,
conv_state: None,
state: None,
+ snapshot: None,
+ record: false,
+ trail: None,
}
}
@@ -246,12 +360,39 @@ struct LinearAttn {
eps: f64,
conv_state: Option<Tensor>,
state: Option<Tensor>,
+ /// The memories as they were before a speculative draft, to go back to.
+ snapshot: Option<(Option<Tensor>, Option<Tensor>)>,
+ /// Keep a trail of the next forward, so it can be rewound.
+ record: bool,
+ trail: Option<Trail>,
}
impl LinearAttn {
fn reset(&mut self) {
self.conv_state = None;
self.state = None;
+ self.snapshot = None;
+ }
+
+ fn take_snapshot(&mut self) {
+ self.snapshot = Some((self.conv_state.clone(), self.state.clone()));
+ }
+
+ fn restore_snapshot(&mut self) {
+ if let Some((c, s)) = self.snapshot.take() {
+ self.conv_state = c;
+ self.state = s;
+ }
+ }
+
+ /// Rewind the last recorded forward to its first `m` words: the memory is replayed from
+ /// before it over those words, the convolution window set as it was after them.
+ fn rewind(&mut self, m: usize) -> Result<()> {
+ let Some(t) = self.trail.take() else { return Ok(()) };
+ let taps = self.conv_w.dim(1)?;
+ self.state = Some(if m == 0 { t.s0 } else { delta_steps(&t.qc, &t.kc, &t.vc, &t.beta, &t.log_decay, t.s0, m)?.1 });
+ self.conv_state = Some(if m == 0 { t.conv_before } else { t.padded.narrow(0, m, taps - 1)?.contiguous()? });
+ Ok(())
}
/// The projections of one input, in one layout: q, k and v side by side as `(l, channels)`,
@@ -326,26 +467,18 @@ impl LinearAttn {
Some(s) => s.clone(),
None => Tensor::zeros((n_v, dk, dv), DType::F32, device)?,
};
- let (o, s) = if l > 1 {
+ // Long inputs take the block-at-a-time path; short ones (one word, or a speculative
+ // verify of a few) go word by word, the exact arithmetic plain decoding uses.
+ let s0 = s.clone();
+ let (o, s) = if l > DELTA_STEPS_MAX {
delta_chunked(&qc, &kc, &vc, &beta, &log_decay, s)?
} else {
- let decay = log_decay.exp()?;
- let mut outs = Vec::with_capacity(l);
- for t in 0..l {
- let kt = kc.get(t)?.unsqueeze(1)?.contiguous()?; // (n_v, 1, dk)
- let qt = qc.get(t)?.unsqueeze(1)?.contiguous()?;
- let vt = vc.get(t)?.unsqueeze(1)?; // (n_v, 1, dv)
- let bt = beta.get(t)?.reshape((n_v, 1, 1))?;
- let gt = decay.get(t)?.reshape((n_v, 1, 1))?;
- s = s.broadcast_mul(&gt)?;
- let sk = kt.matmul(&s)?; // (n_v, 1, dv)
- let d = (vt - sk)?.broadcast_mul(&bt)?;
- s = (s + kt.transpose(1, 2)?.contiguous()?.matmul(&d)?)?;
- outs.push(qt.matmul(&s)?.squeeze(1)?); // (n_v, dv)
- }
- (Tensor::stack(&outs, 0)?, s) // (l, n_v, dv)
+ delta_steps(&qc, &kc, &vc, &beta, &log_decay, s, l)?
};
self.state = Some(s);
+ if self.record {
+ self.trail = Some(Trail { s0, conv_before: past, padded: padded.clone(), qc: qc.clone(), kc: kc.clone(), vc: vc.clone(), beta: beta.clone(), log_decay: log_decay.clone() });
+ }
let o = (self.norm.forward(&o)? * candle_nn::ops::silu(&z)?)?;
self.out.forward(&o.reshape((l, n_v * dv))?)?.reshape((b, l, h))
@@ -365,7 +498,7 @@ struct FullAttn {
hd: usize,
rot: usize,
freq_base: f64,
- kv_cache: KvCache,
+ kv_cache: KvBuf,
}
impl FullAttn {
@@ -473,6 +606,15 @@ impl Qwen3Next {
let rot = md_u("rope.dimension_count")?;
let block_count = md_u("block_count")?;
let top_k = md_u("expert_used_count")?;
+ // Lab (`COACHWHIP_TOPK=n`): ask fewer experts per word than the model was trained with.
+ // Fewer experts = fewer bytes per word; the text changes, so quality is measured alongside.
+ let top_k = match std::env::var("COACHWHIP_TOPK").ok().and_then(|v| v.parse::<usize>().ok()) {
+ Some(k) if k >= 1 && k < top_k => {
+ eprintln!("coachwhip: lab top-k {k} (model uses {top_k})");
+ k
+ }
+ _ => top_k,
+ };
let embedding_length = md_u("embedding_length")?;
let d_state = md_u("ssm.state_size")?;
let n_group = md_u("ssm.group_count")?;
@@ -488,12 +630,82 @@ impl Qwen3Next {
let store = ExpertStore::new(&ct, device, block_count, path, settings)?;
let mut gg = Gguf::new(ct, &mut file, device.clone());
let dense = |gg: &mut Gguf<&mut std::fs::File>, name: &str| -> Result<Tensor> { gg.tensor(name)?.dequantize(device)?.to_dtype(DType::F32) };
+ // Lab (`COACHWHIP_DENSE=q2k|q3k|q4k`): the dense weights are shrunk once at load, so the
+ // memory they give back can hold more expert slots. The answers change with them.
+ let dense_q: Option<GgmlDType> = match std::env::var("COACHWHIP_DENSE").ok().as_deref() {
+ Some("q2k") => Some(GgmlDType::Q2K),
+ Some("q3k") => Some(GgmlDType::Q3K),
+ Some("q4k") => Some(GgmlDType::Q4K),
+ _ => None,
+ };
+ let shrunk = std::cell::Cell::new(0usize);
+ let saved = std::cell::Cell::new(0usize);
+ let qm = |gg: &mut Gguf<&mut std::fs::File>, name: &str| -> Result<QMatMul> {
+ let t = gg.tensor(name)?;
+ let Some(dt) = dense_q else { return QMatMul::from_weights(Arc::new(t)) };
+ // Only shrink what is bigger than the target and quantised to begin with.
+ if t.dtype().block_size() == 1 || t.dtype().type_size() * dt.block_size() <= dt.type_size() * t.dtype().block_size() {
+ return QMatMul::from_weights(Arc::new(t));
+ }
+ let dims = t.shape().dims().to_vec();
+ if dims.last().map_or(true, |&k| k % dt.block_size() != 0) {
+ return QMatMul::from_weights(Arc::new(t));
+ }
+ let before = t.storage_size_in_bytes();
+ let f = t.dequantize(&Device::Cpu)?.to_dtype(DType::F32)?;
+ let q = QTensor::quantize(&f, dt)?;
+ let bytes = q.data()?;
+ let on_device = qtensor_from_ggml(dt, &bytes, dims, device)?;
+ shrunk.set(shrunk.get() + 1);
+ saved.set(saved.get() + before.saturating_sub(on_device.storage_size_in_bytes()));
+ QMatMul::from_weights(Arc::new(on_device))
+ };
let embeddings = gg.tensor("token_embd.weight")?.dequantize(device)?.to_dtype(DType::F16)?.to_device(&Device::Cpu)?;
let norm = gg.rms_norm("output_norm.weight", eps)?;
- let output = match gg.qmatmul("output.weight") {
- Ok(v) => v,
- _ => gg.qmatmul("token_embd.weight")?,
+ // The output head goes through the shrink in slices (conveyor belt): dequantise 8,192 rows,
+ // shrink them, stack the bytes, so the load never holds more than one slice in f32 on the CPU.
+ let head_q: Option<GgmlDType> = match std::env::var("COACHWHIP_DENSE_HEAD").ok().as_deref() {
+ Some("q2k") => Some(GgmlDType::Q2K),
+ Some("q3k") => Some(GgmlDType::Q3K),
+ Some("q4k") => Some(GgmlDType::Q4K),
+ Some("off") => None,
+ _ => dense_q,
+ };
+ let head_name = if gg.qmatmul("output.weight").is_ok() { "output.weight" } else { "token_embd.weight" };
+ let output = match head_q {
+ Some(dt) => {
+ let t = gg.tensor(head_name)?;
+ let dims = t.shape().dims().to_vec();
+ let before = t.storage_size_in_bytes();
+ if t.dtype().block_size() == 1 || dims.len() != 2 || dims[1] % dt.block_size() != 0 || t.dtype().type_size() * dt.block_size() <= dt.type_size() * t.dtype().block_size() {
+ QMatMul::from_weights(Arc::new(t))?
+ } else {
+ let f = t.dequantize(device)?.to_dtype(DType::F32)?; // on the GPU, once
+ drop(t);
+ let rows = dims[0];
+ let step = 8192usize;
+ let mut bytes: Vec<u8> = Vec::with_capacity(rows / dt.block_size() * dims[1] * dt.type_size() / dims[1].max(1) * dims[1] / dt.block_size() * dt.type_size() / 1);
+ let mut r = 0;
+ while r < rows {
+ let n = step.min(rows - r);
+ let slice = f.narrow(0, r, n)?.to_device(&Device::Cpu)?;
+ let q = QTensor::quantize(&slice, dt)?;
+ bytes.extend_from_slice(&q.data()?);
+ r += n;
+ }
+ drop(f);
+ let on_device = qtensor_from_ggml(dt, &bytes, dims, device)?;
+ shrunk.set(shrunk.get() + 1);
+ saved.set(saved.get() + before.saturating_sub(on_device.storage_size_in_bytes()));
+ eprintln!("coachwhip: output head shrunk in slices: {:.2} GB -> {:.2} GB", before as f64 / 1e9, on_device.storage_size_in_bytes() as f64 / 1e9);
+ QMatMul::from_weights(Arc::new(on_device))?
+ }
+ }
+ None => match gg.qmatmul("output.weight") {
+ Ok(v) => v,
+ _ => gg.qmatmul("token_embd.weight")?,
+ },
};
let mut layers = Vec::with_capacity(block_count);
@@ -501,10 +713,10 @@ impl Qwen3Next {
let p = format!("blk.{layer}");
let mixer = if (layer + 1) % interval == 0 {
Mixer::Full(FullAttn {
- wq: gg.qmatmul(&format!("{p}.attn_q.weight"))?,
- wk: gg.qmatmul(&format!("{p}.attn_k.weight"))?,
- wv: gg.qmatmul(&format!("{p}.attn_v.weight"))?,
- wo: gg.qmatmul(&format!("{p}.attn_output.weight"))?,
+ wq: qm(&mut gg, &format!("{p}.attn_q.weight"))?,
+ wk: qm(&mut gg, &format!("{p}.attn_k.weight"))?,
+ wv: qm(&mut gg, &format!("{p}.attn_v.weight"))?,
+ wo: qm(&mut gg, &format!("{p}.attn_output.weight"))?,
q_norm: gg.rms_norm(&format!("{p}.attn_q_norm.weight"), eps)?,
k_norm: gg.rms_norm(&format!("{p}.attn_k_norm.weight"), eps)?,
n_head,
@@ -512,19 +724,19 @@ impl Qwen3Next {
hd,
rot,
freq_base,
- kv_cache: KvCache::new(2, 4096),
+ kv_cache: KvBuf::new(4096),
})
} else {
let conv_w = dense(&mut gg, &format!("{p}.ssm_conv1d.weight"))?; // (channels, taps)
let proj = if split {
Proj::Split {
- qkv: gg.qmatmul(&format!("{p}.attn_qkv.weight"))?,
- z: gg.qmatmul(&format!("{p}.attn_gate.weight"))?,
- beta: gg.qmatmul(&format!("{p}.ssm_beta.weight"))?,
- alpha: gg.qmatmul(&format!("{p}.ssm_alpha.weight"))?,
+ qkv: qm(&mut gg, &format!("{p}.attn_qkv.weight"))?,
+ z: qm(&mut gg, &format!("{p}.attn_gate.weight"))?,
+ beta: qm(&mut gg, &format!("{p}.ssm_beta.weight"))?,
+ alpha: qm(&mut gg, &format!("{p}.ssm_alpha.weight"))?,
}
} else {
- Proj::Fused { qkvz: gg.qmatmul(&format!("{p}.ssm_in.weight"))?, ba: gg.qmatmul(&format!("{p}.ssm_ba.weight"))? }
+ Proj::Fused { qkvz: qm(&mut gg, &format!("{p}.ssm_in.weight"))?, ba: qm(&mut gg, &format!("{p}.ssm_ba.weight"))? }
};
Mixer::Linear(LinearAttn {
proj,
@@ -532,7 +744,7 @@ impl Qwen3Next {
dt_bias: dense(&mut gg, &format!("{p}.ssm_dt.bias"))?,
a: dense(&mut gg, &format!("{p}.ssm_a"))?,
norm: gg.rms_norm(&format!("{p}.ssm_norm.weight"), eps)?,
- out: gg.qmatmul(&format!("{p}.ssm_out.weight"))?,
+ out: qm(&mut gg, &format!("{p}.ssm_out.weight"))?,
n_k: n_group,
n_v: dt_rank,
dk: d_state,
@@ -540,6 +752,9 @@ impl Qwen3Next {
eps,
conv_state: None,
state: None,
+ snapshot: None,
+ record: false,
+ trail: None,
})
};
let gate = dense(&mut gg, &format!("{p}.ffn_gate_inp.weight"))?;
@@ -547,6 +762,7 @@ impl Qwen3Next {
layer,
gate: Linear::new(gate, None),
next_gate: None,
+ gate1: None,
ahead: settings.ahead.max(1),
store: store.clone(),
top_k,
@@ -555,9 +771,9 @@ impl Qwen3Next {
};
let shared = SharedExpert {
gate_inp: dense(&mut gg, &format!("{p}.ffn_gate_inp_shexp.weight"))?,
- gate: gg.qmatmul(&format!("{p}.ffn_gate_shexp.weight"))?,
- up: gg.qmatmul(&format!("{p}.ffn_up_shexp.weight"))?,
- down: gg.qmatmul(&format!("{p}.ffn_down_shexp.weight"))?,
+ gate: qm(&mut gg, &format!("{p}.ffn_gate_shexp.weight"))?,
+ up: qm(&mut gg, &format!("{p}.ffn_up_shexp.weight"))?,
+ down: qm(&mut gg, &format!("{p}.ffn_down_shexp.weight"))?,
};
layers.push(Layer {
mixer,
@@ -567,7 +783,13 @@ impl Qwen3Next {
shared,
});
}
+ if dense_q.is_some() {
+ eprintln!("coachwhip: dense weights shrunk at load: {} tensors, {:.2} GB given back to the bank", shrunk.get(), saved.get() as f64 / 1e9);
+ }
wire_lookahead(&mut layers, settings.ahead);
+ if let Ok(path) = std::env::var("COACHWHIP_PREDICTOR") {
+ load_predictor(&mut layers, &path, settings.ahead.max(1), device)?;
+ }
Ok(Self { embeddings: Embedding::new(embeddings, embedding_length), layers, norm, output, store, device: device.clone(), think, progress: None })
}
@@ -585,7 +807,210 @@ impl Qwen3Next {
}
}
+ /// S6 measurement. Drafts `k` words after `last` with routing confined to the bank (no reads),
+ /// takes the memories back, then writes the same `k` words the plain way and counts how many
+ /// drafted words the plain path agrees with, in order. Returns the plain words (the model has
+ /// read all but the last, exactly as after `k` plain steps) and the accepted count.
+ pub fn speculate_measure(&mut self, last: u32, offset: usize, k: usize) -> Result<(Vec<u32>, usize)> {
+ let argmax = |logits: Tensor| -> Result<u32> { Ok(logits.argmax(D::Minus1)?.to_vec1::<u32>()?[0]) };
+ // A cold bank (right after a prompt read outside it) has nothing to draft from: write the
+ // words the plain way and count nothing; the next block drafts.
+ let cold = self.layers.iter().any(|l| self.store.resident_ready(l.moe.layer).map_or(true, |r| r.len() < l.moe.top_k));
+ if cold {
+ let mut plain = Vec::with_capacity(k);
+ let mut t = last;
+ for i in 0..k {
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ t = argmax(self.forward(&x, offset + i)?)?;
+ plain.push(t);
+ }
+ return Ok((plain, 0));
+ }
+ let kv_len = self.layers.iter().find_map(|l| match &l.mixer {
+ Mixer::Full(a) => Some(a.kv_cache.len),
+ _ => None,
+ });
+ for layer in self.layers.iter_mut() {
+ if let Mixer::Linear(a) = &mut layer.mixer {
+ a.take_snapshot();
+ }
+ }
+ self.store.set_draft(true);
+ let mut draft = Vec::with_capacity(k);
+ let mut t = last;
+ let drafted: Result<()> = (|| {
+ for i in 0..k {
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ t = argmax(self.forward(&x, offset + i)?)?;
+ draft.push(t);
+ }
+ Ok(())
+ })();
+ self.store.set_draft(false);
+ for layer in self.layers.iter_mut() {
+ match &mut layer.mixer {
+ Mixer::Linear(a) => a.restore_snapshot(),
+ Mixer::Full(a) => a.kv_cache.truncate(kv_len.unwrap_or(0)),
+ }
+ }
+ drafted?;
+ // The plain way, word by word: the truth the draft is scored against.
+ let mut plain = Vec::with_capacity(k);
+ let mut t = last;
+ for i in 0..k {
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ t = argmax(self.forward(&x, offset + i)?)?;
+ plain.push(t);
+ }
+ let accepted = draft.iter().zip(plain.iter()).take_while(|(d, p)| d == p).count();
+ self.store.note_speculation(k, accepted);
+ Ok((plain, accepted))
+ }
+
+ /// S6: draft `k` words from the bank, check them all in one plain pass, keep the ones the
+ /// model agrees with and the corrected word after them, and rewind the memories to match.
+ /// Returns None when speculation cannot run (cold bank); otherwise the words to emit, the
+ /// last of which the model has not read yet, exactly as after that many plain steps.
+ pub fn speculate(&mut self, last: u32, offset: usize, k: usize) -> Result<Option<Vec<u32>>> {
+ let argmax = |logits: Tensor| -> Result<u32> { Ok(logits.argmax(D::Minus1)?.to_vec1::<u32>()?[0]) };
+ if k == 0 || self.layers.iter().any(|l| self.store.resident_ready(l.moe.layer).map_or(true, |r| r.len() < l.moe.top_k)) {
+ return Ok(None);
+ }
+ let kv_len = self.layers.iter().find_map(|l| match &l.mixer {
+ Mixer::Full(a) => Some(a.kv_cache.len),
+ _ => None,
+ }).unwrap_or(0);
+ for layer in self.layers.iter_mut() {
+ if let Mixer::Linear(a) = &mut layer.mixer {
+ a.take_snapshot();
+ }
+ }
+ // Draft.
+ self.store.set_draft(true);
+ let mut draft = Vec::with_capacity(k);
+ let mut t = last;
+ let drafted: Result<()> = (|| {
+ for i in 0..k {
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ t = argmax(self.forward(&x, offset + i)?)?;
+ draft.push(t);
+ }
+ Ok(())
+ })();
+ self.store.set_draft(false);
+ for layer in self.layers.iter_mut() {
+ match &mut layer.mixer {
+ Mixer::Linear(a) => {
+ a.restore_snapshot();
+ a.record = true;
+ }
+ Mixer::Full(a) => a.kv_cache.truncate(kv_len),
+ }
+ }
+ drafted?;
+ // Load: the last word and the draft in one pass. Its only job is to bring every expert
+ // those words need into the bank in one batched read; its arithmetic is thrown away, so
+ // the words below come from the exact same path plain decoding takes.
+ let mut words = Vec::with_capacity(k + 1);
+ words.push(last);
+ words.extend_from_slice(&draft);
+ let x = Tensor::new(words.as_slice(), &self.device)?.unsqueeze(0)?;
+ let loaded = self.forward_inner(&x, offset, false);
+ for layer in self.layers.iter_mut() {
+ match &mut layer.mixer {
+ Mixer::Linear(a) => {
+ a.record = false;
+ a.rewind(0)?;
+ }
+ Mixer::Full(a) => a.kv_cache.truncate(kv_len),
+ }
+ }
+ loaded?;
+ // Check, the plain way, word by word, with the bank hot: keep a drafted word only while
+ // the plain path says the same; the first disagreement is the plain word, and ends it.
+ let mut seq = Vec::with_capacity(k + 1);
+ let mut t = last;
+ for i in 0..=k {
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ let w = argmax(self.forward(&x, offset + i)?)?;
+ seq.push(w);
+ if i < k && w == draft[i] {
+ t = w;
+ } else {
+ break;
+ }
+ }
+ let accepted = seq.len() - 1;
+ self.store.note_speculation(k, accepted);
+ Ok(Some(seq))
+ }
+
+ /// Foresight: one bank-only draft pass of `last`, whose only product is the reads it starts for
+ /// the real pass that follows. Nothing it computes is kept. False when the bank is cold.
+ pub fn foresee(&mut self, last: u32, offset: usize, steps: usize) -> Result<bool> {
+ let argmax = |logits: Tensor| -> Result<u32> { Ok(logits.argmax(D::Minus1)?.to_vec1::<u32>()?[0]) };
+ if self.layers.iter().any(|l| self.store.resident_ready(l.moe.layer).map_or(true, |r| r.len() < l.moe.top_k)) {
+ return Ok(false);
+ }
+ let kv_len = self.layers.iter().find_map(|l| match &l.mixer {
+ Mixer::Full(a) => Some(a.kv_cache.len),
+ _ => None,
+ }).unwrap_or(0);
+ for layer in self.layers.iter_mut() {
+ if let Mixer::Linear(a) = &mut layer.mixer {
+ a.take_snapshot();
+ }
+ }
+ self.store.set_draft(true);
+ let mut t = last;
+ let drafted: Result<()> = (|| {
+ let steps = steps.max(1);
+ for i in 0..steps {
+ self.store.set_foresee(true, i as u64);
+ let x = Tensor::new(&[t], &self.device)?.unsqueeze(0)?;
+ if i + 1 == steps {
+ // The last step's word is never needed, only the reads its layers started.
+ self.body(&x, offset + i)?;
+ } else {
+ t = argmax(self.forward(&x, offset + i)?)?;
+ }
+ let top_k = self.layers[0].moe.top_k;
+ self.store.flush_foresight(top_k)?;
+ }
+ Ok(())
+ })();
+ self.store.set_foresee(false, 0);
+ self.store.set_draft(false);
+ for layer in self.layers.iter_mut() {
+ match &mut layer.mixer {
+ Mixer::Linear(a) => a.restore_snapshot(),
+ Mixer::Full(a) => a.kv_cache.truncate(kv_len),
+ }
+ }
+ drafted?;
+ Ok(true)
+ }
+
pub fn forward(&mut self, x: &Tensor, offset: usize) -> Result<Tensor> {
+ self.forward_inner(x, offset, false)
+ }
+
+ /// `all`: scores for every position, not only the last.
+ fn forward_inner(&mut self, x: &Tensor, offset: usize, all: bool) -> Result<Tensor> {
+ let (xs, l) = self.body(x, offset)?;
+ if all {
+ let xs = self.norm.forward(&xs)?;
+ return self.output.forward(&xs)?.to_dtype(DType::F32)?.squeeze(0);
+ }
+ let xs = self.norm.forward(&xs.narrow(1, l - 1, 1)?)?;
+ self.output.forward(&xs)?.to_dtype(DType::F32)?.squeeze(1)
+ }
+
+ /// The layers only, no output head: the hidden state and the number of positions.
+ fn body(&mut self, x: &Tensor, offset: usize) -> Result<(Tensor, usize)> {
+ if !self.store.drafting() {
+ self.store.note_tokens(x.flatten_all()?.to_vec1()?);
+ }
let mut xs = self.embeddings.forward(&x.to_device(&Device::Cpu)?)?.to_device(&self.device)?.to_dtype(DType::F32)?;
let (_b, l) = x.dims2()?;
let mask = if l == 1 {
@@ -611,7 +1036,6 @@ impl Qwen3Next {
}
}
}
- let xs = self.norm.forward(&xs.narrow(1, l - 1, 1)?)?;
- self.output.forward(&xs)?.to_dtype(DType::F32)?.squeeze(1)
+ Ok((xs, l))
}
}
diff --git a/crates/engine/src/mv_id.rs b/crates/engine/src/mv_id.rs
index 0c6b19a..7f06413 100644
--- a/crates/engine/src/mv_id.rs
+++ b/crates/engine/src/mv_id.rs
@@ -31,7 +31,7 @@ pub fn matvec_id(
) -> Result<(), MetalKernelError> {
let (nth0, nth1, align) = match dtype {
GgmlDType::Q4_0 | GgmlDType::Q4_1 | GgmlDType::Q5_0 | GgmlDType::Q5_1 | GgmlDType::Q8_0 | GgmlDType::Q8_1 => (8, 8, 8),
- GgmlDType::Q2K => (2, 32, 4),
+ GgmlDType::Q2K => (2, 32, 8),
GgmlDType::Q4K => (4, 8, 4),
GgmlDType::Q3K | GgmlDType::Q5K => (2, 32, 4),
GgmlDType::Q6K => (2, 32, 2),
diff --git a/crates/engine/src/requant.rs b/crates/engine/src/requant.rs
new file mode 100644
index 0000000..0b1dcb2
--- /dev/null
+++ b/crates/engine/src/requant.rs
@@ -0,0 +1,424 @@
+//! The GPU shrink (Captain's design, 8 Oct): an expert arriving from the file at Q3_K or Q5_K is
+//! shrunk to Q2_K on the GPU the moment its bytes land, so the bank holds Q2 copies and parks
+//! more experts in the same memory. One thread per 256-weight super-block: dequantise with the
+//! same code the matvec kernels use, then fit 16 sub-blocks of 16 to 2 bits by min and max.
+//! Its own command queue, so reader threads can run it without touching Candle's queue.
+
+use candle::{MetalDevice, Result};
+use candle_metal_kernels::metal::{Buffer, ComputePipeline, Device};
+use objc2::rc::Retained;
+use objc2::runtime::ProtocolObject;
+use objc2_metal::{MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLComputeCommandEncoder, MTLDevice, MTLSize};
+use std::time::Instant;
+
+pub const QK_K: usize = 256;
+pub const Q2K_BLOCK_BYTES: usize = 84;
+pub const Q3K_BLOCK_BYTES: usize = 110;
+pub const Q5K_BLOCK_BYTES: usize = 176;
+
+const SOURCE: &str = r#"
+#include <metal_stdlib>
+using namespace metal;
+#define QK_K 256
+#define K_SCALE_SIZE 12
+
+typedef struct {
+ uint8_t scales[QK_K/16];
+ uint8_t qs[QK_K/4];
+ half d;
+ half dmin;
+} block_q2_K;
+
+typedef struct {
+ uint8_t hmask[QK_K/8];
+ uint8_t qs[QK_K/4];
+ uint8_t scales[12];
+ half d;
+} block_q3_K;
+
+typedef struct {
+ half d;
+ half dmin;
+ uint8_t scales[K_SCALE_SIZE];
+ uint8_t qh[QK_K/8];
+ uint8_t qs[QK_K/2];
+} block_q5_K;
+
+static inline uchar2 get_scale_min_k4_just2(int j, int k, device const uchar * q) {
+ return j < 4 ? uchar2{uchar(q[j+0+k] & 63), uchar(q[j+4+k] & 63)}
+ : uchar2{uchar((q[j+4+k] & 0xF) | ((q[j-4+k] & 0xc0) >> 2)), uchar((q[j+4+k] >> 4) | ((q[j-0+k] & 0xc0) >> 2))};
+}
+
+// 16 values of a Q3_K block (il = 0..15), as the matvec kernels read them.
+void dq_q3(device const block_q3_K *xb, short il, thread float *out) {
+ const half d_all = xb->d;
+ device const uint8_t * q = (device const uint8_t *)xb->qs;
+ device const uint8_t * h = (device const uint8_t *)xb->hmask;
+ device const int8_t * scales = (device const int8_t *)xb->scales;
+ q = q + 32 * (il/8) + 16 * (il&1);
+ h = h + 16 * (il&1);
+ uint8_t m = 1 << (il/2);
+ uint16_t kmask1 = (il/4)>1 ? ((il/4)>2 ? 192 : 48) : ((il/4)>0 ? 12 : 3);
+ uint16_t kmask2 = il/8 ? 0xF0 : 0x0F;
+ uint16_t scale_2 = scales[il%8], scale_1 = scales[8 + il%4];
+ int16_t dl_int = (il/4)&1 ? (scale_2&kmask2) | ((scale_1&kmask1) << 2) : (scale_2&kmask2) | ((scale_1&kmask1) << 4);
+ float dl = il<8 ? d_all * (dl_int - 32.f) : d_all * (dl_int / 16.f - 32.f);
+ const float ml = 4.f * dl;
+ short il2 = (il/2) & 3;
+ const half coef = il2>1 ? (il2>2 ? 1/64.h : 1/16.h) : (il2>0 ? 1/4.h : 1.h);
+ const uint8_t mask = il2>1 ? (il2>2 ? 192 : 48) : (il2>0 ? 12 : 3);
+ dl *= coef;
+ for (int i = 0; i < 16; ++i) out[i] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml);
+}
+
+typedef struct {
+ half d;
+ half dmin;
+ uint8_t scales[K_SCALE_SIZE];
+ uint8_t qs[QK_K/2];
+} block_q4_K;
+
+void dq_q4(device const block_q4_K *xb, short il, thread float *out) {
+ device const uchar * q = xb->qs;
+ short is = (il/4) * 2;
+ q = q + (il/4) * 32 + 16 * (il&1);
+ short il2 = il & 3;
+ const uchar2 sc = get_scale_min_k4_just2(is, il2/2, xb->scales);
+ const float d = il2 < 2 ? xb->d : xb->d / 16.h;
+ const float min = xb->dmin;
+ const float dl = d * sc[0];
+ const float ml = min * sc[1];
+ const ushort mask = il2<2 ? 0x0F : 0xF0;
+ for (int i = 0; i < 16; ++i) out[i] = dl * (q[i] & mask) - ml;
+}
+
+void dq_q5(device const block_q5_K *xb, short il, thread float *out) {
+ device const uint8_t * q = xb->qs;
+ device const uint8_t * qh = xb->qh;
+ short is = (il/4) * 2;
+ q = q + 32 * (il/4) + 16 * (il&1);
+ qh = qh + 16 * (il&1);
+ uint8_t ul = 1 << (il/2);
+ short il2 = il & 3;
+ const uchar2 sc = get_scale_min_k4_just2(is, il2/2, xb->scales);
+ const float d = il2 < 2 ? xb->d : xb->d / 16.f;
+ const float min = xb->dmin;
+ const float dl = d * sc[0];
+ const float ml = min * sc[1];
+ const ushort mask = il2<2 ? 0x0F : 0xF0;
+ const float qh_val = il2<2 ? 16.f : 256.f;
+ for (int i = 0; i < 16; ++i) out[i] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml;
+}
+
+// Fit 256 values to a Q2_K block: per sub-block of 16, scale = (max-min)/3 and min; the 16 scales
+// and mins go to 4 bits against the block's largest; quants are 2 bits.
+// Weighted fit of one sub-block of 16: given a trial (scale, min), the quants are fixed by rounding,
+// then scale and min are re-solved by weighted least squares on those quants. Two rounds.
+static inline void fit16(thread const float *x, thread const float *w, thread float &scale, thread float &mn) {
+ for (int round = 0; round < 2; ++round) {
+ float sw = 0.f, swl = 0.f, swll = 0.f, swx = 0.f, swlx = 0.f;
+ for (int i = 0; i < 16; ++i) {
+ int l = 0;
+ if (scale > 0.f) { l = (int)((x[i] + mn) / scale + 0.5f); l = clamp(l, 0, 3); }
+ const float wi = w[i];
+ sw += wi; swl += wi * l; swll += wi * l * l; swx += wi * x[i]; swlx += wi * l * x[i];
+ }
+ // x ~ scale*l - mn : solve for (scale, mn) weighted
+ const float det = sw * swll - swl * swl;
+ if (det > 1e-12f) {
+ const float a = (sw * swlx - swl * swx) / det; // scale
+ const float b = (swl * swlx - swll * swx) / det; // = mn
+ if (a > 0.f && b >= 0.f) { scale = a; mn = b; }
+ }
+ }
+}
+
+void q2k_encode_w(thread const float *x, device const float *w, uint w_offset, device block_q2_K *y) {
+ float scales[16], mins[16];
+ float max_scale = 0.f, max_min = 0.f;
+ for (int j = 0; j < 16; ++j) {
+ float lo = x[16*j], hi = x[16*j];
+ for (int i = 1; i < 16; ++i) { lo = min(lo, x[16*j+i]); hi = max(hi, x[16*j+i]); }
+ if (lo > 0.f) lo = 0.f;
+ float sc = (hi - lo) / 3.f;
+ float mn = -lo;
+ float wl[16];
+ for (int i = 0; i < 16; ++i) wl[i] = sqrt(max(w[w_offset + 16*j + i], 0.f)) + 1e-6f;
+ fit16(x + 16*j, wl, sc, mn);
+ scales[j] = sc;
+ mins[j] = mn;
+ max_scale = max(max_scale, scales[j]);
+ max_min = max(max_min, mins[j]);
+ }
+ float inv_scale = max_scale > 0.f ? 15.f / max_scale : 0.f;
+ float inv_min = max_min > 0.f ? 15.f / max_min : 0.f;
+ uint8_t ls[16], lm[16];
+ for (int j = 0; j < 16; ++j) {
+ ls[j] = (uint8_t)min(15, (int)(scales[j] * inv_scale + 0.5f));
+ lm[j] = (uint8_t)min(15, (int)(mins[j] * inv_min + 0.5f));
+ y->scales[j] = ls[j] | (lm[j] << 4);
+ }
+ y->d = half(max_scale / 15.f);
+ y->dmin = half(max_min / 15.f);
+ const float d = float(y->d), dmin = float(y->dmin);
+ uint8_t L[256];
+ for (int j = 0; j < 16; ++j) {
+ const float dj = d * ls[j];
+ const float mj = dmin * lm[j];
+ for (int i = 0; i < 16; ++i) {
+ int l = 0;
+ if (dj > 0.f) { l = (int)((x[16*j+i] + mj) / dj + 0.5f); l = clamp(l, 0, 3); }
+ L[16*j+i] = (uint8_t)l;
+ }
+ }
+ for (int j = 0; j < QK_K; j += 128) {
+ for (int l = 0; l < 32; ++l) {
+ y->qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
+ }
+ }
+}
+
+void q2k_encode(thread const float *x, device block_q2_K *y) {
+ float scales[16], mins[16];
+ float max_scale = 0.f, max_min = 0.f;
+ const float ones[16] = {1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f};
+ for (int j = 0; j < 16; ++j) {
+ float lo = x[16*j], hi = x[16*j];
+ for (int i = 1; i < 16; ++i) { lo = min(lo, x[16*j+i]); hi = max(hi, x[16*j+i]); }
+ if (lo > 0.f) lo = 0.f;
+ float sc = (hi - lo) / 3.f;
+ float mn = -lo;
+ fit16(x + 16*j, ones, sc, mn);
+ scales[j] = sc;
+ mins[j] = mn;
+ max_scale = max(max_scale, scales[j]);
+ max_min = max(max_min, mins[j]);
+ }
+ float inv_scale = max_scale > 0.f ? 15.f / max_scale : 0.f;
+ float inv_min = max_min > 0.f ? 15.f / max_min : 0.f;
+ uint8_t ls[16], lm[16];
+ for (int j = 0; j < 16; ++j) {
+ ls[j] = (uint8_t)min(15, (int)(scales[j] * inv_scale + 0.5f));
+ lm[j] = (uint8_t)min(15, (int)(mins[j] * inv_min + 0.5f));
+ y->scales[j] = ls[j] | (lm[j] << 4);
+ }
+ y->d = half(max_scale / 15.f);
+ y->dmin = half(max_min / 15.f);
+ const float d = float(y->d), dmin = float(y->dmin);
+ uint8_t L[256];
+ for (int j = 0; j < 16; ++j) {
+ const float dj = d * ls[j];
+ const float mj = dmin * lm[j];
+ for (int i = 0; i < 16; ++i) {
+ int l = 0;
+ if (dj > 0.f) {
+ l = (int)((x[16*j+i] + mj) / dj + 0.5f);
+ l = clamp(l, 0, 3);
+ }
+ L[16*j+i] = (uint8_t)l;
+ }
+ }
+ for (int j = 0; j < QK_K; j += 128) {
+ for (int l = 0; l < 32; ++l) {
+ y->qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6);
+ }
+ }
+}
+
+kernel void coachwhip_requant_q3k_to_q2k(
+ device const block_q3_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q3(src + tid, il, x + 16*il);
+ q2k_encode(x, dst + tid);
+}
+
+kernel void coachwhip_requant_q3k_to_q2k_w(
+ device const block_q3_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ device const float *shape [[buffer(3)]],
+ constant uint& blocks_per_row [[buffer(4)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q3(src + tid, il, x + 16*il);
+ q2k_encode_w(x, shape, (tid % blocks_per_row) * 256, dst + tid);
+}
+
+kernel void coachwhip_requant_q4k_to_q2k(
+ device const block_q4_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q4(src + tid, il, x + 16*il);
+ q2k_encode(x, dst + tid);
+}
+
+kernel void coachwhip_requant_q4k_to_q2k_w(
+ device const block_q4_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ device const float *shape [[buffer(3)]],
+ constant uint& blocks_per_row [[buffer(4)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q4(src + tid, il, x + 16*il);
+ q2k_encode_w(x, shape, (tid % blocks_per_row) * 256, dst + tid);
+}
+
+kernel void coachwhip_requant_q5k_to_q2k(
+ device const block_q5_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q5(src + tid, il, x + 16*il);
+ q2k_encode(x, dst + tid);
+}
+
+kernel void coachwhip_requant_q5k_to_q2k_w(
+ device const block_q5_K *src [[buffer(0)]],
+ device block_q2_K *dst [[buffer(1)]],
+ constant uint& n_blocks [[buffer(2)]],
+ device const float *shape [[buffer(3)]],
+ constant uint& blocks_per_row [[buffer(4)]],
+ uint tid [[thread_position_in_grid]])
+{
+ if (tid >= n_blocks) return;
+ float x[256];
+ for (short il = 0; il < 16; ++il) dq_q5(src + tid, il, x + 16*il);
+ q2k_encode_w(x, shape, (tid % blocks_per_row) * 256, dst + tid);
+}
+"#;
+
+/// The shrink: two pipelines and a command queue of its own.
+/// Which quantisation the arriving bytes are in.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SrcKind {
+ Q3K,
+ Q4K,
+ Q5K,
+}
+
+impl SrcKind {
+ pub fn of(dtype: candle::quantized::GgmlDType) -> Option<Self> {
+ use candle::quantized::GgmlDType as G;
+ match dtype {
+ G::Q3K => Some(Self::Q3K),
+ G::Q4K => Some(Self::Q4K),
+ G::Q5K => Some(Self::Q5K),
+ _ => None,
+ }
+ }
+}
+
+pub struct Requant {
+ queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
+ q3: ComputePipeline,
+ q4: ComputePipeline,
+ q5: ComputePipeline,
+ q3w: ComputePipeline,
+ q4w: ComputePipeline,
+ q5w: ComputePipeline,
+}
+
+unsafe impl Send for Requant {}
+unsafe impl Sync for Requant {}
+
+impl Requant {
+ pub fn new(metal: &MetalDevice) -> Result<Self> {
+ let device: &Device = metal.device();
+ let lib = device.new_library_with_source(SOURCE, None).map_err(candle::MetalError::from)?;
+ let mut get = |name: &str| -> Result<ComputePipeline> {
+ let f = lib.get_function(name, None).map_err(candle::MetalError::from)?;
+ Ok(device.new_compute_pipeline_state_with_function(&f).map_err(candle::MetalError::from)?)
+ };
+ let q3 = get("coachwhip_requant_q3k_to_q2k")?;
+ let q4 = get("coachwhip_requant_q4k_to_q2k")?;
+ let q5 = get("coachwhip_requant_q5k_to_q2k")?;
+ let q3w = get("coachwhip_requant_q3k_to_q2k_w")?;
+ let q4w = get("coachwhip_requant_q4k_to_q2k_w")?;
+ let q5w = get("coachwhip_requant_q5k_to_q2k_w")?;
+ let queue = device.as_ref().newCommandQueue().ok_or_else(|| candle::Error::Msg("no Metal command queue for the shrink".into()))?;
+ Ok(Self { queue, q3, q4, q5, q3w, q4w, q5w })
+ }
+
+ /// Shrink `n_blocks` super-blocks from `src` (Q3_K or Q5_K bytes, from `src_offset`) into
+ /// `dst` at `dst_offset` (Q2_K bytes). Waits for the GPU, so the caller may mark the slot ready.
+ pub fn run(&self, kind: SrcKind, src: &Buffer, src_offset: usize, dst: &Buffer, dst_offset: usize, n_blocks: usize) -> Result<()> {
+ let cb = self.queue.commandBuffer().ok_or_else(|| candle::Error::Msg("no command buffer for the shrink".into()))?;
+ let enc = cb.computeCommandEncoder().ok_or_else(|| candle::Error::Msg("no encoder for the shrink".into()))?;
+ let pipe = match kind { SrcKind::Q3K => &self.q3, SrcKind::Q4K => &self.q4, SrcKind::Q5K => &self.q5 };
+ enc.setComputePipelineState(pipe.as_ref());
+ unsafe {
+ enc.setBuffer_offset_atIndex(Some(src.as_ref()), src_offset, 0);
+ enc.setBuffer_offset_atIndex(Some(dst.as_ref()), dst_offset, 1);
+ let n = n_blocks as u32;
+ enc.setBytes_length_atIndex(std::ptr::NonNull::new(&n as *const u32 as *mut std::ffi::c_void).unwrap(), 4, 2);
+ }
+ let tg = 64usize;
+ let groups = (n_blocks + tg - 1) / tg;
+ enc.dispatchThreadgroups_threadsPerThreadgroup(MTLSize { width: groups, height: 1, depth: 1 }, MTLSize { width: tg, height: 1, depth: 1 });
+ enc.endEncoding();
+ cb.commit();
+ unsafe { cb.waitUntilCompleted() };
+ Ok(())
+ }
+}
+
+impl Requant {
+ /// The shaped shrink: like `run`, but each input column's error is weighted by `shape`
+ /// (one float per column, `k` of them), the running importance of that column at this layer.
+ pub fn run_shaped(&self, kind: SrcKind, src: &Buffer, src_offset: usize, dst: &Buffer, dst_offset: usize, n_blocks: usize, shape: &Buffer, k: usize) -> Result<()> {
+ let cb = self.queue.commandBuffer().ok_or_else(|| candle::Error::Msg("no command buffer for the shrink".into()))?;
+ let enc = cb.computeCommandEncoder().ok_or_else(|| candle::Error::Msg("no encoder for the shrink".into()))?;
+ let pipe = match kind { SrcKind::Q3K => &self.q3w, SrcKind::Q4K => &self.q4w, SrcKind::Q5K => &self.q5w };
+ enc.setComputePipelineState(pipe.as_ref());
+ unsafe {
+ enc.setBuffer_offset_atIndex(Some(src.as_ref()), src_offset, 0);
+ enc.setBuffer_offset_atIndex(Some(dst.as_ref()), dst_offset, 1);
+ let n = n_blocks as u32;
+ enc.setBytes_length_atIndex(std::ptr::NonNull::new(&n as *const u32 as *mut std::ffi::c_void).unwrap(), 4, 2);
+ enc.setBuffer_offset_atIndex(Some(shape.as_ref()), 0, 3);
+ let bpr = (k / QK_K) as u32;
+ enc.setBytes_length_atIndex(std::ptr::NonNull::new(&bpr as *const u32 as *mut std::ffi::c_void).unwrap(), 4, 4);
+ }
+ let tg = 64usize;
+ let groups = (n_blocks + tg - 1) / tg;
+ enc.dispatchThreadgroups_threadsPerThreadgroup(MTLSize { width: groups, height: 1, depth: 1 }, MTLSize { width: tg, height: 1, depth: 1 });
+ enc.endEncoding();
+ cb.commit();
+ unsafe { cb.waitUntilCompleted() };
+ Ok(())
+ }
+}
+
+/// Lab timing, run by the `gpu_shrink` test: one expert's three matrices through the shrink.
+pub fn time_one_expert(metal: &MetalDevice, parts: &[(SrcKind, Vec<u8>, usize)]) -> Result<(f64, usize, usize)> {
+ let rq = Requant::new(metal)?;
+ let mut bytes_in = 0;
+ let mut bytes_out = 0;
+ let started = Instant::now();
+ for (kind, data, n_blocks) in parts {
+ let src = metal.new_buffer_builder().with_size(data.len()).with_label("shrink_src").build()?;
+ unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), src.contents() as *mut u8, data.len()) };
+ let dst = metal.new_buffer_builder().with_size(n_blocks * Q2K_BLOCK_BYTES).with_label("shrink_dst").build()?;
+ rq.run(*kind, &src, 0, &dst, 0, *n_blocks)?;
+ bytes_in += data.len();
+ bytes_out += n_blocks * Q2K_BLOCK_BYTES;
+ }
+ Ok((started.elapsed().as_secs_f64() * 1e3, bytes_in, bytes_out))
+}
diff --git a/crates/engine/tests/dequant_metal.rs b/crates/engine/tests/dequant_metal.rs
new file mode 100644
index 0000000..a8e7853
--- /dev/null
+++ b/crates/engine/tests/dequant_metal.rs
@@ -0,0 +1,33 @@
+//! Does Candle's Metal dequantize agree with the CPU for every type the 122B files use?
+
+use candle::quantized::{GgmlDType, QStorage, QTensor};
+use candle::{Device, Tensor};
+
+fn check(dtype: GgmlDType, shape: (usize, usize)) -> (f32, f32) {
+ let cpu = Device::Cpu;
+ let metal = Device::new_metal(0).expect("metal");
+ let w = Tensor::randn(0f32, 1.0, shape, &cpu).unwrap();
+ let q = QTensor::quantize(&w, dtype).unwrap();
+ let truth = q.dequantize(&cpu).unwrap();
+ let data = q.data().unwrap();
+ let qm = QTensor::new(QStorage::from_data(data, &metal, dtype).unwrap(), q.shape().clone()).unwrap();
+ let got = qm.dequantize(&metal).unwrap().to_device(&cpu).unwrap();
+ let diff = (&truth - &got).unwrap().abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
+ let scale = truth.abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
+ (diff, scale)
+}
+
+#[test]
+fn dequantize_metal_matches_cpu() {
+ let mut bad = vec![];
+ for (name, dtype) in [("Q2_K", GgmlDType::Q2K), ("Q3_K", GgmlDType::Q3K), ("Q4_K", GgmlDType::Q4K), ("Q5_K", GgmlDType::Q5K), ("Q6_K", GgmlDType::Q6K)] {
+ for shape in [(64, 1024), (3072, 8192)] {
+ let (d, s) = check(dtype, shape);
+ eprintln!("{name} {shape:?}: max diff {d:.5} of {s:.2}");
+ if d > s * 1e-3 {
+ bad.push(format!("{name} {shape:?}"));
+ }
+ }
+ }
+ assert!(bad.is_empty(), "metal dequantize differs from cpu: {bad:?}");
+}
diff --git a/crates/engine/tests/gpu_shrink.rs b/crates/engine/tests/gpu_shrink.rs
new file mode 100644
index 0000000..8758ae9
--- /dev/null
+++ b/crates/engine/tests/gpu_shrink.rs
@@ -0,0 +1,41 @@
+//! Lab timing: one expert of the official 122B file through the GPU shrink (Q3_K/Q5_K -> Q2_K).
+use candle::quantized::gguf_file;
+use candle::Device;
+use coachwhip_engine::requant::{time_one_expert, SrcKind, QK_K};
+use std::os::unix::fs::FileExt;
+
+#[test]
+fn gpu_shrink_one_expert() {
+ let path = std::env::var("COACHWHIP_JIT_MODEL").unwrap_or_default();
+ if path.is_empty() {
+ eprintln!("set COACHWHIP_JIT_MODEL to the official 122B gguf to run this timing");
+ return;
+ }
+ let dev = Device::new_metal(0).unwrap();
+ let Device::Metal(metal) = &dev else { panic!("metal") };
+ let mut file = std::fs::File::open(&path).unwrap();
+ let ct = gguf_file::Content::read(&mut file).unwrap();
+ let mut parts = Vec::new();
+ for m in ["gate", "up", "down"] {
+ let info = &ct.tensor_infos[&format!("blk.0.ffn_{m}_exps.weight")];
+ let dims = info.shape.dims().to_vec();
+ let per_expert: usize = dims[1..].iter().product();
+ let bytes = per_expert / info.ggml_dtype.block_size() * info.ggml_dtype.type_size();
+ let mut buf = vec![0u8; bytes];
+ file.read_exact_at(&mut buf, ct.tensor_data_offset + info.offset).unwrap();
+ let kind = SrcKind::of(info.ggml_dtype).unwrap_or_else(|| panic!("expert {m} is {:?}", info.ggml_dtype));
+ parts.push((kind, buf, per_expert / QK_K));
+ }
+ // warm the pipelines once, then time
+ let _ = time_one_expert(metal, &parts).unwrap();
+ let mut total = 0.0;
+ let reps = 20;
+ let (mut bi, mut bo) = (0, 0);
+ for _ in 0..reps {
+ let (ms, a, b) = time_one_expert(metal, &parts).unwrap();
+ total += ms;
+ bi = a;
+ bo = b;
+ }
+ eprintln!("GPU shrink, one expert: {:.2} MB -> {:.2} MB in {:.2} ms (mean of {reps}, includes buffer setup and the wait)", bi as f64 / 1e6, bo as f64 / 1e6, total / reps as f64);
+}
diff --git a/crates/engine/tests/jit_quant.rs b/crates/engine/tests/jit_quant.rs
new file mode 100644
index 0000000..71628cc
--- /dev/null
+++ b/crates/engine/tests/jit_quant.rs
@@ -0,0 +1,53 @@
+//! Lab timing: how long does it take to shrink one expert of the official 122B file from its
+//! Q3_K_M bytes to Q2_K on the CPU (dequantise, then quantise)? Decides whether just-in-time
+//! quantisation can ride on the reader threads or needs its own.
+use candle::quantized::{ggml_file::qtensor_from_ggml, gguf_file, GgmlDType, QTensor};
+use candle::Device;
+use std::os::unix::fs::FileExt;
+use std::time::Instant;
+
+#[test]
+fn jit_quant_one_expert() {
+ let path = std::env::var("COACHWHIP_JIT_MODEL").unwrap_or_default();
+ if path.is_empty() {
+ eprintln!("set COACHWHIP_JIT_MODEL to the official 122B gguf to run this timing");
+ return;
+ }
+ let mut file = std::fs::File::open(&path).unwrap();
+ let ct = gguf_file::Content::read(&mut file).unwrap();
+ let dev = Device::Cpu;
+ let mut total_dq = 0.0;
+ let mut total_q = 0.0;
+ let mut bytes_in = 0usize;
+ let mut bytes_out = 0usize;
+ for m in ["gate", "up", "down"] {
+ let info = &ct.tensor_infos[&format!("blk.0.ffn_{m}_exps.weight")];
+ let dims = info.shape.dims().to_vec();
+ let per_expert: usize = dims[1..].iter().product();
+ let bytes = per_expert / info.ggml_dtype.block_size() * info.ggml_dtype.type_size();
+ let mut buf = vec![0u8; bytes];
+ file.read_exact_at(&mut buf, ct.tensor_data_offset + info.offset).unwrap();
+ let t0 = Instant::now();
+ let q = qtensor_from_ggml(info.ggml_dtype, &buf, dims[1..].to_vec(), &dev).unwrap();
+ let f = q.dequantize(&dev).unwrap();
+ let dq = t0.elapsed().as_secs_f64() * 1e3;
+ let t1 = Instant::now();
+ let q2 = QTensor::quantize(&f, GgmlDType::Q2K).unwrap();
+ let qt = t1.elapsed().as_secs_f64() * 1e3;
+ let out = per_expert / GgmlDType::Q2K.block_size() * GgmlDType::Q2K.type_size();
+ eprintln!("{m}: {:?} {} MB -> Q2_K {} MB: dequantise {dq:.1} ms, quantise {qt:.1} ms", info.ggml_dtype, bytes as f64 / 1e6, out as f64 / 1e6);
+ let _ = q2;
+ total_dq += dq;
+ total_q += qt;
+ bytes_in += bytes;
+ bytes_out += out;
+ }
+ eprintln!(
+ "one expert: {:.2} MB -> {:.2} MB; dequantise {:.1} ms + quantise {:.1} ms = {:.1} ms on one CPU core",
+ bytes_in as f64 / 1e6,
+ bytes_out as f64 / 1e6,
+ total_dq,
+ total_q,
+ total_dq + total_q
+ );
+}
diff --git a/crates/engine/tests/lookahead.rs b/crates/engine/tests/lookahead.rs
index 4a22215..95ef38d 100644
--- a/crates/engine/tests/lookahead.rs
+++ b/crates/engine/tests/lookahead.rs
@@ -44,6 +44,11 @@ fn a_guess_is_stale_once_the_word_reaches_its_layer() {
assert!(is_stale(5, 7, 8, 7), "the word has passed that layer");
}
+#[test]
+fn a_guess_for_the_next_word_is_fresh_whatever_the_layer() {
+ assert!(!is_stale(3, 8, 40, 7), "foresight reads for the coming word must survive");
+}
+
#[test]
fn a_guess_from_an_earlier_word_is_stale_whatever_its_layer() {
assert!(is_stale(40, 6, 3, 7));
diff --git a/crates/engine/tests/q2_gap.rs b/crates/engine/tests/q2_gap.rs
new file mode 100644
index 0000000..79dac90
--- /dev/null
+++ b/crates/engine/tests/q2_gap.rs
@@ -0,0 +1,62 @@
+//! How much worse is the GPU shrink's Q2_K than candle's own Q2_K quantiser, on the same expert?
+use candle::quantized::{ggml_file::qtensor_from_ggml, gguf_file, GgmlDType, QTensor};
+use candle::Device;
+use coachwhip_engine::requant::{Requant, SrcKind, Q2K_BLOCK_BYTES, QK_K};
+use std::os::unix::fs::FileExt;
+
+fn rel_err(a: &[f32], b: &[f32]) -> f64 {
+ let (mut se, mut tr) = (0.0f64, 0.0f64);
+ for (x, y) in a.iter().zip(b.iter()) {
+ let d = (*x - *y) as f64;
+ se += d * d;
+ tr += (*y as f64) * (*y as f64);
+ }
+ (se / tr).sqrt()
+}
+
+#[test]
+fn gpu_q2_vs_candle_q2() {
+ let path = std::env::var("COACHWHIP_JIT_MODEL").unwrap_or_default();
+ if path.is_empty() {
+ return;
+ }
+ let dev = Device::new_metal(0).unwrap();
+ let Device::Metal(metal) = &dev else { panic!("metal") };
+ let rq = Requant::new(metal).unwrap();
+ let mut file = std::fs::File::open(&path).unwrap();
+ let ct = gguf_file::Content::read(&mut file).unwrap();
+ for (layer, m) in [(0, "gate"), (0, "up"), (0, "down"), (20, "gate"), (20, "down")] {
+ let info = &ct.tensor_infos[&format!("blk.{layer}.ffn_{m}_exps.weight")];
+ let dims = info.shape.dims().to_vec();
+ let (n, k) = (dims[1], dims[2]);
+ let per_expert = n * k;
+ let bytes = per_expert / info.ggml_dtype.block_size() * info.ggml_dtype.type_size();
+ let mut buf = vec![0u8; bytes];
+ file.read_exact_at(&mut buf, ct.tensor_data_offset + info.offset).unwrap();
+ let truth_q = qtensor_from_ggml(info.ggml_dtype, &buf, vec![n, k], &Device::Cpu).unwrap();
+ let truth_t = truth_q.dequantize(&Device::Cpu).unwrap();
+ let truth: Vec<f32> = truth_t.flatten_all().unwrap().to_vec1().unwrap();
+ // candle's own Q2_K on the CPU
+ let cq = QTensor::quantize(&truth_t, GgmlDType::Q2K).unwrap();
+ let candle_back: Vec<f32> = cq.dequantize(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1().unwrap();
+ // the GPU shrink
+ let kind = SrcKind::of(info.ggml_dtype).unwrap();
+ let n_blocks = per_expert / QK_K;
+ let src = metal.new_buffer_builder().with_size(bytes).with_label("src").build().unwrap();
+ unsafe { std::ptr::copy_nonoverlapping(buf.as_ptr(), src.contents() as *mut u8, bytes) };
+ let dst = metal.new_buffer_builder().with_size(n_blocks * Q2K_BLOCK_BYTES).with_label("dst").build().unwrap();
+ rq.run(kind, &src, 0, &dst, 0, n_blocks).unwrap();
+ let q2 = unsafe { std::slice::from_raw_parts(dst.contents() as *const u8, n_blocks * Q2K_BLOCK_BYTES) }.to_vec();
+ let gpu_back: Vec<f32> = qtensor_from_ggml(GgmlDType::Q2K, &q2, vec![n, k], &Device::Cpu).unwrap().dequantize(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1().unwrap();
+ // and candle's Q3_K, as the yardstick for what "keep it at Q3" costs
+ let c3 = QTensor::quantize(&truth_t, GgmlDType::Q3K).unwrap();
+ let c3_back: Vec<f32> = c3.dequantize(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1().unwrap();
+ eprintln!(
+ "layer {layer} {m} ({:?}): candle Q2_K error {:.3}, GPU shrink Q2_K error {:.3}, candle Q3_K error {:.3}",
+ info.ggml_dtype,
+ rel_err(&candle_back, &truth),
+ rel_err(&gpu_back, &truth),
+ rel_err(&c3_back, &truth)
+ );
+ }
+}
diff --git a/crates/engine/tests/q2k_metal.rs b/crates/engine/tests/q2k_metal.rs
new file mode 100644
index 0000000..3d20083
--- /dev/null
+++ b/crates/engine/tests/q2k_metal.rs
@@ -0,0 +1,27 @@
+//! Does Candle's Metal Q2_K matvec agree with the CPU? Q3_K as the control.
+
+use candle::quantized::{GgmlDType, QMatMul, QTensor};
+use candle::{Device, Module, Tensor};
+
+fn check(dtype: GgmlDType) -> (f32, f32) {
+ let cpu = Device::Cpu;
+ let metal = Device::new_metal(0).expect("metal");
+ let w = Tensor::randn(0f32, 1.0, (512, 1024), &cpu).unwrap();
+ let x = Tensor::randn(0f32, 1.0, (1, 1024), &cpu).unwrap();
+ let qw = QTensor::quantize(&w, dtype).unwrap();
+ let truth = QMatMul::from_qtensor(qw).unwrap().forward(&x).unwrap();
+ let qm = QTensor::quantize(&w.to_device(&metal).unwrap(), dtype).unwrap();
+ let got = QMatMul::from_qtensor(qm).unwrap().forward(&x.to_device(&metal).unwrap()).unwrap().to_device(&cpu).unwrap();
+ let diff = (&truth - &got).unwrap().abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
+ let scale = truth.abs().unwrap().max_all().unwrap().to_scalar::<f32>().unwrap();
+ (diff, scale)
+}
+
+#[test]
+fn q2k_metal_matches_cpu() {
+ let (d3, s3) = check(GgmlDType::Q3K);
+ let (d2, s2) = check(GgmlDType::Q2K);
+ eprintln!("Q3_K: max diff {d3:.4} of {s3:.2}; Q2_K: max diff {d2:.4} of {s2:.2}");
+ assert!(d3 < s3 * 0.05, "Q3_K metal differs from cpu");
+ assert!(d2 < s2 * 0.05, "Q2_K metal differs from cpu");
+}
diff --git a/crates/engine/tests/shape_check.rs b/crates/engine/tests/shape_check.rs
new file mode 100644
index 0000000..997e7c5
--- /dev/null
+++ b/crates/engine/tests/shape_check.rs
@@ -0,0 +1,78 @@
+//! Does the shaped shrink reconstruct an expert better than the plain one, measured against the
+//! file's own values, weighted by a real token shape? Offline, one expert, no engine run.
+use candle::quantized::{ggml_file::qtensor_from_ggml, gguf_file, GgmlDType};
+use candle::{Device, Tensor};
+use coachwhip_engine::requant::{Requant, SrcKind, Q2K_BLOCK_BYTES, QK_K};
+use std::os::unix::fs::FileExt;
+
+fn dequant_bytes(dtype: GgmlDType, bytes: &[u8], dims: Vec<usize>, dev: &Device) -> Vec<f32> {
+ let q = qtensor_from_ggml(dtype, bytes, dims, dev).unwrap();
+ q.dequantize(dev).unwrap().to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::<f32>().unwrap()
+}
+
+#[test]
+fn shaped_vs_plain_reconstruction() {
+ let path = std::env::var("COACHWHIP_JIT_MODEL").unwrap_or_default();
+ let shape_path = std::env::var("COACHWHIP_SHAPE_FILE").unwrap_or_default();
+ if path.is_empty() || shape_path.is_empty() {
+ eprintln!("set COACHWHIP_JIT_MODEL and COACHWHIP_SHAPE_FILE (f32 x^2 over the hidden size, layer 0)");
+ return;
+ }
+ let dev = Device::new_metal(0).unwrap();
+ let Device::Metal(metal) = &dev else { panic!("metal") };
+ let rq = Requant::new(metal).unwrap();
+ let mut file = std::fs::File::open(&path).unwrap();
+ let ct = gguf_file::Content::read(&mut file).unwrap();
+ let shape: Vec<f32> = std::fs::read(&shape_path).unwrap().chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect();
+ for m in ["gate", "up"] {
+ let info = &ct.tensor_infos[&format!("blk.0.ffn_{m}_exps.weight")];
+ let dims = info.shape.dims().to_vec(); // (experts, n, k)
+ let (n, k) = (dims[1], dims[2]);
+ assert_eq!(k, shape.len(), "shape length");
+ let per_expert = n * k;
+ let bytes = per_expert / info.ggml_dtype.block_size() * info.ggml_dtype.type_size();
+ let mut buf = vec![0u8; bytes];
+ file.read_exact_at(&mut buf, ct.tensor_data_offset + info.offset).unwrap();
+ let kind = SrcKind::of(info.ggml_dtype).unwrap();
+ let n_blocks = per_expert / QK_K;
+ let truth = dequant_bytes(info.ggml_dtype, &buf, vec![n, k], &dev);
+ let src = metal.new_buffer_builder().with_size(bytes).with_label("src").build().unwrap();
+ unsafe { std::ptr::copy_nonoverlapping(buf.as_ptr(), src.contents() as *mut u8, bytes) };
+ let out_bytes = n_blocks * Q2K_BLOCK_BYTES;
+ let mut results = Vec::new();
+ for shaped in [false, true] {
+ let dst = metal.new_buffer_builder().with_size(out_bytes).with_label("dst").build().unwrap();
+ if shaped {
+ let sb = metal.new_buffer_builder().with_size(k * 4).with_label("shape").build().unwrap();
+ unsafe { std::ptr::copy_nonoverlapping(shape.as_ptr() as *const u8, sb.contents() as *mut u8, k * 4) };
+ rq.run_shaped(kind, &src, 0, &dst, 0, n_blocks, &sb, k).unwrap();
+ } else {
+ rq.run(kind, &src, 0, &dst, 0, n_blocks).unwrap();
+ }
+ let q2 = unsafe { std::slice::from_raw_parts(dst.contents() as *const u8, out_bytes) }.to_vec();
+ let back = dequant_bytes(GgmlDType::Q2K, &q2, vec![n, k], &dev);
+ // errors: plain squared error, and squared error weighted by the shape per column
+ let (mut se, mut wse, mut ref_w) = (0.0f64, 0.0f64, 0.0f64);
+ for r in 0..n {
+ for c in 0..k {
+ let i = r * k + c;
+ let d = (back[i] - truth[i]) as f64;
+ se += d * d;
+ wse += d * d * shape[c] as f64;
+ ref_w += (truth[i] as f64).powi(2) * shape[c] as f64;
+ }
+ }
+ let tr: f64 = truth.iter().map(|v| (*v as f64).powi(2)).sum();
+ results.push((shaped, (se / tr).sqrt(), (wse / ref_w).sqrt()));
+ }
+ // the output of the expert on a random-ish token: y = W x, compare directions
+ let x: Vec<f32> = shape.iter().map(|s| s.sqrt()).collect();
+ let xt = Tensor::from_vec(x, (k, 1), &Device::Cpu).unwrap();
+ let wt = Tensor::from_vec(truth.clone(), (n, k), &Device::Cpu).unwrap();
+ let y_true = wt.matmul(&xt).unwrap().flatten_all().unwrap().to_vec1::<f32>().unwrap();
+ for (shaped, rel, wrel) in &results {
+ eprintln!("{m}: shaped={shaped}: relative error {:.3}, shape-weighted relative error {:.3}", rel, wrel);
+ }
+ let _ = y_true;
+ }
+}
diff --git a/crates/prepare/Cargo.toml b/crates/prepare/Cargo.toml
new file mode 100644
index 0000000..77209dd
--- /dev/null
+++ b/crates/prepare/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "coachwhip-prepare"
+description = "Prepare a model file for Coachwhip: rewrite the experts of a GGUF for speed on a 16 GB Mac."
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[[bin]]
+name = "coachwhip-prepare"
+path = "src/main.rs"
+
+[dependencies]
+candle.workspace = true
+anyhow.workspace = true
+byteorder = "1"
diff --git a/crates/prepare/src/main.rs b/crates/prepare/src/main.rs
new file mode 100644
index 0000000..90d7ae9
--- /dev/null
+++ b/crates/prepare/src/main.rs
@@ -0,0 +1,205 @@
+//! Prepare a GGUF for Coachwhip: rewrite the expert tensors for speed on a 16 GB Mac and copy
+//! everything else untouched, streaming, so the whole model never sits in memory.
+//!
+//! coachwhip-prepare <in.gguf> <out.gguf>
+
+use anyhow::{bail, Context, Result};
+use byteorder::{LittleEndian, WriteBytesExt};
+use candle::quantized::gguf_file::{Content, Value, ValueType};
+use candle::quantized::{GgmlDType, QStorage, QTensor};
+use candle::Device;
+use std::borrow::Cow;
+use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
+use std::time::Instant;
+
+/// What each tensor becomes. The experts carry the bytes per word; the rest stays as it came.
+fn target(name: &str, dtype: GgmlDType) -> GgmlDType {
+ if name.ends_with(".ffn_gate_exps.weight") || name.ends_with(".ffn_up_exps.weight") {
+ GgmlDType::Q2K
+ } else if name.ends_with(".ffn_down_exps.weight") {
+ GgmlDType::Q3K
+ } else {
+ dtype
+ }
+}
+
+fn value_type_code(t: ValueType) -> u32 {
+ match t {
+ ValueType::U8 => 0,
+ ValueType::I8 => 1,
+ ValueType::U16 => 2,
+ ValueType::I16 => 3,
+ ValueType::U32 => 4,
+ ValueType::I32 => 5,
+ ValueType::F32 => 6,
+ ValueType::Bool => 7,
+ ValueType::String => 8,
+ ValueType::Array => 9,
+ ValueType::U64 => 10,
+ ValueType::I64 => 11,
+ ValueType::F64 => 12,
+ }
+}
+
+fn write_string<W: Write>(w: &mut W, s: &str) -> Result<()> {
+ w.write_u64::<LittleEndian>(s.len() as u64)?;
+ w.write_all(s.as_bytes())?;
+ Ok(())
+}
+
+fn write_value<W: Write>(w: &mut W, v: &Value) -> Result<()> {
+ match v {
+ Value::U8(x) => w.write_u8(*x)?,
+ Value::I8(x) => w.write_i8(*x)?,
+ Value::U16(x) => w.write_u16::<LittleEndian>(*x)?,
+ Value::I16(x) => w.write_i16::<LittleEndian>(*x)?,
+ Value::U32(x) => w.write_u32::<LittleEndian>(*x)?,
+ Value::I32(x) => w.write_i32::<LittleEndian>(*x)?,
+ Value::U64(x) => w.write_u64::<LittleEndian>(*x)?,
+ Value::I64(x) => w.write_i64::<LittleEndian>(*x)?,
+ Value::F32(x) => w.write_f32::<LittleEndian>(*x)?,
+ Value::F64(x) => w.write_f64::<LittleEndian>(*x)?,
+ Value::Bool(x) => w.write_u8(u8::from(*x))?,
+ Value::String(s) => write_string(w, s)?,
+ Value::Array(items) => {
+ let t = items.first().map(|i| i.value_type()).unwrap_or(ValueType::U32);
+ w.write_u32::<LittleEndian>(value_type_code(t))?;
+ w.write_u64::<LittleEndian>(items.len() as u64)?;
+ for item in items {
+ write_value(w, item)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+/// GGUF's type codes (Candle keeps its own mapping crate-private).
+fn dtype_code(d: GgmlDType) -> u32 {
+ match d {
+ GgmlDType::F32 => 0,
+ GgmlDType::F16 => 1,
+ GgmlDType::Q4_0 => 2,
+ GgmlDType::Q4_1 => 3,
+ GgmlDType::Q5_0 => 6,
+ GgmlDType::Q5_1 => 7,
+ GgmlDType::Q8_0 => 8,
+ GgmlDType::Q8_1 => 9,
+ GgmlDType::Q2K => 10,
+ GgmlDType::Q3K => 11,
+ GgmlDType::Q4K => 12,
+ GgmlDType::Q5K => 13,
+ GgmlDType::Q6K => 14,
+ GgmlDType::Q8K => 15,
+ GgmlDType::BF16 => 30,
+ }
+}
+
+fn bytes_for(dtype: GgmlDType, elems: usize) -> usize {
+ elems / dtype.block_size() * dtype.type_size()
+}
+
+fn pad_to(w: &mut impl Write, pos: u64, align: u64) -> Result<u64> {
+ let padding = (align - pos % align) % align;
+ if padding > 0 {
+ w.write_all(&vec![0u8; padding as usize])?;
+ }
+ Ok(pos + padding)
+}
+
+fn main() -> Result<()> {
+ let args: Vec<String> = std::env::args().collect();
+ if args.len() != 3 {
+ bail!("usage: coachwhip-prepare <in.gguf> <out.gguf>");
+ }
+ let (src_path, dst_path) = (&args[1], &args[2]);
+ let mut src = std::fs::File::open(src_path).with_context(|| format!("opening {src_path}"))?;
+ let content = Content::read(&mut src).context("reading the GGUF header")?;
+ let align = match content.metadata.get("general.alignment") {
+ Some(Value::U32(a)) => *a as u64,
+ _ => 32,
+ };
+
+ // Tensors in the order they sit in the source file.
+ let mut infos: Vec<(&String, &candle::quantized::gguf_file::TensorInfo)> = content.tensor_infos.iter().collect();
+ infos.sort_by_key(|(_, i)| i.offset);
+
+ // New offsets, from the new sizes.
+ let mut new_offsets = Vec::with_capacity(infos.len());
+ let mut offset = 0u64;
+ let mut changed = 0usize;
+ for (name, info) in &infos {
+ let to = target(name, info.ggml_dtype);
+ if to != info.ggml_dtype {
+ changed += 1;
+ }
+ new_offsets.push(offset);
+ offset += bytes_for(to, info.shape.elem_count()) as u64;
+ offset = (offset + align - 1) / align * align;
+ }
+ eprintln!("coachwhip-prepare: {} tensors, {changed} to rewrite, {:.1} GB out", infos.len(), offset as f64 / 1e9);
+
+ let out = std::fs::File::create(dst_path).with_context(|| format!("creating {dst_path}"))?;
+ let mut w = BufWriter::with_capacity(16 << 20, out);
+ // Header.
+ w.write_u32::<LittleEndian>(0x4655_4747)?;
+ w.write_u32::<LittleEndian>(3)?;
+ w.write_u64::<LittleEndian>(infos.len() as u64)?;
+ w.write_u64::<LittleEndian>(content.metadata.len() as u64)?;
+ let mut keys: Vec<&String> = content.metadata.keys().collect();
+ keys.sort();
+ for k in keys {
+ let v = &content.metadata[k];
+ write_string(&mut w, k)?;
+ w.write_u32::<LittleEndian>(value_type_code(v.value_type()))?;
+ write_value(&mut w, v)?;
+ }
+ for ((name, info), new_off) in infos.iter().zip(&new_offsets) {
+ write_string(&mut w, name)?;
+ let dims = info.shape.dims();
+ w.write_u32::<LittleEndian>(dims.len() as u32)?;
+ for &d in dims.iter().rev() {
+ w.write_u64::<LittleEndian>(d as u64)?;
+ }
+ w.write_u32::<LittleEndian>(dtype_code(target(name, info.ggml_dtype)))?;
+ w.write_u64::<LittleEndian>(*new_off)?;
+ }
+ w.flush()?;
+ let pos = w.get_ref().metadata()?.len();
+ let data_start = pad_to(&mut w, pos, align)?;
+
+ // Data, tensor by tensor.
+ let started = Instant::now();
+ let mut written = data_start;
+ let total = infos.len();
+ for (i, ((name, info), new_off)) in infos.iter().zip(&new_offsets).enumerate() {
+ let expect = data_start + new_off;
+ if written != expect {
+ bail!("offset drift at {name}: at {written}, expected {expect}");
+ }
+ let elems = info.shape.elem_count();
+ let src_len = bytes_for(info.ggml_dtype, elems);
+ src.seek(SeekFrom::Start(content.tensor_data_offset + info.offset))?;
+ let mut buf = vec![0u8; src_len];
+ src.read_exact(&mut buf).with_context(|| format!("reading {name}"))?;
+ let to = target(name, info.ggml_dtype);
+ if to == info.ggml_dtype {
+ w.write_all(&buf)?;
+ written += src_len as u64;
+ } else {
+ let storage = QStorage::from_data(Cow::Owned(buf), &Device::Cpu, info.ggml_dtype)?;
+ let q = QTensor::new(storage, info.shape.clone())?;
+ let f = q.dequantize(&Device::Cpu)?;
+ let q2 = QTensor::quantize(&f, to)?;
+ let data = q2.data()?;
+ w.write_all(&data)?;
+ written += data.len() as u64;
+ }
+ written = pad_to(&mut w, written, align)?;
+ if i % 10 == 0 || i + 1 == total {
+ eprintln!("coachwhip-prepare: {}/{} tensors, {:.1} GB written, {:.0} s", i + 1, total, (written as f64) / 1e9, started.elapsed().as_secs_f64());
+ }
+ }
+ w.flush()?;
+ eprintln!("coachwhip-prepare: done, {:.1} GB in {:.0} s", written as f64 / 1e9, started.elapsed().as_secs_f64());
+ Ok(())
+}
diff --git a/crates/server/src/chat.rs b/crates/server/src/chat.rs
index 50cc602..8ba99d4 100644
--- a/crates/server/src/chat.rs
+++ b/crates/server/src/chat.rs
@@ -94,6 +94,13 @@ pub struct Answer {
/// Runs the model and hands every new piece of text to `emit` as soon as it exists.
#[allow(clippy::too_many_arguments)]
+
+/// Foresight (lab): COACHWHIP_FORESIGHT=N drafts N words from the bank before each real word, only
+/// to start the reads those words will need; the text is unchanged.
+fn foresight() -> usize {
+ std::env::var("COACHWHIP_FORESIGHT").ok().and_then(|v| v.parse().ok()).unwrap_or(0)
+}
+
pub fn generate(
model: &mut Model,
tokenizer: &Tokenizer,
@@ -232,7 +239,41 @@ fn answer(
};
stream_text(&out, &mut sent)?;
let t1 = std::time::Instant::now();
+ // S6 (lab): COACHWHIP_SPECULATE=K drafts K words from the bank and checks them in one pass;
+ // COACHWHIP_SPECULATE_MEASURE=K only measures, writing the answer the plain way.
+ let speculate: usize = std::env::var("COACHWHIP_SPECULATE").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
+ let measure: usize = std::env::var("COACHWHIP_SPECULATE_MEASURE").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
+ let greedy = matches!(sampling, Sampling::ArgMax);
while out.len() < max_new && next != eos {
+ if speculate > 0 && greedy && max_new - out.len() > speculate {
+ if let Some(seq) = model.speculate(next, base + out.len() - 1, speculate)? {
+ for &w in &seq {
+ next = w;
+ if w == eos {
+ break;
+ }
+ out.push(w);
+ stream_text(&out, &mut sent)?;
+ }
+ continue;
+ }
+ }
+ if measure > 0 && greedy && max_new - out.len() >= measure {
+ if let Some((plain, _accepted)) = model.speculate_measure(next, base + out.len() - 1, measure)? {
+ for &w in &plain {
+ next = w;
+ if w == eos {
+ break;
+ }
+ out.push(w);
+ stream_text(&out, &mut sent)?;
+ }
+ continue;
+ }
+ }
+ if foresight() > 0 {
+ model.foresee(next, base + out.len() - 1, foresight())?;
+ }
let logits = model.forward(&Tensor::new(&[next], device)?.unsqueeze(0)?, base + out.len() - 1)?.squeeze(0)?;
next = sampler.sample(&logits)?;
if next != eos {
@@ -304,6 +345,9 @@ fn summarise(model: &mut Model, tokenizer: &Tokenizer, device: &Device, session:
(t.borrow_mut())(Step::Summary(out.len()));
}
}
+ if foresight() > 0 {
+ model.foresee(next, base + out.len() - 1, foresight())?;
+ }
let logits = model.forward(&Tensor::new(&[next], device)?.unsqueeze(0)?, base + out.len() - 1)?.squeeze(0)?;
next = sampler.sample(&logits)?;
}
diff --git a/vendor/candle-metal-kernels/Cargo.toml b/vendor/candle-metal-kernels/Cargo.toml
new file mode 100644
index 0000000..6756d91
--- /dev/null
+++ b/vendor/candle-metal-kernels/Cargo.toml
@@ -0,0 +1,45 @@
+[package]
+name = "candle-metal-kernels"
+version = "0.11.0"
+edition = "2021"
+
+description = "Metal kernels for Candle"
+repository = "https://github.com/huggingface/candle"
+keywords = ["blas", "tensor", "machine-learning"]
+categories = ["science"]
+license = "MIT OR Apache-2.0"
+
+
+[features]
+default = []
+# Emit per-dispatch Metal debug groups for Xcode GPU captures / Instruments.
+debug-labels = []
+
+[dependencies]
+half = { version = "2.5.0", features = [
+ "num-traits",
+ "use-intrinsics",
+ "rand_distr",
+] }
+once_cell = "1.21"
+thiserror = "2"
+tracing = "0.1.41"
+objc2-metal = { version = "0.3.2", features = ["block2"] }
+block2 = { version = ">=0.6.1, <0.8.0", features = ["alloc"], default-features = false }
+objc2 = "0.6.3"
+objc2-foundation = "0.3.2"
+
+[dev-dependencies]
+clap = { version = "4.5.49", features = ["derive"] }
+half = { version = "2.7.1", features = [
+ "num-traits",
+ "use-intrinsics",
+ "rand_distr",
+] }
+anyhow = "1"
+rand = "0.9.2"
+rand_distr = "0.5.1"
+
+[profile.profiling]
+inherits = "release"
+debug = 2
diff --git a/vendor/candle-metal-kernels/README.md b/vendor/candle-metal-kernels/README.md
new file mode 100644
index 0000000..ec923e9
--- /dev/null
+++ b/vendor/candle-metal-kernels/README.md
@@ -0,0 +1,3 @@
+# candle-metal-kernels
+
+This crate contains Metal kernels used from candle.
\ No newline at end of file
diff --git a/vendor/candle-metal-kernels/examples/metal_benchmarks.rs b/vendor/candle-metal-kernels/examples/metal_benchmarks.rs
new file mode 100644
index 0000000..f338ee8
--- /dev/null
+++ b/vendor/candle-metal-kernels/examples/metal_benchmarks.rs
@@ -0,0 +1,129 @@
+use anyhow::Result;
+use candle_metal_kernels::{
+ metal::{Commands, Device, ResidencySet},
+ GemmDType, RESOURCE_OPTIONS,
+};
+/// This example contains some simple benchmarks so that it's easy to run them in perf etc.
+use clap::{Parser, Subcommand};
+use half::f16;
+
+fn run_gemm(f32: bool, n: usize) -> Result<()> {
+ const WARMUP_ITERS: usize = 2;
+ const MIN_DUR: f64 = 4.;
+
+ let device = Device::system_default().unwrap();
+
+ let (b, m, n, k) = (1, n, n, n);
+ let kernels = candle_metal_kernels::Kernels::new();
+ let residency_set = std::sync::Arc::new(ResidencySet::new(&device));
+ let options = RESOURCE_OPTIONS;
+
+ let (lhs, rhs) = if f32 {
+ let lhs: Vec<f32> = (0..b * m * k).map(|f| f as f32).collect();
+ let rhs: Vec<f32> = (0..b * n * k).map(|f| f as f32).collect();
+ let lhs = device
+ .new_buffer_with_data(
+ lhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(&lhs),
+ options,
+ )
+ .unwrap();
+ let rhs = device
+ .new_buffer_with_data(
+ rhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(&rhs),
+ options,
+ )
+ .unwrap();
+ (lhs, rhs)
+ } else {
+ let lhs: Vec<f16> = (0..b * m * k).map(|f| f16::from_f32(f as f32)).collect();
+ let rhs: Vec<f16> = (0..b * n * k).map(|f| f16::from_f32(f as f32)).collect();
+ let lhs = device
+ .new_buffer_with_data(
+ lhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(&lhs),
+ options,
+ )
+ .unwrap();
+ let rhs = device
+ .new_buffer_with_data(
+ rhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(&rhs),
+ options,
+ )
+ .unwrap();
+ (lhs, rhs)
+ };
+ let (dtype, sizeof) = if f32 {
+ (GemmDType::F32, core::mem::size_of::<f32>())
+ } else {
+ (GemmDType::F16, core::mem::size_of::<f16>())
+ };
+ let output = device.new_buffer(b * m * n * sizeof, options).unwrap();
+
+ let mut sum_dt = 0f64;
+ let mut iters = 0usize;
+ for idx in 0.. {
+ let command_queue = device.new_command_queue().unwrap();
+ let commands = Commands::new(command_queue, &residency_set).unwrap();
+ let encoder = commands.command_encoder().unwrap();
+ let start_time = std::time::Instant::now();
+ candle_metal_kernels::call_mlx_gemm(
+ &device,
+ &encoder,
+ &kernels,
+ dtype,
+ (b, m, n, k),
+ &[m * k, k, 1],
+ 0,
+ &lhs,
+ &[n * k, n, 1],
+ 0,
+ &rhs,
+ &output,
+ )?;
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ let dt = start_time.elapsed().as_secs_f64();
+ if idx < WARMUP_ITERS {
+ continue;
+ }
+ sum_dt += dt;
+ iters += 1;
+ if sum_dt > MIN_DUR {
+ break;
+ }
+ }
+ let gflops = (2 * n * n * n * iters) as f64 / (1e9 * sum_dt);
+ println!("{dtype:?}, {n:6} gflops {gflops:.0}");
+
+ Ok(())
+}
+
+#[derive(Subcommand, Debug, Clone)]
+enum Task {
+ Gemm,
+}
+
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+pub struct Args {
+ /// The benchmark to be run.
+ #[command(subcommand)]
+ task: Task,
+}
+
+fn main() -> Result<()> {
+ let args = Args::parse();
+ match args.task {
+ Task::Gemm => {
+ for f32 in [false, true] {
+ for n in [512, 1024, 2048, 4096] {
+ run_gemm(f32, n)?;
+ }
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/err.rs b/vendor/candle-metal-kernels/src/err.rs
new file mode 100644
index 0000000..46a822b
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/err.rs
@@ -0,0 +1,65 @@
+use crate::kernels::sdpa::SdpaDType;
+
+#[derive(thiserror::Error, Debug)]
+pub enum MetalKernelError {
+ #[error("Command buffer had following error: {0}")]
+ CommandBufferError(String),
+ #[error("Could not lock resource: {0}")]
+ LockError(String),
+ #[error("Error while loading library: {0}")]
+ LoadLibraryError(String),
+ #[error("Error while loading function: {0}")]
+ LoadFunctionError(String),
+ #[error("Unsupported dtype {0} for operation {1}")]
+ UnsupportedDTypeForOp(&'static str, &'static str),
+ #[error("Failed to create compute function")]
+ FailedToCreateComputeFunction,
+ #[error("Invalid input: {0}")]
+ InvalidInput(String),
+ #[error("Failed to create metal resource: {0}")]
+ FailedToCreateResource(String),
+ #[error("Failed to create pipeline")]
+ FailedToCreatePipeline(String),
+ #[error("Invalid matmul arguments {lhs_stride:?} {rhs_stride:?} {mnk:?}")]
+ MatMulNonContiguous {
+ lhs_stride: Vec<usize>,
+ rhs_stride: Vec<usize>,
+ mnk: (usize, usize, usize),
+ },
+ #[error("Sdpa {variation} head size was {got}, expectd {expected:?}")]
+ SdpaHeadSizeMismatch {
+ variation: &'static str,
+ got: usize,
+ expected: Vec<usize>,
+ },
+ #[error("Sdpa {variation} got dtype {got:?}")]
+ SdpaHeadDTypeMismatch {
+ variation: &'static str,
+ got: SdpaDType,
+ },
+ #[error("{inner}\n{backtrace}")]
+ WithBacktrace {
+ inner: Box<Self>,
+ backtrace: Box<std::backtrace::Backtrace>,
+ },
+}
+
+impl MetalKernelError {
+ pub fn bt(self) -> Self {
+ let backtrace = std::backtrace::Backtrace::capture();
+ match backtrace.status() {
+ std::backtrace::BacktraceStatus::Disabled
+ | std::backtrace::BacktraceStatus::Unsupported => self,
+ _ => Self::WithBacktrace {
+ inner: Box::new(self),
+ backtrace: Box::new(backtrace),
+ },
+ }
+ }
+}
+
+impl<T> From<std::sync::PoisonError<T>> for MetalKernelError {
+ fn from(e: std::sync::PoisonError<T>) -> Self {
+ Self::LockError(e.to_string())
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/kernel.rs b/vendor/candle-metal-kernels/src/kernel.rs
new file mode 100644
index 0000000..ab95f84
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernel.rs
@@ -0,0 +1,260 @@
+use crate::source::{
+ AFFINE, BINARY, CAST, CONV, FILL, GEMV, INDEXING, MLX_GEMM, MLX_SORT, QUANTIZED, RANDOM,
+ REDUCE, SDPA, SORT, TERNARY, UNARY,
+};
+use crate::utils::get_env_bool;
+use crate::{
+ ComputePipeline, ConstantValues, Device, Function, Library, MTLCompileOptions,
+ MTLMathFloatingPointFunctions, MTLMathMode, MetalKernelError, Source,
+};
+use objc2::available;
+use objc2::rc::Retained;
+use std::collections::HashMap;
+use std::sync::RwLock;
+
+#[derive(Debug, Clone)]
+pub enum KernelName {
+ Ref(&'static str),
+ Value(String),
+}
+
+impl AsRef<str> for KernelName {
+ fn as_ref(&self) -> &str {
+ match self {
+ Self::Ref(r) => r,
+ Self::Value(v) => v.as_str(),
+ }
+ }
+}
+
+impl std::hash::Hash for KernelName {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ match self {
+ Self::Ref(r) => r.hash(state),
+ Self::Value(v) => v.hash(state),
+ }
+ }
+}
+
+impl PartialEq for KernelName {
+ fn eq(&self, other: &Self) -> bool {
+ let v1: &str = self.as_ref();
+ let v2: &str = other.as_ref();
+ v1 == v2
+ }
+}
+
+impl Eq for KernelName {}
+
+impl From<&'static str> for KernelName {
+ fn from(value: &'static str) -> Self {
+ Self::Ref(value)
+ }
+}
+
+impl From<String> for KernelName {
+ fn from(value: String) -> Self {
+ Self::Value(value)
+ }
+}
+
+type Libraries = HashMap<Source, Library>;
+type Pipelines = HashMap<(Source, KernelName, Option<ConstantValues>), ComputePipeline>;
+
+#[derive(Debug)]
+pub struct Kernels {
+ libraries: RwLock<Libraries>,
+ pipelines: RwLock<Pipelines>,
+}
+
+impl Default for Kernels {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Kernels {
+ pub fn new() -> Self {
+ let libraries = RwLock::new(Libraries::new());
+ let pipelines = RwLock::new(Pipelines::new());
+ Self {
+ libraries,
+ pipelines,
+ }
+ }
+
+ fn get_library_source(&self, source: Source) -> &'static str {
+ match source {
+ Source::Affine => AFFINE,
+ Source::Binary => BINARY,
+ Source::Cast => CAST,
+ Source::Conv => CONV,
+ Source::Fill => FILL,
+ Source::Gemm => MLX_GEMM,
+ Source::Gemv => GEMV,
+ Source::Indexing => INDEXING,
+ Source::MlxSort => MLX_SORT,
+ Source::Quantized => QUANTIZED,
+ Source::Random => RANDOM,
+ Source::Reduce => REDUCE,
+ Source::Sort => SORT,
+ Source::Ternary => TERNARY,
+ Source::Unary => UNARY,
+ Source::Sdpa => SDPA,
+ }
+ }
+
+ /// Load the give library from its [`source`].
+ /// If this has been previously loaded it will just fetch it from cache.
+ pub fn load_library(
+ &self,
+ device: &Device,
+ source: Source,
+ ) -> Result<Library, MetalKernelError> {
+ if let Some(lib) = self.libraries.read()?.get(&source) {
+ return Ok(lib.clone());
+ }
+
+ let mut libraries = self.libraries.write()?;
+ // Recheck after acquiring the write lock in case another thread inserted it.
+ if let Some(lib) = libraries.get(&source) {
+ Ok(lib.clone())
+ } else {
+ let lib = {
+ let source_content = self.get_library_source(source);
+ let compile_options = get_compile_options();
+ device
+ .new_library_with_source(source_content, Some(&compile_options))
+ .map_err(|e| MetalKernelError::LoadLibraryError(e.to_string()))?
+ };
+ libraries.insert(source, lib.clone());
+ Ok(lib)
+ }
+ }
+
+ fn load_function(
+ &self,
+ device: &Device,
+ source: Source,
+ name: &str,
+ constants: Option<&ConstantValues>,
+ ) -> Result<Function, MetalKernelError> {
+ let func = self
+ .load_library(device, source)?
+ .get_function(name, constants)?;
+ Ok(func)
+ }
+
+ /// Load the give pipeline
+ /// loads the library from source, then gets the function [`name`] from
+ /// that source
+ pub fn load_pipeline_with_constants(
+ &self,
+ device: &Device,
+ source: Source,
+ name: impl Into<KernelName>,
+ constants: Option<ConstantValues>,
+ ) -> Result<ComputePipeline, MetalKernelError> {
+ let key = (source, name.into(), constants);
+ if let Some(pipeline) = self.pipelines.read()?.get(&key) {
+ return Ok(pipeline.clone());
+ }
+
+ let mut pipelines = self.pipelines.write()?;
+ // Recheck after acquiring the write lock in case another thread inserted it.
+ if let Some(pipeline) = pipelines.get(&key) {
+ Ok(pipeline.clone())
+ } else {
+ let (source, name, constants) = key;
+ let func = self.load_function(device, source, name.as_ref(), constants.as_ref())?;
+ let pipeline = device
+ .new_compute_pipeline_state_with_function(&func)
+ .map_err(|e| MetalKernelError::FailedToCreatePipeline(e.to_string()))?;
+ pipelines.insert((source, name, constants), pipeline.clone());
+
+ Ok(pipeline)
+ }
+ }
+
+ /// Load the give pipeline
+ /// loads the library from source, then gets the function [`name`] from
+ /// that source (without constants)
+ pub fn load_pipeline(
+ &self,
+ device: &Device,
+ source: Source,
+ name: impl Into<KernelName>,
+ ) -> Result<ComputePipeline, MetalKernelError> {
+ self.load_pipeline_with_constants(device, source, name, None)
+ }
+}
+
+fn get_compile_options() -> Retained<MTLCompileOptions> {
+ let compile_options = MTLCompileOptions::new();
+ //unsafe { compile_options.setEnableLogging(true) };
+
+ let fast_math_enabled = get_env_bool("CANDLE_METAL_ENABLE_FAST_MATH", true);
+ // Ref availability:
+ // https://developer.apple.com/documentation/metal/mtlcompileoptions/mathmode
+ if available!(macos = 15, ios = 18) {
+ if fast_math_enabled {
+ compile_options.setMathMode(MTLMathMode::Fast);
+ compile_options.setMathFloatingPointFunctions(MTLMathFloatingPointFunctions::Fast);
+ } else {
+ compile_options.setMathMode(MTLMathMode::Relaxed);
+ compile_options.setMathFloatingPointFunctions(MTLMathFloatingPointFunctions::Precise);
+ }
+ } else {
+ // For older OS versions we use the old api
+ #[allow(deprecated)]
+ compile_options.setFastMathEnabled(fast_math_enabled);
+ }
+ compile_options
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Barrier;
+
+ #[test]
+ fn concurrent_cache_loads_insert_once() {
+ const THREADS: usize = 8;
+ const WARM_HITS: usize = 100;
+
+ let device = Device::system_default().unwrap();
+ let kernels = Kernels::new();
+ let barrier = Barrier::new(THREADS);
+
+ let pipelines = std::thread::scope(|scope| {
+ let handles = (0..THREADS)
+ .map(|_| {
+ scope.spawn(|| {
+ barrier.wait();
+ let pipeline = kernels
+ .load_pipeline(&device, Source::Unary, "cos_f32")
+ .unwrap();
+ for _ in 0..WARM_HITS {
+ let cached = kernels
+ .load_pipeline(&device, Source::Unary, "cos_f32")
+ .unwrap();
+ assert!(std::ptr::eq(pipeline.as_ref(), cached.as_ref()));
+ kernels.load_library(&device, Source::Unary).unwrap();
+ }
+ pipeline
+ })
+ })
+ .collect::<Vec<_>>();
+ handles
+ .into_iter()
+ .map(|handle| handle.join().unwrap())
+ .collect::<Vec<_>>()
+ });
+
+ assert!(pipelines
+ .iter()
+ .all(|pipeline| std::ptr::eq(pipelines[0].as_ref(), pipeline.as_ref())));
+ assert_eq!(kernels.libraries.read().unwrap().len(), 1);
+ assert_eq!(kernels.pipelines.read().unwrap().len(), 1);
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/affine.rs b/vendor/candle-metal-kernels/src/kernels/affine.rs
new file mode 100644
index 0000000..a3fa451
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/affine.rs
@@ -0,0 +1,207 @@
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+use crate::{get_tile_size, linear_split};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_affine(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ dtype_size: usize,
+ size: usize,
+ input: BufferOffset,
+ output: &Buffer,
+ mul: f32,
+ add: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "affine {name} elems={size}");
+
+ set_params!(encoder, (size, mul, add, &input, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = size.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_affine_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ input: BufferOffset,
+ input_stride: &[usize],
+ output: &Buffer,
+ mul: f32,
+ add: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+ let size: usize = shape.iter().product();
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "affine_strided {name} elems={size}");
+
+ set_params!(
+ encoder,
+ (
+ size,
+ shape.len(),
+ shape,
+ input_stride,
+ mul,
+ add,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, size);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_powf(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ dtype_size: usize,
+ size: usize,
+ input: BufferOffset,
+ output: &Buffer,
+ mul: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "powf {name} elems={size}");
+
+ set_params!(encoder, (size, mul, &input, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = size.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_powf_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ input: BufferOffset,
+ input_stride: &[usize],
+ output: &Buffer,
+ mul: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+ let size: usize = shape.iter().product();
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "powf_strided {name} elems={size}");
+
+ set_params!(
+ encoder,
+ (
+ size,
+ shape.len(),
+ shape,
+ input_stride,
+ mul,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, size);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_elu(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ dtype_size: usize,
+ size: usize,
+ input: BufferOffset,
+ output: &Buffer,
+ mul: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "elu {name} elems={size}");
+
+ set_params!(encoder, (size, mul, &input, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = size.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_elu_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ input: BufferOffset,
+ input_stride: &[usize],
+ output: &Buffer,
+ mul: f32,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Affine, name)?;
+ let size: usize = shape.iter().product();
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "elu_strided {name} elems={size}");
+
+ set_params!(
+ encoder,
+ (
+ size,
+ shape.len(),
+ shape,
+ input_stride,
+ mul,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, size);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/binary.rs b/vendor/candle-metal-kernels/src/kernels/binary.rs
new file mode 100644
index 0000000..735b4c2
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/binary.rs
@@ -0,0 +1,83 @@
+use crate::kernels::macros::ops;
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+use crate::{get_tile_size, linear_split};
+
+ops!(badd, bsub, bmul, bdiv, bminimum, bmaximum, eq, ne, le, lt, ge, gt);
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_binary_contiguous<S: ToString>(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: S,
+ dtype_size: usize,
+ length: usize,
+ left: BufferOffset,
+ right: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let kernel_name = kernel_name.to_string();
+ let pipeline = kernels.load_pipeline(device, Source::Binary, kernel_name.clone())?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "binary {kernel_name} elems={length}");
+
+ set_params!(encoder, (length, &left, &right, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = length.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_binary_strided<S: ToString>(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: S,
+ dtype_size: usize,
+ shape: &[usize],
+ left_input: BufferOffset,
+ left_strides: &[usize],
+ right_input: BufferOffset,
+ right_strides: &[usize],
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let kernel_name = kernel_name.to_string();
+ let pipeline = kernels.load_pipeline(device, Source::Binary, kernel_name.clone())?;
+
+ let num_dims: usize = shape.len();
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let length: usize = shape.iter().product();
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = length.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "binary_strided {kernel_name} elems={length}");
+ set_params!(
+ encoder,
+ (
+ length,
+ num_dims,
+ shape,
+ left_strides,
+ right_strides,
+ &left_input,
+ &right_input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/cast.rs b/vendor/candle-metal-kernels/src/kernels/cast.rs
new file mode 100644
index 0000000..ce7dd70
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/cast.rs
@@ -0,0 +1,71 @@
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+use crate::{get_tile_size, linear_split};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_cast_contiguous(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ dtype_size: usize,
+ length: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Cast, kernel_name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "cast {kernel_name} elems={length}");
+
+ set_params!(encoder, (length, &input, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = length.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_cast_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ shape: &[usize],
+ input: BufferOffset,
+ input_strides: &[usize],
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Cast, kernel_name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+
+ let length: usize = shape.iter().product();
+ debug_group!(encoder, "cast_strided {kernel_name} elems={length}");
+
+ set_params!(
+ encoder,
+ (
+ length,
+ shape.len(),
+ shape,
+ input_strides,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/convolution.rs b/vendor/candle-metal-kernels/src/kernels/convolution.rs
new file mode 100644
index 0000000..4495d72
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/convolution.rs
@@ -0,0 +1,377 @@
+use crate::linear_split;
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_im2col1d_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ (k_size, stride, padding, dilation): (usize, usize, usize, usize),
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let l_out = (shape[2] + 2 * padding - dilation * (k_size - 1) - 1) / stride + 1;
+ let dst_el = shape[0] * l_out * shape[1] * k_size;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "im2col1d {name} dst_el={dst_el}");
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ l_out,
+ k_size,
+ stride,
+ padding,
+ dilation,
+ shape,
+ strides,
+ &input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_col2im1d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ k_size: usize,
+ stride: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let l_in = shape[1];
+ let c_out = shape[2];
+ let l_out = (l_in - 1) * stride + k_size;
+ let dst_el = shape[0] * c_out * l_out;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "col2im1d {name} dst_el={dst_el}");
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ l_out,
+ l_in,
+ c_out,
+ k_size,
+ stride,
+ &input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_im2col_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ (h_k, w_k, stride, padding, dilation): (usize, usize, usize, usize, usize),
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+
+ let h = shape[2];
+ let w = shape[3];
+ let h_out = (h + 2 * padding - dilation * (h_k - 1) - 1) / stride + 1;
+ let w_out = (w + 2 * padding - dilation * (w_k - 1) - 1) / stride + 1;
+
+ let dst_el = shape[0] * h_out * w_out * shape[1] * h_k * w_k;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "im2col {name} dst_el={dst_el}");
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ h_out,
+ w_out,
+ h_k,
+ w_k,
+ stride,
+ padding,
+ dilation,
+ shape,
+ strides,
+ &input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_upsample_nearest_2d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ out_w: usize,
+ out_h: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let dst_el = out_w * out_h * shape[0] * shape[1];
+ let scale_w = shape[2] as f32 / out_w as f32;
+ let scale_h = shape[3] as f32 / out_h as f32;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "upsample_nearest2d {name} {out_w}x{out_h}");
+ set_params!(
+ encoder,
+ (
+ out_w,
+ out_h,
+ scale_w,
+ scale_h,
+ shape,
+ strides,
+ &input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_upsample_bilinear_2d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ out_w: usize,
+ out_h: usize,
+ align_corners: bool,
+ scale_h: Option<f64>,
+ scale_w: Option<f64>,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let dst_el = out_w * out_h * shape[0] * shape[1];
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "upsample_bilinear2d {name} {out_w}x{out_h}");
+
+ set_params!(
+ encoder,
+ (
+ out_w,
+ out_h,
+ align_corners,
+ scale_h.is_some(),
+ scale_h.unwrap_or(0.0) as f32,
+ scale_w.is_some(),
+ scale_w.unwrap_or(0.0) as f32,
+ shape,
+ strides,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_pool2d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ out_w: usize,
+ out_h: usize,
+ w_k: usize,
+ h_k: usize,
+ w_stride: usize,
+ h_stride: usize,
+ input: &Buffer,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dst_el = out_w * out_h * shape[0] * shape[1];
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "pool2d {name} {out_w}x{out_h} k={w_k}x{h_k}");
+ set_params!(
+ encoder,
+ (
+ w_k,
+ h_k,
+ w_stride,
+ h_stride,
+ shape,
+ strides,
+ input,
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_conv_transpose1d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ dilation: usize,
+ stride: usize,
+ padding: usize,
+ out_padding: usize,
+ c_out: usize,
+ l_out: usize,
+ b_size: usize,
+ src_shape: &[usize],
+ src_strides: &[usize],
+ kernel_shape: &[usize],
+ kernel_strides: &[usize],
+ input: &Buffer,
+ input_offset: usize,
+ kernel: &Buffer,
+ kernel_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dst_el = c_out * l_out * b_size;
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "conv_transpose1d {name} c_out={c_out} l_out={l_out} b={b_size}"
+ );
+ set_params!(
+ encoder,
+ (
+ l_out,
+ stride,
+ padding,
+ out_padding,
+ dilation,
+ src_shape,
+ src_strides,
+ kernel_shape,
+ kernel_strides,
+ (input, input_offset),
+ (kernel, kernel_offset),
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+pub struct CallConvTranspose2dCfg<'a> {
+ pub dilation: usize,
+ pub stride: usize,
+ pub padding: usize,
+ pub output_padding: usize,
+ pub c_out: usize,
+ pub out_w: usize,
+ pub out_h: usize,
+ pub b_size: usize,
+ pub input_dims: &'a [usize],
+ pub input_stride: &'a [usize],
+ pub kernel_dims: &'a [usize],
+ pub kernel_stride: &'a [usize],
+ pub input_offset: usize,
+ pub kernel_offset: usize,
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_conv_transpose2d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ cfg: CallConvTranspose2dCfg,
+ input: &Buffer,
+ kernel: &Buffer,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dst_el = cfg.c_out * cfg.out_w * cfg.out_h * cfg.b_size;
+ let pipeline = kernels.load_pipeline(device, Source::Conv, name)?;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "conv_transpose2d {name} c_out={} {}x{} b={}",
+ cfg.c_out,
+ cfg.out_w,
+ cfg.out_h,
+ cfg.b_size
+ );
+ set_params!(
+ encoder,
+ (
+ cfg.out_w,
+ cfg.out_h,
+ cfg.stride,
+ cfg.padding,
+ cfg.output_padding,
+ cfg.dilation,
+ cfg.input_dims,
+ cfg.input_stride,
+ cfg.kernel_dims,
+ cfg.kernel_stride,
+ (input, cfg.input_offset),
+ (kernel, cfg.kernel_offset),
+ Output::new(output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/fill.rs b/vendor/candle-metal-kernels/src/kernels/fill.rs
new file mode 100644
index 0000000..fd919b3
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/fill.rs
@@ -0,0 +1,25 @@
+use crate::linear_split;
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, EncoderParam, EncoderProvider,
+ Kernels, MetalKernelError, Output, Source,
+};
+
+pub fn call_const_fill(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ length: usize,
+ output: &Buffer,
+ v: impl EncoderParam,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Fill, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "const_fill {name} elems={length}");
+ set_params!(encoder, (Output::new(output), v, length));
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/indexing.rs b/vendor/candle-metal-kernels/src/kernels/indexing.rs
new file mode 100644
index 0000000..66910ca
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/indexing.rs
@@ -0,0 +1,200 @@
+use crate::linear_split;
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_index_select(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ ids_size: usize,
+ dim: usize,
+ contiguous: bool,
+ src_dims: &[usize],
+ src_strides: &[usize],
+ input: BufferOffset,
+ ids: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let left_size: usize = shape[..dim].iter().product();
+ let right_size: usize = shape[dim + 1..].iter().product();
+ let src_dim_size = shape[dim];
+ let dst_el = ids_size * left_size * right_size;
+
+ let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "index_select {name} dim={dim} dst_el={dst_el}");
+
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ left_size,
+ src_dim_size,
+ right_size,
+ ids_size,
+ contiguous,
+ src_dims,
+ src_strides,
+ &input,
+ &ids,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_gather(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ shape: &[usize],
+ ids_size: usize,
+ dim: usize,
+ input: BufferOffset,
+ ids: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let left_size: usize = shape[..dim].iter().product();
+ let right_size: usize = shape[dim + 1..].iter().product();
+ let src_dim_size = shape[dim];
+ let dst_el = ids_size * left_size * right_size;
+
+ let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "gather {name} dim={dim} dst_el={dst_el}");
+
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ left_size,
+ src_dim_size,
+ right_size,
+ ids_size,
+ &input,
+ &ids,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_scatter(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ src_shape: &[usize],
+ dst_shape: &[usize],
+ dim: usize,
+ input: BufferOffset,
+ ids: BufferOffset,
+ output: BufferOffset,
+) -> Result<(), MetalKernelError> {
+ let left_size: usize = src_shape[..dim].iter().product();
+ let right_size: usize = src_shape[dim + 1..].iter().product();
+ let src_dim_size = src_shape[dim];
+ let dst_el = left_size * right_size;
+ let dst_dim_size = dst_shape[dim];
+
+ let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "scatter {name} dim={dim} dst_el={dst_el}");
+
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ left_size,
+ src_dim_size,
+ right_size,
+ dst_dim_size,
+ &input,
+ &ids,
+ Output::from_buffer_offset(&output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_index_add(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ src_shape: &[usize],
+ dst_shape: &[usize],
+ ids_shape: &[usize],
+ dim: usize,
+ input: BufferOffset,
+ ids: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let left_size: usize = src_shape[..dim].iter().product();
+ let right_size: usize = src_shape[dim + 1..].iter().product();
+ let src_dim_size = src_shape[dim];
+ let dst_el = left_size * right_size;
+ let dst_dim_size = dst_shape[dim];
+ let ids_dim_size = ids_shape[0];
+
+ let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "index_add {name} dim={dim} dst_el={dst_el}");
+
+ set_params!(
+ encoder,
+ (
+ dst_el,
+ left_size,
+ src_dim_size,
+ right_size,
+ dst_dim_size,
+ ids_dim_size,
+ &input,
+ &ids,
+ Output::new(output)
+ )
+ );
+
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/macros.rs b/vendor/candle-metal-kernels/src/kernels/macros.rs
new file mode 100644
index 0000000..9cff967
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/macros.rs
@@ -0,0 +1,53 @@
+macro_rules! ops{
+ ($($name:ident),+) => {
+
+ pub mod contiguous {
+ pub struct Kernel(pub &'static str);
+ $(
+ pub mod $name {
+ use super::Kernel;
+ pub const FLOAT: Kernel = Kernel(concat!(stringify!($name), "_f32"));
+ pub const HALF: Kernel = Kernel(concat!(stringify!($name), "_f16"));
+ pub const BFLOAT: Kernel = Kernel(concat!(stringify!($name), "_bf16"));
+ pub const I64: Kernel = Kernel(concat!(stringify!($name), "_i64"));
+ pub const U32: Kernel = Kernel(concat!(stringify!($name), "_u32"));
+ pub const U8: Kernel = Kernel(concat!(stringify!($name), "_u8"));
+ }
+ )+
+ pub mod copy {
+ use super::Kernel;
+ pub const FLOAT: Kernel = Kernel("copy_f32");
+ pub const HALF: Kernel = Kernel("copy_f16");
+ pub const BFLOAT: Kernel = Kernel("copy_bf16");
+ pub const I64: Kernel = Kernel("copy_i64");
+ pub const U32: Kernel = Kernel("copy_u32");
+ pub const U8: Kernel = Kernel("copy_u8");
+ }
+ }
+
+ pub mod strided {
+ pub struct Kernel(pub &'static str);
+ $(
+ pub mod $name {
+ use super::Kernel;
+ pub const FLOAT: Kernel = Kernel(concat!(stringify!($name), "_f32_strided"));
+ pub const HALF: Kernel = Kernel(concat!(stringify!($name), "_f16_strided"));
+ pub const BFLOAT: Kernel = Kernel(concat!(stringify!($name), "_bf16_strided"));
+ pub const I64: Kernel = Kernel(concat!(stringify!($name), "_i64_strided"));
+ pub const U32: Kernel = Kernel(concat!(stringify!($name), "_u32_strided"));
+ pub const U8: Kernel = Kernel(concat!(stringify!($name), "_u8_strided"));
+ }
+ )+
+ pub mod copy {
+ use super::Kernel;
+ pub const FLOAT: Kernel = Kernel("copy_f32_strided");
+ pub const HALF: Kernel = Kernel("copy_f16_strided");
+ pub const BFLOAT: Kernel = Kernel("copy_bf16_strided");
+ pub const I64: Kernel = Kernel("copy_i64_strided");
+ pub const U32: Kernel = Kernel("copy_u32_strided");
+ pub const U8: Kernel = Kernel("copy_u8_strided");
+ }
+ }
+ };
+}
+pub(crate) use ops;
diff --git a/vendor/candle-metal-kernels/src/kernels/mlx_gemm.rs b/vendor/candle-metal-kernels/src/kernels/mlx_gemm.rs
new file mode 100644
index 0000000..3931906
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/mlx_gemm.rs
@@ -0,0 +1,668 @@
+use crate::metal::{Buffer, ComputeCommandEncoder, Device, MetalDeviceType};
+use crate::utils::{EncoderProvider, Input};
+use crate::{
+ debug_group, set_params, ConstantValues, EncoderParam, Kernels, MetalKernelError, Output,
+ Source, Value,
+};
+use objc2_metal::MTLSize;
+
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
+pub enum GemmDType {
+ BF16,
+ F16,
+ F32,
+}
+
+/// Tile configuration for GEMM kernel.
+///
+/// These parameters control the block sizes and warp tiling for the Metal GEMM kernel.
+/// Different configurations are optimal for different matrix sizes and data types.
+///
+/// Reference: MLX steel_gemm_fused.metal
+#[derive(Copy, Clone, Debug)]
+struct TileConfig {
+ bm: usize, // Block size M
+ bn: usize, // Block size N
+ bk: usize, // Block size K
+ wm: usize, // Warp tiles M
+ wn: usize, // Warp tiles N
+}
+
+impl TileConfig {
+ const fn new(bm: usize, bn: usize, bk: usize, wm: usize, wn: usize) -> Self {
+ Self { bm, bn, bk, wm, wn }
+ }
+}
+
+// Predefined tile configurations matching MLX's steel_gemm_fused.metal
+// Note: TILE_32_32_16_2_2 is kept for backward compatibility and as a fallback.
+// It's used by MLX for small devices ('g'/'p') but we default to medium device configs.
+#[allow(dead_code)]
+const TILE_32_32_16_2_2: TileConfig = TileConfig::new(32, 32, 16, 2, 2);
+const TILE_64_64_16_2_2: TileConfig = TileConfig::new(64, 64, 16, 2, 2);
+const TILE_64_64_16_1_2: TileConfig = TileConfig::new(64, 64, 16, 1, 2);
+const TILE_64_32_32_2_2: TileConfig = TileConfig::new(64, 32, 32, 2, 2);
+const TILE_32_64_16_1_2: TileConfig = TileConfig::new(32, 64, 16, 1, 2);
+
+/// Select optimal tile configuration based on matrix dimensions, data type, transpose mode,
+/// and device type.
+///
+/// This implements MLX's GEMM_TPARAM_MACRO tile selection logic.
+/// Reference: refs/mlx/mlx/backend/metal/matmul.cpp lines 88-170
+///
+/// The selection is based on:
+/// - Device type (phone/base-pro for small, ultra for large, others for medium)
+/// - Total output size (batch_size * M * N)
+/// - Data type (F32 vs F16/BF16)
+/// - Transpose mode (nn, nt, tn, tt)
+/// - K dimension relative to M and N
+fn select_tile_config(
+ dtype: GemmDType,
+ m: usize,
+ n: usize,
+ k: usize,
+ batch_size: usize,
+ a_trans: bool,
+ b_trans: bool,
+ device_type: MetalDeviceType,
+) -> TileConfig {
+ // Special case: For very small M (vector-matrix multiply),
+ // use the original 32x32 tile to avoid thread waste.
+ // When M is very small (< bm), using larger bm values causes significant
+ // thread underutilization because most threads in the M dimension have no work.
+ // This is critical for benchmarks like [1, 2048] @ [2048, 2048] (m=1).
+ //
+ // We use m < 16 as the threshold because:
+ // - For m=1 to m=15, even 32x32 tile has some waste but it's the smallest available
+ // - For m >= 16, the larger tiles can provide better throughput despite some waste
+ if m < 16 {
+ return TILE_32_32_16_2_2;
+ }
+
+ // MLX uses batch_size * M * N >= 1M as the threshold for "large matmul"
+ let total_output = batch_size * m * n;
+ let is_large_matmul = total_output >= (1 << 20); // 1M elements
+
+ match device_type {
+ // Small devices: phone ('p') and base/pro ('g')
+ MetalDeviceType::Phone | MetalDeviceType::BasePro => {
+ // MLX: if (devc == 'g' || devc == 'p')
+ if !a_trans && b_trans {
+ // nt mode
+ TILE_64_32_32_2_2
+ } else if dtype != GemmDType::F32 {
+ // half and bfloat
+ TILE_64_64_16_1_2
+ } else {
+ // float32 default
+ TILE_64_64_16_2_2
+ }
+ }
+ // Large device: ultra ('d')
+ MetalDeviceType::Ultra => {
+ // MLX: if (devc == 'd')
+ if is_large_matmul {
+ // Large matmul
+ if dtype != GemmDType::F32 {
+ // half and bfloat
+ if 2 * m.max(n) > k {
+ // Reasonable K
+ TILE_64_64_16_1_2
+ } else if !a_trans && b_trans {
+ // nt with large K
+ TILE_64_32_32_2_2
+ } else {
+ // nn with large K
+ TILE_32_64_16_1_2
+ }
+ } else {
+ // float32 takes default
+ TILE_64_64_16_2_2
+ }
+ } else {
+ // Smaller matmul
+ if dtype != GemmDType::F32 {
+ // half and bfloat
+ if !a_trans && b_trans {
+ // nt
+ TILE_64_32_32_2_2
+ } else {
+ // nn
+ TILE_64_64_16_1_2
+ }
+ } else {
+ // floats
+ if !a_trans && b_trans {
+ // nt
+ TILE_32_64_16_1_2
+ } else {
+ // nn
+ TILE_64_32_32_2_2
+ }
+ }
+ }
+ }
+ // Medium devices: max ('s') and unknown
+ MetalDeviceType::Max | MetalDeviceType::Medium => {
+ // MLX: default medium device config
+ // Use the same logic as before but with medium device defaults
+ match dtype {
+ GemmDType::F32 => {
+ if !is_large_matmul {
+ if !a_trans && b_trans {
+ TILE_32_64_16_1_2
+ } else {
+ TILE_64_32_32_2_2
+ }
+ } else {
+ TILE_64_64_16_2_2
+ }
+ }
+ GemmDType::F16 | GemmDType::BF16 => {
+ if is_large_matmul {
+ if 2 * m.max(n) > k {
+ TILE_64_64_16_1_2
+ } else if !a_trans && b_trans {
+ TILE_64_32_32_2_2
+ } else {
+ TILE_32_64_16_1_2
+ }
+ } else if !a_trans && b_trans {
+ TILE_64_32_32_2_2
+ } else {
+ TILE_64_64_16_1_2
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Check if batch can be collapsed into M dimension.
+///
+/// MLX's batch collapse optimization (from matmul.cpp lines 700-740):
+/// When B is broadcasted (2D), we can collapse batch into M dimension:
+/// - [batch, M, K] @ [K, N] -> [batch*M, K] @ [K, N]
+///
+/// Conditions for batch collapse:
+/// 1. batch_size > 1
+/// 2. !transpose_a (A is not transposed, i.e., row-major for M dimension)
+/// 3. A is contiguous in batch dimension (batch_stride_a == M * K)
+/// 4. B is broadcasted (batch_stride_b == 0, meaning B is 2D)
+///
+/// Returns (effective_batch, effective_m, should_collapse)
+fn check_batch_collapse(
+ b: usize,
+ m: usize,
+ k: usize,
+ a_trans: bool,
+ lhs_stride: &[usize],
+ rhs_stride: &[usize],
+) -> (usize, usize, bool) {
+ if b <= 1 {
+ return (b, m, false);
+ }
+
+ // A must not be transposed for batch collapse
+ if a_trans {
+ return (b, m, false);
+ }
+
+ // Check A's batch stride - must be contiguous (batch_stride_a == M * K)
+ let a_batch_stride = if lhs_stride.len() > 2 {
+ lhs_stride[lhs_stride.len() - 3]
+ } else {
+ m * k
+ };
+
+ // Check B's batch stride - must be 0 (broadcasted) for collapse
+ let b_batch_stride = if rhs_stride.len() > 2 {
+ rhs_stride[rhs_stride.len() - 3]
+ } else {
+ 0 // B is 2D, effectively broadcasted
+ };
+
+ // For batch collapse:
+ // - A must be contiguous: batch_stride_a == M * K
+ // - B must be broadcasted: batch_stride_b == 0
+ let a_contiguous = a_batch_stride == m * k;
+ let b_broadcasted = b_batch_stride == 0;
+
+ if a_contiguous && b_broadcasted {
+ // Collapse batch into M: new_m = batch * m, new_batch = 1
+ (1, b * m, true)
+ } else {
+ (b, m, false)
+ }
+}
+
+/// Check if we can use split-K strategy for better performance.
+///
+/// MLX uses split-K when:
+/// - batch_size == 1
+/// - (M/16) * (N/16) <= 32 (small output)
+/// - K/16 >= 8 (large K)
+///
+/// This is useful for tall-skinny matrices where K >> M*N
+#[allow(dead_code)]
+fn should_use_split_k(b: usize, m: usize, n: usize, k: usize) -> bool {
+ if b != 1 {
+ return false;
+ }
+ let tm = m / 16;
+ let tn = n / 16;
+ let tk = k / 16;
+ (tm * tn) <= 32 && tk >= 8
+}
+
+/// M=1 -> gemv_t (vec[K] x mat[K,N] -> vec[N])
+/// N=1 -> gemv (mat[M,K] x vec[K] -> vec[M])
+#[allow(clippy::too_many_arguments)]
+pub fn call_mlx_gemv(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: GemmDType,
+ (b, m, n, k): (usize, usize, usize, usize),
+ lhs_stride: &[usize],
+ lhs_offset: usize,
+ lhs_buffer: &Buffer,
+ rhs_stride: &[usize],
+ rhs_offset: usize,
+ rhs_buffer: &Buffer,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ debug_assert!(m == 1 || n == 1, "call_mlx_gemv requires M=1 or N=1");
+
+ assert!(rhs_stride.len() >= 2);
+ assert!(lhs_stride.len() >= 2);
+
+ // Determine transpose flags from strides (same logic as call_mlx_gemm)
+ let rhs_m1 = rhs_stride[rhs_stride.len() - 1];
+ let rhs_m2 = rhs_stride[rhs_stride.len() - 2];
+ let lhs_m1 = lhs_stride[lhs_stride.len() - 1];
+ let lhs_m2 = lhs_stride[lhs_stride.len() - 2];
+
+ let (lda, a_trans) = if (lhs_m1 == 1 || k == 1) && (lhs_m2 == k || m == 1) {
+ (k as i32, false)
+ } else if (lhs_m1 == m || k == 1) && (lhs_m2 == 1 || m == 1) {
+ (m as i32, true)
+ } else {
+ return Err(MetalKernelError::MatMulNonContiguous {
+ lhs_stride: lhs_stride.to_vec(),
+ rhs_stride: rhs_stride.to_vec(),
+ mnk: (m, n, k),
+ }
+ .bt())?;
+ };
+
+ let (ldb, b_trans) = if (rhs_m1 == 1 || n == 1) && (rhs_m2 == n || k == 1) {
+ (n as i32, false)
+ } else if (rhs_m1 == k || n == 1) && (rhs_m2 == 1 || k == 1) {
+ (k as i32, true)
+ } else {
+ return Err(MetalKernelError::MatMulNonContiguous {
+ lhs_stride: lhs_stride.to_vec(),
+ rhs_stride: rhs_stride.to_vec(),
+ mnk: (m, n, k),
+ }
+ .bt())?;
+ };
+
+ // Figure out if transpose is needed.
+ let is_b_matrix = n != 1;
+ let transpose_mat = if is_b_matrix { !b_trans } else { a_trans };
+ let mat_ld = if is_b_matrix {
+ ldb as usize
+ } else {
+ lda as usize
+ };
+ let in_vec_size = k;
+ let out_vec_size = if is_b_matrix { n } else { m };
+
+ let (mat_buffer, mat_offset, vec_buffer, vec_offset) = if is_b_matrix {
+ (rhs_buffer, rhs_offset, lhs_buffer, lhs_offset)
+ } else {
+ (lhs_buffer, lhs_offset, rhs_buffer, rhs_offset)
+ };
+
+ // Batch strides (elements per batch item)
+ let vec_batch_stride: i64 = if is_b_matrix {
+ if lhs_stride.len() > 2 {
+ lhs_stride[lhs_stride.len() - 3] as i64
+ } else {
+ k as i64
+ }
+ } else {
+ if rhs_stride.len() > 2 {
+ rhs_stride[rhs_stride.len() - 3] as i64
+ } else {
+ k as i64
+ }
+ };
+ // Weight matrix is often 2D (shared across batch) -> stride = 0
+ let mat_batch_stride: i64 = if is_b_matrix {
+ if rhs_stride.len() > 2 {
+ rhs_stride[rhs_stride.len() - 3] as i64
+ } else {
+ 0
+ }
+ } else {
+ if lhs_stride.len() > 2 {
+ lhs_stride[lhs_stride.len() - 3] as i64
+ } else {
+ 0
+ }
+ };
+
+ // Tile selection
+ let (bm, bn, sm, sn, tm, tn) = if transpose_mat {
+ // gemv_t: vec[K] x mat[K,N_out] -> out[N_out]
+ let (sm, sn) = if in_vec_size >= 8192 && out_vec_size >= 2048 {
+ (4usize, 8usize)
+ } else {
+ (8, 4)
+ };
+ let bn = if out_vec_size >= 2048 {
+ 16usize
+ } else if out_vec_size >= 512 {
+ 4
+ } else {
+ 2
+ };
+ let tn: usize = if out_vec_size < 4 { 1 } else { 4 };
+ (1usize, bn, sm, sn, 4usize, tn)
+ } else {
+ // gemv: mat[M_out,K] x vec[K] -> out[M_out]
+ let (bm, bn, sm, sn): (usize, usize, usize, usize) = if in_vec_size <= 64 {
+ (1, 1, 8, 4)
+ } else if in_vec_size >= 16 * out_vec_size {
+ (1, 8, 1, 32)
+ } else if out_vec_size >= 4096 {
+ (8, 1, 1, 32)
+ } else {
+ (4, 1, 1, 32)
+ };
+ let tm: usize = if out_vec_size < 4 { 1 } else { 4 };
+ (bm, bn, sm, sn, tm, 4usize)
+ };
+
+ let dtype_str = match dtype {
+ GemmDType::F32 => "float32",
+ GemmDType::F16 => "float16",
+ GemmDType::BF16 => "bfloat16",
+ };
+ let kernel_prefix = if transpose_mat { "gemv_t" } else { "gemv" };
+ let name = format!(
+ "{}_{}_bm{}_bn{}_sm{}_sn{}_tm{}_tn{}_nc0_axpby0",
+ kernel_prefix, dtype_str, bm, bn, sm, sn, tm, tn
+ );
+
+ let pipeline = kernels.load_pipeline(device, Source::Gemv, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+
+ let batch_shape = [b as i32];
+ let vec_batch_strides = [vec_batch_stride];
+ let mat_batch_strides = [mat_batch_stride];
+ let bias_batch_strides = [0i64];
+
+ set_params!(
+ encoder,
+ (
+ Input::with_offset(mat_buffer, mat_offset),
+ Input::with_offset(vec_buffer, vec_offset),
+ (), // bias
+ Output::new(output),
+ in_vec_size as i32,
+ out_vec_size as i32,
+ mat_ld as i32,
+ 1.0f32, // alpha
+ 0.0f32, // beta
+ 1i32, // batch_ndim
+ &batch_shape[..],
+ &vec_batch_strides[..],
+ &mat_batch_strides[..],
+ &bias_batch_strides[..],
+ 1i32 // bias_stride
+ )
+ );
+
+ let n_out_per_tgp = if transpose_mat {
+ bn * sn * tn
+ } else {
+ bm * sm * tm
+ };
+ let n_tgp = out_vec_size.div_ceil(n_out_per_tgp);
+ let grid_size = MTLSize {
+ width: n_tgp,
+ height: 1,
+ depth: b,
+ };
+ let group_size = MTLSize {
+ width: 32,
+ height: bn,
+ depth: bm,
+ };
+ encoder.dispatch_thread_groups(grid_size, group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_mlx_gemm(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: GemmDType,
+ (b, m, n, k): (usize, usize, usize, usize),
+ lhs_stride: &[usize],
+ lhs_offset: usize,
+ lhs_buffer: &Buffer,
+ rhs_stride: &[usize],
+ rhs_offset: usize,
+ rhs_buffer: &Buffer,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ #[derive(Debug)]
+ #[repr(C)]
+ struct GemmParams {
+ m: i32,
+ n: i32,
+ k: i32,
+ lda: i32,
+ ldb: i32,
+ ldd: i32,
+ tiles_n: i32,
+ tiles_m: i32,
+ batch_stride_a: isize,
+ batch_stride_b: isize,
+ batch_stride_d: isize,
+ swizzle_log: i32,
+ gemm_k_iterations_aligned: i32,
+ batch_ndim: i32,
+ }
+ assert!(rhs_stride.len() >= 2);
+ assert!(lhs_stride.len() >= 2);
+ let rhs_m1 = rhs_stride[rhs_stride.len() - 1];
+ let rhs_m2 = rhs_stride[rhs_stride.len() - 2];
+ let lhs_m1 = lhs_stride[lhs_stride.len() - 1];
+ let lhs_m2 = lhs_stride[lhs_stride.len() - 2];
+ // lhs has shape b, m, k
+ // We also allow for the case where the stride on the minor dimension is not as expected but
+ // there is a single element.
+ let (lda, a_trans) = if (lhs_m1 == 1 || k == 1) && (lhs_m2 == k || m == 1) {
+ (k as i32, false)
+ } else if (lhs_m1 == m || k == 1) && (lhs_m2 == 1 || m == 1) {
+ (m as i32, true)
+ } else {
+ return Err(MetalKernelError::MatMulNonContiguous {
+ lhs_stride: lhs_stride.to_vec(),
+ rhs_stride: rhs_stride.to_vec(),
+ mnk: (m, n, k),
+ }
+ .bt())?;
+ };
+ // rhs has shape b, k, n
+ let (ldb, b_trans) = if (rhs_m1 == 1 || n == 1) && (rhs_m2 == n || k == 1) {
+ (n as i32, false)
+ } else if (rhs_m1 == k || n == 1) && (rhs_m2 == 1 || k == 1) {
+ (k as i32, true)
+ } else {
+ return Err(MetalKernelError::MatMulNonContiguous {
+ lhs_stride: lhs_stride.to_vec(),
+ rhs_stride: rhs_stride.to_vec(),
+ mnk: (m, n, k),
+ }
+ .bt())?;
+ };
+
+ if m == 1 || n == 1 {
+ return call_mlx_gemv(
+ device,
+ ep,
+ kernels,
+ dtype,
+ (b, m, n, k),
+ lhs_stride,
+ lhs_offset,
+ lhs_buffer,
+ rhs_stride,
+ rhs_offset,
+ rhs_buffer,
+ output,
+ );
+ }
+
+ // Check for batch collapse optimization (MLX matmul.cpp lines 700-740)
+ // When B is broadcasted (2D), collapse batch into M dimension
+ let (effective_batch, effective_m, batch_collapsed) =
+ check_batch_collapse(b, m, k, a_trans, lhs_stride, rhs_stride);
+
+ // Use effective dimensions after potential batch collapse
+ let m = effective_m;
+ let b = effective_batch;
+
+ // Dynamic tile selection based on matrix dimensions, dtype, transpose mode, and device type
+ // Reference: MLX GEMM_TPARAM_MACRO in matmul.cpp
+ let device_type = device.device_type();
+ let tile = select_tile_config(dtype, m, n, k, b, a_trans, b_trans, device_type);
+ let (bm, bn, bk, wm, wn) = (tile.bm, tile.bn, tile.bk, tile.wm, tile.wn);
+
+ // https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/matmul.cpp#L422
+ // has_batch should be true when b > 1, matching the original candle behavior
+ let has_batch = b > 1;
+
+ let constants = Some(ConstantValues::new(vec![
+ (10, Value::Bool(has_batch)),
+ (100, Value::Bool(/* use_out_source */ false)),
+ (110, Value::Bool(/* do_axpby */ false)),
+ (200, Value::Bool(/* align_m */ m % bm == 0)),
+ (201, Value::Bool(/* align_n */ n % bn == 0)),
+ (202, Value::Bool(/* align_k */ k % bk == 0)),
+ (300, Value::Bool(/* do_gather */ false)),
+ ]));
+
+ let swizzle_log = 0;
+ let tile_swizzle = 1 << swizzle_log;
+ let tn = n.div_ceil(bn);
+ let tm = m.div_ceil(bm);
+ let tn = tn * tile_swizzle;
+ let tm = tm.div_ceil(tile_swizzle);
+
+ // Calculate batch strides based on whether batch was collapsed
+ let (batch_stride_a, batch_stride_b) = if batch_collapsed {
+ // After batch collapse, there's no batch dimension
+ (0isize, 0isize)
+ } else {
+ let a_stride = if lhs_stride.len() > 2 {
+ lhs_stride[lhs_stride.len() - 3] as isize
+ } else {
+ (m * k) as isize
+ };
+ let b_stride = if rhs_stride.len() > 2 {
+ rhs_stride[rhs_stride.len() - 3] as isize
+ } else {
+ (n * k) as isize
+ };
+ (a_stride, b_stride)
+ };
+
+ let gemm_params = GemmParams {
+ m: m as i32,
+ n: n as i32,
+ k: k as i32,
+ lda: if batch_collapsed { k as i32 } else { lda }, // After collapse, lda = K
+ ldb,
+ ldd: n as i32,
+ tiles_n: tn as i32,
+ tiles_m: tm as i32,
+ swizzle_log,
+ batch_stride_a,
+ batch_stride_b,
+ batch_stride_d: (m * n) as isize,
+ batch_ndim: 1i32,
+ gemm_k_iterations_aligned: (k / bk) as i32,
+ };
+
+ // Dynamically generate kernel name based on dtype, transpose mode, and tile config
+ // Format: gemm_{trans}_{itype}_{otype}_{bm}_{bn}_{bk}_{wm}_{wn}
+ let dtype_str = match dtype {
+ GemmDType::F32 => "f32",
+ GemmDType::F16 => "f16",
+ GemmDType::BF16 => "bf16",
+ };
+ let trans_str = match (a_trans, b_trans) {
+ (false, false) => "nn",
+ (true, false) => "tn",
+ (false, true) => "nt",
+ (true, true) => "tt",
+ };
+ let name = format!(
+ "gemm_{}_{}_{}_{}_{}_{}_{}_{}",
+ trans_str, dtype_str, dtype_str, bm, bn, bk, wm, wn
+ );
+
+ let pipeline =
+ kernels.load_pipeline_with_constants(device, Source::Gemm, name.clone(), constants)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "mlx_gemm {name} B={b} M={m} N={n} K={k}");
+
+ impl EncoderParam for GemmParams {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_bytes(position, &data);
+ }
+ }
+
+ // Batch strides for buffer 7 (same as main branch)
+ let batch_strides = [batch_stride_a, batch_stride_b];
+
+ set_params!(
+ encoder,
+ (
+ (lhs_buffer, lhs_offset),
+ (rhs_buffer, rhs_offset),
+ (),
+ Output::new(output),
+ gemm_params,
+ (),
+ b as i32,
+ &batch_strides[..]
+ )
+ );
+
+ let grid_size = MTLSize {
+ width: tn,
+ height: tm,
+ depth: /* batch_size_out */ b,
+ };
+ let group_size = MTLSize {
+ width: 32,
+ height: wn,
+ depth: wm,
+ };
+ encoder.dispatch_thread_groups(grid_size, group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/mod.rs b/vendor/candle-metal-kernels/src/kernels/mod.rs
new file mode 100644
index 0000000..9587b28
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/mod.rs
@@ -0,0 +1,32 @@
+pub mod affine;
+pub mod binary;
+pub mod cast;
+pub mod convolution;
+pub mod fill;
+pub mod indexing;
+mod macros;
+pub mod mlx_gemm;
+pub mod quantized;
+pub mod random;
+pub mod reduce;
+pub mod sdpa;
+pub mod sort;
+pub mod ternary;
+pub mod unary;
+
+pub use affine::*;
+pub use binary::{call_binary_contiguous, call_binary_strided};
+pub use cast::{call_cast_contiguous, call_cast_strided};
+pub use convolution::*;
+pub use fill::*;
+pub use indexing::*;
+pub use mlx_gemm::{call_mlx_gemm, call_mlx_gemv, GemmDType};
+pub use quantized::{
+ call_quantized_get_rows, call_quantized_matmul_mm_t, call_quantized_matmul_mv_t, GgmlDType,
+};
+pub use random::*;
+pub use reduce::*;
+pub use sdpa::{call_sdpa_full, call_sdpa_vector, call_sdpa_vector_2pass, SdpaDType};
+pub use sort::{call_arg_sort, call_mlx_arg_sort};
+pub use ternary::call_where_cond;
+pub use unary::*;
diff --git a/vendor/candle-metal-kernels/src/kernels/quantized.rs b/vendor/candle-metal-kernels/src/kernels/quantized.rs
new file mode 100644
index 0000000..ad73950
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/quantized.rs
@@ -0,0 +1,361 @@
+use crate::utils::EncoderProvider;
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+use objc2_metal::MTLSize;
+
+#[derive(Debug, Clone, Copy)]
+pub enum GgmlDType {
+ Q4_0,
+ Q4_1,
+ Q5_0,
+ Q5_1,
+ Q8_0,
+ Q8_1,
+ Q2K,
+ Q3K,
+ Q4K,
+ Q5K,
+ Q6K,
+ Q8K,
+ F16,
+ F32,
+ BF16,
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_quantized_matmul_mv_t(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: GgmlDType,
+ (b, m, n, k): (usize, usize, usize, usize),
+ lhs: &Buffer,
+ lhs_offset: usize,
+ rhs: &Buffer,
+ dst_offset: usize,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ // Everything is in reverse
+ let ne00 = k as i64;
+ let ne01 = n as i64;
+ let ne02 = b as i64;
+ let ne03 = 1i64;
+
+ let nb00 = 0i64;
+ let nb01 = 0i64;
+ let nb02 = 0i64;
+
+ let ne10 = k as i64;
+ let ne11 = m as i64;
+ let ne12 = b as i64;
+ let ne13 = 1i64;
+
+ let nb10 = 0i64;
+ let nb11 = 0i64;
+ let nb12 = 0i64;
+
+ let ne0 = n as i64;
+ let ne1 = m as i64;
+ let r2: u32 = (ne12 / ne02) as u32;
+ let r3: u32 = (ne13 / ne03) as u32;
+
+ let (nth0, nth1, align) = match dtype {
+ GgmlDType::Q4_0
+ | GgmlDType::Q4_1
+ | GgmlDType::Q5_0
+ | GgmlDType::Q5_1
+ | GgmlDType::Q8_0
+ | GgmlDType::Q8_1 => {
+ let nth0 = 8;
+ let nth1 = 8;
+ let align = 8;
+ (nth0, nth1, align)
+ }
+ GgmlDType::Q2K => {
+ // Fixing a bug in Metal for GGML
+ // https://github.com/ggerganov/llama.cpp/blob/b8109bc0139f15a5b321909f47510b89dca47ffc/ggml-metal.m#L1576
+ let nth0 = 2;
+ let nth1 = 32;
+ let align = 8;
+ (nth0, nth1, align)
+ }
+ GgmlDType::Q4K => {
+ let nth0 = 4;
+ let nth1 = 8;
+ let align = 4;
+ (nth0, nth1, align)
+ }
+ GgmlDType::Q3K | GgmlDType::Q5K => {
+ let nth0 = 2;
+ let nth1 = 32;
+ let align = 4;
+ (nth0, nth1, align)
+ }
+ GgmlDType::Q6K => {
+ let nth0 = 2;
+ let nth1 = 32;
+ let align = 2;
+ (nth0, nth1, align)
+ }
+ GgmlDType::F16 | GgmlDType::BF16 | GgmlDType::Q8K => {
+ // Original implem uses rows
+ let nth0 = 32;
+ let nth1 = 1;
+ let align = 8;
+ (nth0, nth1, align)
+ }
+ GgmlDType::F32 => {
+ let nth0 = 32;
+ let nth1 = 1;
+ let align = 8;
+ (nth0, nth1, align)
+ }
+ };
+ let thread_groups_count = MTLSize {
+ width: divide(ne01 as usize, align),
+ height: ne11 as usize,
+ depth: (ne12 * ne13) as usize,
+ };
+ let threads_per_threadgroup = MTLSize {
+ width: nth0,
+ height: nth1,
+ depth: 1,
+ };
+ let name = match dtype {
+ GgmlDType::Q4_0 => "kernel_mul_mv_q4_0_f32",
+ GgmlDType::Q4_1 => "kernel_mul_mv_q4_1_f32",
+ GgmlDType::Q5_0 => "kernel_mul_mv_q5_0_f32",
+ GgmlDType::Q5_1 => "kernel_mul_mv_q5_1_f32",
+ GgmlDType::Q8_0 => "kernel_mul_mv_q8_0_f32",
+ GgmlDType::Q8_1 => "kernel_mul_mv_q8_1_f32",
+ GgmlDType::Q2K => "kernel_mul_mv_q2_K_f32",
+ GgmlDType::Q3K => "kernel_mul_mv_q3_K_f32",
+ GgmlDType::Q4K => "kernel_mul_mv_q4_K_f32",
+ GgmlDType::Q5K => "kernel_mul_mv_q5_K_f32",
+ GgmlDType::Q6K => "kernel_mul_mv_q6_K_f32",
+ GgmlDType::Q8K => "kernel_mul_mv_q8_K_f32",
+ GgmlDType::F16 => "kernel_mul_mv_f16_f32",
+ GgmlDType::BF16 => "kernel_mul_mv_bf16_f32",
+ GgmlDType::F32 => "kernel_mul_mv_f32_f32",
+ };
+
+ let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "qmm_mv {name} B={b} M={m} K={k} N={n}");
+
+ set_params!(
+ encoder,
+ (
+ rhs,
+ (lhs, lhs_offset),
+ Output::with_offset(dst, dst_offset),
+ ne00,
+ ne01,
+ ne02,
+ nb00,
+ nb01,
+ nb02,
+ ne10,
+ ne11,
+ ne12,
+ nb10,
+ nb11,
+ nb12,
+ ne0,
+ ne1,
+ r2,
+ r3
+ )
+ );
+
+ encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup);
+ Ok(())
+}
+
+/// - src0 is usually weight
+/// - src1 is usually xs
+#[allow(clippy::too_many_arguments)]
+pub fn call_quantized_matmul_mm_t(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: GgmlDType,
+ src0_shape: &[usize],
+ src0_stride: &[usize],
+ src0: &Buffer,
+ src1_shape: &[usize],
+ src1_stride: &[usize],
+ src1: &Buffer,
+ src1_offset: usize,
+ dst_shape: &[usize],
+ dst_offset: usize,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ // Everything is in reverse
+ let ne00 = src0_shape[src0_shape.len() - 1] as i64;
+ let ne01 = src0_shape[src0_shape.len() - 2] as i64;
+ let ne02 = src0_shape[src0_shape.len() - 3] as i64;
+ let ne03 = src0_shape[src0_shape.len() - 4] as i64;
+
+ let nb01 = src0_stride[src0_stride.len() - 2] as i64;
+ let nb02 = src0_stride[src0_stride.len() - 3] as i64;
+ let nb03 = src0_stride[src0_stride.len() - 4] as i64;
+
+ let ne11 = src1_shape[src1_shape.len() - 2] as i64;
+ let ne12 = src1_shape[src1_shape.len() - 3] as i64;
+ let ne13 = src1_shape[src1_shape.len() - 4] as i64;
+
+ let nb10 = src1_stride[src1_stride.len() - 1] as i64;
+ let nb11 = src1_stride[src1_stride.len() - 2] as i64;
+ let nb12 = src1_stride[src1_stride.len() - 3] as i64;
+ let nb13 = src1_stride[src1_stride.len() - 4] as i64;
+
+ let ne0 = dst_shape[dst_shape.len() - 1] as i64;
+ let ne1 = dst_shape[dst_shape.len() - 2] as i64;
+ let r2 = (ne12 / ne02) as u32;
+ let r3 = (ne13 / ne03) as u32;
+
+ let thread_groups_count = MTLSize {
+ width: divide(ne11 as usize, 32),
+ height: divide(ne01 as usize, 64),
+ depth: (ne12 * ne13) as usize,
+ };
+ let threads_per_threadgroup = MTLSize {
+ width: 128,
+ height: 1,
+ depth: 1,
+ };
+ let name = match dtype {
+ GgmlDType::Q4_0 => "kernel_mul_mm_q4_0_f32",
+ GgmlDType::Q4_1 => "kernel_mul_mm_q4_1_f32",
+ GgmlDType::Q5_0 => "kernel_mul_mm_q5_0_f32",
+ GgmlDType::Q5_1 => "kernel_mul_mm_q5_1_f32",
+ GgmlDType::Q8_0 => "kernel_mul_mm_q8_0_f32",
+ GgmlDType::Q2K => "kernel_mul_mm_q2_K_f32",
+ GgmlDType::Q3K => "kernel_mul_mm_q3_K_f32",
+ GgmlDType::Q4K => "kernel_mul_mm_q4_K_f32",
+ GgmlDType::Q5K => "kernel_mul_mm_q5_K_f32",
+ GgmlDType::Q6K => "kernel_mul_mm_q6_K_f32",
+ GgmlDType::F16 => "kernel_mul_mm_f16_f32",
+ GgmlDType::BF16 => "kernel_mul_mm_bf16_f32",
+ GgmlDType::F32 => "kernel_mul_mm_f32_f32",
+ GgmlDType::Q8_1 => Err(MetalKernelError::UnsupportedDTypeForOp("Q8_1", "qmatmul"))?,
+ GgmlDType::Q8K => Err(MetalKernelError::UnsupportedDTypeForOp("Q8K", "qmatmul"))?,
+ };
+
+ let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "qmm_mm {name} M={ne11} K={ne00} N={ne01}");
+
+ set_params!(
+ encoder,
+ (
+ src0,
+ (src1, src1_offset),
+ Output::with_offset(dst, dst_offset),
+ ne00,
+ ne02,
+ nb01,
+ nb02,
+ nb03,
+ ne12,
+ nb10,
+ nb11,
+ nb12,
+ nb13,
+ ne0,
+ ne1,
+ r2,
+ r3
+ )
+ );
+
+ encoder.set_threadgroup_memory_length(0, 8192);
+
+ encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_quantized_get_rows(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: GgmlDType,
+ hidden_size: usize,
+ row_stride: usize,
+ ids_len: usize,
+ src: &Buffer,
+ ids: &Buffer,
+ ids_offset: usize,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dst_row_stride = hidden_size * core::mem::size_of::<f32>();
+ let name = match dtype {
+ GgmlDType::F32 => "kernel_get_rows_f32",
+ GgmlDType::F16 => "kernel_get_rows_f16",
+ GgmlDType::BF16 => "kernel_get_rows_bf16",
+ GgmlDType::Q4_0 => "kernel_get_rows_q4_0",
+ GgmlDType::Q4_1 => "kernel_get_rows_q4_1",
+ GgmlDType::Q5_0 => "kernel_get_rows_q5_0",
+ GgmlDType::Q5_1 => "kernel_get_rows_q5_1",
+ GgmlDType::Q8_0 => "kernel_get_rows_q8_0",
+ GgmlDType::Q2K => "kernel_get_rows_q2_K",
+ GgmlDType::Q3K => "kernel_get_rows_q3_K",
+ GgmlDType::Q4K => "kernel_get_rows_q4_K",
+ GgmlDType::Q5K => "kernel_get_rows_q5_K",
+ GgmlDType::Q6K => "kernel_get_rows_q6_K",
+ GgmlDType::Q8_1 => Err(MetalKernelError::UnsupportedDTypeForOp("Q8_1", "get_rows"))?,
+ GgmlDType::Q8K => Err(MetalKernelError::UnsupportedDTypeForOp("Q8K", "get_rows"))?,
+ };
+
+ let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "qget_rows {name} ids={ids_len} hidden={hidden_size}"
+ );
+
+ let thread_groups_count = MTLSize {
+ width: ids_len,
+ height: 1,
+ depth: 1,
+ };
+ let threads_per_threadgroup = MTLSize {
+ width: 128,
+ height: 1,
+ depth: 1,
+ };
+
+ set_params!(
+ encoder,
+ (
+ src,
+ (ids, ids_offset),
+ Output::new(dst),
+ hidden_size as i64,
+ row_stride as u64,
+ 0u64,
+ ids_len as i64,
+ core::mem::size_of::<u32>() as u64,
+ 0u64,
+ dst_row_stride as u64,
+ 0u64
+ )
+ );
+
+ encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup);
+ Ok(())
+}
+
+fn divide(m: usize, b: usize) -> usize {
+ m.div_ceil(b)
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/random.rs b/vendor/candle-metal-kernels/src/kernels/random.rs
new file mode 100644
index 0000000..b637f7f
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/random.rs
@@ -0,0 +1,73 @@
+use crate::linear_split;
+use crate::utils::EncoderProvider;
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_random_uniform(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ min: f32,
+ max: f32,
+ length: usize,
+ seed: &Buffer,
+ buffer: &Buffer,
+) -> Result<(), MetalKernelError> {
+ if min >= max {
+ return Err(MetalKernelError::LoadLibraryError(
+ "min must be less than max".to_string(),
+ ));
+ }
+ let pipeline = kernels.load_pipeline(device, Source::Random, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ let odd = (length % 2 != 0) as usize;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length / 2 + odd);
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "rand_uniform {name} elems={length}");
+
+ set_params!(
+ encoder,
+ (length, min, max, Output::new(seed), Output::new(buffer))
+ );
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_random_normal(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ mean: f32,
+ stddev: f32,
+ length: usize,
+ seed: &Buffer,
+ buffer: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Random, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ let odd = (length % 2 != 0) as usize;
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length / 2 + odd);
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "rand_normal {name} elems={length}");
+
+ set_params!(
+ encoder,
+ (length, mean, stddev, Output::new(seed), Output::new(buffer))
+ );
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/reduce.rs b/vendor/candle-metal-kernels/src/kernels/reduce.rs
new file mode 100644
index 0000000..dc63575
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/reduce.rs
@@ -0,0 +1,427 @@
+use crate::linear_split;
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError,
+ Output, Source,
+};
+use objc2_metal::MTLSize;
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_reduce_contiguous(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ shape: &[usize],
+ out_length: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let length: usize = shape.iter().product();
+ let num_dims = shape.len();
+ let work_per_threadgroup = length / out_length;
+
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "reduce {kernel_name} length={length} out_length={out_length}"
+ );
+
+ let shape: Vec<u32> = shape.iter().map(|&x| x as u32).collect();
+ set_params!(
+ encoder,
+ (
+ length as u32,
+ num_dims as u32,
+ shape.as_slice(),
+ work_per_threadgroup as u32,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let width = std::cmp::min(
+ pipeline.max_total_threads_per_threadgroup(),
+ (work_per_threadgroup / 2).next_power_of_two(),
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize {
+ width: out_length,
+ height: 1,
+ depth: 1,
+ },
+ MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ },
+ );
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_reduce_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ shape: &[usize],
+ strides: &[usize],
+ out_length: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let length: usize = shape.iter().product();
+ let num_dims = shape.len();
+ let work_per_threadgroup = length / out_length;
+
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "reduce_strided {kernel_name} length={length} out_length={out_length}"
+ );
+
+ let shape: Vec<u32> = shape.iter().map(|&x| x as u32).collect();
+ let strides: Vec<u32> = strides.iter().map(|&x| x as u32).collect();
+ set_params!(
+ encoder,
+ (
+ length as u32,
+ num_dims as u32,
+ shape.as_slice(),
+ strides.as_slice(),
+ work_per_threadgroup as u32,
+ &input,
+ Output::new(output)
+ )
+ );
+
+ let width = std::cmp::min(
+ pipeline.max_total_threads_per_threadgroup(),
+ (work_per_threadgroup / 2).next_power_of_two(),
+ );
+ encoder.dispatch_thread_groups(
+ MTLSize {
+ width: out_length,
+ height: 1,
+ depth: 1,
+ },
+ MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ },
+ );
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_last_softmax(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ length: usize,
+ elements: usize,
+ input: &Buffer,
+ input_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let work_per_threadgroup = elements;
+
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "softmax {kernel_name} length={length} elements={elements}"
+ );
+
+ set_params!(
+ encoder,
+ (
+ length,
+ work_per_threadgroup,
+ (input, input_offset),
+ Output::new(output)
+ )
+ );
+
+ let out_length = length / work_per_threadgroup;
+
+ let thread_group_count = MTLSize {
+ width: out_length,
+ height: 1,
+ depth: 1,
+ };
+
+ let width = std::cmp::min(
+ pipeline.max_total_threads_per_threadgroup(),
+ (work_per_threadgroup / 2).next_power_of_two(),
+ );
+
+ let thread_group_size = MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_rms_norm(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ length: usize,
+ elements_to_sum: usize,
+ eps: f32,
+ input: &Buffer,
+ input_offset: usize,
+ alpha: &Buffer,
+ alpha_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "rms_norm {kernel_name} length={length} elements_to_sum={elements_to_sum}"
+ );
+
+ set_params!(
+ encoder,
+ (
+ length,
+ elements_to_sum,
+ (input, input_offset),
+ Output::new(output),
+ (alpha, alpha_offset),
+ eps
+ )
+ );
+ let work_per_threadgroup = elements_to_sum;
+
+ let out_length = length / work_per_threadgroup;
+
+ let thread_group_count = MTLSize {
+ width: out_length,
+ height: 1,
+ depth: 1,
+ };
+
+ let width = std::cmp::min(
+ pipeline.max_total_threads_per_threadgroup(),
+ (work_per_threadgroup / 2).next_power_of_two(),
+ );
+
+ let thread_group_size = MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_layer_norm(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ length: usize,
+ elements_to_sum: usize,
+ eps: f32,
+ input: &Buffer,
+ input_offset: usize,
+ alpha: &Buffer,
+ alpha_offset: usize,
+ beta: &Buffer,
+ beta_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "layer_norm {kernel_name} length={length} elements_to_sum={elements_to_sum}"
+ );
+
+ set_params!(
+ encoder,
+ (
+ length,
+ elements_to_sum,
+ (input, input_offset),
+ Output::new(output),
+ (alpha, alpha_offset),
+ (beta, beta_offset),
+ eps
+ )
+ );
+
+ let work_per_threadgroup = elements_to_sum;
+
+ let out_length = length / work_per_threadgroup;
+
+ let thread_group_count = MTLSize {
+ width: out_length,
+ height: 1,
+ depth: 1,
+ };
+
+ let width = std::cmp::min(
+ pipeline.max_total_threads_per_threadgroup(),
+ (work_per_threadgroup / 2).next_power_of_two(),
+ );
+
+ let thread_group_size = MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_rope_i(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ bh: usize,
+ td: usize,
+ stride_b: usize,
+ src: &Buffer,
+ src_offset: usize,
+ cos: &Buffer,
+ cos_offset: usize,
+ sin: &Buffer,
+ sin_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "rope_i {kernel_name} bh={bh} td={td}");
+
+ set_params!(
+ encoder,
+ (
+ bh,
+ td,
+ stride_b,
+ (src, src_offset),
+ (cos, cos_offset),
+ (sin, sin_offset),
+ Output::new(output)
+ )
+ );
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, (bh * td) / 2);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_rope_thd(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ b: usize,
+ t: usize,
+ h: usize,
+ d: usize,
+ stride_b: usize,
+ src: &Buffer,
+ src_offset: usize,
+ cos: &Buffer,
+ cos_offset: usize,
+ sin: &Buffer,
+ sin_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "rope_thd {kernel_name} b={b} t={t} h={h} d={d}");
+
+ set_params!(
+ encoder,
+ (
+ b,
+ t,
+ h,
+ d,
+ stride_b,
+ (src, src_offset),
+ (cos, cos_offset),
+ (sin, sin_offset),
+ Output::new(output)
+ )
+ );
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, (b * t * h * d) / 2);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_rope(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: &'static str,
+ bh: usize,
+ td: usize,
+ d: usize,
+ stride_b: usize,
+ src: &Buffer,
+ src_offset: usize,
+ cos: &Buffer,
+ cos_offset: usize,
+ sin: &Buffer,
+ sin_offset: usize,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "rope {kernel_name} bh={bh} td={td} d={d}");
+
+ set_params!(
+ encoder,
+ (
+ bh,
+ td,
+ d,
+ stride_b,
+ (src, src_offset),
+ (cos, cos_offset),
+ (sin, sin_offset),
+ Output::new(output)
+ )
+ );
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, (bh * td) / 2);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/sdpa.rs b/vendor/candle-metal-kernels/src/kernels/sdpa.rs
new file mode 100644
index 0000000..c233e51
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/sdpa.rs
@@ -0,0 +1,543 @@
+use crate::utils::EncoderProvider;
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, ConstantValues, Device, EncoderParam,
+ Kernels, MetalKernelError, Output, Source, Value,
+};
+use objc2_metal::MTLSize;
+
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
+pub enum SdpaDType {
+ BF16,
+ F16,
+ F32,
+}
+
+/// SDPA full is supported when:
+/// - q head dim == 64, 128
+/// - no mask
+/// - q heads == kv heads
+/// - final type != bf16 (TODO maybe just template this kernel too?)
+/// - q,k,v are contiguous
+#[allow(clippy::too_many_arguments)]
+pub fn call_sdpa_full(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ q_offset: usize,
+ q_shape: &[usize],
+ q_strides: &[usize],
+ q_buffer: &Buffer,
+ k_offset: usize,
+ k_shape: &[usize],
+ k_strides: &[usize],
+ k_buffer: &Buffer,
+ v_offset: usize,
+ v_buffer: &Buffer,
+ v_strides: &[usize],
+ mask_type: Option<SdpaDType>,
+ mask_buffer: Option<&Buffer>,
+ m_strides: Option<&[usize]>,
+ output: &Buffer,
+ o_strides: &[usize],
+ scale: f32,
+ do_causal: bool,
+ itype: SdpaDType,
+) -> Result<(), MetalKernelError> {
+ #[derive(Debug)]
+ #[repr(C)]
+ struct AttnParams {
+ b: i32,
+ h: i32,
+ d: i32,
+ ql: i32,
+ kl: i32,
+ gqa_factor: i32,
+ scale: f32,
+ softcapping: f32, // Must match Metal struct layout (1.0 = disabled)
+ nq: i32,
+ nk: i32,
+ nq_aligned: i32,
+ nk_aligned: i32,
+ ql_rem: i32,
+ kl_rem: i32,
+ ql_off: i32,
+ q_strides: [i64; 3],
+ k_strides: [i64; 3],
+ v_strides: [i64; 3],
+ o_strides: [i64; 3],
+ }
+
+ #[derive(Debug)]
+ #[repr(C)]
+ struct AttnMaskParams {
+ m_strides: [i64; 3],
+ }
+
+ let bd = q_shape[q_shape.len() - 1];
+ if ![32, 64, 72, 80, 96, 128, 256, 512].contains(&bd) {
+ return Err(MetalKernelError::SdpaHeadSizeMismatch {
+ variation: "full",
+ got: bd,
+ expected: vec![32, 64, 72, 80, 96, 128, 256, 512],
+ });
+ };
+
+ // BD=512 uses reduced tiles to fit 32KB threadgroup memory (f16/bf16 only).
+ let (bq, bk, wm, wn): (usize, usize, usize, usize) = if bd == 512 {
+ if itype == SdpaDType::F32 {
+ return Err(MetalKernelError::SdpaHeadSizeMismatch {
+ variation: "full (f32 unsupported at head_dim=512)",
+ got: bd,
+ expected: vec![32, 64, 72, 80, 96, 128, 256],
+ });
+ }
+ (8, 8, 1, 1)
+ } else {
+ let bk = if bd < 128 { 32 } else { 16 };
+ (32, bk, 4, 1)
+ };
+
+ let b = q_shape[0];
+ let h = q_shape[1];
+ let d = q_shape[3];
+ let gqa_factor = q_shape[1] / k_shape[1];
+
+ let ql = q_shape[2];
+ let kl = k_shape[2];
+
+ let align_q = (ql % bq) == 0;
+ let align_k = (kl % bk) == 0;
+ let has_mask = mask_buffer.is_some();
+
+ // When an explicit additive mask is supplied it already encodes causality.
+ // Also enabling the in-kernel `do_causal` path double-applies causality and,
+ // at periodic sequence lengths, leaves a query row fully masked -> softmax
+ // normalizer sum(exp) == 0 -> final divide computes 0/0 = NaN logits.
+ let do_causal = do_causal && !has_mask;
+
+ let itype_repr = match itype {
+ SdpaDType::BF16 => "bfloat16",
+ SdpaDType::F16 => "float16",
+ SdpaDType::F32 => "float32",
+ };
+ let mask_repr = match mask_type {
+ Some(SdpaDType::BF16) => "bfloat16",
+ Some(SdpaDType::F16) => "float16",
+ Some(SdpaDType::F32) => "float32",
+ None => itype_repr,
+ };
+ let name =
+ format!("steel_attention_{itype_repr}_bq{bq}_bk{bk}_bd{bd}_wm{wm}_wn{wn}_mask{mask_repr}");
+
+ let constants = Some(ConstantValues::new(vec![
+ (200, Value::Bool(/* align_Q */ align_q)),
+ (201, Value::Bool(/* align_K */ align_k)),
+ (300, Value::Bool(/* has_mask */ has_mask)),
+ (301, Value::Bool(/* do_causal */ do_causal)),
+ ]));
+
+ #[cfg(feature = "debug-labels")]
+ let name_for_label = name.clone();
+ let pipeline = kernels.load_pipeline_with_constants(device, Source::Sdpa, name, constants)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "sdpa_full {name_for_label} B={b} H={h} D={d} QL={ql} KL={kl}"
+ );
+
+ let nq = (ql + bq - 1) / bq;
+ let nk = (kl + bk - 1) / bk;
+
+ let nq_aligned = ql / bq;
+ let nk_aligned = kl / bk;
+
+ let params = AttnParams {
+ b: b as i32,
+ h: h as i32,
+ d: d as i32,
+ ql: ql as i32,
+ kl: kl as i32,
+ gqa_factor: gqa_factor as i32,
+ scale,
+ softcapping: 1.0, // SDPA full doesn't support softcapping, always 1.0
+ nq: nq as i32,
+ nk: nk as i32,
+ nq_aligned: nq_aligned as i32,
+ nk_aligned: nk_aligned as i32,
+ ql_rem: ql.wrapping_sub(nq_aligned * bq) as i32,
+ kl_rem: kl.wrapping_sub(nk_aligned * bk) as i32,
+ ql_off: kl.wrapping_sub(ql) as i32,
+ q_strides: [
+ q_strides[0] as i64,
+ q_strides[1] as i64,
+ q_strides[2] as i64,
+ ],
+ k_strides: [
+ k_strides[0] as i64,
+ k_strides[1] as i64,
+ k_strides[2] as i64,
+ ],
+ v_strides: [
+ v_strides[0] as i64,
+ v_strides[1] as i64,
+ v_strides[2] as i64,
+ ],
+ o_strides: [
+ o_strides[0] as i64,
+ o_strides[1] as i64,
+ o_strides[2] as i64,
+ ],
+ };
+
+ impl EncoderParam for AttnParams {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_bytes(position, &data);
+ }
+ }
+
+ impl EncoderParam for AttnMaskParams {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_bytes(position, &data);
+ }
+ }
+
+ if let Some(mask) = mask_buffer {
+ let mask_strides = m_strides.unwrap();
+ let mask_params = AttnMaskParams {
+ m_strides: [
+ mask_strides[0] as i64,
+ mask_strides[1] as i64,
+ mask_strides[2] as i64,
+ ],
+ };
+
+ set_params!(
+ encoder,
+ (
+ (q_buffer, q_offset),
+ (k_buffer, k_offset),
+ (v_buffer, v_offset),
+ Output::new(output),
+ params,
+ mask_params,
+ mask
+ )
+ );
+ } else {
+ set_params!(
+ encoder,
+ (
+ (q_buffer, q_offset),
+ (k_buffer, k_offset),
+ (v_buffer, v_offset),
+ Output::new(output),
+ params
+ )
+ );
+ }
+
+ let grid_dims = MTLSize {
+ width: nq,
+ height: h,
+ depth: b,
+ };
+ let group_dims = MTLSize {
+ width: 32,
+ height: wm,
+ depth: wn,
+ };
+ encoder.dispatch_thread_groups(grid_dims, group_dims);
+
+ Ok(())
+}
+
+/// SDPA full is supported when:
+/// - q head dim == 64, 96, 128
+/// - no mask
+/// - q,k,v are contiguous
+#[allow(clippy::too_many_arguments)]
+pub fn call_sdpa_vector(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ q_offset: usize,
+ q_shape: &[usize],
+ q_buffer: &Buffer,
+ k_offset: usize,
+ k_shape: &[usize],
+ k_stride: &[usize],
+ k_buffer: &Buffer,
+ v_offset: usize,
+ v_stride: &[usize],
+ v_buffer: &Buffer,
+ output: &Buffer,
+ alpha: f32,
+ softcapping: f32,
+ itype: SdpaDType,
+) -> Result<(), MetalKernelError> {
+ let bk = q_shape.last().unwrap();
+
+ let gqa_factor = (q_shape[1] / k_shape[1]) as i32;
+ let n = k_shape[2] as i32;
+ let b = (q_shape[0] * q_shape[1]) as i32;
+ let kstride = k_stride[1];
+ let vstride = v_stride[1];
+
+ let name = match (bk, itype) {
+ (32, SdpaDType::F16) => "sdpa_vector_float16_t_32",
+ (64, SdpaDType::F16) => "sdpa_vector_float16_t_64",
+ (96, SdpaDType::F16) => "sdpa_vector_float16_t_96",
+ (128, SdpaDType::F16) => "sdpa_vector_float16_t_128",
+ (256, SdpaDType::F16) => "sdpa_vector_float16_t_256",
+ (512, SdpaDType::F16) => "sdpa_vector_float16_t_512",
+ (32, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_32",
+ (64, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_64",
+ (96, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_96",
+ (128, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_128",
+ (256, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_256",
+ (512, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_512",
+ (32, SdpaDType::F32) => "sdpa_vector_float_32",
+ (64, SdpaDType::F32) => "sdpa_vector_float_64",
+ (96, SdpaDType::F32) => "sdpa_vector_float_96",
+ (128, SdpaDType::F32) => "sdpa_vector_float_128",
+ (256, SdpaDType::F32) => "sdpa_vector_float_256",
+ (512, SdpaDType::F32) => "sdpa_vector_float_512",
+ (other, _) => {
+ return Err(MetalKernelError::SdpaHeadSizeMismatch {
+ variation: "vector",
+ got: *other,
+ expected: vec![32, 64, 96, 128, 256, 512],
+ })
+ }
+ };
+
+ let alpha = if softcapping != 1. {
+ alpha / softcapping
+ } else {
+ alpha
+ };
+
+ let constants = Some(ConstantValues::new(vec![(
+ 20,
+ Value::Bool(/* sdpa_vector_has_mask */ false),
+ )]));
+
+ let pipeline = kernels.load_pipeline_with_constants(device, Source::Sdpa, name, constants)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "sdpa_vector bk={bk} B={b} N={n}");
+
+ // q = (bs, qhead, seq, hidden)
+ // k/v = (bs, kv_head, kv_seq, hidden)
+
+ set_params!(
+ encoder,
+ (
+ (q_buffer, q_offset),
+ (k_buffer, k_offset),
+ (v_buffer, v_offset),
+ Output::new(output),
+ gqa_factor,
+ n,
+ kstride,
+ vstride,
+ alpha,
+ softcapping
+ )
+ );
+
+ let grid_dims = MTLSize {
+ width: 1,
+ height: b as usize,
+ depth: 1,
+ };
+ let group_dims = MTLSize {
+ width: 1024,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(grid_dims, group_dims);
+ Ok(())
+}
+
+pub const SDPA_2PASS_BLOCKS: usize = 32;
+
+/// SDPA vector 2pass is supported when:
+/// - q head dim == 64, 96, 128
+/// - no mask
+/// - q,k,v are contiguous
+#[allow(clippy::too_many_arguments)]
+pub fn call_sdpa_vector_2pass(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ q_offset: usize,
+ q_shape: &[usize],
+ q_buffer: &Buffer,
+ k_offset: usize,
+ k_shape: &[usize],
+ k_stride: &[usize],
+ k_buffer: &Buffer,
+ v_offset: usize,
+ v_stride: &[usize],
+ v_buffer: &Buffer,
+ output: &Buffer,
+ intermediate: &Buffer,
+ sums: &Buffer,
+ maxs: &Buffer,
+ alpha: f32,
+ softcapping: f32,
+ itype: SdpaDType,
+) -> Result<(), MetalKernelError> {
+ let bk = q_shape.last().unwrap();
+
+ // First pass
+ {
+ let name_pass1 = match (bk, itype) {
+ (32, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_32",
+ (64, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_64",
+ (96, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_96",
+ (128, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_128",
+ (256, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_256",
+ (512, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_512",
+ (32, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_32",
+ (64, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_64",
+ (96, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_96",
+ (128, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_128",
+ (256, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_256",
+ (512, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_512",
+ (32, SdpaDType::F32) => "sdpa_vector_2pass_1_float_32",
+ (64, SdpaDType::F32) => "sdpa_vector_2pass_1_float_64",
+ (96, SdpaDType::F32) => "sdpa_vector_2pass_1_float_96",
+ (128, SdpaDType::F32) => "sdpa_vector_2pass_1_float_128",
+ (256, SdpaDType::F32) => "sdpa_vector_2pass_1_float_256",
+ (512, SdpaDType::F32) => "sdpa_vector_2pass_1_float_512",
+ (other, _) => {
+ return Err(MetalKernelError::SdpaHeadSizeMismatch {
+ variation: "vector_2pass_1",
+ got: *other,
+ expected: vec![32, 64, 96, 128, 256, 512],
+ })
+ }
+ };
+
+ let gqa_factor = (q_shape[1] / k_shape[1]) as i32;
+ let n = k_shape[2] as i32;
+ let b = (q_shape[0] * q_shape[1]) as i32;
+ let kstride = k_stride[1];
+ let vstride = v_stride[1];
+
+ let alpha = if softcapping != 1. {
+ alpha / softcapping
+ } else {
+ alpha
+ };
+
+ let constants = Some(ConstantValues::new(vec![(
+ 20,
+ Value::Bool(/* sdpa_vector_has_mask */ false),
+ )]));
+
+ let pipeline =
+ kernels.load_pipeline_with_constants(device, Source::Sdpa, name_pass1, constants)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "sdpa_vector_2pass pass1 bk={bk} B={b} N={n}");
+
+ // q = (bs, qhead, seq, hidden)
+ // k/v = (bs, kv_head, kv_seq, hidden)
+
+ set_params!(
+ encoder,
+ (
+ (q_buffer, q_offset),
+ (k_buffer, k_offset),
+ (v_buffer, v_offset),
+ Output::new(intermediate),
+ Output::new(sums),
+ Output::new(maxs),
+ gqa_factor,
+ n,
+ kstride,
+ vstride,
+ alpha,
+ softcapping
+ )
+ );
+
+ let grid_dims = MTLSize {
+ width: 1,
+ height: b as usize,
+ depth: SDPA_2PASS_BLOCKS,
+ };
+ let group_dims = MTLSize {
+ width: 8 * 32,
+ height: 1,
+ depth: 1,
+ };
+
+ encoder.dispatch_thread_groups(grid_dims, group_dims);
+ }
+
+ // Final pass
+ {
+ let name_pass2 = match (bk, itype) {
+ (32, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_32",
+ (64, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_64",
+ (96, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_96",
+ (128, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_128",
+ (256, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_256",
+ (512, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_512",
+ (32, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_32",
+ (64, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_64",
+ (96, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_96",
+ (128, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_128",
+ (256, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_256",
+ (512, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_512",
+ (32, SdpaDType::F32) => "sdpa_vector_2pass_2_float_32",
+ (64, SdpaDType::F32) => "sdpa_vector_2pass_2_float_64",
+ (96, SdpaDType::F32) => "sdpa_vector_2pass_2_float_96",
+ (128, SdpaDType::F32) => "sdpa_vector_2pass_2_float_128",
+ (256, SdpaDType::F32) => "sdpa_vector_2pass_2_float_256",
+ (512, SdpaDType::F32) => "sdpa_vector_2pass_2_float_512",
+ (other, _) => {
+ return Err(MetalKernelError::SdpaHeadSizeMismatch {
+ variation: "vector_2pass_2",
+ got: *other,
+ expected: vec![32, 64, 96, 128, 256, 512],
+ })
+ }
+ };
+
+ let b = q_shape[0] * q_shape[1];
+
+ let pipeline = kernels.load_pipeline(device, Source::Sdpa, name_pass2)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "sdpa_vector_2pass pass2 bk={bk} B={b}");
+
+ // q = (bs, qhead, seq, hidden)
+ // k/v = (bs, kv_head, kv_seq, hidden)
+
+ set_params!(encoder, (intermediate, sums, maxs, Output::new(output)));
+
+ let grid_dims = MTLSize {
+ width: 1,
+ height: b,
+ depth: 1,
+ };
+ let group_dims = MTLSize {
+ width: 1024,
+ height: 1,
+ depth: 1,
+ };
+
+ encoder.dispatch_thread_groups(grid_dims, group_dims);
+ }
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/sort.rs b/vendor/candle-metal-kernels/src/kernels/sort.rs
new file mode 100644
index 0000000..750d373
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/sort.rs
@@ -0,0 +1,316 @@
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, metal_label, set_params, DType, Kernels, MetalKernelError, Output, Source,
+};
+use crate::{Buffer, ComputeCommandEncoder, Device, MTLSize, RESOURCE_OPTIONS};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_arg_sort(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ nrows: usize,
+ ncols: usize,
+ ncols_pad: usize,
+ src: BufferOffset,
+ dst: &Buffer,
+) -> Result<(), crate::MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Sort, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "arg_sort {name} nrows={nrows} ncols={ncols}");
+
+ set_params!(
+ encoder,
+ (&src, Output::new(dst), ncols as i64, ncols_pad as i64)
+ );
+
+ let thread_group_count = MTLSize {
+ width: 1,
+ height: nrows,
+ depth: 1,
+ };
+ let thread_group_size = MTLSize {
+ width: ncols_pad,
+ height: 1,
+ depth: 1,
+ };
+
+ encoder.set_threadgroup_memory_length(0, (ncols_pad * 4).max(16));
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+fn mlx_dtype_str(dtype: DType) -> &'static str {
+ match dtype {
+ DType::U8 => "uint8",
+ DType::U32 => "uint32",
+ DType::I64 => "int64",
+ DType::F16 => "float16",
+ DType::BF16 => "bfloat16",
+ DType::F32 => "float32",
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn multi_block_sort(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: DType,
+ bn: usize,
+ tn: usize,
+ nblocks: usize,
+ nrows: usize,
+ ncols: usize,
+ src: BufferOffset,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dtype_str = mlx_dtype_str(dtype);
+ // Do allocations
+ let el_count = nrows * ncols;
+ let bytes_len = el_count * dtype.size_in_bytes();
+ let mut dev_vals_0 = device.new_buffer(bytes_len, RESOURCE_OPTIONS)?;
+ metal_label!(dev_vals_0, "mlx_arg_sort dev_vals_0");
+ let mut dev_vals_1 = device.new_buffer(bytes_len, RESOURCE_OPTIONS)?;
+ metal_label!(dev_vals_1, "mlx_arg_sort dev_vals_1");
+ let mut dev_idxs_0 = device.new_buffer(el_count * 4, RESOURCE_OPTIONS)?;
+ metal_label!(dev_idxs_0, "mlx_arg_sort dev_idxs_0");
+ let mut dev_idxs_1 = device.new_buffer(el_count * 4, RESOURCE_OPTIONS)?;
+ metal_label!(dev_idxs_1, "mlx_arg_sort dev_idxs_1");
+ let mut block_partitions = device.new_buffer((nrows * (nblocks + 1)) * 4, RESOURCE_OPTIONS)?;
+ metal_label!(block_partitions, "mlx_arg_sort block_partitions");
+ // Prepare command encoder
+ let encoder_guard = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder_guard.as_ref();
+ // Do blockwise sort
+ {
+ let name = format!("sort_mbsort_{dtype_str}_uint32_bn{bn}_tn{tn}");
+ let pipeline = kernels.load_pipeline(device, Source::MlxSort, name)?;
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "mlx_arg_sort multi_block block_sort {dtype_str} nrows={nrows} ncols={ncols} blocks={nblocks}"
+ );
+ set_params!(
+ encoder,
+ (
+ &src,
+ &mut dev_vals_0,
+ &mut dev_idxs_0,
+ /* size_sorted_axis */ ncols as i32,
+ /* stride_sorted_axis */ 1i32,
+ /* nc_dim */ 1i32,
+ /* nc_shape */ nrows as i32,
+ /* nc_str */ ncols as i64
+ )
+ );
+ let thread_group_count = MTLSize {
+ width: nblocks,
+ height: nrows,
+ depth: 1,
+ };
+ let thread_group_size = MTLSize {
+ width: bn,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ }
+ // Do merges
+ let mut ping = false;
+ let mut merge_tiles = 2;
+ let n_thr_per_group = usize::min(nblocks + 1, 1024);
+ let partition_name = format!("partition_mbsort_{dtype_str}_uint32_bn{bn}_tn{tn}");
+ let merge_name = format!("merge_mbsort_float32_uint32_bn{bn}_tn{tn}");
+ while merge_tiles / 2 < nblocks {
+ let (dev_vals_in, dev_vals_out) = if ping {
+ (&mut dev_vals_1, &mut dev_vals_0)
+ } else {
+ (&mut dev_vals_0, &mut dev_vals_1)
+ };
+ let (dev_idxs_in, dev_idxs_out) = if ping {
+ (&mut dev_idxs_1, &mut dev_idxs_0)
+ } else {
+ (&mut dev_idxs_0, &mut dev_idxs_1)
+ };
+ ping = !ping;
+ // Do partition
+ {
+ let pipeline =
+ kernels.load_pipeline(device, Source::MlxSort, partition_name.clone())?;
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "mlx_arg_sort multi_block partition {dtype_str} merge_tiles={merge_tiles} blocks={nblocks}"
+ );
+ set_params!(
+ encoder,
+ (
+ &mut block_partitions,
+ &*dev_vals_in,
+ &*dev_idxs_in,
+ /* size_sorted_axis */ ncols as i32,
+ /* merge_tiles */ merge_tiles as i32,
+ /* n_blocks */ nblocks as i32
+ )
+ );
+ let thread_group_count = MTLSize {
+ width: 1,
+ height: nrows,
+ depth: 1,
+ };
+ let thread_group_size = MTLSize {
+ width: n_thr_per_group,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ }
+ // Do merge
+ {
+ let pipeline = kernels.load_pipeline(device, Source::MlxSort, merge_name.clone())?;
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "mlx_arg_sort multi_block merge {dtype_str} merge_tiles={merge_tiles} blocks={nblocks}"
+ );
+ set_params!(
+ encoder,
+ (
+ &block_partitions,
+ &*dev_vals_in,
+ &*dev_idxs_in,
+ Output::new(&*dev_vals_out),
+ Output::new(&*dev_idxs_out),
+ /* size_sorted_axis */ ncols as i32,
+ /* merge_tiles */ merge_tiles as i32,
+ /* n_blocks */ nblocks as i32
+ )
+ );
+ let thread_group_count = MTLSize {
+ width: nblocks,
+ height: nrows,
+ depth: 1,
+ };
+ let thread_group_size = MTLSize {
+ width: bn,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ }
+ merge_tiles *= 2;
+ }
+ let dev_idxs_out = if ping {
+ &mut dev_idxs_1
+ } else {
+ &mut dev_idxs_0
+ };
+ // Copy output with appropriate strides
+ let copy_kernel = match dtype {
+ DType::U8 => crate::copy2d::U8,
+ DType::U32 => crate::copy2d::U32,
+ DType::I64 => crate::copy2d::I64,
+ DType::BF16 => crate::copy2d::BFLOAT,
+ DType::F16 => crate::copy2d::HALF,
+ DType::F32 => crate::copy2d::FLOAT,
+ };
+ crate::call_copy2d(
+ device,
+ encoder,
+ kernels,
+ copy_kernel,
+ dev_idxs_out,
+ dst,
+ /* d1 */ nrows,
+ /* d2 */ ncols,
+ /* src_s */ ncols,
+ /* dst_s */ ncols,
+ /* src_o_in_bytes */ 0,
+ /*dst_o_in_bytes */ 0,
+ )?;
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+fn block_sort(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: DType,
+ bn: usize,
+ tn: usize,
+ nrows: usize,
+ ncols: usize,
+ src: BufferOffset,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let dtype_str = mlx_dtype_str(dtype);
+ let name = format!("carg_block_sort_{dtype_str}_uint32_bn{bn}_tn{tn}");
+ #[cfg(feature = "debug-labels")]
+ let name_for_label = name.clone();
+ let pipeline = kernels.load_pipeline(device, Source::MlxSort, name)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(
+ encoder,
+ "mlx_arg_sort block {name_for_label} nrows={nrows} ncols={ncols}"
+ );
+ set_params!(
+ encoder,
+ (
+ &src,
+ Output::new(dst),
+ ncols as i32,
+ 1i32,
+ 1i32,
+ ncols as i32,
+ ncols as i32
+ )
+ );
+ let thread_group_count = MTLSize {
+ width: 1,
+ height: nrows,
+ depth: 1,
+ };
+ let thread_group_size = MTLSize {
+ width: bn,
+ height: 1,
+ depth: 1,
+ };
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_mlx_arg_sort(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ dtype: DType,
+ nrows: usize,
+ ncols: usize,
+ src: BufferOffset,
+ dst: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let tn = 8;
+ let bn = match ncols.div_ceil(tn) {
+ 257.. if dtype.size_in_bytes() <= 4 => 512,
+ 129.. => 256,
+ 0..129 => 128,
+ };
+ let n_per_block = bn * tn;
+ let n_blocks = ncols.div_ceil(n_per_block);
+ if n_blocks > 1 {
+ multi_block_sort(
+ device, ep, kernels, dtype, bn, tn, n_blocks, nrows, ncols, src, dst,
+ )?
+ } else {
+ block_sort(device, ep, kernels, dtype, bn, tn, nrows, ncols, src, dst)?
+ }
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/ternary.rs b/vendor/candle-metal-kernels/src/kernels/ternary.rs
new file mode 100644
index 0000000..5e76eb7
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/ternary.rs
@@ -0,0 +1,65 @@
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, ConstantValues, Device, Kernels,
+ MetalKernelError, Output, Source, Value,
+};
+use crate::{get_tile_size, linear_split};
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_where_cond(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: &'static str,
+ dtype_size: usize,
+ shape: &[usize],
+ cond: BufferOffset,
+ cond_stride: &[usize],
+ cond_is_contiguous: bool,
+ left: BufferOffset,
+ left_stride: &[usize],
+ left_is_contiguous: bool,
+ right: BufferOffset,
+ right_stride: &[usize],
+ right_is_contiguous: bool,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let constants = Some(ConstantValues::new(vec![
+ (0, Value::Bool(cond_is_contiguous)),
+ (1, Value::Bool(left_is_contiguous)),
+ (2, Value::Bool(right_is_contiguous)),
+ ]));
+ let pipeline =
+ kernels.load_pipeline_with_constants(device, Source::Ternary, name, constants)?;
+
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+
+ let size: usize = shape.iter().product();
+ let rank = shape.len();
+ debug_group!(encoder, "where {name} elems={size}");
+
+ set_params!(
+ encoder,
+ (
+ size,
+ rank,
+ shape,
+ cond_stride,
+ left_stride,
+ right_stride,
+ &cond,
+ &left,
+ &right,
+ Output::new(output)
+ )
+ );
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = size.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/kernels/unary.rs b/vendor/candle-metal-kernels/src/kernels/unary.rs
new file mode 100644
index 0000000..4ccadc2
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/kernels/unary.rs
@@ -0,0 +1,195 @@
+use crate::kernels::macros::ops;
+use crate::utils::{BufferOffset, EncoderProvider};
+use crate::{
+ debug_group, set_params, Buffer, ComputeCommandEncoder, Device, EncoderParam, Kernels,
+ MetalKernelError, Output, Source,
+};
+use crate::{get_block_dims, get_tile_size, linear_split};
+use objc2_metal::MTLSize;
+
+ops!(
+ cos, sin, exp, sqr, sqrt, neg, log, gelu, abs, ceil, floor, relu, round, erf, gelu_erf, tanh,
+ recip, silu, sign, sigmoid, const_set
+);
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_unary_contiguous(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: contiguous::Kernel,
+ dtype_size: usize,
+ length: usize,
+ input: BufferOffset,
+ output: &Buffer,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "unary {} elems={length}", kernel_name.0);
+
+ set_params!(encoder, (length, &input, Output::new(output)));
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = length.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_unary_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: strided::Kernel,
+ shape: &[usize],
+ input: BufferOffset,
+ strides: &[usize],
+ output: BufferOffset,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?;
+
+ let length: usize = shape.iter().product();
+ let num_dims: usize = shape.len();
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length);
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "unary_strided {} elems={length}", name.0);
+ set_params!(
+ encoder,
+ (
+ length,
+ num_dims,
+ shape,
+ strides,
+ &input,
+ Output::from_buffer_offset(&output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_const_set_contiguous(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ kernel_name: contiguous::Kernel,
+ dtype_size: usize,
+ length: usize,
+ input: impl EncoderParam,
+ output: BufferOffset,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "const_set {} elems={length}", kernel_name.0);
+ set_params!(
+ encoder,
+ (length, input, Output::from_buffer_offset(&output))
+ );
+
+ let tile_size = get_tile_size(dtype_size);
+ let tiles = length.div_ceil(tile_size);
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles);
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_const_set_strided(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: strided::Kernel,
+ shape: &[usize],
+ input: impl EncoderParam,
+ strides: &[usize],
+ output: BufferOffset,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?;
+
+ let length: usize = shape.iter().product();
+ let num_dims: usize = shape.len();
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ let (thread_group_count, thread_group_size) = linear_split(&pipeline, length);
+
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "const_set_strided {} elems={length}", name.0);
+ set_params!(
+ encoder,
+ (
+ length,
+ num_dims,
+ shape,
+ strides,
+ input,
+ Output::from_buffer_offset(&output)
+ )
+ );
+ encoder.dispatch_thread_groups(thread_group_count, thread_group_size);
+ Ok(())
+}
+
+pub mod copy2d {
+ pub struct Kernel(pub &'static str);
+ pub const FLOAT: Kernel = Kernel("copy2d_f32");
+ pub const HALF: Kernel = Kernel("copy2d_f16");
+ pub const BFLOAT: Kernel = Kernel("copy2d_bf16");
+ pub const I64: Kernel = Kernel("copy2d_i64");
+ pub const I32: Kernel = Kernel("copy2d_i32");
+ pub const I16: Kernel = Kernel("copy2d_i16");
+ pub const U32: Kernel = Kernel("copy2d_u32");
+ pub const U8: Kernel = Kernel("copy2d_u8");
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn call_copy2d(
+ device: &Device,
+ ep: impl EncoderProvider,
+ kernels: &Kernels,
+ name: copy2d::Kernel,
+ input: &Buffer,
+ output: &Buffer,
+ d1: usize,
+ d2: usize,
+ src_s: usize,
+ dst_s: usize,
+ src_o_in_bytes: usize,
+ dst_o_in_bytes: usize,
+) -> Result<(), MetalKernelError> {
+ let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?;
+ let encoder = ep.encoder();
+ let encoder: &ComputeCommandEncoder = encoder.as_ref();
+ encoder.set_compute_pipeline_state(&pipeline);
+ debug_group!(encoder, "copy2d {} d1={d1} d2={d2}", name.0);
+ set_params!(
+ encoder,
+ (
+ d1 as i64,
+ d2 as i64,
+ src_s as i64,
+ dst_s as i64,
+ (input, src_o_in_bytes),
+ Output::with_offset(output, dst_o_in_bytes)
+ )
+ );
+
+ let grid_dims = MTLSize {
+ width: d1,
+ height: d2,
+ depth: 1,
+ };
+ let group_dims = get_block_dims(d1, d2, 1);
+ encoder.dispatch_threads(grid_dims, group_dims);
+ Ok(())
+}
diff --git a/vendor/candle-metal-kernels/src/lib.rs b/vendor/candle-metal-kernels/src/lib.rs
new file mode 100644
index 0000000..c75cdb7
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/lib.rs
@@ -0,0 +1,52 @@
+pub mod err;
+pub mod kernel;
+pub mod kernels;
+pub mod metal;
+pub mod source;
+pub mod utils;
+
+pub use err::MetalKernelError;
+pub use kernel::Kernels;
+pub use kernels::{
+ affine::*, call_binary_contiguous, call_binary_strided, call_mlx_gemm, cast::*, convolution::*,
+ fill::*, indexing::*, quantized::*, random::*, reduce::*, sdpa::*, sort::*, ternary::*, unary,
+ unary::*, GemmDType, GgmlDType,
+};
+use metal::{
+ Buffer, CommandQueue, ComputeCommandEncoder, ComputePipeline, ConstantValues, Device, Function,
+ Library, MTLResourceOptions, Value,
+};
+use objc2_metal::{MTLCompileOptions, MTLMathFloatingPointFunctions, MTLMathMode, MTLSize};
+use source::Source;
+use utils::{get_block_dims, get_tile_size, linear_split, EncoderParam, EncoderProvider};
+pub use utils::{BufferOffset, Output};
+
+pub const RESOURCE_OPTIONS: MTLResourceOptions = objc2_metal::MTLResourceOptions(
+ MTLResourceOptions::StorageModeShared.0 | MTLResourceOptions::HazardTrackingModeUntracked.0,
+);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum DType {
+ BF16,
+ F16,
+ F32,
+ I64,
+ U32,
+ U8,
+}
+
+impl DType {
+ fn size_in_bytes(&self) -> usize {
+ match self {
+ Self::U8 => 1,
+ Self::U32 => 4,
+ Self::I64 => 8,
+ Self::BF16 => 2,
+ Self::F16 => 2,
+ Self::F32 => 4,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/vendor/candle-metal-kernels/src/metal/buffer.rs b/vendor/candle-metal-kernels/src/metal/buffer.rs
new file mode 100644
index 0000000..eecf163
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/buffer.rs
@@ -0,0 +1,62 @@
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::{NSRange, NSString};
+use objc2_metal::{MTLBuffer, MTLResource};
+use std::{collections::HashMap, sync::Arc};
+
+pub type MetalResource = ProtocolObject<dyn MTLResource>;
+pub type MTLResourceOptions = objc2_metal::MTLResourceOptions;
+
+#[derive(Clone, Debug, Hash, PartialEq)]
+pub struct Buffer {
+ raw: Retained<ProtocolObject<dyn MTLBuffer>>,
+}
+
+unsafe impl Send for Buffer {}
+unsafe impl Sync for Buffer {}
+
+impl Buffer {
+ pub fn new(raw: Retained<ProtocolObject<dyn MTLBuffer>>) -> Buffer {
+ Buffer { raw }
+ }
+
+ pub fn contents(&self) -> *mut u8 {
+ self.data()
+ }
+
+ pub fn data(&self) -> *mut u8 {
+ use objc2_metal::MTLBuffer as _;
+ self.as_ref().contents().as_ptr() as *mut u8
+ }
+
+ /// Get the raw pointer to the underlying Metal buffer object.
+ /// Used for dependency tracking in the compute encoder.
+ pub(crate) fn raw_ptr(&self) -> *const ProtocolObject<dyn MTLBuffer> {
+ Retained::as_ptr(&self.raw)
+ }
+
+ pub fn length(&self) -> usize {
+ self.as_ref().length()
+ }
+
+ pub fn did_modify_range(&self, range: NSRange) {
+ self.as_ref().didModifyRange(range);
+ }
+
+ pub fn set_label(&self, label: &str) {
+ self.raw.setLabel(Some(&NSString::from_str(label)))
+ }
+}
+
+impl AsRef<ProtocolObject<dyn MTLBuffer>> for Buffer {
+ fn as_ref(&self) -> &ProtocolObject<dyn MTLBuffer> {
+ &self.raw
+ }
+}
+
+impl<'a> From<&'a Buffer> for &'a MetalResource {
+ fn from(val: &'a Buffer) -> Self {
+ ProtocolObject::from_ref(val.as_ref())
+ }
+}
+
+pub type BufferMap = HashMap<usize, Vec<Arc<Buffer>>>;
diff --git a/vendor/candle-metal-kernels/src/metal/command_buffer.rs b/vendor/candle-metal-kernels/src/metal/command_buffer.rs
new file mode 100644
index 0000000..38633e7
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/command_buffer.rs
@@ -0,0 +1,92 @@
+use super::{BlitCommandEncoder, ComputeCommandEncoder, Device, Fence, PrevCeOutputs};
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::NSString;
+use objc2_metal::{MTLCommandBuffer, MTLCommandBufferStatus, MTLDispatchType};
+use std::borrow::Cow;
+use std::sync::Arc;
+
+#[derive(Clone, Debug)]
+pub struct CommandBuffer {
+ raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+}
+
+unsafe impl Send for CommandBuffer {}
+unsafe impl Sync for CommandBuffer {}
+
+impl CommandBuffer {
+ pub fn new(raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>) -> Self {
+ Self { raw }
+ }
+
+ /// Create a compute command encoder with the provided per-encoder fence and global output map.
+ pub fn compute_command_encoder(&self, fence: &Arc<Fence>) -> ComputeCommandEncoder {
+ self.as_ref()
+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
+ .map(|raw| ComputeCommandEncoder::new(raw, self.raw.clone(), Arc::clone(fence)))
+ .unwrap()
+ }
+
+ /// Create a compute command encoder with freshly allocated fence and a standalone output map.
+ /// Used by tests and `EncoderProvider` implementations that don't share a global fence map.
+ pub fn compute_command_encoder_no_fence(&self) -> ComputeCommandEncoder {
+ let device = Device::new(self.raw.device());
+ let fence = Arc::new(Fence::new(&device));
+ self.as_ref()
+ .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent)
+ .map(|raw| ComputeCommandEncoder::new(raw, self.raw.clone(), fence))
+ .unwrap()
+ }
+
+ pub fn blit_command_encoder(
+ &self,
+ fence: &Arc<Fence>,
+ prev_ce_outputs: &PrevCeOutputs,
+ ) -> BlitCommandEncoder {
+ self.as_ref()
+ .blitCommandEncoder()
+ .map(|raw| BlitCommandEncoder::new(raw, Arc::clone(fence), Arc::clone(prev_ce_outputs)))
+ .unwrap()
+ }
+
+ pub fn commit(&self) {
+ self.raw.commit()
+ }
+
+ /// Coachwhip: everything encoded into this buffer after this point waits until the event
+ /// reaches `value`. Must be called while no encoder is open on the buffer.
+ pub fn encode_wait_for_event(&self, event: &objc2::runtime::ProtocolObject<dyn objc2_metal::MTLEvent>, value: u64) {
+ self.raw.encodeWaitForEvent_value(event, value)
+ }
+
+ pub fn enqueue(&self) {
+ self.raw.enqueue()
+ }
+
+ pub fn set_label(&self, label: &str) {
+ self.as_ref().setLabel(Some(&NSString::from_str(label)))
+ }
+
+ pub fn status(&self) -> MTLCommandBufferStatus {
+ self.raw.status()
+ }
+
+ pub fn error(&self) -> Option<Cow<'_, str>> {
+ unsafe {
+ self.raw.error().map(|error| {
+ let description = error.localizedDescription();
+ let c_str = core::ffi::CStr::from_ptr(description.UTF8String());
+ c_str.to_string_lossy()
+ })
+ }
+ }
+
+ pub fn wait_until_completed(&self) {
+ self.raw.waitUntilCompleted();
+ }
+}
+
+impl AsRef<ProtocolObject<dyn MTLCommandBuffer>> for CommandBuffer {
+ fn as_ref(&self) -> &ProtocolObject<dyn MTLCommandBuffer> {
+ &self.raw
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/commands.rs b/vendor/candle-metal-kernels/src/metal/commands.rs
new file mode 100644
index 0000000..5317e3b
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/commands.rs
@@ -0,0 +1,418 @@
+use crate::metal::{
+ BlitCommandEncoder, Buffer, CommandBuffer, ComputeCommandEncoder, ComputePipeline, Device,
+ Fence, PrevCeOutputs, ResidencySet,
+};
+use crate::MetalKernelError;
+use block2::RcBlock;
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_metal::{MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandQueue};
+use std::collections::HashMap;
+use std::ptr::NonNull;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, MutexGuard};
+
+// Use Retained when appropriate. Gives us a more elegant way of handling memory (peaks) than autoreleasepool.
+// https://docs.rs/objc2/latest/objc2/rc/struct.Retained.html
+pub type CommandQueue = Retained<ProtocolObject<dyn MTLCommandQueue>>;
+
+const DEFAULT_CANDLE_METAL_COMPUTE_PER_BUFFER: usize = 50;
+
+/// Coachwhip: the last `Commands` that encoded work, so the engine can flush and queue waits.
+static LAST: std::sync::atomic::AtomicPtr<Commands> = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
+
+fn create_command_buffer(command_queue: &CommandQueue) -> Result<CommandBuffer, MetalKernelError> {
+ command_queue.commandBuffer().map(CommandBuffer::new).ok_or(
+ MetalKernelError::FailedToCreateResource("CommandBuffer".to_string()),
+ )
+}
+
+/// RAII guard for compute command encoder operations.
+pub struct CommandsGuard<'a> {
+ guard: MutexGuard<'a, EntryState>,
+}
+
+impl AsRef<ComputeCommandEncoder> for CommandsGuard<'_> {
+ fn as_ref(&self) -> &ComputeCommandEncoder {
+ self.guard.current_encoder.as_ref().unwrap()
+ }
+}
+
+impl CommandsGuard<'_> {
+ pub fn set_label(&self, label: &str) {
+ self.as_ref().set_label(label);
+ }
+
+ pub fn set_compute_pipeline_state(&self, pipeline: &ComputePipeline) {
+ self.as_ref().set_compute_pipeline_state(pipeline);
+ }
+
+ #[cfg(feature = "debug-labels")]
+ #[must_use = "the debug group is popped when the returned guard is dropped"]
+ pub fn debug_group(&self, label: &str) -> crate::metal::DebugGroupGuard<'_> {
+ self.as_ref().debug_group(label)
+ }
+}
+
+/// RAII guard for blit command encoder operations.
+pub struct BlitCommandsGuard<'a> {
+ _guard: MutexGuard<'a, EntryState>,
+ state: BlitCommandEncoder,
+}
+
+impl<'a> AsRef<BlitCommandEncoder> for BlitCommandsGuard<'a> {
+ fn as_ref(&self) -> &BlitCommandEncoder {
+ &self.state
+ }
+}
+
+impl<'a> AsMut<BlitCommandEncoder> for BlitCommandsGuard<'a> {
+ fn as_mut(&mut self) -> &mut BlitCommandEncoder {
+ &mut self.state
+ }
+}
+
+impl BlitCommandsGuard<'_> {
+ pub fn set_label(&self, label: &str) {
+ self.as_ref().set_label(label);
+ }
+
+ pub fn copy_from_buffer(
+ &mut self,
+ src_buffer: &Buffer,
+ src_offset: usize,
+ dst_buffer: &Buffer,
+ dst_offset: usize,
+ size: usize,
+ ) {
+ self.as_mut()
+ .copy_from_buffer(src_buffer, src_offset, dst_buffer, dst_offset, size)
+ }
+
+ pub fn fill_buffer(&mut self, buffer: &Buffer, range: (usize, usize), value: u8) {
+ self.as_mut().fill_buffer(buffer, range, value);
+ }
+}
+
+impl Drop for BlitCommandsGuard<'_> {
+ fn drop(&mut self) {
+ self.as_ref().end_encoding();
+ }
+}
+
+struct EntryState {
+ current: CommandBuffer,
+ in_flight: Vec<CommandBuffer>,
+ current_encoder: Option<ComputeCommandEncoder>,
+}
+
+impl EntryState {
+ pub fn new(cb: CommandBuffer) -> EntryState {
+ EntryState {
+ current: cb,
+ in_flight: vec![],
+ current_encoder: None,
+ }
+ }
+}
+
+pub struct Commands {
+ state: Mutex<EntryState>,
+ compute_count: AtomicUsize,
+ command_queue: CommandQueue,
+ /// The maximum amount of [compute command encoder](https://developer.apple.com/documentation/metal/mtlcomputecommandencoder?language=objc)
+ /// per [command buffer](https://developer.apple.com/documentation/metal/mtlcommandbuffer?language=objc)
+ compute_per_buffer: usize,
+ device: Device,
+ /// Global cross-encoder output map. Maps buffer pointer to the fence of the last encoder
+ /// that wrote it, enabling cross-command-buffer ordering for HazardTrackingModeUntracked.
+ prev_ce_outputs: PrevCeOutputs,
+}
+
+unsafe impl Send for Commands {}
+unsafe impl Sync for Commands {}
+
+impl Commands {
+ pub fn new(
+ command_queue: CommandQueue,
+ residency_set: &ResidencySet,
+ ) -> Result<Self, MetalKernelError> {
+ let compute_per_buffer = match std::env::var("CANDLE_METAL_COMPUTE_PER_BUFFER") {
+ Ok(val) => val
+ .parse()
+ .unwrap_or(DEFAULT_CANDLE_METAL_COMPUTE_PER_BUFFER),
+ _ => DEFAULT_CANDLE_METAL_COMPUTE_PER_BUFFER,
+ };
+
+ if let Some(raw) = residency_set.raw() {
+ command_queue.addResidencySet(raw);
+ }
+
+ let device = Device::new(command_queue.device());
+ let cb = create_command_buffer(&command_queue)?;
+
+ Ok(Self {
+ state: Mutex::new(EntryState::new(cb)),
+ compute_count: AtomicUsize::new(0),
+ command_queue,
+ compute_per_buffer,
+ device,
+ prev_ce_outputs: Arc::new(Mutex::new(HashMap::new())),
+ })
+ }
+
+ pub fn command_encoder(&self) -> Result<CommandsGuard<'_>, MetalKernelError> {
+ LAST.store(self as *const Commands as *mut Commands, Ordering::Release);
+ let mut state_guard = self.state.lock().unwrap();
+ let count = self.compute_count.fetch_add(1, Ordering::Relaxed);
+ let flush = count >= self.compute_per_buffer;
+
+ if flush {
+ self.commit_swap_locked(&mut state_guard, 1)?;
+ }
+
+ if state_guard.current_encoder.is_none() {
+ let fence = Arc::new(Fence::new(&self.device));
+ let enc = state_guard.current.compute_command_encoder(&fence);
+ // Wait for all prior encoder fences before the first dispatch.
+ // Using HazardTrackingModeUntracked implies that Metal does not automatically flush GPU caches
+ // at encoder or command buffer boundaries.
+ {
+ use std::collections::HashSet;
+ let map = self.prev_ce_outputs.lock().unwrap();
+ let mut seen = HashSet::new();
+ for f in map.values() {
+ let ptr = Arc::as_ptr(f) as usize;
+ if seen.insert(ptr) {
+ enc.wait_for_fence(f);
+ }
+ }
+ }
+ state_guard.current_encoder = Some(enc);
+ }
+
+ Ok(CommandsGuard { guard: state_guard })
+ }
+
+ pub fn blit_command_encoder(&self) -> Result<BlitCommandsGuard<'_>, MetalKernelError> {
+ let mut state_guard = self.state.lock().unwrap();
+ let count = self.compute_count.fetch_add(1, Ordering::Relaxed);
+ let flush = count >= self.compute_per_buffer;
+
+ if flush {
+ self.commit_swap_locked(&mut state_guard, 1)?;
+ }
+
+ // End compute encoder before starting blit.
+ if let Some(enc) = state_guard.current_encoder.take() {
+ self.end_encoding(enc);
+ }
+
+ let fence = Arc::new(Fence::new(&self.device));
+ let encoder = state_guard
+ .current
+ .blit_command_encoder(&fence, &self.prev_ce_outputs);
+
+ // Wait for all prior encoder fences before any blit commands execute.
+ // Required for HazardTrackingModeUntracked: GPU caches are not auto-flushed.
+ {
+ use std::collections::HashSet;
+ let map = self.prev_ce_outputs.lock().unwrap();
+ let mut seen = HashSet::new();
+ for f in map.values() {
+ let ptr = Arc::as_ptr(f) as usize;
+ if seen.insert(ptr) {
+ encoder.wait_for_fence(f);
+ }
+ }
+ }
+
+ Ok(BlitCommandsGuard {
+ _guard: state_guard,
+ state: encoder,
+ })
+ }
+
+ pub fn wait_until_completed(&self) -> Result<(), MetalKernelError> {
+ self.flush_and_wait()
+ }
+
+ pub fn flush_and_wait(&self) -> Result<(), MetalKernelError> {
+ let to_wait = {
+ let mut state = self.state.lock()?;
+ if self.compute_count.load(Ordering::Acquire) > 0 {
+ self.commit_swap_locked(&mut state, 0)?;
+ }
+ std::mem::take(&mut state.in_flight)
+ };
+
+ // Wait only on the last CB. Metal executes CBs in queue order, so all earlier
+ // CBs are guaranteed complete when the last one is. Calling waitUntilCompleted on
+ // each CB individually pays OS notification latency (~1-2ms) N times unnecessarily.
+ if let Some(last) = to_wait.last() {
+ Self::ensure_completed(last)?;
+ }
+ // Check earlier CBs for errors (no need to block — they're already done).
+ for cb in &to_wait[..to_wait.len().saturating_sub(1)] {
+ if cb.status() == MTLCommandBufferStatus::Error {
+ let msg = cb
+ .error()
+ .map(|e| e.to_string())
+ .unwrap_or_else(|| "unknown error".to_string());
+ return Err(MetalKernelError::CommandBufferError(msg));
+ }
+ }
+
+ self.prev_ce_outputs.lock()?.clear();
+
+ Ok(())
+ }
+
+ /// Commit the current command buffer and wait on that specific buffer, for CPU readbacks.
+ /// [`Self::wait_until_completed`] waits on the last in-flight buffer, which a concurrent
+ /// `flush_and_wait` on another thread may already have taken, returning before our work ran.
+ pub fn flush_and_wait_current(&self) -> Result<(), MetalKernelError> {
+ let cb = {
+ let mut state = self.state.lock()?;
+ self.commit_swap_locked(&mut state, 0)?;
+ state.in_flight.last().cloned()
+ };
+ if let Some(cb) = cb {
+ Self::ensure_completed(&cb)?;
+ // queue is FIFO: everything committed before cb is done too
+ let mut state = self.state.lock()?;
+ state
+ .in_flight
+ .retain(|c| c.status() != MTLCommandBufferStatus::Completed);
+ }
+ Ok(())
+ }
+
+ /// Coachwhip: the `Commands` most recently used to encode work (one device in practice).
+ pub fn current() -> Option<&'static Commands> {
+ let p = LAST.load(Ordering::Acquire);
+ if p.is_null() {
+ None
+ } else {
+ Some(unsafe { &*p })
+ }
+ }
+
+ /// Coachwhip: commit what is encoded so far and start a fresh command buffer that first waits
+ /// for `event` to reach `value`; everything encoded afterwards runs behind that wait.
+ pub fn encode_wait_for_event(&self, event: &objc2::runtime::ProtocolObject<dyn objc2_metal::MTLEvent>, value: u64) -> Result<(), MetalKernelError> {
+ let mut state = self.state.lock()?;
+ self.commit_swap_locked(&mut state, 0)?;
+ state.current.encode_wait_for_event(event, value);
+ Ok(())
+ }
+
+ pub fn flush(&self) -> Result<(), MetalKernelError> {
+ let mut state = self.state.lock()?;
+ if self.compute_count.load(Ordering::Acquire) > 0 {
+ self.commit_swap_locked(&mut state, 0)?;
+ }
+ Ok(())
+ }
+
+ fn commit_swap_locked(
+ &self,
+ state: &mut EntryState,
+ reset_to: usize,
+ ) -> Result<(), MetalKernelError> {
+ if let Some(enc) = state.current_encoder.take() {
+ self.end_encoding(enc);
+ }
+
+ match state.current.status() {
+ MTLCommandBufferStatus::NotEnqueued | MTLCommandBufferStatus::Enqueued => {
+ state.current.commit();
+ }
+ _ => {}
+ }
+ let new_cb = create_command_buffer(&self.command_queue)?;
+ let old_cb = std::mem::replace(&mut state.current, new_cb);
+ state.in_flight.push(old_cb);
+ self.compute_count.store(reset_to, Ordering::Release);
+
+ Ok(())
+ }
+
+ fn ensure_completed(cb: &CommandBuffer) -> Result<(), MetalKernelError> {
+ match cb.status() {
+ MTLCommandBufferStatus::NotEnqueued | MTLCommandBufferStatus::Enqueued => {
+ cb.commit();
+ cb.wait_until_completed();
+ }
+ MTLCommandBufferStatus::Committed | MTLCommandBufferStatus::Scheduled => {
+ cb.wait_until_completed();
+ }
+ MTLCommandBufferStatus::Completed => {}
+ MTLCommandBufferStatus::Error => return Err(Self::cb_error(cb)),
+ _ => unreachable!(),
+ }
+
+ if cb.status() == MTLCommandBufferStatus::Error {
+ return Err(Self::cb_error(cb));
+ }
+
+ Ok(())
+ }
+
+ fn cb_error(cb: &CommandBuffer) -> MetalKernelError {
+ let msg = cb
+ .error()
+ .map(|e| e.to_string())
+ .unwrap_or_else(|| "unknown error".to_string());
+ MetalKernelError::CommandBufferError(msg)
+ }
+
+ fn end_encoding(&self, encoder: ComputeCommandEncoder) {
+ use objc2_metal::MTLCommandEncoder as _;
+ use objc2_metal::MTLComputeCommandEncoder as _;
+
+ let all_outputs = {
+ let s = encoder.state.lock().unwrap();
+ s.all_outputs.clone()
+ };
+
+ {
+ let mut prev_ce_outputs = self.prev_ce_outputs.lock().unwrap();
+ // Register our outputs so subsequent encoders can wait for us.
+ for output in all_outputs.iter() {
+ let _ = prev_ce_outputs.insert(*output, encoder.fence.clone());
+ }
+ }
+
+ // Signal this encoder's completion fence and end encoding.
+ encoder.raw.updateFence(encoder.fence.raw());
+
+ // Schedule cleanup of our output entries once the GPU completes.
+ if !all_outputs.is_empty() {
+ let fence_for_cleanup = Arc::clone(&encoder.fence);
+ let map_for_cleanup = Arc::clone(&self.prev_ce_outputs);
+ let block = RcBlock::new(move |_cb: NonNull<ProtocolObject<dyn MTLCommandBuffer>>| {
+ let mut map = map_for_cleanup.lock().unwrap();
+ for &buf in &all_outputs {
+ if let Some(f) = map.get(&buf) {
+ if Arc::ptr_eq(f, &fence_for_cleanup) {
+ map.remove(&buf);
+ }
+ }
+ }
+ });
+ unsafe {
+ encoder
+ .command_buffer
+ .addCompletedHandler(RcBlock::as_ptr(&block))
+ };
+ }
+
+ encoder.raw.endEncoding();
+ }
+}
+
+impl Drop for Commands {
+ fn drop(&mut self) {
+ let _ = self.flush();
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/compute_pipeline.rs b/vendor/candle-metal-kernels/src/metal/compute_pipeline.rs
new file mode 100644
index 0000000..4162db2
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/compute_pipeline.rs
@@ -0,0 +1,26 @@
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_metal::MTLComputePipelineState;
+
+#[derive(Clone, Debug)]
+pub struct ComputePipeline {
+ raw: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
+}
+
+unsafe impl Send for ComputePipeline {}
+unsafe impl Sync for ComputePipeline {}
+
+impl ComputePipeline {
+ pub fn new(raw: Retained<ProtocolObject<dyn MTLComputePipelineState>>) -> ComputePipeline {
+ ComputePipeline { raw }
+ }
+
+ pub fn max_total_threads_per_threadgroup(&self) -> usize {
+ self.raw.maxTotalThreadsPerThreadgroup()
+ }
+}
+
+impl AsRef<ProtocolObject<dyn MTLComputePipelineState>> for ComputePipeline {
+ fn as_ref(&self) -> &ProtocolObject<dyn MTLComputePipelineState> {
+ &self.raw
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/device.rs b/vendor/candle-metal-kernels/src/metal/device.rs
new file mode 100644
index 0000000..9d724b2
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/device.rs
@@ -0,0 +1,176 @@
+use crate::{
+ Buffer, CommandQueue, ComputePipeline, Function, Library, MTLResourceOptions, MetalKernelError,
+};
+use objc2::{rc::Retained, runtime::AnyObject, runtime::ProtocolObject};
+use objc2_foundation::NSString;
+use objc2_metal::{MTLCompileOptions, MTLCopyAllDevices, MTLCreateSystemDefaultDevice, MTLDevice};
+use std::{ffi::c_void, ptr};
+
+/// Metal device type classification based on Apple Silicon architecture.
+///
+/// MLX uses the last character of the architecture name to determine device type:
+/// - 'p': phone (iPhone, small device)
+/// - 'g': base/pro (M1/M2/M3 base and Pro variants)
+/// - 's': max (M1/M2/M3 Max)
+/// - 'd': ultra (M1/M2 Ultra)
+///
+/// Reference: refs/mlx/mlx/backend/metal/device.cpp
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum MetalDeviceType {
+ /// Small device (iPhone, 'p' suffix)
+ Phone,
+ /// Base/Pro device (M1/M2/M3 base and Pro, 'g' suffix)
+ BasePro,
+ /// Max device (M1/M2/M3 Max, 's' suffix)
+ Max,
+ /// Ultra device (M1/M2 Ultra, 'd' suffix)
+ Ultra,
+ /// Unknown or medium device (default)
+ Medium,
+}
+
+#[derive(Clone, Debug)]
+pub struct Device {
+ raw: Retained<ProtocolObject<dyn MTLDevice>>,
+}
+unsafe impl Send for Device {}
+unsafe impl Sync for Device {}
+
+impl AsRef<ProtocolObject<dyn MTLDevice>> for Device {
+ fn as_ref(&self) -> &ProtocolObject<dyn MTLDevice> {
+ &self.raw
+ }
+}
+
+impl Device {
+ pub fn new(raw: Retained<ProtocolObject<dyn MTLDevice>>) -> Self {
+ Device { raw }
+ }
+
+ pub fn registry_id(&self) -> u64 {
+ self.as_ref().registryID()
+ }
+
+ /// Returns all Metal devices in the system.
+ pub fn all() -> Vec<Self> {
+ MTLCopyAllDevices()
+ .to_vec()
+ .into_iter()
+ .map(|raw| Device { raw })
+ .collect()
+ }
+
+ /// Returns the system default Metal device, if available.
+ ///
+ /// Falls back to first device from `all` if `MTLCreateSystemDefaultDevice`
+ /// returns nil.
+ pub fn system_default() -> Option<Self> {
+ MTLCreateSystemDefaultDevice()
+ .map(|raw| Device { raw })
+ .or_else(|| Device::all().first().cloned())
+ }
+
+ pub fn new_buffer(
+ &self,
+ length: usize,
+ options: MTLResourceOptions,
+ ) -> Result<Buffer, MetalKernelError> {
+ self.as_ref()
+ .newBufferWithLength_options(length, options)
+ .map(Buffer::new)
+ .ok_or(MetalKernelError::FailedToCreateResource(
+ "Buffer".to_string(),
+ ))
+ }
+
+ pub fn new_buffer_with_data(
+ &self,
+ pointer: *const c_void,
+ length: usize,
+ options: MTLResourceOptions,
+ ) -> Result<Buffer, MetalKernelError> {
+ let pointer = ptr::NonNull::new(pointer as *mut c_void)
+ .ok_or_else(|| MetalKernelError::InvalidInput("Null pointer".to_string()))?;
+ unsafe {
+ self.as_ref()
+ .newBufferWithBytes_length_options(pointer, length, options)
+ .map(Buffer::new)
+ .ok_or(MetalKernelError::FailedToCreateResource(
+ "Buffer".to_string(),
+ ))
+ }
+ }
+
+ pub fn new_library_with_source(
+ &self,
+ source: &str,
+ options: Option<&MTLCompileOptions>,
+ ) -> Result<Library, MetalKernelError> {
+ let raw = self
+ .as_ref()
+ .newLibraryWithSource_options_error(&NSString::from_str(source), options)
+ .map_err(|e| MetalKernelError::LoadLibraryError(e.to_string()))?;
+
+ Ok(Library::new(raw))
+ }
+
+ pub fn new_compute_pipeline_state_with_function(
+ &self,
+ function: &Function,
+ ) -> Result<ComputePipeline, MetalKernelError> {
+ let raw = self
+ .as_ref()
+ .newComputePipelineStateWithFunction_error(function.as_ref())
+ .map_err(|e| MetalKernelError::FailedToCreatePipeline(e.to_string()))?;
+ Ok(ComputePipeline::new(raw))
+ }
+
+ pub fn new_command_queue(&self) -> Result<CommandQueue, MetalKernelError> {
+ self.as_ref()
+ .newCommandQueue()
+ .ok_or_else(|| MetalKernelError::FailedToCreateResource("CommandQueue".to_string()))
+ }
+
+ pub fn recommended_max_working_set_size(&self) -> usize {
+ self.as_ref().recommendedMaxWorkingSetSize() as usize
+ }
+
+ pub fn current_allocated_size(&self) -> usize {
+ self.as_ref().currentAllocatedSize()
+ }
+
+ /// Get the device architecture name (e.g., "applegpu_g13g", "applegpu_g14d").
+ ///
+ /// This returns the full architecture string from the Metal device.
+ /// The last character indicates the device type:
+ /// - 'p': phone
+ /// - 'g': base/pro
+ /// - 's': max
+ /// - 'd': ultra
+ pub fn architecture_name(&self) -> String {
+ // On tvOS/iOS simulators the emulated Metal device returns NULL from
+ // -[MTLDevice architecture], which causes objc2 to panic. Guard
+ // against this by checking the raw pointer before dereferencing.
+ let raw_arch: *const AnyObject = unsafe { objc2::msg_send![self.as_ref(), architecture] };
+ if raw_arch.is_null() {
+ return "unknown".to_string();
+ }
+ let arch = self.as_ref().architecture();
+ arch.name().to_string()
+ }
+
+ /// Get the device type based on architecture name.
+ ///
+ /// This implements the same logic as MLX's device type detection.
+ /// Reference: refs/mlx/mlx/backend/metal/device.cpp
+ pub fn device_type(&self) -> MetalDeviceType {
+ let arch = self.architecture_name();
+ match arch.chars().last() {
+ Some('p') => MetalDeviceType::Phone,
+ Some('g') => MetalDeviceType::BasePro,
+ Some('s') => MetalDeviceType::Max,
+ Some('d') => MetalDeviceType::Ultra,
+ _ => MetalDeviceType::Medium,
+ }
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/encoder.rs b/vendor/candle-metal-kernels/src/metal/encoder.rs
new file mode 100644
index 0000000..a47fe66
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/encoder.rs
@@ -0,0 +1,338 @@
+use crate::metal::{Buffer, ComputePipeline, Fence};
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::{NSRange, NSString};
+use objc2_metal::{
+ MTLBarrierScope, MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder,
+ MTLComputeCommandEncoder, MTLSize,
+};
+use std::{
+ collections::{HashMap, HashSet},
+ ffi::c_void,
+ ptr,
+ sync::{Arc, Mutex},
+};
+
+/// Shared cross-encoder output map: maps buffer pointer -> fence of the last encoder that wrote it.
+/// Used by subsequent encoders to call waitForFence before reading those buffers.
+pub type PrevCeOutputs = Arc<Mutex<HashMap<usize, Arc<Fence>>>>;
+
+/// Barrier tracking state for one encoder session.
+/// Owned by ComputeCommandEncoder via Arc<Mutex<>> so clones share state.
+pub struct EncoderState {
+ /// Buffer ptrs written since last barrier (RAW/WAW detection).
+ pub prev_outputs: HashSet<usize>,
+ pub next_outputs: HashSet<usize>,
+ /// Buffer ptrs read since last barrier (WAR detection).
+ pub prev_inputs: HashSet<usize>,
+ pub next_inputs: HashSet<usize>,
+ pub needs_barrier: bool,
+ /// All inputs seen this encoder session (cross-encoder fence coordination).
+ pub all_inputs: HashSet<usize>,
+ /// All outputs seen this encoder session (registered in global map at end_encoding).
+ pub all_outputs: HashSet<usize>,
+}
+
+impl EncoderState {
+ pub fn new() -> Self {
+ EncoderState {
+ prev_outputs: HashSet::new(),
+ next_outputs: HashSet::new(),
+ prev_inputs: HashSet::new(),
+ next_inputs: HashSet::new(),
+ needs_barrier: false,
+ all_inputs: HashSet::new(),
+ all_outputs: HashSet::new(),
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct ComputeCommandEncoder {
+ pub(crate) raw: Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>,
+ /// Retained so we can register completion handlers on this CB.
+ pub(crate) command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ /// Per-encoder-session fence. Updated at end_encoding.
+ pub(crate) fence: Arc<Fence>,
+ /// Hazard tracking state. Arc shared between the canonical encoder in EntryState
+ /// and the clone held by CommandsGuard. Uncontended in practice (CommandsGuard
+ /// holds the outer Commands mutex for the entire kernel dispatch).
+ pub(crate) state: Arc<Mutex<EncoderState>>,
+}
+
+impl AsRef<ComputeCommandEncoder> for ComputeCommandEncoder {
+ fn as_ref(&self) -> &ComputeCommandEncoder {
+ self
+ }
+}
+
+impl ComputeCommandEncoder {
+ pub fn new(
+ raw: Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>,
+ command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ fence: Arc<Fence>,
+ ) -> ComputeCommandEncoder {
+ ComputeCommandEncoder {
+ raw,
+ command_buffer,
+ fence,
+ state: Arc::new(Mutex::new(EncoderState::new())),
+ }
+ }
+
+ pub fn set_threadgroup_memory_length(&self, index: usize, length: usize) {
+ unsafe { self.raw.setThreadgroupMemoryLength_atIndex(length, index) }
+ }
+
+ pub fn dispatch_threads(&self, threads_per_grid: MTLSize, threads_per_threadgroup: MTLSize) {
+ self.auto_barrier();
+ self.raw
+ .dispatchThreads_threadsPerThreadgroup(threads_per_grid, threads_per_threadgroup)
+ }
+
+ pub fn dispatch_thread_groups(
+ &self,
+ threadgroups_per_grid: MTLSize,
+ threads_per_threadgroup: MTLSize,
+ ) {
+ self.auto_barrier();
+ self.raw.dispatchThreadgroups_threadsPerThreadgroup(
+ threadgroups_per_grid,
+ threads_per_threadgroup,
+ )
+ }
+
+ fn auto_barrier(&self) {
+ let mut s = self.state.lock().unwrap();
+ if s.needs_barrier {
+ self.raw.memoryBarrierWithScope(MTLBarrierScope::Buffers);
+ s.needs_barrier = false;
+ s.prev_outputs = std::mem::take(&mut s.next_outputs);
+ s.prev_inputs = std::mem::take(&mut s.next_inputs);
+ } else {
+ let next_out = std::mem::take(&mut s.next_outputs);
+ s.prev_outputs.extend(next_out);
+ let next_in = std::mem::take(&mut s.next_inputs);
+ s.prev_inputs.extend(next_in);
+ }
+ }
+
+ pub fn set_input_buffer(&self, index: usize, buffer: Option<&Buffer>, offset: usize) {
+ if let Some(buf) = buffer {
+ let ptr = buf.raw_ptr() as usize;
+ let mut s = self.state.lock().unwrap();
+ if s.prev_outputs.contains(&ptr) {
+ s.needs_barrier = true;
+ }
+ s.next_inputs.insert(ptr);
+ s.all_inputs.insert(ptr);
+ }
+ unsafe {
+ self.raw
+ .setBuffer_offset_atIndex(buffer.map(|b| b.as_ref()), offset, index)
+ }
+ }
+
+ pub fn set_output_buffer(&self, index: usize, buffer: Option<&Buffer>, offset: usize) {
+ if let Some(buf) = buffer {
+ let ptr = buf.raw_ptr() as usize;
+ let mut s = self.state.lock().unwrap();
+ if s.prev_outputs.contains(&ptr) || s.prev_inputs.contains(&ptr) {
+ s.needs_barrier = true;
+ }
+ s.next_outputs.insert(ptr);
+ s.all_outputs.insert(ptr);
+ }
+ unsafe {
+ self.raw
+ .setBuffer_offset_atIndex(buffer.map(|b| b.as_ref()), offset, index)
+ }
+ }
+
+ pub fn set_bytes_directly(&self, index: usize, length: usize, bytes: *const c_void) {
+ let pointer = ptr::NonNull::new(bytes as *mut c_void).unwrap();
+ unsafe { self.raw.setBytes_length_atIndex(pointer, length, index) }
+ }
+
+ pub fn set_bytes<T>(&self, index: usize, data: &T) {
+ let size = core::mem::size_of::<T>();
+ let ptr = ptr::NonNull::new(data as *const T as *mut c_void).unwrap();
+ unsafe { self.raw.setBytes_length_atIndex(ptr, size, index) }
+ }
+
+ pub fn set_compute_pipeline_state(&self, pipeline: &ComputePipeline) {
+ self.raw.setComputePipelineState(pipeline.as_ref());
+ }
+
+ /// Insert a memory barrier at buffers scope.
+ pub fn insert_memory_barrier(&self) {
+ self.raw.memoryBarrierWithScope(MTLBarrierScope::Buffers);
+ }
+
+ /// Wait for a fence before continuing execution.
+ pub fn wait_for_fence(&self, fence: &Fence) {
+ self.raw.waitForFence(fence.raw());
+ }
+
+ /// Update a fence after commands complete.
+ pub fn update_fence(&self, fence: &Fence) {
+ self.raw.updateFence(fence.raw());
+ }
+
+ pub fn end_encoding(&self) {
+ use objc2_metal::MTLCommandEncoder as _;
+ self.raw.updateFence(self.fence.raw());
+ self.raw.endEncoding();
+ }
+
+ pub fn encode_pipeline(&mut self, pipeline: &ComputePipeline) {
+ use MTLComputeCommandEncoder as _;
+ self.raw.setComputePipelineState(pipeline.as_ref());
+ }
+
+ pub fn set_label(&self, label: &str) {
+ self.raw.setLabel(Some(&NSString::from_str(label)))
+ }
+}
+
+/// RAII guard that pops a Metal debug group on drop. Debug groups are a stack
+/// scoped to the push/pop range, so each dispatch is attributed correctly on
+/// the shared concurrent encoder where `set_label` cannot.
+#[cfg(feature = "debug-labels")]
+pub struct DebugGroupGuard<'a> {
+ encoder: &'a ComputeCommandEncoder,
+}
+
+#[cfg(feature = "debug-labels")]
+impl Drop for DebugGroupGuard<'_> {
+ fn drop(&mut self) {
+ self.encoder.raw.popDebugGroup();
+ }
+}
+
+#[cfg(feature = "debug-labels")]
+impl ComputeCommandEncoder {
+ /// Push a Metal debug group scoped to the returned guard.
+ #[must_use = "the debug group is popped when the returned guard is dropped"]
+ pub fn debug_group(&self, label: &str) -> DebugGroupGuard<'_> {
+ self.raw.pushDebugGroup(&NSString::from_str(label));
+ DebugGroupGuard { encoder: self }
+ }
+}
+
+pub struct BlitCommandEncoder {
+ pub(crate) raw: Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>,
+ /// Per-encoder fence, updated at end_encoding.
+ fence: Arc<Fence>,
+ /// Shared global cross-encoder output map.
+ prev_ce_outputs: PrevCeOutputs,
+ /// Buffer pointers written by this blit encoder (registered in global map at end_encoding).
+ tracked_outputs: Vec<usize>,
+}
+
+impl AsRef<BlitCommandEncoder> for BlitCommandEncoder {
+ fn as_ref(&self) -> &BlitCommandEncoder {
+ self
+ }
+}
+
+impl BlitCommandEncoder {
+ pub fn new(
+ raw: Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>,
+ fence: Arc<Fence>,
+ prev_ce_outputs: PrevCeOutputs,
+ ) -> BlitCommandEncoder {
+ BlitCommandEncoder {
+ raw,
+ fence,
+ prev_ce_outputs,
+ tracked_outputs: Vec::new(),
+ }
+ }
+
+ /// Wait for a fence before continuing execution.
+ pub fn wait_for_fence(&self, fence: &Fence) {
+ self.raw.waitForFence(fence.raw());
+ }
+
+ /// Update a fence after commands complete.
+ pub fn update_fence(&self, fence: &Fence) {
+ self.raw.updateFence(fence.raw());
+ }
+
+ pub fn end_encoding(&self) {
+ use objc2_metal::MTLCommandEncoder as _;
+
+ // Signal this blit encoder's fence after all blit commands complete
+ self.update_fence(&self.fence);
+ self.raw.endEncoding();
+
+ // Register outputs so subsequent encoders can wait.
+ {
+ let mut map = self.prev_ce_outputs.lock().unwrap();
+ for &out in &self.tracked_outputs {
+ map.insert(out, Arc::clone(&self.fence));
+ }
+ }
+ }
+
+ pub fn set_label(&self, label: &str) {
+ use objc2_metal::MTLCommandEncoder as _;
+ self.raw.setLabel(Some(&NSString::from_str(label)))
+ }
+
+ /// Copy bytes from src to dst. Waits on any fence that wrote to src_buffer to ensure
+ /// correct ordering for HazardTrackingModeUntracked buffers.
+ pub fn copy_from_buffer(
+ &mut self,
+ src_buffer: &Buffer,
+ src_offset: usize,
+ dst_buffer: &Buffer,
+ dst_offset: usize,
+ size: usize,
+ ) {
+ let src_ptr = src_buffer.raw_ptr() as usize;
+ let fence_to_wait = {
+ let map = self.prev_ce_outputs.lock().unwrap();
+ map.get(&src_ptr).cloned()
+ };
+ if let Some(fence) = fence_to_wait {
+ use objc2_metal::MTLBlitCommandEncoder as _;
+ self.raw.waitForFence(fence.raw());
+ }
+
+ self.tracked_outputs.push(dst_buffer.raw_ptr() as usize);
+
+ unsafe {
+ self.raw
+ .copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size(
+ src_buffer.as_ref(),
+ src_offset,
+ dst_buffer.as_ref(),
+ dst_offset,
+ size,
+ )
+ }
+ }
+
+ pub fn fill_buffer(&mut self, buffer: &Buffer, range: (usize, usize), value: u8) {
+ let ptr = buffer.raw_ptr() as usize;
+ let fence_to_wait = {
+ let map = self.prev_ce_outputs.lock().unwrap();
+ map.get(&ptr).cloned()
+ };
+ if let Some(fence) = fence_to_wait {
+ use objc2_metal::MTLBlitCommandEncoder as _;
+ self.raw.waitForFence(fence.raw());
+ }
+ self.tracked_outputs.push(ptr);
+
+ self.raw.fillBuffer_range_value(
+ buffer.as_ref(),
+ NSRange {
+ location: range.0,
+ length: range.1,
+ },
+ value,
+ )
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/fence.rs b/vendor/candle-metal-kernels/src/metal/fence.rs
new file mode 100644
index 0000000..35338f3
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/fence.rs
@@ -0,0 +1,30 @@
+use super::Device;
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_metal::MTLFence;
+
+/// Cross-encoder synchronization primitive for HazardTrackingModeUntracked resources.
+///
+/// memoryBarrierWithScope only works within a single encoder. When transitioning between
+/// encoders (e.g. compute -> blit for to_cpu, blit -> compute for next dispatch), untracked
+/// resources need explicit fence wait/update calls to ensure memory visibility.
+pub struct Fence {
+ raw: Retained<ProtocolObject<dyn MTLFence>>,
+}
+
+unsafe impl Send for Fence {}
+unsafe impl Sync for Fence {}
+
+impl Fence {
+ pub fn new(device: &Device) -> Self {
+ use objc2_metal::MTLDevice as _;
+ let raw = device
+ .as_ref()
+ .newFence()
+ .expect("failed to create MTLFence");
+ Fence { raw }
+ }
+
+ pub fn raw(&self) -> &ProtocolObject<dyn MTLFence> {
+ &self.raw
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/library.rs b/vendor/candle-metal-kernels/src/metal/library.rs
new file mode 100644
index 0000000..07f9217
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/library.rs
@@ -0,0 +1,139 @@
+use crate::MetalKernelError;
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::NSString;
+use objc2_metal::{MTLDataType, MTLFunction, MTLFunctionConstantValues, MTLLibrary};
+use std::{ffi::c_void, ptr};
+
+#[derive(Clone, Debug)]
+pub struct Library {
+ raw: Retained<ProtocolObject<dyn MTLLibrary>>,
+}
+unsafe impl Send for Library {}
+unsafe impl Sync for Library {}
+
+impl Library {
+ pub fn new(raw: Retained<ProtocolObject<dyn MTLLibrary>>) -> Library {
+ Library { raw }
+ }
+
+ pub fn get_function(
+ &self,
+ name: &str,
+ constant_values: Option<&ConstantValues>,
+ ) -> Result<Function, MetalKernelError> {
+ let function = match constant_values {
+ Some(constant_values) => self
+ .raw
+ .newFunctionWithName_constantValues_error(
+ &NSString::from_str(name),
+ &constant_values.function_constant_values().raw,
+ )
+ .map_err(|e| MetalKernelError::LoadFunctionError(e.to_string()))?,
+ None => self
+ .raw
+ .newFunctionWithName(&NSString::from_str(name))
+ .ok_or(MetalKernelError::LoadFunctionError(name.to_string()))?,
+ };
+
+ Ok(Function { raw: function })
+ }
+}
+
+pub struct Function {
+ raw: Retained<ProtocolObject<dyn MTLFunction>>,
+}
+
+impl AsRef<ProtocolObject<dyn MTLFunction>> for Function {
+ fn as_ref(&self) -> &ProtocolObject<dyn MTLFunction> {
+ &self.raw
+ }
+}
+
+pub struct FunctionConstantValues {
+ raw: Retained<MTLFunctionConstantValues>,
+}
+
+impl FunctionConstantValues {
+ pub fn new() -> FunctionConstantValues {
+ FunctionConstantValues {
+ raw: MTLFunctionConstantValues::new(),
+ }
+ }
+
+ pub fn set_constant_value_at_index<T>(&self, value: &T, dtype: MTLDataType, index: usize) {
+ let value = ptr::NonNull::new(value as *const T as *mut c_void).unwrap();
+ unsafe { self.raw.setConstantValue_type_atIndex(value, dtype, index) }
+ }
+}
+
+impl Default for FunctionConstantValues {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[derive(Debug, PartialEq)]
+pub enum Value {
+ USize(usize),
+ Bool(bool),
+ F32(f32),
+ U16(u16),
+}
+
+impl std::hash::Hash for Value {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ match self {
+ Value::F32(v) => v.to_bits().hash(state),
+ Value::USize(v) => v.hash(state),
+ Value::U16(v) => v.hash(state),
+ Value::Bool(v) => v.hash(state),
+ }
+ }
+}
+
+impl Value {
+ fn data_type(&self) -> MTLDataType {
+ match self {
+ // usize is usually u64 aka ulong, but can be u32 on 32-bit systems.
+ // https://developer.apple.com/documentation/objectivec/nsuinteger
+ Value::USize(_) => MTLDataType::ULong,
+ Value::F32(_) => MTLDataType::Float,
+ Value::U16(_) => MTLDataType::UShort,
+ Value::Bool(_) => MTLDataType::Bool,
+ }
+ }
+}
+
+/// Not true, good enough for our purposes.
+impl Eq for Value {}
+
+#[derive(Debug, Eq, PartialEq, Hash)]
+pub struct ConstantValues(Vec<(usize, Value)>);
+
+impl ConstantValues {
+ pub fn new(values: Vec<(usize, Value)>) -> Self {
+ Self(values)
+ }
+
+ fn function_constant_values(&self) -> FunctionConstantValues {
+ let f = FunctionConstantValues::new();
+ for (index, value) in &self.0 {
+ let ty = value.data_type();
+ match value {
+ Value::USize(v) => {
+ f.set_constant_value_at_index(v, ty, *index);
+ }
+ Value::F32(v) => {
+ f.set_constant_value_at_index(v, ty, *index);
+ }
+ Value::U16(v) => {
+ f.set_constant_value_at_index(v, ty, *index);
+ }
+ Value::Bool(v) => {
+ f.set_constant_value_at_index(v, ty, *index);
+ }
+ }
+ }
+ f
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal/mod.rs b/vendor/candle-metal-kernels/src/metal/mod.rs
new file mode 100644
index 0000000..8ba7465
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/mod.rs
@@ -0,0 +1,19 @@
+pub mod buffer;
+pub mod command_buffer;
+pub mod commands;
+pub mod compute_pipeline;
+pub mod device;
+pub mod encoder;
+pub mod fence;
+pub mod library;
+pub mod residency_set;
+
+pub use buffer::*;
+pub use command_buffer::*;
+pub use commands::*;
+pub use compute_pipeline::*;
+pub use device::*;
+pub use encoder::*;
+pub use fence::*;
+pub use library::*;
+pub use residency_set::*;
diff --git a/vendor/candle-metal-kernels/src/metal/residency_set.rs b/vendor/candle-metal-kernels/src/metal/residency_set.rs
new file mode 100644
index 0000000..e4866ee
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal/residency_set.rs
@@ -0,0 +1,78 @@
+use super::{Buffer, Device};
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_metal::{MTLAllocation, MTLDevice as _, MTLResidencySet, MTLResidencySetDescriptor};
+
+/// Keeps Metal buffers resident in GPU memory, removing the need for `useResource` calls.
+///
+/// Add the set to the command queue once via `MTLCommandQueue::addResidencySet`. Then
+/// register every buffer at allocation time and unregister at free time.
+pub struct ResidencySet {
+ raw: Option<Retained<ProtocolObject<dyn MTLResidencySet>>>,
+}
+
+unsafe impl Send for ResidencySet {}
+unsafe impl Sync for ResidencySet {}
+
+impl ResidencySet {
+ pub fn new(device: &Device) -> Self {
+ let descriptor = MTLResidencySetDescriptor::new();
+ let raw = device
+ .as_ref()
+ .newResidencySetWithDescriptor_error(&descriptor)
+ .ok()
+ .inspect(|set| set.requestResidency());
+ ResidencySet { raw }
+ }
+
+ pub fn raw(&self) -> Option<&ProtocolObject<dyn MTLResidencySet>> {
+ self.raw.as_deref()
+ }
+
+ pub fn insert(&self, buf: &Buffer) {
+ self.insert_batch(std::iter::once(buf));
+ }
+
+ /// Adds multiple buffers in a single commit.
+ pub fn insert_batch<'a>(&self, bufs: impl IntoIterator<Item = &'a Buffer>) {
+ if let Some(set) = &self.raw {
+ let mut any = false;
+ for buf in bufs {
+ set.addAllocation(as_allocation(buf));
+ any = true;
+ }
+ if any {
+ set.commit();
+ }
+ }
+ }
+
+ /// Removes multiple buffers in a single commit.
+ pub fn remove_batch<'a>(&self, bufs: impl IntoIterator<Item = &'a Buffer>) {
+ if let Some(set) = &self.raw {
+ let mut any = false;
+ for buf in bufs {
+ set.removeAllocation(as_allocation(buf));
+ any = true;
+ }
+ if any {
+ set.commit();
+ }
+ }
+ }
+
+ pub fn remove(&self, buf: &Buffer) {
+ self.remove_batch(std::iter::once(buf));
+ }
+}
+
+/// Cast a `&Buffer` to `&ProtocolObject<dyn MTLAllocation>`.
+///
+/// Safe because `MTLBuffer: MTLResource: MTLAllocation`. All `ProtocolObject<P>` are
+/// `repr(C)` thin ObjC pointers — the cast only changes the static protocol marker,
+/// not the pointer value or runtime dispatch.
+fn as_allocation(buf: &Buffer) -> &ProtocolObject<dyn MTLAllocation> {
+ unsafe {
+ &*(buf.as_ref() as *const ProtocolObject<dyn objc2_metal::MTLBuffer>
+ as *const ProtocolObject<dyn MTLAllocation>)
+ }
+}
diff --git a/vendor/candle-metal-kernels/src/metal_src/affine.metal b/vendor/candle-metal-kernels/src/metal_src/affine.metal
new file mode 100644
index 0000000..987afe1
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/affine.metal
@@ -0,0 +1,167 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Utils
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+// Kernels
+template <typename T, int W = work_per_thread<T>()>
+[[kernel]] void affine_kernel(
+ constant size_t &dim,
+ constant float &mul,
+ constant float &add,
+ device const T *input,
+ device T *output,
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = static_cast<T>(fma(float(input[i]), mul, add));
+ }
+}
+
+template <typename T>
+[[kernel]] void affine_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant float &mul,
+ constant float &add,
+ constant const T *input,
+ device T *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dim) return;
+ uint idx = get_strided_index(tid, num_dims, dims, strides);
+ float result = fma(float(input[idx]), mul, add);
+ output[tid] = static_cast<T>(result);
+}
+
+template <typename T, int W = work_per_thread<T>()>
+[[kernel]] void powf_kernel(
+ constant size_t &dim,
+ constant float &mul,
+ device const T *input,
+ device T *output,
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = static_cast<T>(pow(static_cast<float>(input[i]), mul));
+ }
+}
+
+template <typename T>
+[[kernel]] void powf_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant float &mul,
+ constant const T *input,
+ device T *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dim) return;
+ uint idx = get_strided_index(tid, num_dims, dims, strides);
+ output[tid] = static_cast<T>(pow(static_cast<float>(input[idx]), mul));
+}
+
+template <typename T, int W = work_per_thread<T>()>
+[[kernel]] void elu_kernel(
+ constant size_t &dim,
+ constant float &mul,
+ device const T *input,
+ device T *output,
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ const T x = input[i];
+ output[i] = static_cast<T>((x > 0) ? x : mul * (exp(x) - 1));
+ }
+}
+
+template <typename T>
+[[kernel]] void elu_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant float &mul,
+ constant const T *input,
+ device T *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dim) return;
+ uint idx = get_strided_index(tid, num_dims, dims, strides);
+ const T x = input[idx];
+ output[tid] = static_cast<T>((x > 0) ? x : mul * (exp(x) - 1));
+}
+
+// Macros to help initialize kernels
+#define init_kernel(name, func, ...) \
+ template [[host_name(name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+#define init_affine(tname, t) \
+ init_kernel("affine_" #tname, affine_kernel, t) \
+ init_kernel("affine_" #tname "_strided", affine_kernel_strided, t)
+
+#define init_powf(tname, t) \
+ init_kernel("powf_" #tname, powf_kernel, t) \
+ init_kernel("powf_" #tname "_strided", powf_kernel_strided, t)
+
+#define init_elu(tname, t) \
+ init_kernel("elu_" #tname, elu_kernel, t) \
+ init_kernel("elu_" #tname "_strided", elu_kernel_strided, t)
+
+
+init_affine(u8, uint8_t);
+init_affine(u32, uint32_t);
+init_affine(i64, int64_t);
+init_affine(f32, float);
+init_affine(f16, half);
+
+init_powf(f32, float);
+init_powf(f16, half);
+
+init_elu(f32, float);
+init_elu(f16, half);
+
+#if defined(__HAVE_BFLOAT__)
+init_affine(bf16, bfloat);
+init_powf(bf16, bfloat);
+init_elu(bf16, bfloat);
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/binary.metal b/vendor/candle-metal-kernels/src/metal_src/binary.metal
new file mode 100644
index 0000000..1399eb1
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/binary.metal
@@ -0,0 +1,212 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Utils
+#define MAX(x, y) ((x) > (y) ? (x) : (y))
+#define MIN(x, y) ((x) < (y) ? (x) : (y))
+
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+struct cont_indexer {
+ METAL_FUNC uint operator()(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+ ) {
+ return idx;
+ }
+};
+
+struct strided_indexer {
+ METAL_FUNC uint operator()(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+ ) {
+ return get_strided_index(idx, num_dims, dims, strides);
+ }
+};
+
+struct scalar_indexer {
+ METAL_FUNC uint operator()(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+ ) {
+ return 0;
+ }
+};
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+// Kernels
+template <typename T, typename U, typename binary, uint W = work_per_thread<T>()>
+[[kernel]] void binary_kernel(
+ constant size_t &dim,
+ device const T *left,
+ device const T *right,
+ device U *output,
+ uint tid [[thread_position_in_grid]]
+) {
+ binary op;
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = static_cast<U>(op(left[i], right[i]));
+ }
+}
+
+template <
+ typename T,
+ typename U,
+ typename binary,
+ typename l_indexer = strided_indexer,
+ typename r_indexer = strided_indexer,
+ uint W = work_per_thread<T>()>
+[[kernel]] void binary_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *left_strides,
+ constant size_t *right_strides,
+ device const T *left,
+ device const T *right,
+ device U *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ binary op;
+ l_indexer l_index;
+ r_indexer r_index;
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ uint l_idx = l_index(i, num_dims, dims, left_strides);
+ uint r_idx = r_index(i, num_dims, dims, right_strides);
+ output[i] = static_cast<U>(op(left[l_idx], right[r_idx]));
+ }
+}
+
+// Macros to help initialize kernels
+#define init_kernel(name, func, ...) \
+ template [[host_name(name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+#define init_binary_k(op_name, binary_op, tname, t, u) \
+ init_kernel(#op_name "_" #tname, binary_kernel, t, u, binary_op) \
+ init_kernel(#op_name "_" #tname "_strided", binary_kernel_strided, t, u, binary_op) \
+ init_kernel(#op_name "_" #tname "_lstrided", binary_kernel_strided, t, u, binary_op, strided_indexer, cont_indexer) \
+ init_kernel(#op_name "_" #tname "_rstrided", binary_kernel_strided, t, u, binary_op, cont_indexer, strided_indexer) \
+ init_kernel(#op_name "_" #tname "_scalar", binary_kernel_strided, t, u, binary_op, scalar_indexer, scalar_indexer) \
+ init_kernel(#op_name "_" #tname "_cs", binary_kernel_strided, t, u, binary_op, cont_indexer, scalar_indexer) \
+ init_kernel(#op_name "_" #tname "_sc", binary_kernel_strided, t, u, binary_op, scalar_indexer, cont_indexer) \
+ init_kernel(#op_name "_" #tname "_rss", binary_kernel_strided, t, u, binary_op, scalar_indexer, strided_indexer) \
+ init_kernel(#op_name "_" #tname "_lss", binary_kernel_strided, t, u, binary_op, strided_indexer, scalar_indexer)
+
+#if defined(__HAVE_BFLOAT__)
+#define init_binary(bop) \
+ init_binary_k(bop, bop, f32, float, float) \
+ init_binary_k(bop, bop, f16, half, half) \
+ init_binary_k(bop, bop, bf16, bfloat, bfloat) \
+ init_binary_k(bop, bop, u8, uint8_t, uint8_t) \
+ init_binary_k(bop, bop, u32, uint32_t, uint32_t)\
+ init_binary_k(bop, bop, i64, int64_t, int64_t)
+#else
+#define init_binary(bop) \
+ init_binary_k(bop, bop, f32, float, float) \
+ init_binary_k(bop, bop, f16, half, half) \
+ init_binary_k(bop, bop, u8, uint8_t, uint8_t) \
+ init_binary_k(bop, bop, u32, uint32_t, uint32_t)\
+ init_binary_k(bop, bop, i64, int64_t, int64_t)
+#endif
+
+#if defined(__HAVE_BFLOAT__)
+#define init_boolean_binary(op_name, binary_op) \
+ init_binary_k(op_name, binary_op, f32, float, bool) \
+ init_binary_k(op_name, binary_op, f16, half, bool) \
+ init_binary_k(op_name, binary_op, bf16, bfloat, bool) \
+ init_binary_k(op_name, binary_op, u8, uint8_t, bool) \
+ init_binary_k(op_name, binary_op, u32, uint32_t, bool) \
+ init_binary_k(op_name, binary_op, i64, int64_t, bool)
+#else
+#define init_boolean_binary(op_name, binary_op) \
+ init_binary_k(op_name, binary_op, f32, float, bool) \
+ init_binary_k(op_name, binary_op, f16, half, bool) \
+ init_binary_k(op_name, binary_op, u8, uint8_t, bool) \
+ init_binary_k(op_name, binary_op, u32, uint32_t, bool) \
+ init_binary_k(op_name, binary_op, i64, int64_t, bool)
+#endif
+
+// Define binary ops
+#define define_binary_op(name, op) \
+struct name { \
+ template <typename T> \
+ METAL_FUNC T operator()(T x, T y) { \
+ return static_cast<T>(op); \
+ } \
+};
+#define define_binary_bool_op(name, op) \
+struct name { \
+ template <typename T> \
+ METAL_FUNC bool operator()(T x, T y) { \
+ return op; \
+ } \
+};
+
+// Define binary ops
+define_binary_op(badd, x + y);
+define_binary_op(bsub, x - y);
+define_binary_op(bmul, x * y);
+define_binary_op(bdiv, x / y);
+define_binary_op(bminimum, MIN(x, y));
+define_binary_op(bmaximum, MAX(x, y));
+
+// Define binary ops that return a bool
+define_binary_bool_op(beq, x == y);
+define_binary_bool_op(bne, x != y);
+define_binary_bool_op(ble, x <= y);
+define_binary_bool_op(blt, x < y);
+define_binary_bool_op(bge, x >= y);
+define_binary_bool_op(bgt, x > y)
+
+// Initialize kernels
+init_binary(badd);
+init_binary(bsub);
+init_binary(bmul);
+init_binary(bdiv);
+init_binary(bminimum);
+init_binary(bmaximum);
+
+init_boolean_binary(eq, beq);
+init_boolean_binary(ne, bne);
+init_boolean_binary(le, ble);
+init_boolean_binary(lt, blt);
+init_boolean_binary(ge, bge);
+init_boolean_binary(gt, bgt);
diff --git a/vendor/candle-metal-kernels/src/metal_src/cast.metal b/vendor/candle-metal-kernels/src/metal_src/cast.metal
new file mode 100644
index 0000000..0cb6c25
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/cast.metal
@@ -0,0 +1,104 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Utils
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+// Kernels
+template <
+ typename T,
+ typename U,
+ typename IR = T,
+ int W = work_per_thread<T>()
+>
+[[kernel]] void cast_kernel(
+ constant size_t &dim,
+ device const T* input,
+ device U* output,
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = static_cast<U>(static_cast<IR>(input[i]));
+ }
+}
+
+template <typename T, typename U, typename IR = T>
+[[kernel]] void cast_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant const T *input,
+ device U *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dim) return;
+ output[tid] = static_cast<U>(
+ static_cast<IR>(input[get_strided_index(tid, num_dims, dims, strides)])
+ );
+}
+
+// Macros to help initialize kernels
+#define init_kernel(name, func, ...) \
+ template [[host_name(name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+#define init_cast(tname, t, uname, u) \
+ init_kernel("cast_" #tname "_" #uname, cast_kernel, t, u) \
+ init_kernel("cast_" #tname "_" #uname "_strided", cast_kernel_strided, t, u)
+
+#if defined(__HAVE_BFLOAT__)
+#define init_cast_all(tname, t) \
+ init_cast(tname, t, f32, float) \
+ init_cast(tname, t, f16, half) \
+ init_cast(tname, t, bf16, bfloat) \
+ init_cast(tname, t, i64, int64_t) \
+ init_cast(tname, t, u32, uint32_t) \
+ init_cast(tname, t, u8, uint8_t)
+#else
+#define init_cast_all(tname, t) \
+ init_cast(tname, t, f32, float) \
+ init_cast(tname, t, f16, half) \
+ init_cast(tname, t, i64, int64_t) \
+ init_cast(tname, t, u32, uint32_t) \
+ init_cast(tname, t, u8, uint8_t)
+#endif
+
+
+init_cast_all(f32, float);
+init_cast_all(f16, half);
+#if defined(__HAVE_BFLOAT__)
+init_cast_all(bf16, bfloat);
+#endif
+init_cast_all(i64, int64_t);
+init_cast_all(u32, uint32_t);
+init_cast_all(u8, uint8_t);
diff --git a/vendor/candle-metal-kernels/src/metal_src/conv.metal b/vendor/candle-metal-kernels/src/metal_src/conv.metal
new file mode 100644
index 0000000..4862b8c
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/conv.metal
@@ -0,0 +1,717 @@
+#include <metal_stdlib>
+
+using namespace metal;
+
+#define MAX(x, y) ((x) > (y) ? (x) : (y))
+
+template <typename T>
+METAL_FUNC void im2col(
+ constant size_t &dst_numel,
+ constant size_t &h_out,
+ constant size_t &w_out,
+ constant size_t &h_k,
+ constant size_t &w_k,
+ constant size_t &stride,
+ constant size_t &padding,
+ constant size_t &dilation,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ device const T *src,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ // dst: (b_size, h_out, w_out, c_in, h_k, w_k)
+ // src: (b_size, c_in, h_in, w_in)
+ if (tid >= dst_numel) {
+ return;
+ }
+ const size_t b_in = src_dims[0];
+ const size_t c_in = src_dims[1];
+ const size_t h_in = src_dims[2];
+ const size_t w_in = src_dims[3];
+
+ const size_t dst_s4 = w_k;
+ const size_t dst_s3 = h_k * dst_s4;
+ const size_t dst_s2 = c_in * dst_s3;
+ const size_t dst_s1 = w_out * dst_s2;
+ const size_t dst_s0 = h_out * dst_s1;
+
+ size_t tmp_tid = tid;
+ const size_t b_idx = tmp_tid / dst_s0;
+ tmp_tid -= b_idx * dst_s0;
+ const size_t h_idx = tmp_tid / dst_s1;
+ tmp_tid -= h_idx * dst_s1;
+ const size_t w_idx = tmp_tid / dst_s2;
+ tmp_tid -= w_idx * dst_s2;
+ const size_t c_idx = tmp_tid / dst_s3;
+ tmp_tid -= c_idx * dst_s3;
+ const size_t h_k_idx = tmp_tid / dst_s4;
+ tmp_tid -= h_k_idx * dst_s4;
+ const size_t w_k_idx = tmp_tid;
+ size_t src_h_idx = h_idx * stride + h_k_idx * dilation;
+ size_t src_w_idx = w_idx * stride + w_k_idx * dilation;
+ if (src_h_idx < padding || src_h_idx >= h_in + padding) {
+ dst[tid] = static_cast<T>(0);
+ }
+ else if (src_w_idx < padding || src_w_idx >= w_in + padding) {
+ dst[tid] = static_cast<T>(0);
+ }
+ else {
+ src_h_idx -= padding;
+ src_w_idx -= padding;
+ const size_t src_i =
+ b_idx * src_strides[0]
+ + c_idx * src_strides[1]
+ + src_h_idx * src_strides[2]
+ + src_w_idx * src_strides[3];
+ dst[tid] = src[src_i];
+ }
+}
+
+template <typename T>
+METAL_FUNC void col2im1d(
+ constant size_t &dst_el,
+ constant size_t &l_out,
+ constant size_t &l_in,
+ constant size_t &c_out,
+ constant size_t &k_size,
+ constant size_t &stride,
+ device const T *src,
+ device T *dst,
+ uint dst_i [[ thread_position_in_grid ]]
+) {
+ // src: (b_size, l_in, c_out, l_k)
+ // dst: (b_size, c_out, l_out)
+ if (dst_i >= dst_el) {
+ return;
+ }
+
+ const size_t dst_s0 = c_out * l_out;
+ const size_t dst_s1 = l_out;
+ const size_t src_s0 = c_out * k_size * l_in;
+ const size_t src_s1 = c_out * k_size;
+ const size_t src_s2 = k_size;
+
+ size_t tmp_dst_i = dst_i;
+ const size_t b_idx = tmp_dst_i / dst_s0;
+ tmp_dst_i -= b_idx * dst_s0;
+ const size_t c_idx = tmp_dst_i / dst_s1;
+ tmp_dst_i -= c_idx * dst_s1;
+ const int l_out_idx = tmp_dst_i;
+
+ dst[dst_i] = static_cast<T>(0);
+
+ int l_in_idx = l_out_idx / stride;
+ int k0 = l_out_idx - l_in_idx * stride;
+ // l_out_idx = l_in_idx * stride + k0
+ for (; k0 < k_size && l_in_idx >= 0; k0 += stride, --l_in_idx) {
+ if (l_in_idx < l_in) {
+ const size_t src_i = b_idx * src_s0 + l_in_idx * src_s1 + c_idx * src_s2 + k0;
+ dst[dst_i] += src[src_i];
+ }
+ }
+}
+
+template <typename T>
+METAL_FUNC void im2col1d(
+ constant size_t &dst_numel,
+ constant size_t &l_out,
+ constant size_t &l_k,
+ constant size_t &stride,
+ constant size_t &padding,
+ constant size_t &dilation,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ device const T *src,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ // dst: (b_size, l_out, c_in, l_k)
+ // src: (b_size, c_in, l_in)
+ if (tid >= dst_numel) {
+ return;
+ }
+ const size_t b_in = src_dims[0];
+ const size_t c_in = src_dims[1];
+ const size_t l_in = src_dims[2];
+
+ const size_t dst_s2 = l_k;
+ const size_t dst_s1 = c_in * dst_s2;
+ const size_t dst_s0 = l_out * dst_s1;
+
+ size_t tmp_dst_i = tid;
+ const size_t b_idx = tmp_dst_i / dst_s0;
+ tmp_dst_i -= b_idx * dst_s0;
+ const size_t l_idx = tmp_dst_i / dst_s1;
+ tmp_dst_i -= l_idx * dst_s1;
+ const size_t c_idx = tmp_dst_i / dst_s2;
+ tmp_dst_i -= c_idx * dst_s2;
+ const size_t l_k_idx = tmp_dst_i;
+ size_t src_l_idx = l_idx * stride + l_k_idx * dilation;
+ if (src_l_idx < padding || src_l_idx >= l_in + padding) {
+ dst[tid] = static_cast<T>(0);
+ }
+ else {
+ src_l_idx -= padding;
+ const size_t src_i = b_idx * src_strides[0] + c_idx * src_strides[1] + src_l_idx * src_strides[2];
+ dst[tid] = src[src_i];
+ }
+}
+
+template <typename T>
+METAL_FUNC void upsample_nearest2d(
+ constant size_t &w_out,
+ constant size_t &h_out,
+ constant float &w_scale,
+ constant float &h_scale,
+ constant size_t *src_dims,
+ constant size_t *src_s,
+ device const T *src,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ // src: (b_size, c_in, w_in, h_in)
+
+ const size_t c = src_dims[1];
+ const size_t w_in = src_dims[2];
+ const size_t h_in = src_dims[3];
+
+ if (tid >= src_dims[0] * c * w_out * h_out) {
+ return;
+ }
+
+ // TODO: Improve this.
+ const size_t b_idx = tid / (w_out * h_out * c);
+ const size_t c_idx = (tid / (w_out * h_out)) % c;
+ const size_t dst_w = (tid / h_out) % w_out;
+ const size_t dst_h = tid % h_out;
+
+ size_t src_w = static_cast<size_t>(dst_w * w_scale);
+ size_t src_h = static_cast<size_t>(dst_h * h_scale);
+ if (src_w >= w_in) {
+ src_w = w_in - 1;
+ }
+ if (src_h >= h_in) {
+ src_h = h_in - 1;
+ }
+
+ const size_t src_i = b_idx * src_s[0] + c_idx * src_s[1] + src_w * src_s[2] + src_h * src_s[3];
+ dst[tid] = src[src_i];
+}
+
+template <typename T>
+METAL_FUNC void upsample_bilinear2d(
+ constant size_t &w_out,
+ constant size_t &h_out,
+ constant bool &align_corners,
+ constant bool &has_scale_h,
+ constant float &scale_h_factor,
+ constant bool &has_scale_w,
+ constant float &scale_w_factor,
+ constant size_t *src_dims,
+ constant size_t *src_s,
+ device const T *src,
+ device T *dst,
+ uint tid [[thread_position_in_grid]]
+) {
+ // src: (b_size, c_in, h_in, w_in) // Standard NCHW layout
+ const size_t c = src_dims[1];
+ const size_t h_in = src_dims[2]; // dims[2] = height
+ const size_t w_in = src_dims[3]; // dims[3] = width
+
+ if (tid >= src_dims[0] * c * h_out * w_out) {
+ return;
+ }
+
+ // Compute output position (NCHW layout)
+ const size_t b_idx = tid / (h_out * w_out * c);
+ const size_t c_idx = (tid / (h_out * w_out)) % c;
+ const size_t dst_h = (tid / w_out) % h_out;
+ const size_t dst_w = tid % w_out;
+
+ // Calculate scale factors following PyTorch's area_pixel_compute_scale logic
+ float h_scale, w_scale;
+ if (align_corners) {
+ h_scale = (h_out > 1) ? static_cast<float>(h_in - 1) / (h_out - 1) : 0.0f;
+ w_scale = (w_out > 1) ? static_cast<float>(w_in - 1) / (w_out - 1) : 0.0f;
+ } else {
+ // PyTorch's compute_scales_value logic
+ h_scale = has_scale_h ? (1.0f / scale_h_factor) : (static_cast<float>(h_in) / h_out);
+ w_scale = has_scale_w ? (1.0f / scale_w_factor) : (static_cast<float>(w_in) / w_out);
+ }
+
+ // Compute source position
+ float src_h_fp, src_w_fp;
+ if (align_corners) {
+ src_h_fp = h_scale * dst_h;
+ src_w_fp = w_scale * dst_w;
+ } else {
+ src_h_fp = h_scale * (dst_h + 0.5f) - 0.5f;
+ src_w_fp = w_scale * (dst_w + 0.5f) - 0.5f;
+ }
+
+ // Clamp to valid range
+ src_h_fp = max(0.0f, src_h_fp);
+ src_w_fp = max(0.0f, src_w_fp);
+
+ // Get integer indices
+ size_t h0 = static_cast<size_t>(floor(src_h_fp));
+ size_t w0 = static_cast<size_t>(floor(src_w_fp));
+ size_t h1 = min(h0 + 1, h_in - 1);
+ size_t w1 = min(w0 + 1, w_in - 1);
+
+ // Compute interpolation weights
+ float weight_h = src_h_fp - h0;
+ float weight_w = src_w_fp - w0;
+ weight_h = clamp(weight_h, 0.0f, 1.0f);
+ weight_w = clamp(weight_w, 0.0f, 1.0f);
+
+ // Get base index
+ const size_t base = b_idx * src_s[0] + c_idx * src_s[1];
+
+ // Read four neighboring pixels
+ const T v00 = src[base + h0 * src_s[2] + w0 * src_s[3]];
+ const T v10 = src[base + h0 * src_s[2] + w1 * src_s[3]];
+ const T v01 = src[base + h1 * src_s[2] + w0 * src_s[3]];
+ const T v11 = src[base + h1 * src_s[2] + w1 * src_s[3]];
+
+ // Bilinear interpolation
+ const float v_top = float(v00) * (1.0f - weight_w) + float(v10) * weight_w;
+ const float v_bottom = float(v01) * (1.0f - weight_w) + float(v11) * weight_w;
+ const float value = v_top * (1.0f - weight_h) + v_bottom * weight_h;
+
+ dst[tid] = T(value);
+}
+
+#define IM2COL_OP(T, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &dst_numel, \
+ constant size_t &h_out, \
+ constant size_t &w_out, \
+ constant size_t &h_k, \
+ constant size_t &w_k, \
+ constant size_t &stride, \
+ constant size_t &padding, \
+ constant size_t &dilation, \
+ constant size_t *src_dims, \
+ constant size_t *src_strides, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ im2col<T>(dst_numel, h_out, w_out, h_k, w_k, stride, padding, dilation, src_dims, src_strides, src, dst, tid); \
+} \
+
+#define IM2COL1D_OP(T, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &dst_numel, \
+ constant size_t &l_out, \
+ constant size_t &l_k, \
+ constant size_t &stride, \
+ constant size_t &padding, \
+ constant size_t &dilation, \
+ constant size_t *src_dims, \
+ constant size_t *src_strides, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ im2col1d<T>(dst_numel, l_out, l_k, stride, padding, dilation, src_dims, src_strides, src, dst, tid); \
+} \
+
+#define COL2IM1D_OP(T, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &dst_el, \
+ constant size_t &l_out, \
+ constant size_t &l_in, \
+ constant size_t &c_out, \
+ constant size_t &k_size, \
+ constant size_t &stride, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ col2im1d<T>(dst_el, l_out, l_in, c_out, k_size, stride, src, dst, tid); \
+} \
+
+#define UPSAMPLE_NEAREST2D_OP(TYPENAME, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &w_out, \
+ constant size_t &h_out, \
+ constant float &w_scale, \
+ constant float &h_scale, \
+ constant size_t *dims, \
+ constant size_t *strides, \
+ device const TYPENAME *src, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ upsample_nearest2d<TYPENAME>(w_out, h_out, w_scale, h_scale, dims, strides, src, dst, tid); \
+} \
+
+#define UPSAMPLE_BILINEAR2D_OP(TYPENAME, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &w_out [[buffer(0)]], \
+ constant size_t &h_out [[buffer(1)]], \
+ constant bool &align_corners [[buffer(2)]], \
+ constant bool &has_scale_h [[buffer(3)]], \
+ constant float &scale_h_factor [[buffer(4)]], \
+ constant bool &has_scale_w [[buffer(5)]], \
+ constant float &scale_w_factor [[buffer(6)]], \
+ constant size_t *src_dims [[buffer(7)]], \
+ constant size_t *src_s [[buffer(8)]], \
+ device const TYPENAME *src [[buffer(9)]], \
+ device TYPENAME *dst [[buffer(10)]], \
+ uint tid [[thread_position_in_grid]] \
+) { \
+ upsample_bilinear2d<TYPENAME>(w_out, h_out, align_corners, has_scale_h, scale_h_factor, has_scale_w, scale_w_factor, src_dims, src_s, src, dst, tid); \
+} \
+
+template <typename T, typename A>
+METAL_FUNC void avg_pool2d(
+ constant size_t &w_k,
+ constant size_t &h_k,
+ constant size_t &w_stride,
+ constant size_t &h_stride,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ device const T *src,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ const size_t c = src_dims[1];
+ const size_t w_in = src_dims[2];
+ const size_t h_in = src_dims[3];
+
+ const size_t w_out = (w_in - w_k) / w_stride + 1;
+ const size_t h_out = (h_in - h_k) / h_stride + 1;
+ if (tid >= src_dims[0] * c * w_out * h_out) {
+ return;
+ }
+
+ const size_t b_idx = tid / (w_out * h_out * c);
+ const size_t c_idx = (tid / (w_out * h_out)) % c;
+ const size_t dst_w = (tid / h_out) % w_out;
+ const size_t dst_h = tid % h_out;
+
+ const size_t src_idx0 = b_idx * src_strides[0];
+ A d = 0;
+ for (size_t w_offset = 0; w_offset < w_k; ++w_offset) {
+ size_t src_w = w_stride * dst_w + w_offset;
+ if (src_w >= w_in){
+ continue;
+ }
+ for (size_t h_offset = 0; h_offset < h_k; ++h_offset) {
+ size_t src_h = h_stride * dst_h + h_offset;
+ if (src_h >= h_in) {
+ continue;
+ }
+ const size_t src_idx = src_idx0 + c_idx * src_strides[1] + src_w * src_strides[2] + src_h * src_strides[3];
+ d += static_cast<A>(src[src_idx]);
+ }
+ }
+ dst[tid] = static_cast<T>(d / (w_k * h_k));
+}
+
+#define AVGPOOL2D_OP(TYPENAME, TYPEACC, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &w_k, \
+ constant size_t &h_k, \
+ constant size_t &w_s, \
+ constant size_t &h_s, \
+ constant size_t *src_dims, \
+ constant size_t *src_s, \
+ device const TYPENAME *src, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ avg_pool2d<TYPENAME, TYPEACC>(w_k, h_k, w_s, h_s, src_dims, src_s, src, dst, tid); \
+} \
+
+template <typename T>
+METAL_FUNC void max_pool2d(
+ constant size_t &w_k,
+ constant size_t &h_k,
+ constant size_t &w_stride,
+ constant size_t &h_stride,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ device const T *src,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ const size_t c = src_dims[1];
+ const size_t w_in = src_dims[2];
+ const size_t h_in = src_dims[3];
+
+ const size_t w_out = (w_in - w_k) / w_stride + 1;
+ const size_t h_out = (h_in - h_k) / h_stride + 1;
+ if (tid >= src_dims[0] * c * w_out * h_out) {
+ return;
+ }
+
+ const size_t b_idx = tid / (w_out * h_out * c);
+ const size_t c_idx = (tid / (w_out * h_out)) % c;
+ const size_t dst_w = (tid / h_out) % w_out;
+ const size_t dst_h = tid % h_out;
+
+ const size_t src_idx0 = b_idx * src_strides[0];
+ T d = 0;
+ bool set = false;
+ for (size_t w_offset = 0; w_offset < w_k; ++w_offset) {
+ size_t src_w = w_stride * dst_w + w_offset;
+ if (src_w >= w_in){
+ continue;
+ }
+ for (size_t h_offset = 0; h_offset < h_k; ++h_offset) {
+ size_t src_h = h_stride * dst_h + h_offset;
+ if (src_h >= h_in) {
+ continue;
+ }
+ const size_t src_idx = src_idx0 + c_idx * src_strides[1] + src_w * src_strides[2] + src_h * src_strides[3];
+ if (set) {
+ d = MAX(d, src[src_idx]);
+ }
+ else {
+ d = src[src_idx];
+ set = true;
+ }
+ }
+ }
+ dst[tid] = d;
+}
+
+#define MAXPOOL2D_OP(TYPENAME, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &w_k, \
+ constant size_t &h_k, \
+ constant size_t &w_s, \
+ constant size_t &h_s, \
+ constant size_t *src_dims, \
+ constant size_t *src_s, \
+ device const TYPENAME *src, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ max_pool2d<TYPENAME>(w_k, h_k, w_s, h_s, src_dims, src_s, src, dst, tid); \
+} \
+
+
+// Naive implementation of conv_transpose1d.
+template <typename T, typename A>
+METAL_FUNC void conv_transpose1d(
+ constant size_t &l_out,
+ constant size_t &stride,
+ constant size_t &padding,
+ constant size_t &out_padding,
+ constant size_t &dilation,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ constant size_t *k_dims,
+ constant size_t *k_strides,
+ device const T *src,
+ device const T *k,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ // src: (b_size, c_in, l_in)
+ // kernel: (c_in, c_out, l_k)
+ const size_t l_k = k_dims[2];
+ const size_t c_out = k_dims[1];
+ const size_t c_in = src_dims[1];
+ const size_t l_in = src_dims[2];
+ if (tid >= src_dims[0] * c_out * l_out) {
+ return;
+ }
+
+ const size_t b_idx = tid / (l_out * c_out);
+ const size_t dst_c_idx = (tid / l_out) % c_out;
+ const size_t out_x = tid % l_out;
+
+ const size_t src_idx0 = b_idx * src_strides[0];
+ A d = 0;
+ for (int k_x = 0; k_x < (int)l_k; ++k_x) {
+ // let out_x = inp_x * p.stride + k_x * p.dilation - p.padding;
+ int inp_x_stride = (int)(out_x + padding) - k_x * dilation;
+ if (inp_x_stride < 0 || inp_x_stride % stride) {
+ continue;
+ }
+ int inp_x = inp_x_stride / stride;
+ if (inp_x >= l_in) continue;
+ for (size_t src_c_idx = 0; src_c_idx < c_in; ++src_c_idx) {
+ const size_t src_idx = src_idx0 + src_c_idx * src_strides[1] + inp_x * src_strides[2];
+ const size_t k_idx = src_c_idx * k_strides[0] + dst_c_idx * k_strides[1] + k_x * k_strides[2];
+ d += static_cast<A>(src[src_idx]) * static_cast<A>(k[k_idx]);
+ }
+ }
+ dst[tid] = static_cast<T>(d);
+}
+
+#define CONVT1D_OP(TYPENAME, TYPEACC, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &l_out, \
+ constant size_t &stride, \
+ constant size_t &padding, \
+ constant size_t &out_padding, \
+ constant size_t &dilation, \
+ constant size_t *src_dims, \
+ constant size_t *src_strides, \
+ constant size_t *k_dims, \
+ constant size_t *k_strides, \
+ device const TYPENAME *src, \
+ device const TYPENAME *k, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ conv_transpose1d<TYPENAME, TYPEACC>(l_out, stride, padding, out_padding, dilation, src_dims, src_strides, k_dims, k_strides, src, k, dst, tid); \
+} \
+
+template <typename T, typename A>
+METAL_FUNC void conv_transpose2d(
+ constant size_t &w_out,
+ constant size_t &h_out,
+ constant size_t &stride,
+ constant size_t &padding,
+ constant size_t &out_padding,
+ constant size_t &dilation,
+ constant size_t *input_dims,
+ constant size_t *input_stride,
+ constant size_t *k_dims,
+ constant size_t *k_stride,
+ device const T *src,
+ device const T *k,
+ device T *dst,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ const size_t h_k = k_dims[2];
+ const size_t w_k = k_dims[3];
+ const size_t c_out = k_dims[1];
+ const size_t c_in = input_dims[1];
+ const size_t h_in = input_dims[2];
+ const size_t w_in = input_dims[3];
+
+ if (tid >= input_dims[0] * c_out * w_out * h_out) {
+ return;
+ }
+
+ const size_t b_idx = tid / (w_out * h_out * c_out);
+ const size_t dst_c_idx = (tid / (w_out * h_out)) % c_out;
+ const size_t out_y = (tid / w_out) % h_out;
+ const size_t out_x = tid % w_out;
+
+ const size_t src_idx0 = b_idx * input_stride[0];
+
+ A d = 0;
+ for (int k_x = 0; k_x < (int)w_k; ++k_x) {
+ const int inp_x_stride = (int)(out_x + padding) - k_x * dilation;
+ if (inp_x_stride < 0 || inp_x_stride % stride) {
+ continue;
+ }
+ const int inp_x = inp_x_stride / stride;
+ if (inp_x >= w_in) continue;
+ for (int k_y = 0; k_y < (int)h_k; ++k_y) {
+ const int inp_y_stride = (int)(out_y + padding) - k_y * dilation;
+ if (inp_y_stride < 0 || inp_y_stride % stride) {
+ continue;
+ }
+ const int inp_y = inp_y_stride / stride;
+ if (inp_y >= h_in) continue;
+ for (size_t src_c_idx = 0; src_c_idx < c_in; ++src_c_idx) {
+ const size_t src_idx = src_idx0 + src_c_idx * input_stride[1] + inp_y * input_stride[2] + inp_x * input_stride[3];
+ const size_t k_idx = src_c_idx * k_stride[0] + dst_c_idx * k_stride[1] + k_y * k_stride[2] + k_x * k_stride[3];
+ d += static_cast<A>(src[src_idx]) * static_cast<A>(k[k_idx]);
+ }
+ }
+ }
+ dst[tid] = static_cast<T>(d);
+}
+
+#define CONVT2D_OP(TYPENAME, TYPEACC, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &w_out, \
+ constant size_t &h_out, \
+ constant size_t &stride, \
+ constant size_t &padding, \
+ constant size_t &out_padding, \
+ constant size_t &dilation, \
+ constant size_t *input_dims, \
+ constant size_t *input_stride, \
+ constant size_t *k_dims, \
+ constant size_t *k_stride, \
+ device const TYPENAME *src, \
+ device const TYPENAME *k, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ conv_transpose2d<TYPENAME, TYPEACC>(w_out, h_out, stride, padding, out_padding, dilation, input_dims, input_stride, k_dims, k_stride, src, k, dst, tid); \
+} \
+
+IM2COL_OP(float, im2col_f32)
+IM2COL_OP(half, im2col_f16)
+IM2COL_OP(uint8_t, im2col_u8)
+IM2COL_OP(uint32_t, im2col_u32)
+#if defined(__HAVE_BFLOAT__)
+IM2COL_OP(bfloat, im2col_bf16)
+#endif
+
+COL2IM1D_OP(float, col2im1d_f32)
+COL2IM1D_OP(half, col2im1d_f16)
+COL2IM1D_OP(uint8_t, col2im1d_u8)
+COL2IM1D_OP(uint32_t, col2im1d_u32)
+#if defined(__HAVE_BFLOAT__)
+COL2IM1D_OP(bfloat, col2im1d_bf16)
+#endif
+
+IM2COL1D_OP(float, im2col1d_f32)
+IM2COL1D_OP(half, im2col1d_f16)
+IM2COL1D_OP(uint8_t, im2col1d_u8)
+IM2COL1D_OP(uint32_t, im2col1d_u32)
+#if defined(__HAVE_BFLOAT__)
+IM2COL1D_OP(bfloat, im2col1d_bf16)
+#endif
+
+UPSAMPLE_NEAREST2D_OP(float, upsample_nearest2d_f32)
+UPSAMPLE_NEAREST2D_OP(half, upsample_nearest2d_f16)
+UPSAMPLE_NEAREST2D_OP(uint8_t, upsample_nearest2d_u8)
+UPSAMPLE_NEAREST2D_OP(uint32_t, upsample_nearest2d_u32)
+#if defined(__HAVE_BFLOAT__)
+UPSAMPLE_NEAREST2D_OP(bfloat, upsample_nearest2d_bf16)
+#endif
+
+UPSAMPLE_BILINEAR2D_OP(float, upsample_bilinear2d_f32)
+UPSAMPLE_BILINEAR2D_OP(half, upsample_bilinear2d_f16)
+UPSAMPLE_BILINEAR2D_OP(uint8_t, upsample_bilinear2d_u8)
+UPSAMPLE_BILINEAR2D_OP(uint32_t, upsample_bilinear2d_u32)
+#if defined(__HAVE_BFLOAT__)
+UPSAMPLE_BILINEAR2D_OP(bfloat, upsample_bilinear2d_bf16)
+#endif
+
+MAXPOOL2D_OP(float, max_pool2d_f32)
+MAXPOOL2D_OP(half, max_pool2d_f16)
+MAXPOOL2D_OP(uint32_t, max_pool2d_u32)
+MAXPOOL2D_OP(uint8_t, max_pool2d_u8)
+#if defined(__HAVE_BFLOAT__)
+MAXPOOL2D_OP(bfloat, max_pool2d_bf16)
+#endif
+
+AVGPOOL2D_OP(float, float, avg_pool2d_f32)
+AVGPOOL2D_OP(half, float, avg_pool2d_f16)
+AVGPOOL2D_OP(uint32_t, uint32_t, avg_pool2d_u32)
+AVGPOOL2D_OP(uint8_t, uint8_t, avg_pool2d_u8)
+#if defined(__HAVE_BFLOAT__)
+AVGPOOL2D_OP(bfloat, float, avg_pool2d_bf16)
+#endif
+
+CONVT1D_OP(float, float, conv_transpose1d_f32)
+CONVT1D_OP(half, float, conv_transpose1d_f16)
+CONVT1D_OP(uint8_t, uint8_t, conv_transpose1d_u8)
+CONVT1D_OP(uint32_t, uint32_t, conv_transpose1d_u32)
+#if defined(__HAVE_BFLOAT__)
+CONVT1D_OP(bfloat, float, conv_transpose1d_bf16)
+#endif
+
+CONVT2D_OP(float, float, conv_transpose2d_f32)
+CONVT2D_OP(half, float, conv_transpose2d_f16)
+#if defined(__HAVE_BFLOAT__)
+CONVT2D_OP(bfloat, float, conv_transpose2d_bf16)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/fill.metal b/vendor/candle-metal-kernels/src/metal_src/fill.metal
new file mode 100644
index 0000000..dfb24a2
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/fill.metal
@@ -0,0 +1,39 @@
+#include <metal_stdlib>
+
+using namespace metal;
+
+template<typename T> METAL_FUNC void fill_with(
+ device T *out,
+ constant T &value,
+ constant size_t &numel,
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid >= numel) {
+ return;
+ }
+ out[tid] = value;
+}
+
+#define FILL_OP(NAME, T) \
+kernel void fill_##NAME( \
+ device T *out, \
+ constant T &value, \
+ constant size_t &numel, \
+ uint tid [[thread_position_in_grid]] \
+) { \
+ fill_with<T>(out, value, numel, tid); \
+} \
+
+
+#define FILL_OPS(NAME, T) \
+FILL_OP(NAME, T) \
+
+FILL_OPS(u8, uchar)
+FILL_OPS(u32, uint)
+FILL_OPS(i64, long)
+FILL_OPS(f16, half)
+FILL_OPS(f32, float)
+
+#if __METAL_VERSION__ >= 310
+FILL_OPS(bf16, bfloat)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/gemv.metal b/vendor/candle-metal-kernels/src/metal_src/gemv.metal
new file mode 100644
index 0000000..c4fbb93
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/gemv.metal
@@ -0,0 +1,527 @@
+// GEMV kernel adapted from MLX:
+// https://github.com/ml-explore/mlx/blob/main/mlx/backend/metal/kernels/gemv.metal
+// Copyright © 2023-2024 Apple Inc.
+
+#include <metal_simdgroup>
+#include <metal_stdlib>
+
+using namespace metal;
+
+#define MLX_MTL_CONST static constant constexpr const
+#define MLX_MTL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")
+
+// elem_to_loc for nc=1 batch handling
+template <typename stride_t>
+METAL_FUNC stride_t gemv_elem_to_loc(
+ uint elem,
+ constant const int* shape,
+ constant const stride_t* strides,
+ int ndim) {
+ stride_t loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * strides[i];
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+template <typename U>
+struct GemvDefaultAccT {
+ using type = float;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+/// Matrix-vector: mat [M_out, K] × vec [K] → out [M_out]
+/// (mat rows = output dimension, mat cols = K)
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ const int BM, // Threadgroup rows (in simdgroups)
+ const int BN, // Threadgroup cols (in simdgroups)
+ const int SM, // Simdgroup rows (in threads)
+ const int SN, // Simdgroup cols (in threads)
+ const int TM, // Thread rows (in elements)
+ const int TN, // Thread cols (in elements)
+ const bool kDoAxpby,
+ typename AccT = typename GemvDefaultAccT<T>::type>
+struct GEMVKernel {
+ using acc_type = AccT;
+
+ MLX_MTL_CONST int threadsM = BM * SM;
+ MLX_MTL_CONST int threadsN = BN * SN;
+
+ MLX_MTL_CONST int blockM = threadsM * TM;
+ MLX_MTL_CONST int blockN = threadsN * TN;
+
+ static_assert(SM * SN == 32, "simdgroup must have 32 threads");
+ static_assert(SN == 4 || SN == 8 || SN == 16 || SN == 32,
+ "gemv block must have width 4, 8, 16, or 32");
+
+ MLX_MTL_CONST short tgp_mem_size = BN > 1 ? BN * (blockM + TM) : 0;
+ MLX_MTL_CONST bool needs_tgp_reduction = BN > 1;
+
+ template <typename U = T>
+ static METAL_FUNC void load_unsafe(
+ const device T* src, thread U dst[TN], const int src_offset = 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = static_cast<U>(src[src_offset + tn]);
+ }
+ }
+
+ template <typename U = T>
+ static METAL_FUNC void load_safe(
+ const device T* src,
+ thread U dst[TN],
+ const int src_offset = 0,
+ const int src_size = TN) {
+ if (src_offset + TN <= src_size) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = static_cast<U>(src[src_offset + tn]);
+ }
+ } else {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ dst[tn] = src_offset + tn < src_size
+ ? static_cast<U>(src[src_offset + tn])
+ : U(0);
+ }
+ }
+ }
+
+ static METAL_FUNC void run(
+ const device T* mat,
+ const device T* in_vec,
+ const device T* bias,
+ device T* out_vec,
+ const int in_vec_size,
+ const int out_vec_size,
+ const int matrix_ld,
+ const float alpha,
+ const float beta,
+ const int bias_stride,
+ threadgroup AccT* tgp_memory,
+ uint3 tid,
+ uint3 lid,
+ uint simd_gid,
+ uint simd_lid) {
+ (void)lid;
+
+ thread AccT result[TM] = {0};
+ thread T inter[TN];
+ thread AccT v_coeff[TN];
+
+ const int thrM = SN != 32 ? (int)(simd_lid / SN) : 0;
+ const int thrN = SN != 32 ? (int)(simd_lid % SN) : (int)simd_lid;
+
+ const int sgN = BN != 1 ? (int)(simd_gid % BN) : 0;
+ const int simdM = BN != 1 ? SM * (int)(simd_gid / BN) : (int)(SM * simd_gid);
+ const int simdN = BN != 1 ? SN * (int)(simd_gid % BN) : 0;
+
+ int bm = (simdM + thrM) * TM;
+ int bn = (simdN + thrN) * TN;
+
+ // Block position (output row)
+ int out_row = tid.x * blockM + bm;
+
+ if (out_row >= out_vec_size) return;
+
+ out_row = out_row + TM <= out_vec_size ? out_row : out_vec_size - TM;
+
+ mat += out_row * matrix_ld;
+
+ const int loop_stride = blockN;
+ const int in_size = in_vec_size;
+ const int n_iter = in_size / loop_stride;
+ const int last_iter = loop_stride * n_iter;
+ const int leftover = in_size - last_iter;
+
+ for (int i = 0; i < n_iter; ++i) {
+ load_unsafe<AccT>(in_vec, v_coeff, bn);
+
+ int mat_offset = 0;
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ load_unsafe(mat, inter, mat_offset + bn);
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ result[tm] += inter[tn] * v_coeff[tn];
+ }
+ mat_offset += matrix_ld;
+ }
+ bn += blockN;
+ }
+
+ if (leftover > 0) {
+ load_safe<AccT>(in_vec, v_coeff, bn, in_size);
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ load_safe(&mat[tm * matrix_ld], inter, bn, in_size);
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ result[tm] += inter[tn] * v_coeff[tn];
+ }
+ }
+ }
+
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {
+ result[tm] += simd_shuffle_down(result[tm], sn);
+ }
+ }
+
+ if (needs_tgp_reduction) {
+ threadgroup AccT* tgp_results = tgp_memory + sgN * (blockM + TM) + bm;
+ if (thrN == 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ tgp_results[tm] = result[tm];
+ }
+ threadgroup_barrier(mem_flags::mem_none);
+ if (sgN == 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int sgn = 1; sgn < BN; sgn++) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ result[tm] += tgp_results[sgn * (blockM + TM) + tm];
+ }
+ }
+ }
+ }
+ }
+
+ if (simdN == 0 && thrN == 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ if (kDoAxpby) {
+ out_vec[out_row + tm] =
+ static_cast<T>(alpha) * static_cast<T>(result[tm]) +
+ static_cast<T>(beta) * bias[(out_row + tm) * bias_stride];
+ } else {
+ out_vec[out_row + tm] = static_cast<T>(result[tm]);
+ }
+ }
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+/// Vector-matrix: vec [K] × mat [K, N_out] → out [N_out]
+/// (mat rows = K, mat cols = output dimension)
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ const int BM,
+ const int BN,
+ const int SM,
+ const int SN,
+ const int TM,
+ const int TN,
+ const bool kDoAxpby,
+ typename AccT = typename GemvDefaultAccT<T>::type>
+struct GEMVTKernel {
+ using acc_type = AccT;
+
+ MLX_MTL_CONST int threadsM = BM * SM;
+ MLX_MTL_CONST int threadsN = BN * SN;
+
+ MLX_MTL_CONST int blockM = threadsM * TM;
+ MLX_MTL_CONST int blockN = threadsN * TN;
+
+ static_assert(SM * SN == 32, "simdgroup must have 32 threads");
+
+ MLX_MTL_CONST short tgp_mem_size = BM > 1 ? BM * (blockN + TN) : 0;
+ MLX_MTL_CONST bool needs_tgp_reduction = BM > 1;
+
+ static METAL_FUNC void run(
+ const device T* mat,
+ const device T* in_vec,
+ const device T* bias,
+ device T* out_vec,
+ const int in_vec_size,
+ const int out_vec_size,
+ const int marix_ld,
+ const float alpha,
+ const float beta,
+ const int bias_stride,
+ threadgroup AccT* tgp_memory,
+ uint3 tid,
+ uint3 lid,
+ uint simd_gid,
+ uint simd_lid) {
+ (void)lid;
+
+ AccT result[TN] = {0};
+ T inter[TN];
+ AccT v_coeff[TM];
+
+ const int thrM = SN != 32 ? (int)(simd_lid / SN) : 0;
+ const int thrN = SN != 32 ? (int)(simd_lid % SN) : (int)simd_lid;
+
+ const int sgM = BN != 1 ? (int)(simd_gid / BN) : (int)simd_gid;
+ const int sgN = BN != 1 ? (int)(simd_gid % BN) : 0;
+
+ const int simdM = SM * sgM;
+ const int simdN = SN * sgN;
+
+ int cm = (simdM + thrM);
+ int cn = (simdN + thrN);
+
+ int bm = cm * TM;
+ int bn = cn * TN;
+
+ int out_col = tid.x * blockN + bn;
+
+ const int loop_stride = blockM;
+ const int in_size = in_vec_size;
+ const int n_iter = in_size / loop_stride;
+ const int last_iter = loop_stride * n_iter;
+ const int leftover = in_size - last_iter;
+
+ if (out_col < out_vec_size) {
+ out_col = out_col + TN <= out_vec_size ? out_col : out_vec_size - TN;
+
+ for (int i = 0; i < n_iter; ++i) {
+ threadgroup_barrier(mem_flags::mem_none);
+
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);
+ }
+
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tm = 0; tm < TM; tm++) {
+ auto vc = static_cast<AccT>(v_coeff[tm]);
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ inter[tn] = mat[(bm + tm) * marix_ld + out_col + tn];
+ }
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] += vc * inter[tn];
+ }
+ }
+
+ bm += blockM;
+ }
+
+ if (leftover > 0) {
+ for (int tm = 0; tm < TM && bm + tm < in_vec_size; tm++) {
+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ inter[tn] = mat[(bm + tm) * marix_ld + out_col + tn];
+ }
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] += v_coeff[tm] * inter[tn];
+ }
+ }
+ }
+ }
+
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (ushort sm = (SM / 2); sm >= 1; sm >>= 1) {
+ result[tn] += simd_shuffle_down(result[tn], SN * sm);
+ }
+ }
+
+ if (needs_tgp_reduction) {
+ threadgroup AccT* tgp_results = tgp_memory + sgM * (blockN + TN) + bn;
+ if (thrM == 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ tgp_results[tn] = result[tn];
+ }
+ threadgroup_barrier(mem_flags::mem_none);
+ if (sgM == 0) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int sgm = 1; sgm < BM; sgm++) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int tn = 0; tn < TN; tn++) {
+ result[tn] += tgp_results[sgm * (blockN + TN) + tn];
+ }
+ }
+ }
+ }
+ }
+
+ if (cm == 0 && out_col < out_vec_size) {
+ MLX_MTL_PRAGMA_UNROLL
+ for (int j = 0; j < TN; j++) {
+ if (kDoAxpby) {
+ out_vec[out_col + j] =
+ static_cast<T>(alpha) * static_cast<T>(result[j]) +
+ static_cast<T>(beta) * bias[(out_col + j) * bias_stride];
+ } else {
+ out_vec[out_col + j] = static_cast<T>(result[j]);
+ }
+ }
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+/// gemv kernel: mat [M, K] × vec [K] → out [M]
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ const int BM, const int BN,
+ const int SM, const int SN,
+ const int TM, const int TN,
+ const bool kDoNCBatch,
+ const bool kDoAxpby>
+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]]
+void gemv(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& batch_ndim [[buffer(9)]],
+ const constant int* batch_shape [[buffer(10)]],
+ const constant int64_t* vector_batch_stride [[buffer(11)]],
+ const constant int64_t* matrix_batch_stride [[buffer(12)]],
+ const constant int64_t* bias_batch_stride [[buffer(13)]],
+ const constant int& bias_stride [[buffer(14)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ using kernel_t = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;
+ threadgroup typename kernel_t::acc_type tgp_memory[kernel_t::tgp_mem_size == 0 ? 1 : kernel_t::tgp_mem_size];
+
+ if (kDoNCBatch) {
+ in_vec += gemv_elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);
+ mat += gemv_elem_to_loc(tid.z, batch_shape, matrix_batch_stride, batch_ndim);
+ if (kDoAxpby)
+ bias += gemv_elem_to_loc(tid.z, batch_shape, bias_batch_stride, batch_ndim);
+ } else {
+ in_vec += tid.z * vector_batch_stride[0];
+ mat += tid.z * matrix_batch_stride[0];
+ if (kDoAxpby)
+ bias += tid.z * bias_batch_stride[0];
+ }
+ out_vec += tid.z * out_vec_size;
+
+ kernel_t::run(mat, in_vec, bias, out_vec,
+ in_vec_size, out_vec_size, matrix_ld,
+ alpha, beta, bias_stride,
+ kernel_t::tgp_mem_size == 0 ? nullptr : tgp_memory,
+ tid, lid, simd_gid, simd_lid);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+/// gemv_t kernel: vec [K] × mat [K, N] → out [N]
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ const int BM, const int BN,
+ const int SM, const int SN,
+ const int TM, const int TN,
+ const bool kDoNCBatch,
+ const bool kDoAxpby>
+[[kernel, max_total_threads_per_threadgroup(BM * BN * 32)]]
+void gemv_t(
+ const device T* mat [[buffer(0)]],
+ const device T* in_vec [[buffer(1)]],
+ const device T* bias [[buffer(2)]],
+ device T* out_vec [[buffer(3)]],
+ const constant int& in_vec_size [[buffer(4)]],
+ const constant int& out_vec_size [[buffer(5)]],
+ const constant int& matrix_ld [[buffer(6)]],
+ const constant float& alpha [[buffer(7)]],
+ const constant float& beta [[buffer(8)]],
+ const constant int& batch_ndim [[buffer(9)]],
+ const constant int* batch_shape [[buffer(10)]],
+ const constant int64_t* vector_batch_stride [[buffer(11)]],
+ const constant int64_t* matrix_batch_stride [[buffer(12)]],
+ const constant int64_t* bias_batch_stride [[buffer(13)]],
+ const constant int& bias_stride [[buffer(14)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ using kernel_t = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;
+ threadgroup typename kernel_t::acc_type tgp_memory[kernel_t::tgp_mem_size == 0 ? 1 : kernel_t::tgp_mem_size];
+
+ if (kDoNCBatch) {
+ in_vec += gemv_elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);
+ mat += gemv_elem_to_loc(tid.z, batch_shape, matrix_batch_stride, batch_ndim);
+ if (kDoAxpby)
+ bias += gemv_elem_to_loc(tid.z, batch_shape, bias_batch_stride, batch_ndim);
+ } else {
+ in_vec += tid.z * vector_batch_stride[0];
+ mat += tid.z * matrix_batch_stride[0];
+ if (kDoAxpby)
+ bias += tid.z * bias_batch_stride[0];
+ }
+ out_vec += tid.z * out_vec_size;
+
+ kernel_t::run(mat, in_vec, bias, out_vec,
+ in_vec_size, out_vec_size, matrix_ld,
+ alpha, beta, bias_stride,
+ kernel_t::tgp_mem_size == 0 ? nullptr : tgp_memory,
+ tid, lid, simd_gid, simd_lid);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+/// Instantiations
+///////////////////////////////////////////////////////////////////////////////
+
+// Use decltype-based instantiation (MLX defines.h pattern):
+// template [[host_name(...)]] [[kernel]] decltype(func<...>) func<...>;
+// This avoids redeclaring parameter attributes, which Metal rejects.
+#define instantiate_gemv_helper(func, nm, itype, bm, bn, sm, sn, tm, tn, nc, axpby) \
+ template [[host_name( \
+ #func "_" #nm "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn \
+ "_tm" #tm "_tn" #tn "_nc" #nc "_axpby" #axpby)]] \
+ [[kernel]] decltype(func<itype, bm, bn, sm, sn, tm, tn, (bool)nc, (bool)axpby>) \
+ func<itype, bm, bn, sm, sn, tm, tn, (bool)nc, (bool)axpby>;
+
+#define instantiate_gemv_nc_axpby(func, nm, itype, bm, bn, sm, sn, tm, tn) \
+ instantiate_gemv_helper(func, nm, itype, bm, bn, sm, sn, tm, tn, 0, 0) \
+ instantiate_gemv_helper(func, nm, itype, bm, bn, sm, sn, tm, tn, 0, 1) \
+ instantiate_gemv_helper(func, nm, itype, bm, bn, sm, sn, tm, tn, 1, 0) \
+ instantiate_gemv_helper(func, nm, itype, bm, bn, sm, sn, tm, tn, 1, 1)
+
+// gemv blocks: mat×vec (output size = M)
+// bm=4/8 for large output; bm=1,bn=8 for K-heavy; bm=1,bn=1,sm=8,sn=4 for small K
+#define instantiate_gemv_blocks(nm, itype) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 1, 8, 1, 32, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 1, 8, 1, 32, 1, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 1, 1, 8, 4, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 1, 1, 8, 4, 1, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 4, 1, 1, 32, 1, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 4, 1, 1, 32, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv, nm, itype, 8, 1, 1, 32, 4, 4)
+
+// gemv_t blocks: vec×mat (output size = N)
+// bn=2/4/16 for various output sizes; sm/sn tuned for K size
+#define instantiate_gemv_t_blocks(nm, itype) \
+ instantiate_gemv_nc_axpby(gemv_t, nm, itype, 1, 2, 8, 4, 4, 1) \
+ instantiate_gemv_nc_axpby(gemv_t, nm, itype, 1, 2, 8, 4, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv_t, nm, itype, 1, 4, 8, 4, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv_t, nm, itype, 1, 16, 8, 4, 4, 4) \
+ instantiate_gemv_nc_axpby(gemv_t, nm, itype, 1, 16, 4, 8, 4, 4)
+
+instantiate_gemv_blocks(float32, float)
+instantiate_gemv_blocks(float16, half)
+instantiate_gemv_blocks(bfloat16, bfloat)
+
+instantiate_gemv_t_blocks(float32, float)
+instantiate_gemv_t_blocks(float16, half)
+instantiate_gemv_t_blocks(bfloat16, bfloat)
diff --git a/vendor/candle-metal-kernels/src/metal_src/indexing.metal b/vendor/candle-metal-kernels/src/metal_src/indexing.metal
new file mode 100644
index 0000000..c0e16e7
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/indexing.metal
@@ -0,0 +1,360 @@
+#include <metal_stdlib>
+using namespace metal;
+
+template <typename T>
+inline T max_value();
+
+template <>
+inline int64_t max_value<int64_t>() {
+ return 0x7FFFFFFFFFFFFFFF;
+}
+
+template <>
+inline uint32_t max_value<uint32_t>() {
+ return 0xFFFFFFFFu;
+}
+
+template <>
+inline uint8_t max_value<uint8_t>() {
+ return 0xFF;
+}
+
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+template<typename TYPENAME, typename INDEX_TYPENAME>
+METAL_FUNC void index(
+ constant size_t &dst_size,
+ constant size_t &left_size,
+ constant size_t &src_dim_size,
+ constant size_t &right_size,
+ constant size_t &ids_size,
+ constant bool &contiguous,
+ constant size_t *src_dims,
+ constant size_t *src_strides,
+ const device TYPENAME *input,
+ const device INDEX_TYPENAME *input_ids,
+ device TYPENAME *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dst_size) {
+ return;
+ }
+ const size_t id_i = (tid / right_size) % ids_size;
+ if (input_ids[id_i] == max_value<INDEX_TYPENAME>()) {
+ output[tid] = static_cast<TYPENAME>(0);
+ } else {
+ const INDEX_TYPENAME input_i = min(input_ids[id_i], (INDEX_TYPENAME)(src_dim_size - 1));
+ const size_t right_rank_i = tid % right_size;
+ const size_t left_rank_i = tid / right_size / ids_size;
+ /*
+ // Force prevent out of bounds indexing
+ // since there doesn't seem to be a good way to force crash
+ // No need to check for zero we're only allowing unsized.
+ */
+ const size_t src_i = left_rank_i * src_dim_size * right_size + input_i * right_size + right_rank_i;
+ const size_t strided_src_i = contiguous ? src_i : get_strided_index(src_i, src_dim_size, src_dims, src_strides);
+ output[tid] = input[strided_src_i];
+ }
+}
+
+# define INDEX_OP(NAME, INDEX_TYPENAME, TYPENAME) \
+kernel void NAME( \
+ constant size_t &dst_size, \
+ constant size_t &left_size, \
+ constant size_t &src_dim_size, \
+ constant size_t &right_size, \
+ constant size_t &ids_size, \
+ constant bool &contiguous, \
+ constant size_t *src_dims, \
+ constant size_t *src_strides, \
+ const device TYPENAME *input, \
+ const device INDEX_TYPENAME *input_ids, \
+ device TYPENAME *output, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ index<TYPENAME, INDEX_TYPENAME>(dst_size, left_size, src_dim_size, right_size, ids_size, contiguous, src_dims, src_strides, input, input_ids, output, tid); \
+}
+
+
+template<typename TYPENAME, typename INDEX_TYPENAME>
+METAL_FUNC void gather(
+ constant size_t &dst_size,
+ constant size_t &left_size,
+ constant size_t &src_dim_size,
+ constant size_t &right_size,
+ constant size_t &ids_size,
+ const device TYPENAME *input,
+ const device INDEX_TYPENAME *input_ids,
+ device TYPENAME *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dst_size) {
+ return;
+ }
+ const INDEX_TYPENAME input_i = input_ids[tid];
+ if (input_i == max_value<INDEX_TYPENAME>()) {
+ output[tid] = static_cast<TYPENAME>(0);
+ } else {
+ const size_t right_rank_i = tid % right_size;
+ const size_t left_rank_i = tid / right_size / ids_size;
+ const size_t src_i = (left_rank_i * src_dim_size + input_i) * right_size + right_rank_i;
+ output[tid] = input[src_i];
+ }
+}
+
+# define GATHER_OP(NAME, INDEX_TYPENAME, TYPENAME) \
+kernel void NAME( \
+ constant size_t &dst_size, \
+ constant size_t &left_size, \
+ constant size_t &src_dim_size, \
+ constant size_t &right_size, \
+ constant size_t &ids_size, \
+ const device TYPENAME *input, \
+ const device INDEX_TYPENAME *input_ids, \
+ device TYPENAME *output, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ gather<TYPENAME, INDEX_TYPENAME>(dst_size, left_size, src_dim_size, right_size, ids_size, input, input_ids, output, tid); \
+}
+
+template<typename TYPENAME, typename INDEX_TYPENAME>
+METAL_FUNC void scatter(
+ constant size_t &dst_size,
+ constant size_t &left_size,
+ constant size_t &src_dim_size,
+ constant size_t &right_size,
+ constant size_t &dst_dim_size,
+ const device TYPENAME *input,
+ const device INDEX_TYPENAME *input_ids,
+ device TYPENAME *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dst_size) {
+ return;
+ }
+ const size_t right_rank_i = tid % right_size;
+ const size_t left_rank_i = tid / right_size;
+ for (unsigned int j = 0; j < src_dim_size; ++j) {
+ const size_t src_i = (left_rank_i * src_dim_size + j) * right_size + right_rank_i;
+ const INDEX_TYPENAME idx = input_ids[src_i];
+ if (idx < max_value<INDEX_TYPENAME>()) {
+ const size_t dst_i = (left_rank_i * dst_dim_size + idx) * right_size + right_rank_i;
+ output[dst_i] = input[src_i];
+ }
+ }
+}
+
+template<typename TYPENAME, typename INDEX_TYPENAME>
+METAL_FUNC void scatter_add(
+ constant size_t &dst_size,
+ constant size_t &left_size,
+ constant size_t &src_dim_size,
+ constant size_t &right_size,
+ constant size_t &dst_dim_size,
+ const device TYPENAME *input,
+ const device INDEX_TYPENAME *input_ids,
+ device TYPENAME *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dst_size) {
+ return;
+ }
+ const size_t right_rank_i = tid % right_size;
+ const size_t left_rank_i = tid / right_size;
+ for (unsigned int j = 0; j < src_dim_size; ++j) {
+ const size_t src_i = (left_rank_i * src_dim_size + j) * right_size + right_rank_i;
+ const INDEX_TYPENAME idx = input_ids[src_i];
+ if (idx < max_value<INDEX_TYPENAME>()) {
+ const size_t dst_i = (left_rank_i * dst_dim_size + idx) * right_size + right_rank_i;
+ output[dst_i] += input[src_i];
+ }
+ }
+}
+
+# define SCATTER_OP(NAME, INDEX_TYPENAME, TYPENAME) \
+kernel void NAME( \
+ constant size_t &dst_size, \
+ constant size_t &left_size, \
+ constant size_t &src_dim_size, \
+ constant size_t &right_size, \
+ constant size_t &dst_dim_size, \
+ const device TYPENAME *input, \
+ const device INDEX_TYPENAME *input_ids, \
+ device TYPENAME *output, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ scatter<TYPENAME, INDEX_TYPENAME>(dst_size, left_size, src_dim_size, right_size, dst_dim_size, input, input_ids, output, tid); \
+}
+
+# define SCATTER_ADD_OP(NAME, INDEX_TYPENAME, TYPENAME) \
+kernel void NAME( \
+ constant size_t &dst_size, \
+ constant size_t &left_size, \
+ constant size_t &src_dim_size, \
+ constant size_t &right_size, \
+ constant size_t &dst_dim_size, \
+ const device TYPENAME *input, \
+ const device INDEX_TYPENAME *input_ids, \
+ device TYPENAME *output, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ scatter_add<TYPENAME, INDEX_TYPENAME>(dst_size, left_size, src_dim_size, right_size, dst_dim_size, input, input_ids, output, tid); \
+}
+
+template<typename TYPENAME, typename INDEX_TYPENAME>
+METAL_FUNC void index_add(
+ constant size_t &dst_size,
+ constant size_t &left_size,
+ constant size_t &src_dim_size,
+ constant size_t &right_size,
+ constant size_t &dst_dim_size,
+ constant size_t &ids_dim_size,
+ const device TYPENAME *input,
+ const device INDEX_TYPENAME *input_ids,
+ device TYPENAME *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dst_size) {
+ return;
+ }
+ const size_t right_rank_i = tid % right_size;
+ const size_t left_rank_i = tid / right_size;
+ for (unsigned int j = 0; j < ids_dim_size; ++j) {
+ const INDEX_TYPENAME idx = input_ids[j];
+ if (idx < max_value<INDEX_TYPENAME>()) {
+ const size_t src_i = (left_rank_i * src_dim_size + j) * right_size + right_rank_i;
+ const size_t dst_i = (left_rank_i * dst_dim_size + idx) * right_size + right_rank_i;
+ output[dst_i] += input[src_i];
+ }
+ }
+}
+
+# define INDEX_ADD_OP(NAME, INDEX_TYPENAME, TYPENAME) \
+kernel void NAME( \
+ constant size_t &dst_size, \
+ constant size_t &left_size, \
+ constant size_t &src_dim_size, \
+ constant size_t &right_size, \
+ constant size_t &dst_dim_size, \
+ constant size_t &ids_dim_size, \
+ const device TYPENAME *input, \
+ const device INDEX_TYPENAME *input_ids, \
+ device TYPENAME *output, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ index_add<TYPENAME, INDEX_TYPENAME>(dst_size, left_size, src_dim_size, right_size, dst_dim_size, ids_dim_size, input, input_ids, output, tid); \
+}
+
+
+INDEX_OP(is_i64_i64, int64_t, int64_t)
+INDEX_OP(is_i64_f32, int64_t, float)
+INDEX_OP(is_i64_f16, int64_t, half)
+#if defined(__HAVE_BFLOAT__)
+INDEX_OP(is_i64_bf16, int64_t, bfloat)
+#endif
+
+INDEX_OP(is_u32_u8, uint32_t, uint8_t)
+INDEX_OP(is_u32_u32, uint32_t, uint32_t)
+INDEX_OP(is_u32_i64, uint32_t, int64_t)
+INDEX_OP(is_u32_f32, uint32_t, float)
+INDEX_OP(is_u32_f16, uint32_t, half)
+#if defined(__HAVE_BFLOAT__)
+INDEX_OP(is_u32_bf16, uint32_t, bfloat)
+#endif
+
+INDEX_OP(is_u8_u8, uint8_t, uint8_t)
+INDEX_OP(is_u8_u32, uint8_t, uint32_t)
+INDEX_OP(is_u8_i64, uint8_t, int64_t)
+INDEX_OP(is_u8_f32, uint8_t, float)
+INDEX_OP(is_u8_f16, uint8_t, half)
+#if defined(__HAVE_BFLOAT__)
+INDEX_OP(is_u8_bf16, uint8_t, bfloat)
+#endif
+
+GATHER_OP(gather_u8_f32, uint8_t, float)
+GATHER_OP(gather_u8_f16, uint8_t, half)
+GATHER_OP(gather_i64_f32, int64_t, float)
+GATHER_OP(gather_i64_f16, int64_t, half)
+GATHER_OP(gather_u32_f32, uint, float)
+GATHER_OP(gather_u32_f16, uint, half)
+#if defined(__HAVE_BFLOAT__)
+GATHER_OP(gather_u8_bf16, uint8_t, bfloat)
+GATHER_OP(gather_i64_bf16, int64_t, bfloat)
+GATHER_OP(gather_u32_bf16, uint, bfloat)
+#endif
+GATHER_OP(gather_u8_u8, uint8_t, uint8_t)
+GATHER_OP(gather_u8_i64, uint8_t, int64_t)
+GATHER_OP(gather_u8_u32, uint8_t, uint)
+GATHER_OP(gather_u32_u32, uint, uint)
+GATHER_OP(gather_u32_i64, uint, int64_t)
+GATHER_OP(gather_i64_u32, int64_t, uint)
+GATHER_OP(gather_i64_i64, int64_t, int64_t)
+
+SCATTER_ADD_OP(sa_u32_f32, uint32_t, float)
+SCATTER_ADD_OP(sa_u8_f32, uint8_t, float)
+SCATTER_ADD_OP(sa_i64_f32, int64_t, float)
+SCATTER_ADD_OP(sa_u32_u32, uint32_t, uint32_t)
+SCATTER_ADD_OP(sa_u32_f16, uint32_t, half)
+SCATTER_ADD_OP(sa_u8_f16, uint8_t, half)
+SCATTER_ADD_OP(sa_i64_f16, int64_t, half)
+#if defined(__HAVE_BFLOAT__)
+SCATTER_ADD_OP(sa_u32_bf16, uint32_t, bfloat)
+SCATTER_ADD_OP(sa_u8_bf16, uint8_t, bfloat)
+SCATTER_ADD_OP(sa_i64_bf16, int64_t, bfloat)
+#endif
+
+SCATTER_OP(s_u32_f32, uint32_t, float)
+SCATTER_OP(s_u8_f32, uint8_t, float)
+SCATTER_OP(s_i64_f32, int64_t, float)
+SCATTER_OP(s_u32_u32, uint32_t, uint32_t)
+SCATTER_OP(s_u32_f16, uint32_t, half)
+SCATTER_OP(s_u8_f16, uint8_t, half)
+SCATTER_OP(s_i64_f16, int64_t, half)
+#if defined(__HAVE_BFLOAT__)
+SCATTER_OP(s_u32_bf16, uint32_t, bfloat)
+SCATTER_OP(s_u8_bf16, uint8_t, bfloat)
+SCATTER_OP(s_i64_bf16, int64_t, bfloat)
+#endif
+
+// i64
+INDEX_ADD_OP(ia_i64_f16, int64_t, half)
+INDEX_ADD_OP(ia_i64_f32, int64_t, float)
+INDEX_ADD_OP(ia_i64_i64, int64_t, int64_t)
+INDEX_ADD_OP(ia_i64_u32, int64_t, uint32_t)
+INDEX_ADD_OP(ia_i64_u8, int64_t, uint8_t)
+#if defined(__HAVE_BFLOAT__)
+INDEX_ADD_OP(ia_i64_bf16, int64_t, bfloat)
+#endif
+
+// u32
+INDEX_ADD_OP(ia_u32_f16, uint32_t, half)
+INDEX_ADD_OP(ia_u32_f32, uint32_t, float)
+INDEX_ADD_OP(ia_u32_i64, uint32_t, int64_t)
+INDEX_ADD_OP(ia_u32_u32, uint32_t, uint32_t)
+INDEX_ADD_OP(ia_u32_u8, uint32_t, uint8_t)
+#if defined(__HAVE_BFLOAT__)
+INDEX_ADD_OP(ia_u32_bf16, uint32_t, bfloat)
+#endif
+
+// u8
+INDEX_ADD_OP(ia_u8_f16, uint8_t, half)
+INDEX_ADD_OP(ia_u8_f32, uint8_t, float)
+INDEX_ADD_OP(ia_u8_i64, uint8_t, int64_t)
+INDEX_ADD_OP(ia_u8_u32, uint8_t, uint32_t)
+INDEX_ADD_OP(ia_u8_u8, uint8_t, uint8_t)
+#if defined(__HAVE_BFLOAT__)
+INDEX_ADD_OP(ia_u8_bf16, uint8_t, bfloat)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/mlx_gemm.metal b/vendor/candle-metal-kernels/src/metal_src/mlx_gemm.metal
new file mode 100644
index 0000000..cc2279f
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/mlx_gemm.metal
@@ -0,0 +1,1483 @@
+// MLX Kernel extracted from:
+// https://github.com/ml-explore/mlx/blob/main/mlx/backend/metal/kernels/steel/gemm
+// Copyright © 2024 Apple Inc.
+
+#include <metal_simdgroup>
+#include <metal_simdgroup_matrix>
+#include <metal_stdlib>
+
+#define STEEL_CONST static constant constexpr const
+#define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")
+
+using namespace metal;
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/params.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// GEMM param classes
+///////////////////////////////////////////////////////////////////////////////
+
+struct GEMMParams {
+ const int M;
+ const int N;
+ const int K;
+
+ const int lda;
+ const int ldb;
+ const int ldd;
+
+ const int tiles_n;
+ const int tiles_m;
+
+ const size_t batch_stride_a;
+ const size_t batch_stride_b;
+ const size_t batch_stride_d;
+
+ const int swizzle_log;
+ const int gemm_k_iterations_aligned;
+
+ const int batch_ndim;
+};
+
+struct GEMMSpiltKParams {
+ const int M;
+ const int N;
+ const int K;
+
+ const int lda;
+ const int ldb;
+ const int ldc;
+
+ const int tiles_n;
+ const int tiles_m;
+
+ const int split_k_partitions;
+ const int split_k_partition_stride;
+ const int split_k_partition_size;
+
+ const int gemm_k_iterations_aligned;
+};
+
+struct GEMMAddMMParams {
+ const int ldc;
+ const int fdc;
+
+ const size_t batch_stride_c;
+
+ const float alpha;
+ const float beta;
+};
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/loader.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// Loading helper
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ short BROWS,
+ short BCOLS,
+ short dst_ld,
+ short reduction_dim,
+ short tgp_size,
+ short alignment = 1,
+ short n_reads = (BCOLS * BROWS) / (tgp_size),
+ short TCOLS = BCOLS / n_reads,
+ short TROWS = tgp_size / TCOLS>
+struct BlockLoader {
+ STEEL_CONST short n_rows = (BROWS + TROWS - 1) / TROWS;
+ STEEL_CONST short vec_size = n_reads;
+
+ // Leading dimension for src
+ const int src_ld;
+ const int tile_stride;
+
+ // Thread location indices
+ const short thread_idx;
+ const short bi;
+ const short bj;
+
+ // threadgroup and device memory
+ threadgroup T* dst;
+ const device T* src;
+
+ struct alignas(alignment * sizeof(T)) ReadVector {
+ uint8_t v[sizeof(T) * vec_size];
+ };
+
+ /* Constructor */
+ METAL_FUNC BlockLoader(
+ const device T* src_,
+ const int src_ld_,
+ threadgroup T* dst_,
+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],
+ ushort simd_lane_id [[thread_index_in_simdgroup]])
+ : src_ld(src_ld_),
+ tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),
+ thread_idx(simd_group_id * 32 + simd_lane_id),
+ bi(thread_idx / TCOLS),
+ bj(vec_size * (thread_idx % TCOLS)),
+ dst(dst_ + bi * dst_ld + bj),
+ src(src_ + bi * src_ld + bj) {}
+
+ /* Apply operation to threadgroup without bound checking */
+ template <typename UnaryOp>
+ METAL_FUNC void apply_inplace_op(thread const UnaryOp& op) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = op.apply(dst[i * dst_ld + j]);
+ }
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - without bound checking */
+ METAL_FUNC void load_unsafe() const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ *((threadgroup ReadVector*)(&dst[i * dst_ld])) =
+ *((const device ReadVector*)(&src[i * src_ld]));
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - with bound checking */
+ METAL_FUNC void load_safe(short2 src_tile_dim) const {
+ src_tile_dim = src_tile_dim - short2(bj, bi);
+
+ // Skip loading if thread has no valid reads
+ if (src_tile_dim.x <= 0 || src_tile_dim.y <= 0) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = T(0);
+ }
+ }
+ return;
+ }
+
+ // Use fast thread memory for bound checks
+ bool tmp_idx[vec_size];
+ T tmp_val[vec_size];
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ // Make sure tmp_idx only contains valid indices
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_idx[j] = (i < src_tile_dim.y) && (j < src_tile_dim.x);
+ }
+
+ // Read valid indices into tmp_val
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = src[(tmp_idx[j] ? i * src_ld + j : 0)];
+ }
+
+ // Zero out unneeded values
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = tmp_idx[j] ? tmp_val[j] : T(0);
+ }
+
+ // Copy values to threadgroup memory
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = tmp_val[j];
+ }
+ }
+ }
+
+ /* Iteration helper */
+ METAL_FUNC void next() {
+ src += tile_stride;
+ }
+};
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/transforms.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// Transforms and Epilogues
+///////////////////////////////////////////////////////////////////////////////
+
+template <typename OutT, typename InT>
+struct TransformNone {
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ static METAL_FUNC OutT apply(InT x, OutT) {
+ return static_cast<OutT>(x);
+ }
+};
+
+template <typename OutT, typename InT>
+struct TransformAdd {
+ TransformAdd(const float, const float) {}
+
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ static METAL_FUNC OutT apply(InT x, OutT c) {
+ return static_cast<OutT>(x) + c;
+ }
+};
+
+template <typename OutT, typename InT>
+struct TransformAxpby {
+ const float alpha;
+ const float beta;
+
+ TransformAxpby(const float alpha_, const float beta_)
+ : alpha(alpha_), beta(beta_) {}
+
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ METAL_FUNC OutT apply(InT x, OutT c) const {
+ return static_cast<OutT>(x * alpha + (beta * c));
+ }
+};
+
+template <typename T>
+struct AccumHelper {
+ typedef float accum_type;
+};
+
+struct BlockSwizzle {
+ static METAL_FUNC int2
+ swizzle(uint3 tid [[threadgroup_position_in_grid]], const int swizzle_log) {
+ const int tid_x = (tid.x) >> swizzle_log;
+ const int tid_y =
+ ((tid.y) << swizzle_log) + ((tid.x) & ((1 << swizzle_log) - 1));
+ return int2(tid_x, tid_y);
+ }
+};
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/mma.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// MMA helper
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ typename U,
+ int BM,
+ int BN,
+ int BK,
+ int WM,
+ int WN,
+ bool transpose_a,
+ bool transpose_b,
+ short lda_tgp,
+ short ldb_tgp,
+ typename AccumType = float,
+ typename Epilogue = TransformNone<U, AccumType>>
+struct BlockMMA {
+ // Warp tile simdgroup matrix strides along M
+ STEEL_CONST short TM_stride = 8 * WM;
+ // Warp tile simdgroup matrix strides along M
+ STEEL_CONST short TN_stride = 8 * WN;
+
+ // Warp tile size along M
+ STEEL_CONST short TM = BM / TM_stride;
+ // Warp tile size along N
+ STEEL_CONST short TN = BN / TN_stride;
+
+ // Strides of A, B along reduction axis
+ STEEL_CONST short simd_stride_a = {
+ transpose_a ? TM_stride : TM_stride * lda_tgp};
+ STEEL_CONST short simd_stride_b = {
+ transpose_b ? TN_stride * ldb_tgp : TN_stride};
+
+ // Jump between elements
+ STEEL_CONST short jump_a = {transpose_a ? lda_tgp : 1};
+ STEEL_CONST short jump_b = {transpose_b ? ldb_tgp : 1};
+
+ STEEL_CONST short tile_stride_a = {transpose_a ? 8 * lda_tgp : 8};
+ STEEL_CONST short tile_stride_b = {transpose_b ? 8 : 8 * ldb_tgp};
+
+ // Simdgroup matrices
+ simdgroup_matrix<AccumType, 8, 8> Asimd[TM];
+ simdgroup_matrix<AccumType, 8, 8> Bsimd[TN];
+ simdgroup_matrix<AccumType, 8, 8> results[TM * TN] = {
+ simdgroup_matrix<AccumType, 8, 8>(0)};
+
+ // Offsets within threadgroup
+ const short tm;
+ const short tn;
+
+ short sm;
+ short sn;
+
+ short As_offset;
+ short Bs_offset;
+
+ /* Constructor */
+ METAL_FUNC BlockMMA(
+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],
+ ushort simd_lane_id [[thread_index_in_simdgroup]])
+ : tm(8 * (simd_group_id / WN)), tn(8 * (simd_group_id % WN)) {
+ // Determine thread position in simdgroup matrix
+ short qid = simd_lane_id / 4;
+ sm = (qid & 4) + (simd_lane_id / 2) % 4;
+ sn = (qid & 2) * 2 + (simd_lane_id % 2) * 2;
+
+ // Determine thread and simdgroup offset
+ As_offset =
+ transpose_a ? ((sn)*lda_tgp + (tm + sm)) : ((sn) + (tm + sm) * lda_tgp);
+ Bs_offset =
+ transpose_b ? ((tn + sn) * ldb_tgp + (sm)) : ((sm)*ldb_tgp + (tn + sn));
+ }
+
+ /* (BM, BK) X (BK, BN) multiply accumulate function */
+ METAL_FUNC void mma(const threadgroup T* As, const threadgroup T* Bs) {
+ // Adjust for simdgroup and thread location
+ As += As_offset;
+ Bs += Bs_offset;
+
+ // Iterate over BK in blocks of 8
+ STEEL_PRAGMA_UNROLL
+ for (short kk = 0; kk < BK; kk += 8) {
+ simdgroup_barrier(mem_flags::mem_none);
+
+ // Load elements from threadgroup A as simdgroup matrices
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ Asimd[i].thread_elements()[0] =
+ static_cast<AccumType>(As[i * simd_stride_a + 0]);
+ Asimd[i].thread_elements()[1] =
+ static_cast<AccumType>(As[i * simd_stride_a + jump_a]);
+ }
+
+ simdgroup_barrier(mem_flags::mem_none);
+
+ // Load elements from threadgroup B as simdgroup matrices
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ Bsimd[j].thread_elements()[0] =
+ static_cast<AccumType>(Bs[j * simd_stride_b + 0]);
+ Bsimd[j].thread_elements()[1] =
+ static_cast<AccumType>(Bs[j * simd_stride_b + jump_b]);
+ }
+
+ simdgroup_barrier(mem_flags::mem_none);
+
+ // Multiply and accumulate into result simdgroup matrices
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ short j_serp = (i % 2) ? (TN - 1 - j) : j;
+
+ simdgroup_multiply_accumulate(
+ results[i * TN + j_serp],
+ Asimd[i],
+ Bsimd[j_serp],
+ results[i * TN + j_serp]);
+ }
+ }
+
+ // Progress to next simdgroup tile
+ As += tile_stride_a;
+ Bs += tile_stride_b;
+ }
+ }
+
+ /* Store results from simdgroup_matrix results into device memory */
+ METAL_FUNC void store_result(device U* D, const int ldd) const {
+ // Adjust for simdgroup and thread location
+ D += (sm + tm) * ldd + tn + sn;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = results[i * TN + j].thread_elements();
+ int offset = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue
+ U outs[2] = {Epilogue::apply(accum[0]), Epilogue::apply(accum[1])};
+
+ // Write out D
+ D[offset] = outs[0];
+ D[offset + 1] = outs[1];
+ }
+ }
+ }
+
+ METAL_FUNC void
+ store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) const {
+ // Adjust for simdgroup and thread location
+ D += (sm + tm) * ldd + (tn + sn);
+ dst_tile_dims -= short2(tn + sn, sm + tm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ STEEL_PRAGMA_UNROLL
+ for (int i = 0; i < TM; i++) {
+ if (i * TM_stride < dst_tile_dims.y) {
+ STEEL_PRAGMA_UNROLL
+ for (int j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = results[i * TN + j].thread_elements();
+ int offset = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue and output C
+ if (j * TN_stride < dst_tile_dims.x) {
+ D[offset] = Epilogue::apply(accum[0]);
+ }
+
+ if (j * TN_stride + 1 < dst_tile_dims.x) {
+ D[offset + 1] = Epilogue::apply(accum[1]);
+ }
+ }
+ }
+ }
+ }
+
+ /* Apply epilogue */
+ template <typename UnaryEpilogue>
+ METAL_FUNC void apply_epilogue(thread const UnaryEpilogue& epilogue_op) {
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread auto& accum = results[i * TN + j].thread_elements();
+
+ // Apply epilogue
+ accum[0] = epilogue_op.apply(accum[0]);
+ accum[1] = epilogue_op.apply(accum[1]);
+ }
+ }
+ }
+
+ /* Apply epilogue */
+ template <typename BinaryEpilogue>
+ METAL_FUNC void apply_epilogue(
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ thread const BinaryEpilogue& epilogue_op) {
+ // Adjust for simdgroup and thread location
+ C += (sm + tm) * ldc + (tn + sn) * fdc;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread auto& accum = results[i * TN + j].thread_elements();
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+
+ // Apply epilogue
+ accum[0] = epilogue_op.apply(accum[0], C[offset_c]);
+ accum[1] = epilogue_op.apply(accum[1], C[offset_c + fdc]);
+ }
+ }
+ }
+
+ /* Apply epilogue */
+ template <typename BinaryEpilogue>
+ METAL_FUNC void apply_epilogue_safe(
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ short2 dst_tile_dims,
+ thread const BinaryEpilogue& epilogue_op) {
+ // Adjust for simdgroup and thread location
+ C += (sm + tm) * ldc + (tn + sn) * fdc;
+ dst_tile_dims -= short2(tn + sn, sm + tm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread auto& accum = results[i * TN + j].thread_elements();
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+
+ // Read C
+ U c_elems[2] = {0};
+
+ if ((j * TN_stride + 1) < dst_tile_dims.x) {
+ c_elems[0] = C[offset_c];
+ c_elems[1] = C[offset_c + fdc];
+ } else if ((j * TN_stride) < dst_tile_dims.x) {
+ c_elems[0] = C[offset_c];
+ }
+
+ // Apply epilogue
+ accum[0] = epilogue_op.apply(accum[0], c_elems[0]);
+ accum[1] = epilogue_op.apply(accum[1], c_elems[1]);
+ }
+ }
+ }
+
+ /* Store results from simdgroup_matrix results into device memory */
+ METAL_FUNC void store_result(
+ device U* D,
+ const int ldd,
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ thread const Epilogue& epilogue_op) const {
+ // Adjust for simdgroup and thread location
+ C += (sm + tm) * ldc + (tn + sn) * fdc;
+ D += (sm + tm) * ldd + tn + sn;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = results[i * TN + j].thread_elements();
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue
+ U outs[2] = {
+ epilogue_op.apply(accum[0], C[offset_c]),
+ epilogue_op.apply(accum[1], C[offset_c + fdc])};
+
+ // Write out D
+ D[offset_d] = outs[0];
+ D[offset_d + 1] = outs[1];
+ }
+ }
+ }
+
+ METAL_FUNC void store_result_safe(
+ device U* D,
+ const int ldd,
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ short2 dst_tile_dims,
+ thread const Epilogue& epilogue_op) const {
+ // Adjust for simdgroup and thread location
+ C += (sm + tm) * ldc + (tn + sn) * fdc;
+ D += (sm + tm) * ldd + tn + sn;
+ dst_tile_dims -= short2(tn + sn, sm + tm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ STEEL_PRAGMA_UNROLL
+ for (int i = 0; i < TM; i++) {
+ if (i * TM_stride < dst_tile_dims.y) {
+ STEEL_PRAGMA_UNROLL
+ for (int j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = results[i * TN + j].thread_elements();
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue and output C
+ if (j * TN_stride < dst_tile_dims.x) {
+ D[offset_d] = epilogue_op.apply(accum[0], C[offset_c]);
+ }
+
+ if (j * TN_stride + 1 < dst_tile_dims.x) {
+ D[offset_d + 1] = epilogue_op.apply(accum[1], C[offset_c + fdc]);
+ }
+ }
+ }
+ }
+ }
+};
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/gemm.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// GEMM kernel class
+///////////////////////////////////////////////////////////////////////////////
+
+template <bool M_aligned, bool N_aligned, bool K_aligned>
+struct LoopAlignment {};
+
+template <
+ typename T,
+ typename U,
+ int BM,
+ int BN,
+ int BK,
+ int WM,
+ int WN,
+ bool transpose_a,
+ bool transpose_b,
+ bool MN_aligned,
+ bool K_aligned,
+ typename AccumType = typename AccumHelper<T>::accum_type,
+ typename Epilogue = TransformNone<U, AccumType>>
+struct GEMMKernel {
+ STEEL_CONST short tgp_padding_a = 16 / sizeof(T);
+ STEEL_CONST short tgp_padding_b = 16 / sizeof(T);
+ STEEL_CONST short tgp_mem_size_a =
+ transpose_a ? BK * (BM + tgp_padding_a) : BM * (BK + tgp_padding_a);
+ STEEL_CONST short tgp_mem_size_b =
+ transpose_b ? BN * (BK + tgp_padding_b) : BK * (BN + tgp_padding_b);
+ STEEL_CONST short tgp_mem_size = tgp_mem_size_a + tgp_mem_size_b;
+
+ STEEL_CONST short tgp_size = WM * WN * 32;
+
+ using loader_a_t = BlockLoader<
+ T,
+ transpose_a ? BK : BM,
+ transpose_a ? BM : BK,
+ transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a,
+ !transpose_a,
+ tgp_size>;
+ using loader_b_t = BlockLoader<
+ T,
+ transpose_b ? BN : BK,
+ transpose_b ? BK : BN,
+ transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b,
+ transpose_b,
+ tgp_size>;
+ using mma_t = BlockMMA<
+ T,
+ U,
+ BM,
+ BN,
+ BK,
+ WM,
+ WN,
+ transpose_a,
+ transpose_b,
+ transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a,
+ transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b,
+ AccumType,
+ Epilogue>;
+
+ /* Main kernel function */
+ template <bool M_aligned, bool N_aligned, bool K_aligned_>
+ static METAL_FUNC void gemm_loop(
+ threadgroup T* As [[threadgroup(0)]],
+ threadgroup T* Bs [[threadgroup(1)]],
+ const int gemm_k_iterations,
+ thread loader_a_t& loader_a,
+ thread loader_b_t& loader_b,
+ thread mma_t& mma_op,
+ thread const short& tgp_bm,
+ thread const short& tgp_bn,
+ thread const short& lbk,
+ LoopAlignment<M_aligned, N_aligned, K_aligned_> l = {}) {
+ // Appease the compiler
+ (void)l;
+
+ short2 tile_dims_A = transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);
+
+ short2 tile_dims_B = transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);
+
+ for (int k = 0; k < gemm_k_iterations; k++) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // Load elements into threadgroup
+ if (M_aligned) {
+ loader_a.load_unsafe();
+ } else {
+ loader_a.load_safe(tile_dims_A);
+ }
+
+ if (N_aligned) {
+ loader_b.load_unsafe();
+ } else {
+ loader_b.load_safe(tile_dims_B);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Multiply and accumulate threadgroup elements
+ mma_op.mma(As, Bs);
+
+ // Prepare for next iteration
+ loader_a.next();
+ loader_b.next();
+ }
+
+ if (!K_aligned_) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ short2 tile_dims_A_last =
+ transpose_a ? short2(tgp_bm, lbk) : short2(lbk, tgp_bm);
+ short2 tile_dims_B_last =
+ transpose_b ? short2(lbk, tgp_bn) : short2(tgp_bn, lbk);
+
+ loader_a.load_safe(tile_dims_A_last);
+ loader_b.load_safe(tile_dims_B_last);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ mma_op.mma(As, Bs);
+ }
+ }
+
+ /* Main kernel function */
+ static METAL_FUNC void run(
+ const device T* A [[buffer(0)]],
+ const device T* B [[buffer(1)]],
+ device U* D [[buffer(2)]],
+ const constant GEMMParams* params [[buffer(3)]],
+ threadgroup T* As [[threadgroup(0)]],
+ threadgroup T* Bs [[threadgroup(1)]],
+ uint simd_lane_id [[thread_index_in_simdgroup]],
+ uint simd_group_id [[simdgroup_index_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ // Pacifying compiler
+ (void)lid;
+
+ const int tid_y = ((tid.y) << params->swizzle_log) +
+ ((tid.x) & ((1 << params->swizzle_log) - 1));
+ const int tid_x = (tid.x) >> params->swizzle_log;
+
+ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {
+ return;
+ }
+
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Find block in A, B, C
+ const int c_row = tid_y * BM;
+ const int c_col = tid_x * BN;
+ const size_t c_row_long = size_t(c_row);
+ const size_t c_col_long = size_t(c_col);
+
+ A += transpose_a ? c_row_long : c_row_long * params->lda;
+ B += transpose_b ? c_col_long * params->ldb : c_col_long;
+ D += c_row_long * params->ldd + c_col_long;
+
+ // Prepare threadgroup loading operations
+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);
+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);
+
+ // Prepare threadgroup mma operation
+ thread mma_t mma_op(simd_group_id, simd_lane_id);
+
+ int gemm_k_iterations = params->gemm_k_iterations_aligned;
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // MNK aligned loop
+ if (MN_aligned) {
+ for (int k = 0; k < gemm_k_iterations; k++) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // Load elements into threadgroup
+ loader_a.load_unsafe();
+ loader_b.load_unsafe();
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Multiply and accumulate threadgroup elements
+ mma_op.mma(As, Bs);
+
+ // Prepare for next iteration
+ loader_a.next();
+ loader_b.next();
+ }
+
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Loop tail
+ if (!K_aligned) {
+ int lbk = params->K - params->gemm_k_iterations_aligned * BK;
+ short2 tile_dims_A = transpose_a ? short2(BM, lbk) : short2(lbk, BM);
+ short2 tile_dims_B = transpose_b ? short2(lbk, BN) : short2(BN, lbk);
+
+ loader_a.load_safe(tile_dims_A);
+ loader_b.load_safe(tile_dims_B);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ mma_op.mma(As, Bs);
+ }
+
+ // Store results to device memory
+ mma_op.store_result(D, params->ldd);
+ return;
+
+ }
+ ///////////////////////////////////////////////////////////////////////////////
+ // MN unaligned loop
+ else { // Loop over K - unaligned case
+ short tgp_bm = min(BM, params->M - c_row);
+ short tgp_bn = min(BN, params->N - c_col);
+ short leftover_bk = params->K - params->gemm_k_iterations_aligned * BK;
+
+ if (tgp_bm == BM && tgp_bn == BN) {
+ gemm_loop<true, true, K_aligned>(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk);
+
+ mma_op.store_result(D, params->ldd);
+ return;
+
+ } else if (tgp_bn == BN) {
+ gemm_loop<false, true, K_aligned>(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk);
+
+ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+ return;
+
+ } else if (tgp_bm == BM) {
+ gemm_loop<true, false, K_aligned>(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk);
+
+ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+ return;
+
+ } else {
+ gemm_loop<false, false, K_aligned>(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk);
+
+ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+ return;
+ }
+ }
+ }
+};
+
+// utils.h
+///////////////////////////////////////////////////////////////////////////////
+// Single Array with generic dims
+
+template <typename stride_t>
+METAL_FUNC stride_t elem_to_loc(
+ uint elem,
+ device const int* shape,
+ device const stride_t* strides,
+ int ndim) {
+ stride_t loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * strides[i];
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+template <typename stride_t>
+METAL_FUNC stride_t elem_to_loc(
+ uint elem,
+ constant const int* shape,
+ constant const stride_t* strides,
+ int ndim) {
+ stride_t loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * strides[i];
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+template <typename stride_t>
+METAL_FUNC stride_t elem_to_loc(
+ stride_t elem,
+ device const int* shape,
+ device const stride_t* strides,
+ int ndim) {
+ stride_t loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * strides[i];
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+template <typename stride_t>
+METAL_FUNC stride_t elem_to_loc(
+ stride_t elem,
+ constant const int* shape,
+ constant const stride_t* strides,
+ int ndim) {
+ stride_t loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * strides[i];
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+// Non templated version to handle arbitrary dims
+template <typename stride_t>
+METAL_FUNC stride_t elem_to_loc(
+ uint3 elem,
+ constant const int* shape,
+ constant const stride_t* strides,
+ int ndim) {
+ stride_t loc = elem.x * strides[ndim - 1] + elem.y * strides[ndim - 2];
+ for (int d = ndim - 3; d >= 0; --d) {
+ loc += (elem.z % shape[d]) * strides[d];
+ elem.z /= shape[d];
+ }
+ return loc;
+}
+
+
+METAL_FUNC ulong2 elem_to_loc_broadcast(
+ uint elem,
+ constant const int* shape,
+ constant const size_t* a_strides,
+ constant const size_t* b_strides,
+ int ndim) {
+ ulong loc_a{0};
+ ulong loc_b{0};
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ int pos_in_dim = (elem % shape[i]);
+ elem /= shape[i];
+ loc_a += pos_in_dim * a_strides[i];
+ loc_b += pos_in_dim * b_strides[i];
+ }
+ return ulong2(loc_a, loc_b);
+}
+
+METAL_FUNC ulong3 elem_to_loc_broadcast(
+ uint elem,
+ constant const int* shape,
+ constant const size_t* a_strides,
+ constant const size_t* b_strides,
+ constant const size_t* c_strides,
+ int ndim) {
+ ulong loc_a{0};
+ ulong loc_b{0};
+ ulong loc_c{0};
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ int pos_in_dim = (elem % shape[i]);
+ elem /= shape[i];
+ loc_a += pos_in_dim * a_strides[i];
+ loc_b += pos_in_dim * b_strides[i];
+ loc_c += pos_in_dim * c_strides[i];
+ }
+ return ulong3(loc_a, loc_b, loc_c);
+}
+
+
+// https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/kernels/steel/gemm/kernels/steel_gemm_fused.h#L1
+///////////////////////////////////////////////////////////////////////////////
+// GEMM kernels
+///////////////////////////////////////////////////////////////////////////////
+
+constant bool has_batch [[function_constant(10)]];
+
+constant bool use_out_source [[function_constant(100)]];
+constant bool do_axpby [[function_constant(110)]];
+
+constant bool align_M [[function_constant(200)]];
+constant bool align_N [[function_constant(201)]];
+constant bool align_K [[function_constant(202)]];
+
+constant bool do_gather [[function_constant(300)]];
+
+constant bool gather_bias = do_gather && use_out_source;
+
+// clang-format off
+template <
+ typename T,
+ int BM,
+ int BN,
+ int BK,
+ int WM,
+ int WN,
+ bool transpose_a,
+ bool transpose_b,
+ typename AccumType = float>
+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm(
+ const device T* A [[buffer(0)]],
+ const device T* B [[buffer(1)]],
+ const device T* C [[buffer(2), function_constant(use_out_source)]],
+ device T* D [[buffer(3)]],
+ const constant GEMMParams* params [[buffer(4)]],
+ const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]],
+ const constant int* batch_shape [[buffer(6), function_constant(has_batch)]],
+ const constant size_t* batch_strides [[buffer(7), function_constant(has_batch)]],
+ const constant uint32_t* lhs_indices [[buffer(10), function_constant(do_gather)]],
+ const constant uint32_t* rhs_indices [[buffer(11), function_constant(do_gather)]],
+ const constant uint32_t* C_indices [[buffer(12), function_constant(gather_bias)]],
+ const constant int* operand_shape [[buffer(13), function_constant(do_gather)]],
+ const constant size_t* operand_strides [[buffer(14), function_constant(do_gather)]],
+ const constant packed_int3& operand_batch_ndim [[buffer(15), function_constant(do_gather)]],
+ uint simd_lane_id [[thread_index_in_simdgroup]],
+ uint simd_group_id [[simdgroup_index_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) { // clang-format on
+ // Pacifying compiler
+ (void)lid;
+
+ using gemm_kernel = GEMMKernel<
+ T,
+ T,
+ BM,
+ BN,
+ BK,
+ WM,
+ WN,
+ transpose_a,
+ transpose_b,
+ true,
+ true,
+ AccumType>;
+
+ using loader_a_t = typename gemm_kernel::loader_a_t;
+ using loader_b_t = typename gemm_kernel::loader_b_t;
+ using mma_t = typename gemm_kernel::mma_t;
+
+ // Find block
+ const int tid_y = ((tid.y) << params->swizzle_log) +
+ ((tid.x) & ((1 << params->swizzle_log) - 1));
+ const int tid_x = (tid.x) >> params->swizzle_log;
+
+ // Exit early if out of bounds
+ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {
+ return;
+ }
+
+ // Adjust for batch
+
+ // Handle gather
+ if (do_gather) {
+ // Read indices
+ uint32_t indx_A, indx_B, indx_C;
+
+ if (has_batch) {
+ const constant size_t* indx_A_bstrides = batch_strides;
+ const constant size_t* indx_B_bstrides =
+ batch_strides + params->batch_ndim;
+
+ ulong2 indx_offsets = elem_to_loc_broadcast(
+ tid.z,
+ batch_shape,
+ indx_A_bstrides,
+ indx_B_bstrides,
+ params->batch_ndim);
+ indx_A = lhs_indices[indx_offsets.x];
+ indx_B = rhs_indices[indx_offsets.y];
+
+ if (use_out_source) {
+ const constant size_t* indx_C_bstrides =
+ indx_B_bstrides + params->batch_ndim;
+ auto indx_offset_C = elem_to_loc(
+ tid.z, batch_shape, indx_C_bstrides, params->batch_ndim);
+ indx_C = C_indices[indx_offset_C];
+ }
+ } else {
+ indx_A = lhs_indices[params->batch_stride_a * tid.z];
+ indx_B = rhs_indices[params->batch_stride_b * tid.z];
+
+ if (use_out_source) {
+ indx_C = C_indices[addmm_params->batch_stride_c * tid.z];
+ }
+ }
+
+ // Translate indices to offsets
+ int batch_ndim_A = operand_batch_ndim.x;
+ const constant int* batch_shape_A = operand_shape;
+ const constant size_t* batch_strides_A = operand_strides;
+ A += elem_to_loc(indx_A, batch_shape_A, batch_strides_A, batch_ndim_A);
+
+ int batch_ndim_B = operand_batch_ndim.y;
+ const constant int* batch_shape_B = batch_shape_A + batch_ndim_A;
+ const constant size_t* batch_strides_B = batch_strides_A + batch_ndim_A;
+ B += elem_to_loc(indx_B, batch_shape_B, batch_strides_B, batch_ndim_B);
+
+ if (use_out_source) {
+ int batch_ndim_C = operand_batch_ndim.z;
+ const constant int* batch_shape_C = batch_shape_B + batch_ndim_B;
+ const constant size_t* batch_strides_C = batch_strides_B + batch_ndim_B;
+ C += elem_to_loc(indx_C, batch_shape_C, batch_strides_C, batch_ndim_C);
+ }
+
+ }
+
+ // Handle regular batch
+ else {
+ if (has_batch) {
+ const constant size_t* A_bstrides = batch_strides;
+ const constant size_t* B_bstrides = batch_strides + params->batch_ndim;
+
+ ulong2 batch_offsets = elem_to_loc_broadcast(
+ tid.z, batch_shape, A_bstrides, B_bstrides, params->batch_ndim);
+
+ A += batch_offsets.x;
+ B += batch_offsets.y;
+
+ if (use_out_source) {
+ const constant size_t* C_bstrides = B_bstrides + params->batch_ndim;
+ C += elem_to_loc(tid.z, batch_shape, C_bstrides, params->batch_ndim);
+ }
+ } else {
+ A += params->batch_stride_a * tid.z;
+ B += params->batch_stride_b * tid.z;
+
+ if (use_out_source) {
+ C += addmm_params->batch_stride_c * tid.z;
+ }
+ }
+ }
+
+ D += params->batch_stride_d * tid.z;
+
+ // Prepare threadgroup memory
+ threadgroup T As[gemm_kernel::tgp_mem_size_a];
+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];
+
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Find block in A, B, C
+ const int c_row = tid_y * BM;
+ const int c_col = tid_x * BN;
+ const size_t c_row_long = size_t(c_row);
+ const size_t c_col_long = size_t(c_col);
+
+ A += transpose_a ? c_row_long : c_row_long * params->lda;
+ B += transpose_b ? c_col_long * params->ldb : c_col_long;
+ D += c_row_long * params->ldd + c_col_long;
+
+ if (use_out_source) {
+ C += c_row_long * addmm_params->ldc + c_col_long * addmm_params->fdc;
+ }
+
+ // Prepare threadgroup mma operation
+ thread mma_t mma_op(simd_group_id, simd_lane_id);
+
+ // Prepare threadgroup loading operations
+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);
+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);
+
+ // Prepare threadgroup bounds
+ const short tgp_bm = align_M ? BM : short(min(BM, params->M - c_row));
+ const short tgp_bn = align_N ? BN : short(min(BN, params->N - c_col));
+
+ // Prepare iterations
+ int gemm_k_iterations = params->gemm_k_iterations_aligned;
+
+ // Do unaligned K iterations first
+ if (!align_K) {
+ const int k_last = params->gemm_k_iterations_aligned * BK;
+ const int k_remain = params->K - k_last;
+ const size_t k_jump_a =
+ transpose_a ? params->lda * size_t(k_last) : size_t(k_last);
+ const size_t k_jump_b =
+ transpose_b ? size_t(k_last) : params->ldb * size_t(k_last);
+
+ // Move loader source ahead to end
+ loader_a.src += k_jump_a;
+ loader_b.src += k_jump_b;
+
+ // Load tile
+ const short2 tile_dims_A =
+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);
+ const short2 tile_dims_B =
+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);
+
+ loader_a.load_safe(tile_dims_A);
+ loader_b.load_safe(tile_dims_B);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Do matmul
+ mma_op.mma(As, Bs);
+
+ // Reset source back to start
+ loader_a.src -= k_jump_a;
+ loader_b.src -= k_jump_b;
+ }
+
+ const TransformAdd<AccumType, AccumType> epilogue_op_add(
+ addmm_params->alpha, addmm_params->beta);
+ const TransformAxpby<AccumType, AccumType> epilogue_op_axpby(
+ addmm_params->alpha, addmm_params->beta);
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // MNK aligned loop
+ if (align_M && align_N) {
+ // Do gemm
+ for (int k = 0; k < gemm_k_iterations; k++) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // Load elements into threadgroup
+ loader_a.load_unsafe();
+ loader_b.load_unsafe();
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Multiply and accumulate threadgroup elements
+ mma_op.mma(As, Bs);
+
+ // Prepare for next iteration
+ loader_a.next();
+ loader_b.next();
+ }
+
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Do epilogue
+ if (use_out_source) {
+ if (do_axpby) {
+ mma_op.apply_epilogue(
+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);
+ } else {
+ mma_op.apply_epilogue(
+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);
+ }
+ }
+
+ // Store results to device memory
+ return mma_op.store_result(D, params->ldd);
+
+ }
+ ///////////////////////////////////////////////////////////////////////////////
+ // MN unaligned loop
+ else { // Loop over K - unaligned case
+ const int leftover_bk = 0;
+
+ if ((align_M || tgp_bm == BM) && (align_N || tgp_bn == BN)) {
+ // Do gemm
+ gemm_kernel::gemm_loop(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk,
+ LoopAlignment<true, true, true>{});
+
+ // Do epilogue
+ if (use_out_source) {
+ if (do_axpby) {
+ mma_op.apply_epilogue(
+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);
+ } else {
+ mma_op.apply_epilogue(
+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);
+ }
+ }
+
+ // Store results to device memory
+ return mma_op.store_result(D, params->ldd);
+
+ } else if (align_N || tgp_bn == BN) {
+ gemm_kernel::gemm_loop(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk,
+ LoopAlignment<false, true, true>{});
+
+ // Do epilogue
+ if (use_out_source) {
+ if (do_axpby) {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_axpby);
+ } else {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_add);
+ }
+ }
+
+ // Store results to device memory
+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+
+ } else if (align_M || tgp_bm == BM) {
+ gemm_kernel::gemm_loop(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk,
+ LoopAlignment<true, false, true>{});
+
+ // Do epilogue
+ if (use_out_source) {
+ if (do_axpby) {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_axpby);
+ } else {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_add);
+ }
+ }
+
+ // Store results to device memory
+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+
+ } else {
+ gemm_kernel::gemm_loop(
+ As,
+ Bs,
+ gemm_k_iterations,
+ loader_a,
+ loader_b,
+ mma_op,
+ tgp_bm,
+ tgp_bn,
+ leftover_bk,
+ LoopAlignment<false, false, true>{});
+
+ // Do epilogue
+ if (use_out_source) {
+ if (do_axpby) {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_axpby);
+ } else {
+ mma_op.apply_epilogue_safe(
+ C,
+ addmm_params->ldc,
+ addmm_params->fdc,
+ short2(tgp_bn, tgp_bm),
+ epilogue_op_add);
+ }
+ }
+
+ // Store results to device memory
+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));
+ }
+ }
+}
+
+#define instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \
+ template [[host_name("gemm_" #tname "_" #iname "_" #oname "_" #bm "_" #bn "_" #bk "_" #wm "_" #wn)]] \
+ [[kernel]] void gemm<itype, bm, bn, bk, wm, wn, trans_a, trans_b, float>( \
+ const device itype *A [[buffer(0)]], \
+ const device itype *B [[buffer(1)]], \
+ const device itype *C [[buffer(2), function_constant(use_out_source)]], \
+ device itype *D [[buffer(3)]], \
+ const constant GEMMParams* params [[buffer(4)]], \
+ const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]], \
+ const constant int* batch_shape [[buffer(6)]], \
+ const constant size_t* batch_strides [[buffer(7)]], \
+ const constant uint32_t* lhs_indices [[buffer(10), function_constant(do_gather)]], \
+ const constant uint32_t* rhs_indices [[buffer(11), function_constant(do_gather)]], \
+ const constant uint32_t* C_indices [[buffer(12), function_constant(gather_bias)]], \
+ const constant int* operand_shape [[buffer(13), function_constant(do_gather)]], \
+ const constant size_t* operand_strides [[buffer(14), function_constant(do_gather)]], \
+ const constant packed_int3& operand_batch_ndim [[buffer(15), function_constant(do_gather)]], \
+ uint simd_lane_id [[thread_index_in_simdgroup]], \
+ uint simd_group_id [[simdgroup_index_in_threadgroup]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint3 lid [[thread_position_in_threadgroup]]);
+
+#define instantiate_gemm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \
+ instantiate_gemm(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \
+ instantiate_gemm(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \
+ instantiate_gemm(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \
+ instantiate_gemm(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)
+
+// ============================================================
+// Tile Configuration: (32, 32, 16, 2, 2) - Original/fallback configuration
+// ============================================================
+instantiate_gemm_transpose_helper(f32, float, f32, float, 32, 32, 16, 2, 2)
+instantiate_gemm_transpose_helper(f16, half, f16, half, 32, 32, 16, 2, 2)
+#if defined(__HAVE_BFLOAT__)
+instantiate_gemm_transpose_helper(bf16, bfloat, bf16, bfloat, 32, 32, 16, 2, 2)
+#endif
+
+// ============================================================
+// Tile Configuration: (64, 64, 16, 2, 2) - Default for medium devices
+// Reference: MLX steel_gemm_fused.metal
+// ============================================================
+instantiate_gemm_transpose_helper(f32, float, f32, float, 64, 64, 16, 2, 2)
+instantiate_gemm_transpose_helper(f16, half, f16, half, 64, 64, 16, 2, 2)
+#if defined(__HAVE_BFLOAT__)
+instantiate_gemm_transpose_helper(bf16, bfloat, bf16, bfloat, 64, 64, 16, 2, 2)
+#endif
+
+// ============================================================
+// Tile Configuration: (64, 64, 16, 1, 2) - For half/bfloat with small K
+// Reference: MLX steel_gemm_fused.metal
+// ============================================================
+instantiate_gemm_transpose_helper(f32, float, f32, float, 64, 64, 16, 1, 2)
+instantiate_gemm_transpose_helper(f16, half, f16, half, 64, 64, 16, 1, 2)
+#if defined(__HAVE_BFLOAT__)
+instantiate_gemm_transpose_helper(bf16, bfloat, bf16, bfloat, 64, 64, 16, 1, 2)
+#endif
+
+// ============================================================
+// Tile Configuration: (64, 32, 32, 2, 2) - For nt mode with large K
+// Reference: MLX steel_gemm_fused.metal
+// ============================================================
+instantiate_gemm_transpose_helper(f32, float, f32, float, 64, 32, 32, 2, 2)
+instantiate_gemm_transpose_helper(f16, half, f16, half, 64, 32, 32, 2, 2)
+#if defined(__HAVE_BFLOAT__)
+instantiate_gemm_transpose_helper(bf16, bfloat, bf16, bfloat, 64, 32, 32, 2, 2)
+#endif
+
+// ============================================================
+// Tile Configuration: (32, 64, 16, 1, 2) - For nn mode with large K
+// Reference: MLX steel_gemm_fused.metal
+// ============================================================
+instantiate_gemm_transpose_helper(f32, float, f32, float, 32, 64, 16, 1, 2)
+instantiate_gemm_transpose_helper(f16, half, f16, half, 32, 64, 16, 1, 2)
+#if defined(__HAVE_BFLOAT__)
+instantiate_gemm_transpose_helper(bf16, bfloat, bf16, bfloat, 32, 64, 16, 1, 2)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/mlx_sort.metal b/vendor/candle-metal-kernels/src/metal_src/mlx_sort.metal
new file mode 100644
index 0000000..3194754
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/mlx_sort.metal
@@ -0,0 +1,856 @@
+// The implementation below comes from MLX.
+// https://github.com/ml-explore/mlx/blob/0cea88bcc5e98e81a24d92eed8870a6976999f05/mlx/backend/metal/kernels/sort.h
+// Copyright © 2023-2024 Apple Inc.
+
+#define MLX_MTL_CONST static constant constexpr const
+#define MLX_MTL_LOOP_UNROLL _Pragma("clang loop unroll(full)")
+
+#include <metal_stdlib>
+using namespace metal;
+typedef bfloat bfloat16_t;
+
+// From utils.h
+///////////////////////////////////////////////////////////////////////////////
+// Type limits utils
+///////////////////////////////////////////////////////////////////////////////
+
+template <typename U>
+struct Limits {
+ static const constant U max = metal::numeric_limits<U>::max();
+ static const constant U min = metal::numeric_limits<U>::min();
+ static const constant U finite_max = metal::numeric_limits<U>::max();
+ static const constant U finite_min = metal::numeric_limits<U>::min();
+};
+
+#define instantiate_default_limit(type) \
+ template <> \
+ struct Limits<type> { \
+ static constexpr constant type max = metal::numeric_limits<type>::max(); \
+ static constexpr constant type min = metal::numeric_limits<type>::min(); \
+ static constexpr constant type finite_max = \
+ metal::numeric_limits<type>::max(); \
+ static constexpr constant type finite_min = \
+ metal::numeric_limits<type>::min(); \
+ };
+
+instantiate_default_limit(uint8_t);
+instantiate_default_limit(uint16_t);
+instantiate_default_limit(uint32_t);
+instantiate_default_limit(uint64_t);
+instantiate_default_limit(int8_t);
+instantiate_default_limit(int16_t);
+instantiate_default_limit(int32_t);
+instantiate_default_limit(int64_t);
+
+#define instantiate_float_limit(type) \
+ template <> \
+ struct Limits<type> { \
+ static constexpr constant type max = \
+ metal::numeric_limits<type>::infinity(); \
+ static constexpr constant type min = \
+ -metal::numeric_limits<type>::infinity(); \
+ static constexpr constant type finite_max = \
+ metal::numeric_limits<type>::max(); \
+ static constexpr constant type finite_min = \
+ -metal::numeric_limits<type>::max(); \
+ };
+
+instantiate_float_limit(half);
+instantiate_float_limit(float);
+instantiate_float_limit(bfloat16_t);
+
+template <>
+struct Limits<bool> {
+ static constexpr constant bool max = true;
+ static constexpr constant bool min = false;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Single Array with generic dims
+
+template <typename IdxT = int64_t>
+METAL_FUNC IdxT elem_to_loc(
+ IdxT elem,
+ constant const int* shape,
+ constant const int64_t* strides,
+ int ndim) {
+ IdxT loc = 0;
+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {
+ loc += (elem % shape[i]) * IdxT(strides[i]);
+ elem /= shape[i];
+ }
+ return loc;
+}
+
+// Non templated version to handle arbitrary dims
+template <typename IdxT = int64_t>
+METAL_FUNC IdxT elem_to_loc(
+ uint3 elem,
+ constant const int* shape,
+ constant const int64_t* strides,
+ int ndim) {
+ IdxT loc =
+ elem.x * IdxT(strides[ndim - 1]) + elem.y * IdxT(strides[ndim - 2]);
+ for (int d = ndim - 3; d >= 0; --d) {
+ loc += (elem.z % shape[d]) * IdxT(strides[d]);
+ elem.z /= shape[d];
+ }
+ return loc;
+}
+
+
+// Instantiate a templated kernel.
+// Extra args are used as template parameters:
+// e.g. instantiate_kernel(binary_int, binary, a, b) ->
+// [[host_name(binary_int)]] [kernel] binary<a, b>
+#define instantiate_kernel(name, func, ...) \
+ template [[host_name( \
+ name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+// Based on GPU merge sort algorithm at
+// https://github.com/NVIDIA/cccl/tree/main/cub/cub
+
+///////////////////////////////////////////////////////////////////////////////
+// Thread-level sort
+///////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+METAL_FUNC void thread_swap(thread T& a, thread T& b) {
+ T w = a;
+ a = b;
+ b = w;
+}
+
+template <typename T>
+struct LessThan {
+ static constexpr constant T init = Limits<T>::max;
+
+ METAL_FUNC bool operator()(T a, T b) {
+ return a < b;
+ }
+};
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short N_PER_THREAD,
+ typename CompareOp>
+struct ThreadSort {
+ static METAL_FUNC void sort(
+ thread val_t (&vals)[N_PER_THREAD],
+ thread idx_t (&idxs)[N_PER_THREAD]) {
+ CompareOp op;
+
+ MLX_MTL_LOOP_UNROLL
+ for (short i = 0; i < N_PER_THREAD; ++i) {
+ MLX_MTL_LOOP_UNROLL
+ for (short j = i & 1; j < N_PER_THREAD - 1; j += 2) {
+ if (op(vals[j + 1], vals[j])) {
+ thread_swap(vals[j + 1], vals[j]);
+ thread_swap(idxs[j + 1], idxs[j]);
+ }
+ }
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Threadgroup-level sort
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD,
+ typename CompareOp>
+struct BlockMergeSort {
+ using thread_sort_t =
+ ThreadSort<val_t, idx_t, ARG_SORT, N_PER_THREAD, CompareOp>;
+ static METAL_FUNC int merge_partition(
+ const threadgroup val_t* As,
+ const threadgroup val_t* Bs,
+ short A_sz,
+ short B_sz,
+ short sort_md) {
+ CompareOp op;
+
+ short A_st = max(0, sort_md - B_sz);
+ short A_ed = min(sort_md, A_sz);
+
+ while (A_st < A_ed) {
+ short md = A_st + (A_ed - A_st) / 2;
+ auto a = As[md];
+ auto b = Bs[sort_md - 1 - md];
+
+ if (op(b, a)) {
+ A_ed = md;
+ } else {
+ A_st = md + 1;
+ }
+ }
+
+ return A_ed;
+ }
+
+ static METAL_FUNC void merge_step(
+ const threadgroup val_t* As,
+ const threadgroup val_t* Bs,
+ const threadgroup idx_t* As_idx,
+ const threadgroup idx_t* Bs_idx,
+ short A_sz,
+ short B_sz,
+ thread val_t (&vals)[N_PER_THREAD],
+ thread idx_t (&idxs)[N_PER_THREAD]) {
+ CompareOp op;
+ short a_idx = 0;
+ short b_idx = 0;
+
+ for (int i = 0; i < N_PER_THREAD; ++i) {
+ auto a = As[a_idx];
+ auto b = Bs[b_idx];
+ bool pred = (b_idx < B_sz) && (a_idx >= A_sz || op(b, a));
+
+ vals[i] = pred ? b : a;
+ idxs[i] = pred ? Bs_idx[b_idx] : As_idx[a_idx];
+
+ b_idx += short(pred);
+ a_idx += short(!pred);
+ }
+ }
+
+ static METAL_FUNC void sort(
+ threadgroup val_t* tgp_vals [[threadgroup(0)]],
+ threadgroup idx_t* tgp_idxs [[threadgroup(1)]],
+ int size_sorted_axis,
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ // Get thread location
+ int idx = lid.x * N_PER_THREAD;
+
+ // Load from shared memory
+ thread val_t thread_vals[N_PER_THREAD];
+ thread idx_t thread_idxs[N_PER_THREAD];
+ for (int i = 0; i < N_PER_THREAD; ++i) {
+ thread_vals[i] = tgp_vals[idx + i];
+ if (ARG_SORT) {
+ thread_idxs[i] = tgp_idxs[idx + i];
+ }
+ }
+
+ // Per thread sort
+ if (idx < size_sorted_axis) {
+ thread_sort_t::sort(thread_vals, thread_idxs);
+ }
+
+ // Do merges using threadgroup memory
+ for (int merge_threads = 2; merge_threads <= BLOCK_THREADS;
+ merge_threads *= 2) {
+ // Update threadgroup memory
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int i = 0; i < N_PER_THREAD; ++i) {
+ tgp_vals[idx + i] = thread_vals[i];
+ if (ARG_SORT) {
+ tgp_idxs[idx + i] = thread_idxs[i];
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Find location in merge step
+ int merge_group = lid.x / merge_threads;
+ int merge_lane = lid.x % merge_threads;
+
+ int sort_sz = N_PER_THREAD * merge_threads;
+ int sort_st = N_PER_THREAD * merge_threads * merge_group;
+
+ // As = tgp_vals[A_st:A_ed] is sorted
+ // Bs = tgp_vals[B_st:B_ed] is sorted
+ int A_st = sort_st;
+ int A_ed = sort_st + sort_sz / 2;
+ int B_st = sort_st + sort_sz / 2;
+ int B_ed = sort_st + sort_sz;
+
+ const threadgroup val_t* As = tgp_vals + A_st;
+ const threadgroup val_t* Bs = tgp_vals + B_st;
+ int A_sz = A_ed - A_st;
+ int B_sz = B_ed - B_st;
+
+ // Find a partition of merge elements
+ // Ci = merge(As[partition:], Bs[sort_md - partition:])
+ // of size N_PER_THREAD for each merge lane i
+ // C = [Ci] is sorted
+ int sort_md = N_PER_THREAD * merge_lane;
+ int partition = merge_partition(As, Bs, A_sz, B_sz, sort_md);
+
+ As += partition;
+ Bs += sort_md - partition;
+
+ A_sz -= partition;
+ B_sz -= sort_md - partition;
+
+ const threadgroup idx_t* As_idx =
+ ARG_SORT ? tgp_idxs + A_st + partition : nullptr;
+ const threadgroup idx_t* Bs_idx =
+ ARG_SORT ? tgp_idxs + B_st + sort_md - partition : nullptr;
+
+ // Merge starting at the partition and store results in thread registers
+ merge_step(As, Bs, As_idx, Bs_idx, A_sz, B_sz, thread_vals, thread_idxs);
+ }
+
+ // Write out to shared memory
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int i = 0; i < N_PER_THREAD; ++i) {
+ tgp_vals[idx + i] = thread_vals[i];
+ if (ARG_SORT) {
+ tgp_idxs[idx + i] = thread_idxs[i];
+ }
+ }
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Kernel sort
+///////////////////////////////////////////////////////////////////////////////
+
+template <
+ typename T,
+ typename U,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD,
+ typename CompareOp = LessThan<T>>
+struct KernelMergeSort {
+ using val_t = T;
+ using idx_t = uint;
+ using block_merge_sort_t = BlockMergeSort<
+ val_t,
+ idx_t,
+ ARG_SORT,
+ BLOCK_THREADS,
+ N_PER_THREAD,
+ CompareOp>;
+
+ MLX_MTL_CONST short N_PER_BLOCK = BLOCK_THREADS * N_PER_THREAD;
+
+ static METAL_FUNC void block_sort(
+ const device T* inp,
+ device U* out,
+ const constant int& size_sorted_axis,
+ const constant int& in_stride_sorted_axis,
+ const constant int& out_stride_sorted_axis,
+ const constant int& in_stride_segment_axis,
+ const constant int& out_stride_segment_axis,
+ threadgroup val_t* tgp_vals,
+ threadgroup idx_t* tgp_idxs,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ // tid.y tells us the segment index
+ inp += tid.y * in_stride_segment_axis;
+ out += tid.y * out_stride_segment_axis;
+
+ // Copy into threadgroup memory
+ for (short i = lid.x; i < N_PER_BLOCK; i += BLOCK_THREADS) {
+ tgp_vals[i] = i < size_sorted_axis ? inp[i * in_stride_sorted_axis]
+ : val_t(CompareOp::init);
+ if (ARG_SORT) {
+ tgp_idxs[i] = i;
+ }
+ }
+
+ // Sort elements within the block
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ block_merge_sort_t::sort(tgp_vals, tgp_idxs, size_sorted_axis, lid);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Write output
+ for (int i = lid.x; i < size_sorted_axis; i += BLOCK_THREADS) {
+ if (ARG_SORT) {
+ out[i * out_stride_sorted_axis] = tgp_idxs[i];
+ } else {
+ out[i * out_stride_sorted_axis] = tgp_vals[i];
+ }
+ }
+ }
+};
+
+template <
+ typename T,
+ typename U,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD>
+[[kernel, max_total_threads_per_threadgroup(BLOCK_THREADS)]] void block_sort(
+ const device T* inp [[buffer(0)]],
+ device U* out [[buffer(1)]],
+ const constant int& size_sorted_axis [[buffer(2)]],
+ const constant int& in_stride_sorted_axis [[buffer(3)]],
+ const constant int& out_stride_sorted_axis [[buffer(4)]],
+ const constant int& in_stride_segment_axis [[buffer(5)]],
+ const constant int& out_stride_segment_axis [[buffer(6)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ using sort_kernel =
+ KernelMergeSort<T, U, ARG_SORT, BLOCK_THREADS, N_PER_THREAD>;
+ using val_t = typename sort_kernel::val_t;
+ using idx_t = typename sort_kernel::idx_t;
+
+ if (ARG_SORT) {
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ threadgroup idx_t tgp_idxs[sort_kernel::N_PER_BLOCK];
+ sort_kernel::block_sort(
+ inp,
+ out,
+ size_sorted_axis,
+ in_stride_sorted_axis,
+ out_stride_sorted_axis,
+ in_stride_segment_axis,
+ out_stride_segment_axis,
+ tgp_vals,
+ tgp_idxs,
+ tid,
+ lid);
+ } else {
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ sort_kernel::block_sort(
+ inp,
+ out,
+ size_sorted_axis,
+ in_stride_sorted_axis,
+ out_stride_sorted_axis,
+ in_stride_segment_axis,
+ out_stride_segment_axis,
+ tgp_vals,
+ nullptr,
+ tid,
+ lid);
+ }
+}
+
+constant constexpr const int zero_helper = 0;
+
+template <
+ typename T,
+ typename U,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD>
+[[kernel, max_total_threads_per_threadgroup(BLOCK_THREADS)]] void block_sort_nc(
+ const device T* inp [[buffer(0)]],
+ device U* out [[buffer(1)]],
+ const constant int& size_sorted_axis [[buffer(2)]],
+ const constant int& in_stride_sorted_axis [[buffer(3)]],
+ const constant int& out_stride_sorted_axis [[buffer(4)]],
+ const constant int& nc_dim [[buffer(5)]],
+ const constant int* nc_shape [[buffer(6)]],
+ const constant int64_t* in_nc_strides [[buffer(7)]],
+ const constant int64_t* out_nc_strides [[buffer(8)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ using sort_kernel =
+ KernelMergeSort<T, U, ARG_SORT, BLOCK_THREADS, N_PER_THREAD>;
+ using val_t = typename sort_kernel::val_t;
+ using idx_t = typename sort_kernel::idx_t;
+
+ auto in_block_idx = elem_to_loc(tid.y, nc_shape, in_nc_strides, nc_dim);
+ auto out_block_idx = elem_to_loc(tid.y, nc_shape, out_nc_strides, nc_dim);
+ inp += in_block_idx;
+ out += out_block_idx;
+
+ if (ARG_SORT) {
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ threadgroup idx_t tgp_idxs[sort_kernel::N_PER_BLOCK];
+ sort_kernel::block_sort(
+ inp,
+ out,
+ size_sorted_axis,
+ in_stride_sorted_axis,
+ out_stride_sorted_axis,
+ zero_helper,
+ zero_helper,
+ tgp_vals,
+ tgp_idxs,
+ tid,
+ lid);
+ } else {
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ sort_kernel::block_sort(
+ inp,
+ out,
+ size_sorted_axis,
+ in_stride_sorted_axis,
+ out_stride_sorted_axis,
+ zero_helper,
+ zero_helper,
+ tgp_vals,
+ nullptr,
+ tid,
+ lid);
+ }
+}
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD,
+ typename CompareOp = LessThan<val_t>>
+struct KernelMultiBlockMergeSort {
+ using block_merge_sort_t = BlockMergeSort<
+ val_t,
+ idx_t,
+ ARG_SORT,
+ BLOCK_THREADS,
+ N_PER_THREAD,
+ CompareOp>;
+
+ MLX_MTL_CONST short N_PER_BLOCK = BLOCK_THREADS * N_PER_THREAD;
+
+ static METAL_FUNC void block_sort(
+ const device val_t* inp,
+ device val_t* out_vals,
+ device idx_t* out_idxs,
+ const constant int& size_sorted_axis,
+ const constant int& stride_sorted_axis,
+ threadgroup val_t* tgp_vals,
+ threadgroup idx_t* tgp_idxs,
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ // tid.y tells us the segment index
+ int base_idx = tid.x * N_PER_BLOCK;
+
+ // Copy into threadgroup memory
+ for (short i = lid.x; i < N_PER_BLOCK; i += BLOCK_THREADS) {
+ int idx = base_idx + i;
+ tgp_vals[i] = idx < size_sorted_axis ? inp[idx * stride_sorted_axis]
+ : val_t(CompareOp::init);
+ tgp_idxs[i] = idx;
+ }
+
+ // Sort elements within the block
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ block_merge_sort_t::sort(tgp_vals, tgp_idxs, size_sorted_axis, lid);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Write output
+ for (int i = lid.x; i < N_PER_BLOCK; i += BLOCK_THREADS) {
+ int idx = base_idx + i;
+ if (idx < size_sorted_axis) {
+ out_vals[idx] = tgp_vals[i];
+ out_idxs[idx] = tgp_idxs[i];
+ }
+ }
+ }
+
+ static METAL_FUNC int merge_partition(
+ const device val_t* As,
+ const device val_t* Bs,
+ int A_sz,
+ int B_sz,
+ int sort_md) {
+ CompareOp op;
+
+ int A_st = max(0, sort_md - B_sz);
+ int A_ed = min(sort_md, A_sz);
+
+ while (A_st < A_ed) {
+ int md = A_st + (A_ed - A_st) / 2;
+ auto a = As[md];
+ auto b = Bs[sort_md - 1 - md];
+
+ if (op(b, a)) {
+ A_ed = md;
+ } else {
+ A_st = md + 1;
+ }
+ }
+
+ return A_ed;
+ }
+};
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD>
+[[kernel, max_total_threads_per_threadgroup(BLOCK_THREADS)]] void mb_block_sort(
+ const device val_t* inp [[buffer(0)]],
+ device val_t* out_vals [[buffer(1)]],
+ device idx_t* out_idxs [[buffer(2)]],
+ const constant int& size_sorted_axis [[buffer(3)]],
+ const constant int& stride_sorted_axis [[buffer(4)]],
+ const constant int& nc_dim [[buffer(5)]],
+ const constant int* nc_shape [[buffer(6)]],
+ const constant int64_t* nc_strides [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ using sort_kernel = KernelMultiBlockMergeSort<
+ val_t,
+ idx_t,
+ ARG_SORT,
+ BLOCK_THREADS,
+ N_PER_THREAD>;
+
+ auto block_idx = elem_to_loc(tid.y, nc_shape, nc_strides, nc_dim);
+ inp += block_idx;
+ out_vals += tid.y * size_sorted_axis;
+ out_idxs += tid.y * size_sorted_axis;
+
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ threadgroup idx_t tgp_idxs[sort_kernel::N_PER_BLOCK];
+
+ sort_kernel::block_sort(
+ inp,
+ out_vals,
+ out_idxs,
+ size_sorted_axis,
+ stride_sorted_axis,
+ tgp_vals,
+ tgp_idxs,
+ tid,
+ lid);
+}
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD>
+[[kernel]] void mb_block_partition(
+ device idx_t* block_partitions [[buffer(0)]],
+ const device val_t* dev_vals [[buffer(1)]],
+ const device idx_t* dev_idxs [[buffer(2)]],
+ const constant int& size_sorted_axis [[buffer(3)]],
+ const constant int& merge_tiles [[buffer(4)]],
+ const constant int& n_blocks [[buffer(5)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]],
+ uint3 tgp_dims [[threads_per_threadgroup]]) {
+ using sort_kernel = KernelMultiBlockMergeSort<
+ val_t,
+ idx_t,
+ ARG_SORT,
+ BLOCK_THREADS,
+ N_PER_THREAD>;
+
+ block_partitions += tid.y * tgp_dims.x;
+ dev_vals += tid.y * size_sorted_axis;
+ dev_idxs += tid.y * size_sorted_axis;
+
+ for (int i = lid.x; i <= n_blocks; i += tgp_dims.x) {
+ // Find location in merge step
+ int merge_group = i / merge_tiles;
+ int merge_lane = i % merge_tiles;
+
+ int sort_sz = sort_kernel::N_PER_BLOCK * merge_tiles;
+ int sort_st = sort_kernel::N_PER_BLOCK * merge_tiles * merge_group;
+
+ int A_st = min(size_sorted_axis, sort_st);
+ int A_ed = min(size_sorted_axis, sort_st + sort_sz / 2);
+ int B_st = A_ed;
+ int B_ed = min(size_sorted_axis, B_st + sort_sz / 2);
+
+ int partition_at = min(B_ed - A_st, sort_kernel::N_PER_BLOCK * merge_lane);
+ int partition = sort_kernel::merge_partition(
+ dev_vals + A_st,
+ dev_vals + B_st,
+ A_ed - A_st,
+ B_ed - B_st,
+ partition_at);
+
+ block_partitions[i] = A_st + partition;
+ }
+}
+
+template <
+ typename val_t,
+ typename idx_t,
+ bool ARG_SORT,
+ short BLOCK_THREADS,
+ short N_PER_THREAD,
+ typename CompareOp = LessThan<val_t>>
+[[kernel, max_total_threads_per_threadgroup(BLOCK_THREADS)]] void
+mb_block_merge(
+ const device idx_t* block_partitions [[buffer(0)]],
+ const device val_t* dev_vals_in [[buffer(1)]],
+ const device idx_t* dev_idxs_in [[buffer(2)]],
+ device val_t* dev_vals_out [[buffer(3)]],
+ device idx_t* dev_idxs_out [[buffer(4)]],
+ const constant int& size_sorted_axis [[buffer(5)]],
+ const constant int& merge_tiles [[buffer(6)]],
+ const constant int& num_tiles [[buffer(7)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ using sort_kernel = KernelMultiBlockMergeSort<
+ val_t,
+ idx_t,
+ ARG_SORT,
+ BLOCK_THREADS,
+ N_PER_THREAD,
+ CompareOp>;
+
+ using block_sort_t = typename sort_kernel::block_merge_sort_t;
+
+ block_partitions += tid.y * (num_tiles + 1);
+ dev_vals_in += tid.y * size_sorted_axis;
+ dev_idxs_in += tid.y * size_sorted_axis;
+ dev_vals_out += tid.y * size_sorted_axis;
+ dev_idxs_out += tid.y * size_sorted_axis;
+
+ int block_idx = tid.x;
+ int merge_group = block_idx / merge_tiles;
+ int sort_st = sort_kernel::N_PER_BLOCK * merge_tiles * merge_group;
+ int sort_sz = sort_kernel::N_PER_BLOCK * merge_tiles;
+ int sort_md = sort_kernel::N_PER_BLOCK * block_idx - sort_st;
+
+ int A_st = block_partitions[block_idx + 0];
+ int A_ed = block_partitions[block_idx + 1];
+ int B_st = min(size_sorted_axis, 2 * sort_st + sort_sz / 2 + sort_md - A_st);
+ int B_ed = min(
+ size_sorted_axis,
+ 2 * sort_st + sort_sz / 2 + sort_md + sort_kernel::N_PER_BLOCK - A_ed);
+
+ if ((block_idx % merge_tiles) == merge_tiles - 1) {
+ A_ed = min(size_sorted_axis, sort_st + sort_sz / 2);
+ B_ed = min(size_sorted_axis, sort_st + sort_sz);
+ }
+
+ int A_sz = A_ed - A_st;
+ int B_sz = B_ed - B_st;
+
+ // Load from global memory
+ thread val_t thread_vals[N_PER_THREAD];
+ thread idx_t thread_idxs[N_PER_THREAD];
+ for (int i = 0; i < N_PER_THREAD; i++) {
+ int idx = BLOCK_THREADS * i + lid.x;
+ if (idx < (A_sz + B_sz)) {
+ thread_vals[i] = (idx < A_sz) ? dev_vals_in[A_st + idx]
+ : dev_vals_in[B_st + idx - A_sz];
+ thread_idxs[i] = (idx < A_sz) ? dev_idxs_in[A_st + idx]
+ : dev_idxs_in[B_st + idx - A_sz];
+ } else {
+ thread_vals[i] = CompareOp::init;
+ thread_idxs[i] = 0;
+ }
+ }
+
+ // Write to shared memory
+ threadgroup val_t tgp_vals[sort_kernel::N_PER_BLOCK];
+ threadgroup idx_t tgp_idxs[sort_kernel::N_PER_BLOCK];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int i = 0; i < N_PER_THREAD; i++) {
+ int idx = BLOCK_THREADS * i + lid.x;
+ tgp_vals[idx] = thread_vals[i];
+ tgp_idxs[idx] = thread_idxs[i];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Merge
+ int sort_md_local = min(A_sz + B_sz, N_PER_THREAD * int(lid.x));
+
+ int A_st_local = block_sort_t::merge_partition(
+ tgp_vals, tgp_vals + A_sz, A_sz, B_sz, sort_md_local);
+ int A_ed_local = A_sz;
+
+ int B_st_local = sort_md_local - A_st_local;
+ int B_ed_local = B_sz;
+
+ int A_sz_local = A_ed_local - A_st_local;
+ int B_sz_local = B_ed_local - B_st_local;
+
+ // Do merge
+ block_sort_t::merge_step(
+ tgp_vals + A_st_local,
+ tgp_vals + A_ed_local + B_st_local,
+ tgp_idxs + A_st_local,
+ tgp_idxs + A_ed_local + B_st_local,
+ A_sz_local,
+ B_sz_local,
+ thread_vals,
+ thread_idxs);
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int i = 0; i < N_PER_THREAD; ++i) {
+ int idx = lid.x * N_PER_THREAD;
+ tgp_vals[idx + i] = thread_vals[i];
+ tgp_idxs[idx + i] = thread_idxs[i];
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // Write output
+ int base_idx = tid.x * sort_kernel::N_PER_BLOCK;
+ for (int i = lid.x; i < sort_kernel::N_PER_BLOCK; i += BLOCK_THREADS) {
+ int idx = base_idx + i;
+ if (idx < size_sorted_axis) {
+ dev_vals_out[idx] = tgp_vals[i];
+ dev_idxs_out[idx] = tgp_idxs[i];
+ }
+ }
+}
+
+#define instantiate_block_sort( \
+ name, itname, itype, otname, otype, arg_sort, bn, tn) \
+ instantiate_kernel("c" #name "_" #itname "_" #otname "_bn" #bn "_tn" #tn, \
+ block_sort, itype, otype, arg_sort, bn, tn) \
+ instantiate_kernel("nc" #name "_" #itname "_" #otname "_bn" #bn "_tn" #tn, \
+ block_sort_nc, itype, otype, arg_sort, bn, tn)
+
+#define instantiate_arg_block_sort_base(itname, itype, bn, tn) \
+ instantiate_block_sort( \
+ arg_block_sort, itname, itype, uint32, uint32_t, true, bn, tn)
+
+#define instantiate_block_sort_base(itname, itype, bn, tn) \
+ instantiate_block_sort( \
+ _block_sort, itname, itype, itname, itype, false, bn, tn)
+
+#define instantiate_block_sort_tn(itname, itype, bn) \
+ instantiate_block_sort_base(itname, itype, bn, 8) \
+ instantiate_arg_block_sort_base(itname, itype, bn, 8)
+
+#define instantiate_block_sort_bn(itname, itype) \
+ instantiate_block_sort_tn(itname, itype, 128) \
+ instantiate_block_sort_tn(itname, itype, 256) \
+ instantiate_block_sort_tn(itname, itype, 512)
+
+instantiate_block_sort_bn(uint8, uint8_t)
+instantiate_block_sort_bn(uint32, uint32_t)
+instantiate_block_sort_bn(float16, half)
+instantiate_block_sort_bn(float32, float)
+instantiate_block_sort_bn(bfloat16, bfloat16_t)
+
+#define instantiate_block_sort_long(itname, itype) \
+ instantiate_block_sort_tn(itname, itype, 128) \
+ instantiate_block_sort_tn(itname, itype, 256)
+
+instantiate_block_sort_long(int64, int64_t)
+
+#define instantiate_multi_block_sort( \
+ vtname, vtype, itname, itype, arg_sort, bn, tn) \
+ instantiate_kernel("sort_mbsort_" #vtname "_" #itname "_bn" #bn "_tn" #tn, \
+ mb_block_sort, vtype, itype, arg_sort, bn, tn) \
+ instantiate_kernel("partition_mbsort_" #vtname "_" #itname "_bn" #bn "_tn" #tn, \
+ mb_block_partition, vtype, itype, arg_sort, bn, tn) \
+ instantiate_kernel("merge_mbsort_" #vtname "_" #itname "_bn" #bn "_tn" #tn, \
+ mb_block_merge, vtype, itype, arg_sort, bn, tn)
+
+#define instantiate_multi_block_sort_base(vtname, vtype) \
+ instantiate_multi_block_sort(vtname, vtype, uint32, uint32_t, true, 512, 8)
+
+instantiate_multi_block_sort_base(uint8, uint8_t)
+instantiate_multi_block_sort_base(uint32, uint32_t)
+instantiate_multi_block_sort_base(float16, half)
+instantiate_multi_block_sort_base(float32, float)
+instantiate_multi_block_sort_base(bfloat16, bfloat16_t)
+
+#define instantiate_multi_block_sort_long(vtname, vtype) \
+ instantiate_multi_block_sort(vtname, vtype, uint32, uint32_t, true, 256, 8)
+
+instantiate_multi_block_sort_long(int64, int64_t) // clang-format on
diff --git a/vendor/candle-metal-kernels/src/metal_src/quantized.metal b/vendor/candle-metal-kernels/src/metal_src/quantized.metal
new file mode 100644
index 0000000..fcf1037
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/quantized.metal
@@ -0,0 +1,7741 @@
+#include <metal_stdlib>
+
+using namespace metal;
+
+#define MAX(x, y) ((x) > (y) ? (x) : (y))
+#define MIN(x, y) ((x) < (y) ? (x) : (y))
+#define SWAP(x, y) { auto tmp = (x); (x) = (y); (y) = tmp; }
+
+#define N_SIMDWIDTH 32 // assuming SIMD group size is 32
+
+#if defined(__HAVE_BFLOAT__)
+typedef matrix<bfloat, 4, 4> bfloat4x4;
+#endif
+
+// QK = number of values after dequantization
+// QK_K = super-block size
+
+#define QK_K 256
+#define K_SCALE_SIZE 12
+
+#define QK4_0 32
+typedef struct {
+ half d; // delta
+ uint8_t qs[QK4_0 / 2]; // nibbles / quants
+} block_q4_0;
+static_assert(sizeof(block_q4_0) == sizeof(half) + QK4_0 / 2, "wrong q4_0 block size/padding");
+
+#define QK4_1 32
+typedef struct {
+ union {
+ struct {
+ half d; // delta
+ half m; // min
+ };
+ half2 dm;
+ };
+ uint8_t qs[QK4_1 / 2]; // nibbles / quants
+} block_q4_1;
+static_assert(sizeof(block_q4_1) == 2 * sizeof(half) + QK4_1 / 2, "wrong q4_1 block size/padding");
+
+#define QK5_0 32
+typedef struct {
+ half d; // delta
+ uint8_t qh[4]; // 5-th bit of quants
+ uint8_t qs[QK5_0 / 2]; // nibbles / quants
+} block_q5_0;
+static_assert(sizeof(block_q5_0) == sizeof(half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding");
+
+#define QK5_1 32
+typedef struct {
+ union {
+ struct {
+ half d; // delta
+ half m; // min
+ };
+ half2 dm;
+ };
+ uint8_t qh[4]; // 5-th bit of quants
+ uint8_t qs[QK5_1 / 2]; // nibbles / quants
+} block_q5_1;
+static_assert(sizeof(block_q5_1) == 2 * sizeof(half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding");
+
+#define QK8_0 32
+typedef struct {
+ half d; // delta
+ int8_t qs[QK8_0]; // quants
+} block_q8_0;
+static_assert(sizeof(block_q8_0) == sizeof(half) + QK8_0, "wrong q8_0 block size/padding");
+
+#define QK8_1 32
+typedef struct {
+ union {
+ struct {
+ half d; // delta
+ half s; // d * sum(qs[i])
+ };
+ half2 ds;
+ };
+ int8_t qs[QK8_1]; // quants
+} block_q8_1;
+static_assert(sizeof(block_q8_1) == 2*sizeof(half) + QK8_1, "wrong q8_1 block size/padding");
+
+typedef struct {
+ half d[4]; // deltas for 4 q4_0 blocks
+ uint8_t qs[QK4_0 * 2]; // nibbles / quants for 4 q4_0 blocks
+} block_q4_0x4;
+static_assert(sizeof(block_q4_0x4) == 4 * sizeof(half) + QK4_0 * 2, "wrong q4_0x4 block size/padding");
+
+typedef struct {
+ half d[8]; // deltas for 8 q4_0 blocks
+ uint8_t qs[QK4_0 * 4]; // nibbles / quants for 8 q4_0 blocks
+} block_q4_0x8;
+static_assert(sizeof(block_q4_0x8) == 8 * sizeof(half) + QK4_0 * 4, "wrong q4_0x8 block size/padding");
+
+typedef struct {
+ half d[4]; // deltas for 4 q8_0 blocks
+ int8_t qs[QK8_0 * 4]; // quants for 4 q8_0 blocks
+} block_q8_0x4;
+static_assert(sizeof(block_q8_0x4) == 4 * sizeof(half) + QK8_0 * 4, "wrong q8_0x4 block size/padding");
+
+typedef struct {
+ half d[8]; // deltas for 8 q8_0 blocks
+ int8_t qs[QK8_0 * 8]; // quants for 8 q8_0 blocks
+} block_q8_0x8;
+static_assert(sizeof(block_q8_0x8) == 8 * sizeof(half) + QK8_0 * 8, "wrong q8_0x8 block size/padding");
+
+//
+// Ternary quantization
+//
+
+// 1.6875 bpw
+typedef struct {
+ uint8_t qs[(QK_K - 4 * QK_K / 64) / 5]; // 5 elements per byte (3^5 = 243 < 256)
+ uint8_t qh[QK_K/64]; // 4 elements per byte
+ half d;
+} block_tq1_0;
+static_assert(sizeof(block_tq1_0) == sizeof(half) + QK_K / 64 + (QK_K - 4 * QK_K / 64) / 5, "wrong tq1_0 block size/padding");
+
+// 2.0625 bpw
+typedef struct {
+ uint8_t qs[QK_K/4]; // 2 bits per element
+ half d;
+} block_tq2_0;
+static_assert(sizeof(block_tq2_0) == sizeof(half) + QK_K / 4, "wrong tq2_0 block size/padding");
+
+//
+// Super-block quantization structures
+//
+
+// 2-bit quantization
+// weight is represented as x = a * q + b
+// 16 blocks of 16 elements each
+// Effectively 2.625 bits per weight
+typedef struct {
+ uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits
+ uint8_t qs[QK_K/4]; // quants
+ union {
+ struct {
+ half d; // super-block scale for quantized scales
+ half dmin; // super-block scale for quantized mins
+ };
+ half2 dm;
+ };
+} block_q2_K;
+static_assert(sizeof(block_q2_K) == 2*sizeof(half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding");
+
+// 3-bit quantization
+// weight is represented as x = a * q
+// 16 blocks of 16 elements each
+// Effectively 3.4375 bits per weight
+typedef struct {
+ uint8_t hmask[QK_K/8]; // quants - high bit
+ uint8_t qs[QK_K/4]; // quants - low 2 bits
+ uint8_t scales[12]; // scales, quantized with 6 bits
+ half d; // super-block scale
+} block_q3_K;
+static_assert(sizeof(block_q3_K) == sizeof(half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding");
+
+// 4-bit quantization
+// 8 blocks of 32 elements each
+// weight is represented as x = a * q + b
+// Effectively 4.5 bits per weight
+typedef struct {
+ union {
+ struct {
+ half d; // super-block scale for quantized scales
+ half dmin; // super-block scale for quantized mins
+ };
+ half2 dm;
+ };
+ uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits
+ uint8_t qs[QK_K/2]; // 4--bit quants
+} block_q4_K;
+static_assert(sizeof(block_q4_K) == 2*sizeof(half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding");
+
+// 5-bit quantization
+// 8 blocks of 32 elements each
+// weight is represented as x = a * q + b
+// Effectively 5.5 bits per weight
+typedef struct {
+ union {
+ struct {
+ half d; // super-block scale for quantized scales
+ half dmin; // super-block scale for quantized mins
+ };
+ half2 dm;
+ };
+ uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits
+ uint8_t qh[QK_K/8]; // quants, high bit
+ uint8_t qs[QK_K/2]; // quants, low 4 bits
+} block_q5_K;
+static_assert(sizeof(block_q5_K) == 2*sizeof(half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding");
+
+// 6-bit quantization
+// weight is represented as x = a * q
+// 16 blocks of 16 elements each
+// Effectively 6.5625 bits per weight
+typedef struct {
+ uint8_t ql[QK_K/2]; // quants, lower 4 bits
+ uint8_t qh[QK_K/4]; // quants, upper 2 bits
+ int8_t scales[QK_K/16]; // scales, quantized with 8 bits
+ half d; // super-block scale
+} block_q6_K;
+static_assert(sizeof(block_q6_K) == sizeof(half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding");
+
+// This is only used for intermediate quantization and dot products
+typedef struct {
+ float d; // delta
+ int8_t qs[QK_K]; // quants
+ int16_t bsums[QK_K/16]; // sum of quants in groups of 16
+} block_q8_K;
+static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding");
+
+// (Almost) "true" 2-bit quantization.
+// Due to the need to use blocks as per ggml design, it ends up using
+// 2.0625 bpw because of the 16-bit scale for each block of 256.
+typedef struct {
+ half d;
+ uint16_t qs[QK_K/8];
+} block_iq2_xxs;
+static_assert(sizeof(block_iq2_xxs) == sizeof(half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding");
+
+// 2.3125 bpw quants
+typedef struct {
+ half d;
+ uint16_t qs[QK_K/8];
+ uint8_t scales[QK_K/32];
+} block_iq2_xs;
+static_assert(sizeof(block_iq2_xs) == sizeof(half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding");
+
+// 2.5625 bpw quants
+typedef struct {
+ half d;
+ uint8_t qs[QK_K/4];
+ uint8_t qh[QK_K/32];
+ uint8_t scales[QK_K/32];
+} block_iq2_s;
+static_assert(sizeof(block_iq2_s) == sizeof(half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding");
+
+// (Almost) "true" 3-bit quantization.
+// Due to the need to use blocks as per ggml design, it ends up using
+// 3.0625 bpw because of the 16-bit scale for each block of 256.
+typedef struct {
+ half d;
+ uint8_t qs[3*QK_K/8];
+} block_iq3_xxs;
+static_assert(sizeof(block_iq3_xxs) == sizeof(half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding");
+
+// 3.4375 bpw
+#define IQ3S_N_SCALE QK_K/64
+typedef struct {
+ half d;
+ uint8_t qs[QK_K/4];
+ uint8_t qh[QK_K/32];
+ uint8_t signs[QK_K/8];
+ uint8_t scales[IQ3S_N_SCALE];
+} block_iq3_s;
+static_assert(sizeof(block_iq3_s) == sizeof(half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding");
+
+// 1.5625 bpw
+typedef struct {
+ half d;
+ uint8_t qs[QK_K/8];
+ uint16_t qh[QK_K/32];
+} block_iq1_s;
+static_assert(sizeof(block_iq1_s) == sizeof(half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding");
+
+// 1.75 bpw
+typedef struct {
+ uint8_t qs[QK_K/8]; // grid index, low 8 bits
+ uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8)
+ uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64)
+} block_iq1_m;
+static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding");
+
+// Used by IQ1_M quants
+typedef union {
+ half f16;
+ uint16_t u16;
+} iq1m_scale_t;
+
+// Non-linear quants
+#define QK4_NL 32
+typedef struct {
+ half d;
+ uint8_t qs[QK4_NL/2];
+} block_iq4_nl;
+static_assert(sizeof(block_iq4_nl) == sizeof(half) + QK4_NL/2, "wrong iq4_nl block size/padding");
+
+typedef struct {
+ half d;
+ uint16_t scales_h;
+ uint8_t scales_l[QK_K/64];
+ uint8_t qs[QK_K/2];
+} block_iq4_xs;
+static_assert(sizeof(block_iq4_xs) == sizeof(half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding");
+
+#define GGML_TABLE_BEGIN(type, name, size) static const constant type name[size] = {
+#define GGML_TABLE_END() };
+
+GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8)
+ 1, 2, 4, 8, 16, 32, 64, 128
+GGML_TABLE_END()
+
+GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128)
+ 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15,
+ 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159,
+ 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175,
+ 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63,
+ 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207,
+ 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95,
+ 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111,
+ 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255,
+GGML_TABLE_END()
+
+//#if __CUDA_ARCH__ >= MIN_CC_DP4A // lowest compute capability for integer intrinsics
+GGML_TABLE_BEGIN(uint64_t, ksigns64, 128)
+ 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff,
+ 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff,
+ 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff,
+ 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff,
+ 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff,
+ 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff,
+ 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff,
+ 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff,
+ 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff,
+ 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff,
+ 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff,
+ 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff,
+ 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff,
+ 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff,
+ 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff,
+ 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff,
+ 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff,
+ 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff,
+ 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff,
+ 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff,
+ 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff,
+ 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff,
+ 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff,
+ 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff,
+ 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff,
+ 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff,
+ 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff,
+ 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff,
+ 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff,
+ 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff,
+ 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff,
+ 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff,
+GGML_TABLE_END()
+//#endif
+
+
+GGML_TABLE_BEGIN(uint64_t, iq2xxs_grid, 256)
+ 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
+ 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808,
+ 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819,
+ 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819,
+ 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b,
+ 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808,
+ 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08,
+ 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b,
+ 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819,
+ 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08,
+ 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808,
+ 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08,
+ 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808,
+ 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808,
+ 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919,
+ 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819,
+ 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08,
+ 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908,
+ 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819,
+ 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808,
+ 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808,
+ 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908,
+ 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808,
+ 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08,
+ 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819,
+ 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819,
+ 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819,
+ 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908,
+ 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19,
+ 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819,
+ 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b,
+ 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808,
+ 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908,
+ 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08,
+ 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08,
+ 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908,
+ 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819,
+ 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808,
+ 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808,
+ 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19,
+ 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819,
+ 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919,
+ 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b,
+ 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08,
+ 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808,
+ 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908,
+ 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b,
+ 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819,
+ 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08,
+ 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08,
+ 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808,
+ 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b,
+ 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b,
+ 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908,
+ 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819,
+ 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808,
+ 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908,
+ 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b,
+ 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808,
+ 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b,
+ 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b,
+ 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808,
+ 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19,
+ 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908,
+GGML_TABLE_END()
+
+GGML_TABLE_BEGIN(uint64_t, iq2xs_grid, 512)
+ 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
+ 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b,
+ 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919,
+ 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b,
+ 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919,
+ 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808,
+ 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819,
+ 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819,
+ 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808,
+ 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b,
+ 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b,
+ 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908,
+ 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908,
+ 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919,
+ 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808,
+ 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919,
+ 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908,
+ 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b,
+ 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908,
+ 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08,
+ 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808,
+ 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808,
+ 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819,
+ 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908,
+ 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819,
+ 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808,
+ 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b,
+ 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819,
+ 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819,
+ 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808,
+ 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908,
+ 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19,
+ 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b,
+ 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b,
+ 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919,
+ 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808,
+ 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819,
+ 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819,
+ 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b,
+ 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908,
+ 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808,
+ 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819,
+ 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808,
+ 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919,
+ 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808,
+ 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808,
+ 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908,
+ 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908,
+ 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808,
+ 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b,
+ 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819,
+ 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919,
+ 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908,
+ 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808,
+ 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908,
+ 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919,
+ 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08,
+ 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19,
+ 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b,
+ 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b,
+ 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808,
+ 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08,
+ 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b,
+ 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908,
+ 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b,
+ 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908,
+ 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08,
+ 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808,
+ 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808,
+ 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08,
+ 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819,
+ 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919,
+ 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808,
+ 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808,
+ 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819,
+ 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819,
+ 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908,
+ 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908,
+ 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b,
+ 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908,
+ 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908,
+ 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908,
+ 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808,
+ 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819,
+ 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819,
+ 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819,
+ 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808,
+ 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b,
+ 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819,
+ 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819,
+ 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08,
+ 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808,
+ 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19,
+ 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919,
+ 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808,
+ 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19,
+ 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b,
+ 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808,
+ 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b,
+ 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b,
+ 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08,
+ 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b,
+ 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808,
+ 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819,
+ 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808,
+ 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808,
+ 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08,
+ 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b,
+ 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19,
+ 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08,
+ 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919,
+ 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08,
+ 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08,
+ 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908,
+ 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908,
+ 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b,
+ 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908,
+ 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808,
+ 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b,
+ 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808,
+ 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808,
+ 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19,
+ 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08,
+ 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808,
+ 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b,
+ 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808,
+ 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b,
+ 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b,
+GGML_TABLE_END()
+
+GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024)
+ 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
+ 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b,
+ 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919,
+ 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b,
+ 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919,
+ 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b,
+ 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919,
+ 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808,
+ 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908,
+ 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b,
+ 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908,
+ 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08,
+ 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19,
+ 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819,
+ 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919,
+ 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b,
+ 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908,
+ 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908,
+ 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919,
+ 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908,
+ 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b,
+ 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919,
+ 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b,
+ 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919,
+ 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908,
+ 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b,
+ 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b,
+ 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08,
+ 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b,
+ 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819,
+ 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808,
+ 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908,
+ 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b,
+ 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908,
+ 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08,
+ 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819,
+ 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808,
+ 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08,
+ 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819,
+ 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b,
+ 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908,
+ 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919,
+ 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b,
+ 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919,
+ 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808,
+ 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819,
+ 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919,
+ 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919,
+ 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808,
+ 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819,
+ 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b,
+ 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908,
+ 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b,
+ 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908,
+ 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919,
+ 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b,
+ 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919,
+ 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b,
+ 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819,
+ 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919,
+ 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908,
+ 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b,
+ 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908,
+ 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b,
+ 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908,
+ 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08,
+ 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908,
+ 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819,
+ 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819,
+ 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808,
+ 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08,
+ 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19,
+ 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819,
+ 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808,
+ 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819,
+ 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919,
+ 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808,
+ 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19,
+ 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08,
+ 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b,
+ 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908,
+ 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808,
+ 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819,
+ 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908,
+ 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819,
+ 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808,
+ 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808,
+ 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819,
+ 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908,
+ 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08,
+ 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819,
+ 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b,
+ 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b,
+ 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08,
+ 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19,
+ 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819,
+ 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919,
+ 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908,
+ 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808,
+ 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808,
+ 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908,
+ 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808,
+ 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08,
+ 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08,
+ 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908,
+ 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919,
+ 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808,
+ 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819,
+ 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908,
+ 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08,
+ 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819,
+ 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808,
+ 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808,
+ 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819,
+ 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808,
+ 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908,
+ 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b,
+ 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819,
+ 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808,
+ 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b,
+ 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808,
+ 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b,
+ 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19,
+ 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819,
+ 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08,
+ 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b,
+ 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908,
+ 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b,
+ 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b,
+ 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919,
+ 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808,
+ 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819,
+ 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908,
+ 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08,
+ 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08,
+ 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819,
+ 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919,
+ 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908,
+ 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b,
+ 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908,
+ 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b,
+ 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908,
+ 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08,
+ 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819,
+ 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808,
+ 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819,
+ 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919,
+ 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808,
+ 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808,
+ 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08,
+ 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819,
+ 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919,
+ 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808,
+ 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819,
+ 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919,
+ 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808,
+ 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b,
+ 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908,
+ 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808,
+ 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908,
+ 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b,
+ 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908,
+ 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b,
+ 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908,
+ 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b,
+ 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908,
+ 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08,
+ 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908,
+ 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b,
+ 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908,
+ 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08,
+ 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819,
+ 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919,
+ 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808,
+ 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19,
+ 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b,
+ 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919,
+ 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808,
+ 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819,
+ 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908,
+ 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919,
+ 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808,
+ 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808,
+ 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b,
+ 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919,
+ 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808,
+ 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b,
+ 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808,
+ 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919,
+ 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b,
+ 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08,
+ 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919,
+ 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808,
+ 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b,
+ 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908,
+ 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808,
+ 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808,
+ 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808,
+ 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908,
+ 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808,
+ 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808,
+ 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b,
+ 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908,
+ 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808,
+ 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808,
+ 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819,
+ 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919,
+ 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b,
+ 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808,
+ 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819,
+ 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b,
+ 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908,
+ 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08,
+ 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908,
+ 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919,
+ 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819,
+ 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908,
+ 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b,
+ 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808,
+ 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819,
+ 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908,
+ 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919,
+ 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808,
+ 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808,
+ 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808,
+ 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919,
+ 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908,
+ 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908,
+ 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08,
+ 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819,
+ 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b,
+ 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808,
+ 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819,
+ 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908,
+ 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819,
+ 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808,
+ 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808,
+ 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b,
+ 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908,
+ 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808,
+ 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908,
+ 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819,
+ 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819,
+ 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808,
+ 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b,
+ 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b,
+ 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819,
+ 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b,
+ 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b,
+ 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b,
+ 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819,
+ 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19,
+ 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819,
+ 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908,
+ 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808,
+ 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b,
+GGML_TABLE_END()
+
+GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256)
+ 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414,
+ 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14,
+ 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404,
+ 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e,
+ 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c,
+ 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c,
+ 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34,
+ 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c,
+ 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c,
+ 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04,
+ 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c,
+ 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414,
+ 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434,
+ 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c,
+ 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e,
+ 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24,
+ 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24,
+ 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c,
+ 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c,
+ 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14,
+ 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414,
+ 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e,
+ 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404,
+ 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c,
+ 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c,
+ 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14,
+ 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c,
+ 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c,
+ 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14,
+ 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14,
+ 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c,
+ 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04,
+GGML_TABLE_END()
+
+GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512)
+ 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305,
+ 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905,
+ 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09,
+ 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b,
+ 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b,
+ 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d,
+ 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03,
+ 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505,
+ 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03,
+ 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901,
+ 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d,
+ 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303,
+ 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501,
+ 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105,
+ 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505,
+ 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101,
+ 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707,
+ 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b,
+ 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01,
+ 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f,
+ 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305,
+ 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103,
+ 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509,
+ 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503,
+ 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b,
+ 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f,
+ 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f,
+ 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f,
+ 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109,
+ 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f,
+ 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509,
+ 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501,
+ 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303,
+ 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f,
+ 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907,
+ 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703,
+ 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03,
+ 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01,
+ 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01,
+ 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903,
+ 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505,
+ 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b,
+ 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107,
+ 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509,
+ 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303,
+ 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103,
+ 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05,
+ 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b,
+ 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f,
+ 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701,
+ 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909,
+ 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305,
+ 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d,
+ 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b,
+ 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d,
+ 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307,
+ 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09,
+ 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309,
+ 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709,
+ 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f,
+ 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303,
+ 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503,
+ 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b,
+ 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101,
+GGML_TABLE_END()
+
+#define NGRID_IQ1S 2048
+#define IQ1S_DELTA 0.125f
+#define IQ1M_DELTA 0.125f
+GGML_TABLE_BEGIN(uint32_t, iq1s_grid_gpu, NGRID_IQ1S)
+ 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000,
+ 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101,
+ 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200,
+ 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212,
+ 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011,
+ 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111,
+ 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220,
+ 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022,
+ 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220,
+ 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101,
+ 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110,
+ 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111,
+ 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010,
+ 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210,
+ 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221,
+ 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021,
+ 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002,
+ 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101,
+ 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101,
+ 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211,
+ 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110,
+ 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022,
+ 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121,
+ 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220,
+ 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001,
+ 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101,
+ 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102,
+ 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012,
+ 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010,
+ 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111,
+ 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122,
+ 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222,
+ 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001,
+ 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102,
+ 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101,
+ 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000,
+ 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101,
+ 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112,
+ 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110,
+ 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211,
+ 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012,
+ 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111,
+ 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120,
+ 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122,
+ 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121,
+ 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221,
+ 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001,
+ 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101,
+ 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101,
+ 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011,
+ 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111,
+ 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011,
+ 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122,
+ 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121,
+ 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222,
+ 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101,
+ 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000,
+ 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200,
+ 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110,
+ 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112,
+ 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222,
+ 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021,
+ 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121,
+ 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201,
+ 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200,
+ 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101,
+ 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011,
+ 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010,
+ 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211,
+ 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121,
+ 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000,
+ 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202,
+ 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202,
+ 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211,
+ 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112,
+ 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020,
+ 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121,
+ 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222,
+ 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102,
+ 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100,
+ 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110,
+ 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011,
+ 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111,
+ 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110,
+ 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121,
+ 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222,
+ 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201,
+ 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102,
+ 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201,
+ 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012,
+ 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010,
+ 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010,
+ 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110,
+ 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011,
+ 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212,
+ 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021,
+ 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021,
+ 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021,
+ 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101,
+ 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101,
+ 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100,
+ 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010,
+ 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111,
+ 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010,
+ 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111,
+ 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120,
+ 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120,
+ 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101,
+ 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001,
+ 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201,
+ 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210,
+ 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211,
+ 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111,
+ 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112,
+ 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211,
+ 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010,
+ 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021,
+ 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122,
+ 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221,
+ 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102,
+ 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100,
+ 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101,
+ 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101,
+ 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101,
+ 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012,
+ 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110,
+ 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112,
+ 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210,
+ 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210,
+ 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210,
+ 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010,
+ 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110,
+ 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122,
+ 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020,
+ 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021,
+ 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022,
+ 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120,
+ 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222,
+ 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221,
+ 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001,
+ 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102,
+ 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201,
+ 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012,
+ 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111,
+ 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012,
+ 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110,
+ 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110,
+ 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121,
+ 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221,
+ 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220,
+ 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222,
+ 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000,
+ 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201,
+ 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012,
+ 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011,
+ 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212,
+ 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221,
+ 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121,
+ 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202,
+ 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202,
+ 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002,
+ 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101,
+ 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210,
+ 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112,
+ 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011,
+ 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011,
+ 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210,
+ 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020,
+ 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220,
+ 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222,
+ 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222,
+ 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001,
+ 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010,
+ 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111,
+ 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010,
+ 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110,
+ 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221,
+ 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122,
+ 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202,
+ 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100,
+ 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101,
+ 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112,
+ 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111,
+ 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211,
+ 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222,
+ 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221,
+ 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022,
+ 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101,
+ 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211,
+ 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111,
+ 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111,
+ 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010,
+ 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121,
+ 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222,
+ 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000,
+ 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202,
+ 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000,
+ 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202,
+ 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110,
+ 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110,
+ 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222,
+ 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120,
+ 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022,
+ 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101,
+ 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202,
+ 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110,
+ 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110,
+ 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111,
+ 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111,
+ 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120,
+ 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121,
+ 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001,
+ 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202,
+ 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001,
+ 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200,
+ 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011,
+ 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212,
+ 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012,
+ 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110,
+ 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012,
+ 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111,
+ 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020,
+ 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121,
+ 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222,
+ 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102,
+ 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102,
+ 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101,
+ 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212,
+ 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210,
+ 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111,
+ 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212,
+ 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221,
+ 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121,
+ 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002,
+ 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000,
+ 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202,
+ 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112,
+ 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111,
+ 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020,
+ 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221,
+ 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022,
+ 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100,
+ 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201,
+ 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112,
+ 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211,
+ 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012,
+ 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121,
+ 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020,
+ 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120,
+ 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200,
+ 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200,
+ 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110,
+ 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011,
+ 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222,
+ 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020,
+ 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222,
+GGML_TABLE_END()
+
+
+enum ggml_sort_order {
+ GGML_SORT_ORDER_ASC,
+ GGML_SORT_ORDER_DESC,
+};
+
+// general-purpose kernel for addition, subtraction, multiplication and division of two tensors
+// pros: works for non-contiguous tensors, supports broadcast across all dims
+// cons: not very efficient
+kernel void kernel_add(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant int64_t & offs,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig.z;
+ const int64_t i02 = tgpig.y;
+ const int64_t i01 = tgpig.x;
+
+ const int64_t i13 = i03 % ne13;
+ const int64_t i12 = i02 % ne12;
+ const int64_t i11 = i01 % ne11;
+
+ device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01 + offs;
+ device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
+ device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1 + offs;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int i10 = i0 % ne10;
+ *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) + *((device float *)(src1_ptr + i10*nb10));
+ }
+}
+
+kernel void kernel_sub(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant int64_t & offs,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig.z;
+ const int64_t i02 = tgpig.y;
+ const int64_t i01 = tgpig.x;
+
+ const int64_t i13 = i03 % ne13;
+ const int64_t i12 = i02 % ne12;
+ const int64_t i11 = i01 % ne11;
+
+ device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01 + offs;
+ device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
+ device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1 + offs;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int i10 = i0 % ne10;
+ *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) - *((device float *)(src1_ptr + i10*nb10));
+ }
+}
+
+kernel void kernel_mul(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig.z;
+ const int64_t i02 = tgpig.y;
+ const int64_t i01 = tgpig.x;
+
+ const int64_t i13 = i03 % ne13;
+ const int64_t i12 = i02 % ne12;
+ const int64_t i11 = i01 % ne11;
+
+ device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
+ device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
+ device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int i10 = i0 % ne10;
+ *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) * *((device float *)(src1_ptr + i10*nb10));
+ }
+}
+
+kernel void kernel_div(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig.z;
+ const int64_t i02 = tgpig.y;
+ const int64_t i01 = tgpig.x;
+
+ const int64_t i13 = i03 % ne13;
+ const int64_t i12 = i02 % ne12;
+ const int64_t i11 = i01 % ne11;
+
+ device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
+ device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11;
+ device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int i10 = i0 % ne10;
+ *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) / *((device float *)(src1_ptr + i10*nb10));
+ }
+}
+
+template<typename T>
+kernel void kernel_repeat(
+ device const char * src0,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i3 = tgpig.z;
+ const int64_t i2 = tgpig.y;
+ const int64_t i1 = tgpig.x;
+
+ const int64_t i03 = i3 % ne03;
+ const int64_t i02 = i2 % ne02;
+ const int64_t i01 = i1 % ne01;
+
+ device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01;
+ device char * dst_ptr = dst + i3*nb3 + i2*nb2 + i1*nb1 ;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int i00 = i0 % ne00;
+ *((device T *)(dst_ptr + i0*nb0)) = *((device T *)(src0_ptr + i00*nb00));
+ }
+}
+
+typedef decltype(kernel_repeat<float>) kernel_repeat_t;
+
+template [[host_name("kernel_repeat_f32")]] kernel kernel_repeat_t kernel_repeat<float>;
+template [[host_name("kernel_repeat_f16")]] kernel kernel_repeat_t kernel_repeat<half>;
+template [[host_name("kernel_repeat_i32")]] kernel kernel_repeat_t kernel_repeat<int>;
+template [[host_name("kernel_repeat_i16")]] kernel kernel_repeat_t kernel_repeat<short>;
+
+// assumption: src1 is a row
+// broadcast src1 into src0
+kernel void kernel_add_row(
+ device const float4 * src0,
+ device const float4 * src1,
+ device float4 * dst,
+ constant uint64_t & nb [[buffer(28)]],
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] + src1[tpig % nb];
+}
+
+kernel void kernel_sub_row(
+ device const float4 * src0,
+ device const float4 * src1,
+ device float4 * dst,
+ constant uint64_t & nb [[buffer(28)]],
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] - src1[tpig % nb];
+}
+
+kernel void kernel_mul_row(
+ device const float4 * src0,
+ device const float4 * src1,
+ device float4 * dst,
+ constant uint64_t & nb [[buffer(28)]],
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] * src1[tpig % nb];
+}
+
+kernel void kernel_div_row(
+ device const float4 * src0,
+ device const float4 * src1,
+ device float4 * dst,
+ constant uint64_t & nb [[buffer(28)]],
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] / src1[tpig % nb];
+}
+
+kernel void kernel_scale(
+ device const float * src0,
+ device float * dst,
+ constant float & scale,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] * scale;
+}
+
+kernel void kernel_scale_4(
+ device const float4 * src0,
+ device float4 * dst,
+ constant float & scale,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] * scale;
+}
+
+kernel void kernel_clamp(
+ device const float * src0,
+ device float * dst,
+ constant float & min,
+ constant float & max,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] < min ? min : (src0[tpig] > max ? max : src0[tpig]);
+}
+
+kernel void kernel_relu(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = max(0.0f, src0[tpig]);
+}
+
+kernel void kernel_sigmoid(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = 1.0f / (1.0f + exp(-src0[tpig]));
+}
+
+kernel void kernel_tanh(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float & x = src0[tpig];
+ dst[tpig] = precise::tanh(x);
+}
+
+constant float GELU_COEF_A = 0.044715f;
+constant float GELU_QUICK_COEF = -1.702f;
+constant float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
+
+kernel void kernel_gelu(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float & x = src0[tpig];
+
+ dst[tpig] = 0.5f*x*(1.0f + precise::tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
+}
+
+kernel void kernel_gelu_4(
+ device const float4 * src0,
+ device float4 * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float4 & x = src0[tpig];
+
+ // BEWARE !!!
+ // Simply using "tanh" instead of "precise::tanh" will sometimes results in NaNs!
+ // This was observed with Falcon 7B and 40B models
+ //
+ dst[tpig] = 0.5f*x*(1.0f + precise::tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
+}
+
+kernel void kernel_gelu_quick(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float & x = src0[tpig];
+
+ dst[tpig] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x)));
+}
+
+kernel void kernel_gelu_quick_4(
+ device const float4 * src0,
+ device float4 * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float4 & x = src0[tpig];
+
+ dst[tpig] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x)));
+}
+
+kernel void kernel_silu(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float & x = src0[tpig];
+ dst[tpig] = x / (1.0f + exp(-x));
+}
+
+kernel void kernel_silu_4(
+ device const float4 * src0,
+ device float4 * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ device const float4 & x = src0[tpig];
+ dst[tpig] = x / (1.0f + exp(-x));
+}
+
+kernel void kernel_sqr(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] * src0[tpig];
+}
+
+kernel void kernel_sqrt(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = sqrt(src0[tpig]);
+}
+
+kernel void kernel_sin(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = sin(src0[tpig]);
+}
+
+kernel void kernel_cos(
+ device const float * src0,
+ device float * dst,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = cos(src0[tpig]);
+}
+
+kernel void kernel_sum_rows(
+ device const float * src0,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tpig[[thread_position_in_grid]]) {
+ int64_t i3 = tpig.z;
+ int64_t i2 = tpig.y;
+ int64_t i1 = tpig.x;
+
+ if (i3 >= ne03 || i2 >= ne02 || i1 >= ne01) {
+ return;
+ }
+
+ device const float * src_row = (device const float *) ((device const char *) src0 + i1*nb01 + i2*nb02 + i3*nb03);
+ device float * dst_row = (device float *) ((device char *) dst + i1*nb1 + i2*nb2 + i3*nb3);
+
+ float row_sum = 0;
+
+ for (int64_t i0 = 0; i0 < ne00; i0++) {
+ row_sum += src_row[i0];
+ }
+
+ dst_row[0] = row_sum;
+}
+
+template<typename T>
+kernel void kernel_soft_max(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant float & scale,
+ constant float & max_bias,
+ constant float & m0,
+ constant float & m1,
+ constant uint32_t & n_head_log2,
+ threadgroup float * buf [[threadgroup(0)]],
+ uint tgpig[[threadgroup_position_in_grid]],
+ uint tpitg[[thread_position_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = (tgpig) / (ne02*ne01);
+ const int64_t i02 = (tgpig - i03*ne02*ne01) / ne01;
+ const int64_t i01 = (tgpig - i03*ne02*ne01 - i02*ne01);
+
+ device const float * psrc0 = (device const float *) src0 + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00);
+ device const T * pmask = src1 != src0 ? (device const T *) src1 + i01*ne00 : nullptr;
+ device float * pdst = (device float *) dst + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00);
+
+ float slope = 1.0f;
+
+ // ALiBi
+ if (max_bias > 0.0f) {
+ const int64_t h = i02;
+
+ const float base = h < n_head_log2 ? m0 : m1;
+ const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
+
+ slope = pow(base, exp);
+ }
+
+ // parallel max
+ float lmax = -INFINITY;
+
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ lmax = MAX(lmax, psrc0[i00]*scale + (pmask ? slope*pmask[i00] : 0.0f));
+ }
+
+ // find the max value in the block
+ float max_val = simd_max(lmax);
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = -INFINITY;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = max_val;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ max_val = buf[tiisg];
+ max_val = simd_max(max_val);
+ }
+
+ // parallel sum
+ float lsum = 0.0f;
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ const float exp_psrc0 = exp((psrc0[i00]*scale + (pmask ? slope*pmask[i00] : 0.0f)) - max_val);
+ lsum += exp_psrc0;
+ pdst[i00] = exp_psrc0;
+ }
+
+ // This barrier fixes a failing test
+ // ref: https://github.com/ggerganov/ggml/pull/621#discussion_r1425156335
+ threadgroup_barrier(mem_flags::mem_none);
+
+ float sum = simd_sum(lsum);
+
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = sum;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ sum = buf[tiisg];
+ sum = simd_sum(sum);
+ }
+
+ const float inv_sum = 1.0f/sum;
+
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ pdst[i00] *= inv_sum;
+ }
+}
+
+template<typename T>
+kernel void kernel_soft_max_4(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant float & scale,
+ constant float & max_bias,
+ constant float & m0,
+ constant float & m1,
+ constant uint32_t & n_head_log2,
+ threadgroup float * buf [[threadgroup(0)]],
+ uint tgpig[[threadgroup_position_in_grid]],
+ uint tpitg[[thread_position_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = (tgpig) / (ne02*ne01);
+ const int64_t i02 = (tgpig - i03*ne02*ne01) / ne01;
+ const int64_t i01 = (tgpig - i03*ne02*ne01 - i02*ne01);
+
+ device const float4 * psrc4 = (device const float4 *) src0 + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00)/4;
+ device const T * pmask = src1 != src0 ? (device const T *) src1 + i01*ne00/4 : nullptr;
+ device float4 * pdst4 = (device float4 *) dst + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00)/4;
+
+ float slope = 1.0f;
+
+ if (max_bias > 0.0f) {
+ const int64_t h = i02;
+
+ const float base = h < n_head_log2 ? m0 : m1;
+ const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
+
+ slope = pow(base, exp);
+ }
+
+ // parallel max
+ float4 lmax4 = -INFINITY;
+
+ for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) {
+ lmax4 = fmax(lmax4, psrc4[i00]*scale + (float4)((pmask ? slope*pmask[i00] : 0.0f)));
+ }
+
+ const float lmax = MAX(MAX(lmax4[0], lmax4[1]), MAX(lmax4[2], lmax4[3]));
+
+ float max_val = simd_max(lmax);
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = -INFINITY;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = max_val;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ max_val = buf[tiisg];
+ max_val = simd_max(max_val);
+ }
+
+ // parallel sum
+ float4 lsum4 = 0.0f;
+ for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) {
+ const float4 exp_psrc4 = exp((psrc4[i00]*scale + (float4)((pmask ? slope*pmask[i00] : 0.0f))) - max_val);
+ lsum4 += exp_psrc4;
+ pdst4[i00] = exp_psrc4;
+ }
+
+ const float lsum = lsum4[0] + lsum4[1] + lsum4[2] + lsum4[3];
+
+ // This barrier fixes a failing test
+ // ref: https://github.com/ggerganov/ggml/pull/621#discussion_r1425156335
+ threadgroup_barrier(mem_flags::mem_none);
+
+ float sum = simd_sum(lsum);
+
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = sum;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ sum = buf[tiisg];
+ sum = simd_sum(sum);
+ }
+
+ const float inv_sum = 1.0f/sum;
+
+ for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) {
+ pdst4[i00] *= inv_sum;
+ }
+}
+
+typedef decltype(kernel_soft_max<float>) kernel_soft_max_t;
+typedef decltype(kernel_soft_max_4<float4>) kernel_soft_max_4_t;
+
+template [[host_name("kernel_soft_max_f16")]] kernel kernel_soft_max_t kernel_soft_max<half>;
+template [[host_name("kernel_soft_max_f32")]] kernel kernel_soft_max_t kernel_soft_max<float>;
+template [[host_name("kernel_soft_max_f16_4")]] kernel kernel_soft_max_4_t kernel_soft_max_4<half4>;
+template [[host_name("kernel_soft_max_f32_4")]] kernel kernel_soft_max_4_t kernel_soft_max_4<float4>;
+
+kernel void kernel_diag_mask_inf(
+ device const float * src0,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int & n_past,
+ uint3 tpig[[thread_position_in_grid]]) {
+ const int64_t i02 = tpig[2];
+ const int64_t i01 = tpig[1];
+ const int64_t i00 = tpig[0];
+
+ if (i00 > n_past + i01) {
+ dst[i02*ne01*ne00 + i01*ne00 + i00] = -INFINITY;
+ } else {
+ dst[i02*ne01*ne00 + i01*ne00 + i00] = src0[i02*ne01*ne00 + i01*ne00 + i00];
+ }
+}
+
+kernel void kernel_diag_mask_inf_8(
+ device const float4 * src0,
+ device float4 * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int & n_past,
+ uint3 tpig[[thread_position_in_grid]]) {
+
+ const int64_t i = 2*tpig[0];
+
+ dst[i+0] = src0[i+0];
+ dst[i+1] = src0[i+1];
+ int64_t i4 = 4*i;
+ const int64_t i02 = i4/(ne00*ne01); i4 -= i02*ne00*ne01;
+ const int64_t i01 = i4/(ne00); i4 -= i01*ne00;
+ const int64_t i00 = i4;
+ for (int k = 3; k >= 0; --k) {
+ if (i00 + 4 + k <= n_past + i01) {
+ break;
+ }
+ dst[i+1][k] = -INFINITY;
+ if (i00 + k > n_past + i01) {
+ dst[i][k] = -INFINITY;
+ }
+ }
+}
+
+// ref: ggml.c:ggml_compute_forward_ssm_conv_f32
+// TODO: optimize
+kernel void kernel_ssm_conv_f32(
+ device const void * src0,
+ device const void * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t ir = tgpig.x;
+ const int64_t i2 = tgpig.y;
+ const int64_t i3 = tgpig.z;
+
+ const int64_t nc = ne10;
+ const int64_t ncs = ne00;
+ const int64_t nr = ne01;
+ const int64_t n_t = ne1;
+ const int64_t n_s = ne2;
+
+ device const float * s = (device const float *) ((device const char *) src0 + ir*nb01 + i2*nb00 + i3*nb02);
+ device const float * c = (device const float *) ((device const char *) src1 + ir*nb11);
+ device float * x = (device float *) ((device char *) dst + ir*nb0 + i2*nb1 + i3*nb2);
+
+ float sumf = 0.0f;
+
+ for (int64_t i0 = 0; i0 < nc; ++i0) {
+ sumf += s[i0] * c[i0];
+ }
+
+ x[0] = sumf;
+}
+
+// ref: ggml.c:ggml_compute_forward_ssm_scan_f32
+// TODO: optimize
+kernel void kernel_ssm_scan_f32(
+ device const void * src0,
+ device const void * src1,
+ device const void * src2,
+ device const void * src3,
+ device const void * src4,
+ device const void * src5,
+ device float * dst,
+ constant int64_t & d_state,
+ constant int64_t & d_inner,
+ constant int64_t & n_seq_tokens,
+ constant int64_t & n_seqs,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant uint64_t & nb20,
+ constant uint64_t & nb21,
+ constant uint64_t & nb22,
+ constant uint64_t & nb30,
+ constant uint64_t & nb31,
+ constant uint64_t & nb40,
+ constant uint64_t & nb41,
+ constant uint64_t & nb42,
+ constant uint64_t & nb50,
+ constant uint64_t & nb51,
+ constant uint64_t & nb52,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t ir = tgpig.x;
+ const int64_t i3 = tgpig.y;
+
+ const int64_t nc = d_state;
+ const int64_t nr = d_inner;
+ const int64_t n_t = n_seq_tokens;
+ const int64_t n_s = n_seqs;
+
+ for (int64_t i2 = 0; i2 < n_t; ++i2) {
+ device const float * s0 = (device const float *) ((device const char *) src0 + ir*nb01 + i3*nb02);
+ device const float * x = (device const float *) ((device const char *) src1 + ir*nb10 + i2*nb11 + i3*nb12);
+ device const float * dt = (device const float *) ((device const char *) src2 + ir*nb20 + i2*nb21 + i3*nb22);
+ device const float * A = (device const float *) ((device const char *) src3 + ir*nb31);
+ device const float * B = (device const float *) ((device const char *) src4 + i2*nb41 + i3*nb42);
+ device const float * C = (device const float *) ((device const char *) src5 + i2*nb51 + i3*nb52);
+ device float * y = (device float *) ((device char *) dst + ir*nb10 + i2*nb11 + i3*nb12); // TODO: do not use src1 strides
+ device float * s = (device float *) ((device char *) dst + ir*nb01 + i3*nb02 + nb13);
+
+ if (i2 > 0) {
+ s0 = s;
+ }
+
+ // i1 == 0
+ float dt_soft_plus = dt[0] <= 20.0f ? log(1.0f + exp(dt[0])) : dt[0];
+ float x_dt = x[0] * dt_soft_plus;
+ float sumf = 0.0f;
+
+ for (int64_t i0 = 0; i0 < nc; ++i0) {
+ int64_t i = i0;
+ float state = (s0[i] * exp(dt_soft_plus * A[i])) + (B[i0] * x_dt);
+ sumf += state * C[i0];
+ s[i] = state;
+ }
+
+ y[0] = sumf;
+ }
+}
+
+kernel void kernel_norm(
+ device const void * src0,
+ device float * dst,
+ constant int64_t & ne00,
+ constant uint64_t & nb01,
+ constant float & eps,
+ threadgroup float * sum [[threadgroup(0)]],
+ uint tgpig[[threadgroup_position_in_grid]],
+ uint tpitg[[thread_position_in_threadgroup]],
+ uint ntg[[threads_per_threadgroup]]) {
+ device const float * x = (device const float *) ((device const char *) src0 + tgpig*nb01);
+ // MEAN
+ // parallel sum
+ sum[tpitg] = 0.0f;
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ sum[tpitg] += x[i00];
+ }
+ // reduce
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (uint i = ntg/2; i > 0; i /= 2) {
+ if (tpitg < i) {
+ sum[tpitg] += sum[tpitg + i];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ const float mean = sum[0] / ne00;
+
+ // recenter and VARIANCE
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ device float * y = dst + tgpig*ne00;
+ sum[tpitg] = 0.0f;
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ y[i00] = x[i00] - mean;
+ sum[tpitg] += y[i00] * y[i00];
+ }
+
+ // reduce
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (uint i = ntg/2; i > 0; i /= 2) {
+ if (tpitg < i) {
+ sum[tpitg] += sum[tpitg + i];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ const float variance = sum[0] / ne00;
+
+ const float scale = 1.0f/sqrt(variance + eps);
+ for (int i00 = tpitg; i00 < ne00; i00 += ntg) {
+ y[i00] = y[i00] * scale;
+ }
+}
+
+kernel void kernel_rms_norm(
+ device const void * src0,
+ device float * dst,
+ constant int64_t & ne00,
+ constant uint64_t & nb01,
+ constant float & eps,
+ threadgroup float * buf [[threadgroup(0)]],
+ uint tgpig[[threadgroup_position_in_grid]],
+ uint tpitg[[thread_position_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint ntg[[threads_per_threadgroup]]) {
+ device const float4 * x = (device const float4 *) ((device const char *) src0 + tgpig*nb01);
+
+ float4 sumf = 0;
+ float all_sum = 0;
+
+ // parallel sum
+ for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) {
+ sumf += x[i00] * x[i00];
+ }
+ all_sum = sumf[0] + sumf[1] + sumf[2] + sumf[3];
+ all_sum = simd_sum(all_sum);
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = all_sum;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ all_sum = buf[tiisg];
+ all_sum = simd_sum(all_sum);
+ }
+
+ const float mean = all_sum/ne00;
+ const float scale = 1.0f/sqrt(mean + eps);
+
+ device float4 * y = (device float4 *) (dst + tgpig*ne00);
+ for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) {
+ y[i00] = x[i00] * scale;
+ }
+}
+
+kernel void kernel_group_norm(
+ device const float * src0,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int32_t & n_groups,
+ constant float & eps,
+ threadgroup float * buf [[threadgroup(0)]],
+ uint tgpig[[threadgroup_position_in_grid]],
+ uint tpitg[[thread_position_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint ntg[[threads_per_threadgroup]]) {
+ const int64_t ne = ne00*ne01*ne02;
+ const int64_t gs = ne00*ne01*((ne02 + n_groups - 1) / n_groups);
+
+ int start = tgpig * gs;
+ int end = start + gs;
+
+ start += tpitg;
+
+ if (end >= ne) {
+ end = ne;
+ }
+
+ float tmp = 0.0f; // partial sum for thread in warp
+
+ for (int j = start; j < end; j += ntg) {
+ tmp += src0[j];
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ tmp = simd_sum(tmp);
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = tmp;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ tmp = buf[tiisg];
+ tmp = simd_sum(tmp);
+ }
+
+ const float mean = tmp / gs;
+ tmp = 0.0f;
+
+ for (int j = start; j < end; j += ntg) {
+ float xi = src0[j] - mean;
+ dst[j] = xi;
+ tmp += xi * xi;
+ }
+
+ tmp = simd_sum(tmp);
+ if (ntg > N_SIMDWIDTH) {
+ if (sgitg == 0) {
+ buf[tiisg] = 0.0f;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tiisg == 0) {
+ buf[sgitg] = tmp;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ tmp = buf[tiisg];
+ tmp = simd_sum(tmp);
+ }
+
+ const float variance = tmp / gs;
+ const float scale = 1.0f/sqrt(variance + eps);
+ for (int j = start; j < end; j += ntg) {
+ dst[j] *= scale;
+ }
+}
+
+// function for calculate inner product between half a q4_0 block and 16 floats (yl), sumy is SUM(yl[i])
+// il indicates where the q4 quants begin (0 or QK4_0/4)
+// we assume that the yl's have been multiplied with the appropriate scale factor
+// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096)
+inline float block_q_n_dot_y(device const block_q4_0 * qb_curr, float sumy, thread float * yl, int il) {
+ float d = qb_curr->d;
+
+ float2 acc = 0.f;
+
+ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 1 + il/2);
+
+ for (int i = 0; i < 8; i+=2) {
+ acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F)
+ + yl[i + 1] * (qs[i / 2] & 0x0F00);
+ acc[1] += yl[i + 8] * (qs[i / 2] & 0x00F0)
+ + yl[i + 9] * (qs[i / 2] & 0xF000);
+ }
+ return d * (sumy * -8.f + acc[0] + acc[1]);
+}
+
+// function for calculate inner product between half a q4_1 block and 16 floats (yl), sumy is SUM(yl[i])
+// il indicates where the q4 quants begin (0 or QK4_0/4)
+// we assume that the yl's have been multiplied with the appropriate scale factor
+// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096)
+inline float block_q_n_dot_y(device const block_q4_1 * qb_curr, float sumy, thread float * yl, int il) {
+ float d = qb_curr->d;
+ float m = qb_curr->m;
+
+ float2 acc = 0.f;
+
+ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 2 + il/2);
+
+ for (int i = 0; i < 8; i+=2) {
+ acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F)
+ + yl[i + 1] * (qs[i / 2] & 0x0F00);
+ acc[1] += yl[i + 8] * (qs[i / 2] & 0x00F0)
+ + yl[i + 9] * (qs[i / 2] & 0xF000);
+ }
+ return d * (acc[0] + acc[1]) + sumy * m;
+}
+
+// function for calculate inner product between half a q5_0 block and 16 floats (yl), sumy is SUM(yl[i])
+// il indicates where the q5 quants begin (0 or QK5_0/4)
+// we assume that the yl's have been multiplied with the appropriate scale factor
+// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096)
+inline float block_q_n_dot_y(device const block_q5_0 * qb_curr, float sumy, thread float * yl, int il) {
+ float d = qb_curr->d;
+
+ float2 acc = 0.f;
+
+ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 3 + il/2);
+ const uint32_t qh = *((device const uint32_t *)qb_curr->qh);
+
+ for (int i = 0; i < 8; i+=2) {
+ acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010))
+ + yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000));
+ acc[1] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100))
+ + yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000));
+ }
+ return d * (sumy * -16.f + acc[0] + acc[1]);
+}
+
+// function for calculate inner product between half a q5_1 block and 16 floats (yl), sumy is SUM(yl[i])
+// il indicates where the q5 quants begin (0 or QK5_1/4)
+// we assume that the yl's have been multiplied with the appropriate scale factor
+// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096)
+inline float block_q_n_dot_y(device const block_q5_1 * qb_curr, float sumy, thread float * yl, int il) {
+ float d = qb_curr->d;
+ float m = qb_curr->m;
+
+ float2 acc = 0.f;
+
+ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 4 + il/2);
+ const uint32_t qh = *((device const uint32_t *)qb_curr->qh);
+
+ for (int i = 0; i < 8; i+=2) {
+ acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010))
+ + yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000));
+ acc[1] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100))
+ + yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000));
+ }
+ return d * (acc[0] + acc[1]) + sumy * m;
+}
+
+// putting them in the kernel cause a significant performance penalty
+#define N_DST 4 // each SIMD group works on 4 rows
+#define N_SIMDGROUP 2 // number of SIMD groups in a thread group
+//Note: This is a template, but strictly speaking it only applies to
+// quantizations where the block size is 32. It also does not
+// guard against the number of rows not being divisible by
+// N_DST, so this is another explicit assumption of the implementation.
+template<typename block_q_type, int nr, int nsg, int nw>
+void mul_vec_q_n_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig, uint tiisg, uint sgitg) {
+ const int nb = ne00/QK4_0;
+
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * nsg + sgitg) * nr;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = first_row * nb + (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q_type * x = (device const block_q_type *) src0 + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[16]; // src1 vector cache
+ float sumf[nr] = {0.f};
+
+ const int ix = (tiisg/2);
+ const int il = (tiisg%2)*8;
+
+ device const float * yb = y + ix * QK4_0 + il;
+
+ // each thread in a SIMD group deals with half a block.
+ for (int ib = ix; ib < nb; ib += nw/2) {
+ float sumy = 0;
+ for (int i = 0; i < 8; i += 2) {
+ sumy += yb[i] + yb[i+1];
+ yl[i+0] = yb[i+ 0];
+ yl[i+1] = yb[i+ 1]/256.f;
+
+ sumy += yb[i+16] + yb[i+17];
+ yl[i+8] = yb[i+16]/16.f;
+ yl[i+9] = yb[i+17]/4096.f;
+ }
+
+ for (int row = 0; row < nr; row++) {
+ sumf[row] += block_q_n_dot_y(x+ib+row*nb, sumy, yl, il);
+ }
+
+ yb += QK4_0 * 16;
+ }
+
+ for (int row = 0; row < nr; ++row) {
+ const float tot = simd_sum(sumf[row]);
+ if (tiisg == 0 && first_row + row < ne01) {
+ dst[im*ne0*ne1 + r1*ne0 + first_row + row] = tot;
+ }
+ }
+}
+
+kernel void kernel_mul_mv_q4_0_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ mul_vec_q_n_f32_impl<block_q4_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg);
+}
+
+kernel void kernel_mul_mv_q4_1_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ mul_vec_q_n_f32_impl<block_q4_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg);
+}
+
+kernel void kernel_mul_mv_q5_0_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ mul_vec_q_n_f32_impl<block_q5_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg);
+}
+
+kernel void kernel_mul_mv_q5_1_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ mul_vec_q_n_f32_impl<block_q5_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg);
+}
+
+
+#define NB_Q8_0 8
+
+void kernel_mul_mv_q8_0_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+ const int nr = N_DST;
+ const int nsg = N_SIMDGROUP;
+ const int nw = N_SIMDWIDTH;
+
+ const int nb = ne00/QK8_0;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * nsg + sgitg) * nr;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = first_row * nb + (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q8_0 * x = (device const block_q8_0 *) src0 + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[NB_Q8_0];
+ float sumf[nr]={0.f};
+
+ const int ix = tiisg/4;
+ const int il = tiisg%4;
+
+ device const float * yb = y + ix * QK8_0 + NB_Q8_0*il;
+
+ // each thread in a SIMD group deals with NB_Q8_0 quants at a time
+ for (int ib = ix; ib < nb; ib += nw/4) {
+ for (int i = 0; i < NB_Q8_0; ++i) {
+ yl[i] = yb[i];
+ }
+
+ for (int row = 0; row < nr; row++) {
+ device const int8_t * qs = x[ib+row*nb].qs + NB_Q8_0*il;
+ float sumq = 0.f;
+ for (int iq = 0; iq < NB_Q8_0; ++iq) {
+ sumq += qs[iq] * yl[iq];
+ }
+ sumf[row] += sumq*x[ib+row*nb].d;
+ }
+
+ yb += NB_Q8_0 * nw;
+ }
+
+ for (int row = 0; row < nr; ++row) {
+ const float tot = simd_sum(sumf[row]);
+ if (tiisg == 0 && first_row + row < ne01) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = tot;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_q8_0_f32")]]
+kernel void kernel_mul_mv_q8_0_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ kernel_mul_mv_q8_0_f32_impl(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg);
+}
+
+#define N_MV_T_T 4
+
+template<typename T0, typename T04, typename T1, typename T14>
+void kernel_mul_mv_impl(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ uint64_t nb00,
+ uint64_t nb01,
+ uint64_t nb02,
+ int64_t ne10,
+ int64_t ne11,
+ int64_t ne12,
+ uint64_t nb10,
+ uint64_t nb11,
+ uint64_t nb12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ uint3 tgpig,
+ uint tiisg) {
+ const int64_t r0 = tgpig.x;
+ const int64_t rb = tgpig.y*N_MV_T_T;
+ const int64_t im = tgpig.z;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02;
+
+ device const T0 * x = (device const T0 *) (src0 + offset0);
+
+ if (ne00 < 128) {
+ for (int row = 0; row < N_MV_T_T; ++row) {
+ int r1 = rb + row;
+ if (r1 >= ne11) {
+ break;
+ }
+
+ device const T1 * y = (device const T1 *) (src1 + r1*nb11 + im*nb12);
+
+ float sumf = 0;
+ for (int i = tiisg; i < ne00; i += 32) {
+ sumf += (T0) x[i] * (T1) y[i];
+ }
+
+ float all_sum = simd_sum(sumf);
+ if (tiisg == 0) {
+ dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum;
+ }
+ }
+ } else {
+ device const T04 * x4 = (device const T04 *) x;
+ for (int row = 0; row < N_MV_T_T; ++row) {
+ int r1 = rb + row;
+ if (r1 >= ne11) {
+ break;
+ }
+
+ device const T1 * y = (device const T1 *) (src1 + r1*nb11 + im*nb12);
+ device const T14 * y4 = (device const T14 *) y;
+
+ float sumf = 0;
+ for (int i = tiisg; i < ne00/4; i += 32) {
+ for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]);
+ }
+
+ float all_sum = simd_sum(sumf);
+ if (tiisg == 0) {
+ for (int i = 4*(ne00/4); i < ne00; ++i) all_sum += (float) (x[i] * y[i]);
+ dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum;
+ }
+ }
+ }
+}
+
+template<typename T0, typename T04, typename T1, typename T14>
+kernel void kernel_mul_mv(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]]) {
+ kernel_mul_mv_impl<T0, T04, T1, T14>(
+ src0,
+ src1,
+ dst,
+ ne00,
+ ne01,
+ ne02,
+ nb00,
+ nb01,
+ nb02,
+ ne10,
+ ne11,
+ ne12,
+ nb10,
+ nb11,
+ nb12,
+ ne0,
+ ne1,
+ r2,
+ r3,
+ tgpig,
+ tiisg);
+}
+
+typedef decltype(kernel_mul_mv<half, half4, half, half4>) mul_mv_t;
+
+template [[host_name("kernel_mul_mv_f32_f32")]] kernel mul_mv_t kernel_mul_mv<float, float4, float, float4>;
+template [[host_name("kernel_mul_mv_f16_f32")]] kernel mul_mv_t kernel_mul_mv<half, half4, float, float4>;
+template [[host_name("kernel_mul_mv_f16_f16")]] kernel mul_mv_t kernel_mul_mv<half, half4, half, half4>;
+
+template<typename T, typename T4>
+kernel void kernel_mul_mv_1row(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]]) {
+
+ const int64_t r0 = tgpig.x;
+ const int64_t r1 = tgpig.y;
+ const int64_t im = tgpig.z;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02;
+
+ device const T * x = (device const T *) (src0 + offset0);
+ device const float * y = (device const float *) (src1 + r1*nb11 + im*nb12);
+
+ float sumf = 0;
+ if (ne00 < 128) {
+ for (int i = tiisg; i < ne00; i += 32) {
+ sumf += (float) x[i] * (float) y[i];
+ }
+ float all_sum = simd_sum(sumf);
+ if (tiisg == 0) {
+ dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum;
+ }
+ } else {
+ device const T4 * x4 = (device const T4 *) x;
+ device const float4 * y4 = (device const float4 *) y;
+
+ for (int i = tiisg; i < ne00/4; i += 32) {
+ for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]);
+ }
+
+ float all_sum = simd_sum(sumf);
+
+ if (tiisg == 0) {
+ for (int i = 4*(ne00/4); i < ne00; ++i) all_sum += (float) (x[i] * y[i]);
+ dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum;
+ }
+ }
+}
+
+typedef decltype(kernel_mul_mv_1row<half, half4>) mul_mv_1row_t;
+
+template [[host_name("kernel_mul_mv_f16_f32_1row")]] kernel mul_mv_1row_t kernel_mul_mv_1row<half, half4>;
+
+// Assumes row size (ne00) is a multiple of 4
+template<typename T, typename T4>
+kernel void kernel_mul_mv_l4(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]]) {
+
+ const int nrows = ne11;
+ const int64_t r0 = tgpig.x;
+ const int64_t im = tgpig.z;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02;
+
+ device const T4 * x4 = (device const T4 *) (src0 + offset0);
+
+ for (int r1 = 0; r1 < nrows; ++r1) {
+ device const float4 * y4 = (device const float4 *) (src1 + r1*nb11 + im*nb12);
+
+ float sumf = 0;
+ for (int i = tiisg; i < ne00/4; i += 32) {
+ for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]);
+ }
+
+ float all_sum = simd_sum(sumf);
+ if (tiisg == 0) {
+ dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum;
+ }
+ }
+}
+
+typedef decltype(kernel_mul_mv_l4<half, half4>) mul_mv_l4_t;
+
+template [[host_name("kernel_mul_mv_f16_f32_l4")]] kernel mul_mv_l4_t kernel_mul_mv_l4<half, half4>;
+
+static float rope_yarn_ramp(const float low, const float high, const int i0) {
+ const float y = (i0 / 2 - low) / max(0.001f, high - low);
+ return 1.0f - min(1.0f, max(0.0f, y));
+}
+
+// YaRN algorithm based on LlamaYaRNScaledRotaryEmbedding.py from https://github.com/jquesnelle/yarn
+// MIT licensed. Copyright (c) 2023 Jeffrey Quesnelle and Bowen Peng.
+static void rope_yarn(
+ float theta_extrap, float freq_scale, float corr_dims[2], int64_t i0, float ext_factor, float mscale,
+ thread float * cos_theta, thread float * sin_theta) {
+ // Get n-d rotational scaling corrected for extrapolation
+ float theta_interp = freq_scale * theta_extrap;
+ float theta = theta_interp;
+ if (ext_factor != 0.0f) {
+ float ramp_mix = rope_yarn_ramp(corr_dims[0], corr_dims[1], i0) * ext_factor;
+ theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
+
+ // Get n-d magnitude scaling corrected for interpolation
+ mscale *= 1.0f + 0.1f * log(1.0f / freq_scale);
+ }
+ *cos_theta = cos(theta) * mscale;
+ *sin_theta = sin(theta) * mscale;
+}
+
+// Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
+// `corr_fac(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
+static float rope_yarn_corr_factor(int n_dims, int n_ctx_orig, float n_rot, float base) {
+ return n_dims * log(n_ctx_orig / (n_rot * 2 * M_PI_F)) / (2 * log(base));
+}
+
+static void rope_yarn_corr_dims(
+ int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
+) {
+ // start and end correction dims
+ dims[0] = max(0.0f, floor(rope_yarn_corr_factor(n_dims, n_ctx_orig, beta_fast, freq_base)));
+ dims[1] = min(n_dims - 1.0f, ceil(rope_yarn_corr_factor(n_dims, n_ctx_orig, beta_slow, freq_base)));
+}
+
+template<typename T>
+kernel void kernel_rope_norm(
+ device const void * src0,
+ device const int32_t * src1,
+ device const float * src2,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant int & n_past,
+ constant int & n_dims,
+ constant int & n_ctx_orig,
+ constant float & freq_base,
+ constant float & freq_scale,
+ constant float & ext_factor,
+ constant float & attn_factor,
+ constant float & beta_fast,
+ constant float & beta_slow,
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint3 tptg[[threads_per_threadgroup]],
+ uint3 tgpig[[threadgroup_position_in_grid]]) {
+ const int64_t i3 = tgpig[2];
+ const int64_t i2 = tgpig[1];
+ const int64_t i1 = tgpig[0];
+
+ float corr_dims[2];
+ rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
+
+ device const int32_t * pos = src1;
+
+ const float theta_base = (float) pos[i2];
+ const float inv_ndims = -1.f/n_dims;
+
+ float cos_theta;
+ float sin_theta;
+
+ for (int64_t i0 = 2*tiitg; i0 < ne0; i0 += 2*tptg.x) {
+ if (i0 < n_dims) {
+ const int64_t ic = i0/2;
+
+ const float theta = theta_base * pow(freq_base, inv_ndims*i0);
+
+ const float freq_factor = src2 != src0 ? src2[ic] : 1.0f;
+
+ rope_yarn(theta/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, &cos_theta, &sin_theta);
+
+ device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
+ device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ const float x0 = src[0];
+ const float x1 = src[1];
+
+ dst_data[0] = x0*cos_theta - x1*sin_theta;
+ dst_data[1] = x0*sin_theta + x1*cos_theta;
+ } else {
+ device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
+ device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ dst_data[0] = src[0];
+ dst_data[1] = src[1];
+ }
+ }
+}
+
+template<typename T>
+kernel void kernel_rope_neox(
+ device const void * src0,
+ device const int32_t * src1,
+ device const float * src2,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant int & n_past,
+ constant int & n_dims,
+ constant int & n_ctx_orig,
+ constant float & freq_base,
+ constant float & freq_scale,
+ constant float & ext_factor,
+ constant float & attn_factor,
+ constant float & beta_fast,
+ constant float & beta_slow,
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint3 tptg[[threads_per_threadgroup]],
+ uint3 tgpig[[threadgroup_position_in_grid]]) {
+ const int64_t i3 = tgpig[2];
+ const int64_t i2 = tgpig[1];
+ const int64_t i1 = tgpig[0];
+
+ float corr_dims[2];
+ rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
+
+ device const int32_t * pos = src1;
+
+ const float theta_base = (float) pos[i2];
+ const float inv_ndims = -1.f/n_dims;
+
+ float cos_theta;
+ float sin_theta;
+
+ for (int64_t i0 = 2*tiitg; i0 < ne0; i0 += 2*tptg.x) {
+ if (i0 < n_dims) {
+ const int64_t ic = i0/2;
+
+ const float theta = theta_base * pow(freq_base, inv_ndims*i0);
+
+ const float freq_factor = src2 != src0 ? src2[ic] : 1.0f;
+
+ rope_yarn(theta/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, &cos_theta, &sin_theta);
+
+ device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00);
+ device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0);
+
+ const float x0 = src[0];
+ const float x1 = src[n_dims/2];
+
+ dst_data[0] = x0*cos_theta - x1*sin_theta;
+ dst_data[n_dims/2] = x0*sin_theta + x1*cos_theta;
+ } else {
+ device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
+ device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ dst_data[0] = src[0];
+ dst_data[1] = src[1];
+ }
+ }
+}
+
+typedef decltype(kernel_rope_norm<float>) kernel_rope_norm_t;
+typedef decltype(kernel_rope_neox<float>) kernel_rope_neox_t;
+
+template [[host_name("kernel_rope_norm_f32")]] kernel kernel_rope_norm_t kernel_rope_norm<float>;
+template [[host_name("kernel_rope_norm_f16")]] kernel kernel_rope_norm_t kernel_rope_norm<half>;
+
+template [[host_name("kernel_rope_neox_f32")]] kernel kernel_rope_neox_t kernel_rope_neox<float>;
+template [[host_name("kernel_rope_neox_f16")]] kernel kernel_rope_neox_t kernel_rope_neox<half>;
+
+typedef void (im2col_t)(
+ device const float * x,
+ device char * dst,
+ constant int32_t & ofs0,
+ constant int32_t & ofs1,
+ constant int32_t & IW,
+ constant int32_t & IH,
+ constant int32_t & CHW,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int32_t & d0,
+ constant int32_t & d1,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tgpg[[threadgroups_per_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]);
+
+template <typename T>
+kernel void kernel_im2col(
+ device const float * x,
+ device char * dst,
+ constant int32_t & ofs0,
+ constant int32_t & ofs1,
+ constant int32_t & IW,
+ constant int32_t & IH,
+ constant int32_t & CHW,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int32_t & d0,
+ constant int32_t & d1,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tgpg[[threadgroups_per_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int32_t iiw = tgpig[2] * s0 + tpitg[2] * d0 - p0;
+ const int32_t iih = tgpig[1] * s1 + tpitg[1] * d1 - p1;
+
+ const int32_t offset_dst =
+ (tpitg[0] * tgpg[1] * tgpg[2] + tgpig[1] * tgpg[2] + tgpig[2]) * CHW +
+ (tgpig[0] * (ntg[1] * ntg[2]) + tpitg[1] * ntg[2] + tpitg[2]);
+
+ device T * pdst = (device T *) (dst);
+
+ if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
+ pdst[offset_dst] = 0.0f;
+ } else {
+ const int32_t offset_src = tpitg[0] * ofs0 + tgpig[0] * ofs1;
+ pdst[offset_dst] = x[offset_src + iih * IW + iiw];
+ }
+}
+
+template [[host_name("kernel_im2col_f32")]] kernel im2col_t kernel_im2col<float>;
+template [[host_name("kernel_im2col_f16")]] kernel im2col_t kernel_im2col<half>;
+
+typedef void (im2col_ext_t)(
+ device const float * x,
+ device char * dst,
+ constant int32_t & ofs0,
+ constant int32_t & ofs1,
+ constant int32_t & IW,
+ constant int32_t & IH,
+ constant int32_t & CHW,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int32_t & d0,
+ constant int32_t & d1,
+ constant int32_t & N,
+ constant int32_t & KH,
+ constant int32_t & KW,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tgpg[[threadgroups_per_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]);
+
+template <typename T>
+kernel void kernel_im2col_ext(
+ device const float * x,
+ device char * dst,
+ constant int32_t & ofs0,
+ constant int32_t & ofs1,
+ constant int32_t & IW,
+ constant int32_t & IH,
+ constant int32_t & CHW,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int32_t & d0,
+ constant int32_t & d1,
+ constant int32_t & N,
+ constant int32_t & KH,
+ constant int32_t & KW,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tgpg[[threadgroups_per_grid]], // tgpg[0] = D x IC x KH x KW, CHW = IC x KH x KW
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) { // [M, 1, 1]
+ const int32_t KHW = KH * KW; // KHW == ntg[1] * ntg[2], KW == ntg[2]
+
+ const int32_t d = tgpig[0] / CHW;
+ const int32_t chw = tgpig[0] % CHW;
+ const int32_t tgpig_0 = chw / KHW; // 0 ~ (IC - 1)
+ const int32_t HW = tgpig[0] % KHW;
+
+ const int32_t tpitg_0 = (d * ntg[0]) + tpitg[0];
+ if (tpitg_0 >= N) {
+ return;
+ }
+
+ const int32_t tpitg_1 = HW / KW;
+ const int32_t tpitg_2 = HW % KW;
+
+ const int32_t iiw = tgpig[2] * s0 + tpitg_2 * d0 - p0;
+ const int32_t iih = tgpig[1] * s1 + tpitg_1 * d1 - p1;
+
+ const int32_t offset_dst =
+ (tpitg_0 * tgpg[1] * tgpg[2] + tgpig[1] * tgpg[2] + tgpig[2]) * CHW +
+ (tgpig_0 * KHW + tpitg_1 * KW + tpitg_2);
+
+ device T * pdst = (device T *) (dst);
+
+ if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) {
+ pdst[offset_dst] = 0.0f;
+ } else {
+ const int32_t offset_src = tpitg_0 * ofs0 + tgpig_0 * ofs1;
+ pdst[offset_dst] = x[offset_src + iih * IW + iiw];
+ }
+}
+
+template [[host_name("kernel_im2col_ext_f32")]] kernel im2col_ext_t kernel_im2col_ext<float>;
+template [[host_name("kernel_im2col_ext_f16")]] kernel im2col_ext_t kernel_im2col_ext<half>;
+
+kernel void kernel_upscale_f32(
+ device const char * src0,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant float & sf0,
+ constant float & sf1,
+ constant float & sf2,
+ constant float & sf3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+
+ const int64_t i3 = tgpig.z;
+ const int64_t i2 = tgpig.y;
+ const int64_t i1 = tgpig.x;
+
+ const int64_t i03 = i3/sf3;
+ const int64_t i02 = i2/sf2;
+ const int64_t i01 = i1/sf1;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ const int64_t i00 = i0/sf0;
+
+ device const float * src0_ptr = (device const float *) (src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+ device float * dst_ptr = (device float *) (dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ dst_ptr[0] = src0_ptr[0];
+ }
+}
+
+kernel void kernel_pad_f32(
+ device const char * src0,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+
+ const int64_t i3 = tgpig.z;
+ const int64_t i2 = tgpig.y;
+ const int64_t i1 = tgpig.x;
+
+ const int64_t i03 = i3;
+ const int64_t i02 = i2;
+ const int64_t i01 = i1;
+
+ device const float * src0_ptr = (device const float *) (src0 + i03*nb03 + i02*nb02 + i01*nb01);
+ device float * dst_ptr = (device float *) (dst + i3*nb3 + i2*nb2 + i1*nb1);
+
+ if (i1 < ne01 && i2 < ne02 && i3 < ne03) {
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ if (i0 < ne00) {
+ dst_ptr[i0] = src0_ptr[i0];
+ } else {
+ dst_ptr[i0] = 0.0f;
+ }
+ }
+
+ return;
+ }
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ dst_ptr[i0] = 0.0f;
+ }
+}
+
+kernel void kernel_arange_f32(
+ device char * dst,
+ constant int64_t & ne0,
+ constant float & start,
+ constant float & step,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+
+ device float * dst_ptr = (device float *) dst;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ dst_ptr[i0] = start + step * i0;
+ }
+}
+
+kernel void kernel_timestep_embedding_f32(
+ device const char * src0,
+ device char * dst,
+ constant uint64_t & nb1,
+ constant int & dim,
+ constant int & max_period,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+
+ int i = tgpig.x;
+ device float * embed_data = (device float *)(dst + i*nb1);
+
+ int half_ = dim / 2;
+ for (int j = tpitg.x; j < half_; j += ntg.x) {
+ float timestep = ((device float *)src0)[i];
+ float freq = (float)exp(-log((float)max_period) * j / half_);
+ float arg = timestep * freq;
+ embed_data[j ] = cos(arg);
+ embed_data[j + half_] = sin(arg);
+ }
+
+ if (dim % 2 != 0 && tpitg.x == 0) {
+ embed_data[dim] = 0.f;
+ }
+}
+
+// bitonic sort implementation following the CUDA kernels as reference
+typedef void (argsort_t)(
+ device const float * x,
+ device int32_t * dst,
+ constant int64_t & ncols,
+ constant int64_t & ncols_pad,
+ threadgroup int32_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]]);
+
+template<ggml_sort_order order>
+kernel void kernel_argsort_f32_i32(
+ device const float * x,
+ device int32_t * dst,
+ constant int64_t & ncols,
+ constant int64_t & ncols_pad,
+ threadgroup int32_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]]) {
+ // bitonic sort
+ int col = tpitg[0];
+ int row = tgpig[1];
+
+ if (col >= ncols_pad) return;
+
+ device const float * x_row = x + row * ncols;
+ threadgroup int32_t * dst_row = shared_values;
+
+ // initialize indices
+ dst_row[col] = col;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (int k = 2; k <= ncols_pad; k *= 2) {
+ for (int j = k / 2; j > 0; j /= 2) {
+ int ixj = col ^ j;
+ if (ixj > col) {
+ if ((col & k) == 0) {
+ if (dst_row[col] >= ncols ||
+ (dst_row[ixj] < ncols && (order == GGML_SORT_ORDER_ASC ?
+ x_row[dst_row[col]] > x_row[dst_row[ixj]] :
+ x_row[dst_row[col]] < x_row[dst_row[ixj]]))
+ ) {
+ SWAP(dst_row[col], dst_row[ixj]);
+ }
+ } else {
+ if (dst_row[ixj] >= ncols ||
+ (dst_row[col] < ncols && (order == GGML_SORT_ORDER_ASC ?
+ x_row[dst_row[col]] < x_row[dst_row[ixj]] :
+ x_row[dst_row[col]] > x_row[dst_row[ixj]]))
+ ) {
+ SWAP(dst_row[col], dst_row[ixj]);
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ }
+
+ // copy the result to dst without the padding
+ if (col < ncols) {
+ dst[row * ncols + col] = dst_row[col];
+ }
+}
+
+template [[host_name("kernel_argsort_f32_i32_asc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_ASC>;
+template [[host_name("kernel_argsort_f32_i32_desc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_DESC>;
+
+kernel void kernel_leaky_relu_f32(
+ device const float * src0,
+ device float * dst,
+ constant float & slope,
+ uint tpig[[thread_position_in_grid]]) {
+ dst[tpig] = src0[tpig] > 0.0f ? src0[tpig] : src0[tpig] * slope;
+}
+
+typedef void (flash_attn_ext_f16_t)(
+ device const char * q,
+ device const char * k,
+ device const char * v,
+ device const char * mask,
+ device float * dst,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant uint64_t & nb21,
+ constant uint64_t & nb22,
+ constant uint64_t & nb23,
+ constant uint64_t & nb31,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant float & scale,
+ constant float & max_bias,
+ constant float & m0,
+ constant float & m1,
+ constant uint32_t & n_head_log2,
+ constant float & logit_softcap,
+ threadgroup half * shared,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]],
+ ushort tiisg[[thread_index_in_simdgroup]],
+ ushort sgitg[[simdgroup_index_in_threadgroup]]);
+
+// ref: https://arxiv.org/pdf/2307.08691.pdf
+template<int64_t D, int64_t Q = 8, int64_t C = 32> // head size, queries per threadgroup, cache items per threadgroup
+kernel void kernel_flash_attn_ext_f16(
+ device const char * q,
+ device const char * k,
+ device const char * v,
+ device const char * mask,
+ device float * dst,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant uint64_t & nb21,
+ constant uint64_t & nb22,
+ constant uint64_t & nb23,
+ constant uint64_t & nb31,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant float & scale,
+ constant float & max_bias,
+ constant float & m0,
+ constant float & m1,
+ constant uint32_t & n_head_log2,
+ constant float & logit_softcap,
+ threadgroup half * shared [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]],
+ ushort tiisg[[thread_index_in_simdgroup]],
+ ushort sgitg[[simdgroup_index_in_threadgroup]]) {
+ const short nsg = ntg.y; // number of simdgroups
+
+ const short iq3 = tgpig[2];
+ const short iq2 = tgpig[1];
+ const short iq1 = tgpig[0]*Q;
+
+ const short D4 = D/4;
+ const short D8 = D/8;
+ //const short Q8 = Q/8;
+ const short NW = N_SIMDWIDTH;
+ const short SH = (C + Q); // shared memory per simdgroup in (half)
+
+ const short T = D + 2*nsg*SH; // shared memory size per query in (half)
+ const short TF = T/2; // shared memory size per query in (float)
+ const short T4 = T/4; // shared memory size per query in (half4)
+
+ threadgroup half * sq = (threadgroup half *) (shared + 0*D); // holds the query data
+ threadgroup half4 * sq4 = (threadgroup half4 *) (shared + 0*D); // same as above but in half4
+ threadgroup float * ss = (threadgroup float *) (shared + 2*sgitg*SH + 1*D); // scratch buffer for attention and diagonal matrix
+
+ // store the result for all queries in local memory in 8x8 matrices (the O matrix from the paper)
+ simdgroup_half8x8 lo[D8];
+
+ // load heads from Q to shared memory
+ for (short j = sgitg; j < Q; j += nsg) {
+ device const float4 * q4 = (device const float4 *) ((device const char *) q + ((iq1 + j)*nb01 + iq2*nb02 + iq3*nb03));
+
+ for (short i = tiisg; i < D4; i += NW) {
+ if (iq1 + j < ne01) {
+ sq4[j*T4 + i] = (half4) q4[i];
+ } else {
+ sq4[j*T4 + i] = 0.0h;
+ }
+ }
+ }
+
+ // zero out lo
+ for (short i = 0; i < D8; ++i) {
+ lo[i] = make_filled_simdgroup_matrix<half, 8>(0.0h);
+ }
+
+ // zero out shared memory SH
+ for (short j = 0; j < Q; ++j) {
+ for (short i = tiisg; i < SH; i += NW) {
+ ss[j*TF + i] = 0.0f;
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ {
+ float S[Q] = { [0 ... Q-1] = 0.0h };
+ float M[Q] = { [0 ... Q-1] = -FLT_MAX/2 };
+
+ // assume K and V are same shape
+ const short ne22 = ne12;
+ const short ne23 = ne13;
+
+ // broadcast
+ const short rk2 = ne02/ne12;
+ const short rk3 = ne03/ne13;
+
+ const short rv2 = ne02/ne22;
+ const short rv3 = ne03/ne23;
+
+ // k indices
+ const short ik2 = iq2/rk2;
+ const short ik3 = iq3/rk3;
+
+ // v indices
+ const short iv2 = iq2/rv2;
+ const short iv3 = iq3/rv3;
+
+ // load the queries from shared memory into local memory
+ simdgroup_half8x8 mq[D8];
+
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_load(mq[i], sq + i*8, T);
+ }
+
+ // pointer to the mask
+ device const half * mp = (device const half *) (mask + iq1*nb31);
+
+ float slope = 1.0f;
+
+ // ALiBi
+ if (max_bias > 0.0f) {
+ const uint32_t h = iq2;
+
+ const float base = h < n_head_log2 ? m0 : m1;
+ const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
+
+ slope = pow(base, exph);
+ }
+
+ // loop over the KV cache
+ // each simdgroup handles blocks of Q rows and C columns
+ for (int ic0 = 0; ic0 < ne11; ic0 += C*nsg) {
+ const int ic = ic0 + C*sgitg;
+ if (ic >= ne11) {
+ break;
+ }
+
+ // Q*K^T
+ {
+ for (short cc = 0; cc < C/8; ++cc) {
+ simdgroup_float8x8 mqk = make_filled_simdgroup_matrix<float, 8>(0.h);
+
+ device const half * pk = (device const half *) ((device const char *) k + ((ic + 8*cc)*nb11 + ik2*nb12 + ik3*nb13));
+
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_half8x8 mk;
+ simdgroup_load(mk, pk + i*8, nb11/sizeof(half), 0, true); // transpose
+
+ simdgroup_multiply_accumulate(mqk, mq[i], mk, mqk);
+ }
+
+ simdgroup_store(mqk, ss + 8*cc, TF, 0, false);
+ }
+ }
+
+ // used to detect blocks full of -INF
+ float smax = -INFINITY;
+
+ // online softmax
+ {
+ float ms[Q];
+
+ for (short j = 0; j < Q; ++j) {
+ const float m = M[j];
+
+ // scale and apply the logitcap / mask
+ float s = ss[j*TF + tiisg]*scale;
+
+ if (logit_softcap != 0.0f) {
+ s = logit_softcap*precise::tanh(s);
+ }
+
+ if (mask != q) {
+ // mqk = mqk + mask*slope
+ s += slope*mp[ic + j*nb31/sizeof(half) + tiisg];
+ }
+
+ smax = simd_max(max(smax, s));
+ M[j] = simd_max(max(M[j], s));
+
+ ms[j] = exp(m - M[j]);
+ const float vs = exp(s - M[j]);
+
+ S[j] = S[j]*ms[j] + simd_sum(vs);
+
+ // the P matrix from the paper (Q rows, C columns)
+ ss[j*TF + tiisg] = vs;
+ }
+
+ // create a QxQ diagonal matrix for rescaling the output
+ if (tiisg < Q) {
+ ss[tiisg*TF + C + tiisg] = ms[tiisg];
+ }
+ }
+
+ // skip -INF blocks
+ if (smax == -INFINITY) {
+ continue;
+ }
+
+ // O = diag(ms)*O
+ {
+ simdgroup_float8x8 mm;
+ simdgroup_load(mm, ss + C, TF, 0, false);
+
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_multiply(lo[i], mm, lo[i]);
+ }
+ }
+
+ // O = O + (Q*K^T)*V
+ {
+ for (short cc = 0; cc < C/8; ++cc) {
+ device const half * pv = (device const half *) ((device const char *) v + ((ic + 8*cc)*nb21 + iv2*nb22 + iv3*nb23));
+
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_half8x8 mk;
+ simdgroup_load(mk, pv + i*8, nb21/sizeof(half), 0, false);
+
+ simdgroup_float8x8 mv;
+ simdgroup_load(mv, ss + 8*cc, TF, 0, false);
+
+ simdgroup_multiply_accumulate(lo[i], mv, mk, lo[i]);
+ }
+ }
+ }
+ }
+
+ // these are needed for reducing the results from the simdgroups (reuse the ss buffer)
+ for (short j = 0; j < Q; ++j) {
+ if (tiisg == 0) {
+ ss[j*TF + 0] = S[j];
+ ss[j*TF + 1] = M[j];
+ }
+ }
+ }
+
+ // reduce the warps sequentially
+ for (short sg = 1; sg < nsg; ++sg) {
+ float S = { 0.0h };
+ float M = { -FLT_MAX/2 };
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // each simdgroup stores its output to shared memory, reusing sq
+ if (sgitg == sg) {
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_store(lo[i], sq + i*8, T, 0, false);
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // the first simdgroup accumulates the results from the other simdgroups
+ if (sgitg == 0) {
+ for (short j = 0; j < Q; ++j) {
+ const float S0 = ss[j*TF + 0];
+ const float S1 = ss[j*TF + sg*SH + 0];
+
+ const float M0 = ss[j*TF + 1];
+ const float M1 = ss[j*TF + sg*SH + 1];
+
+ M = max(M0, M1);
+
+ const float ms0 = exp(M0 - M);
+ const float ms1 = exp(M1 - M);
+
+ S = S0*ms0 + S1*ms1;
+
+ if (tiisg == 0) {
+ ss[j*TF + 0] = S;
+ ss[j*TF + 1] = M;
+
+ ss[j*TF + C + j ] = ms0;
+ ss[j*TF + C + j + sg*SH] = ms1;
+ }
+ }
+
+ // O_0 = diag(ms0)*O_0 + diag(ms1)*O_1
+ {
+ simdgroup_half8x8 t;
+ simdgroup_float8x8 ms0;
+ simdgroup_float8x8 ms1;
+
+ simdgroup_load(ms0, ss + C, TF, 0, false);
+ simdgroup_load(ms1, ss + C + sg*SH, TF, 0, false);
+
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_load (t, sq + i*8, T, 0, false);
+ simdgroup_multiply(t, ms1, t);
+
+ simdgroup_multiply_accumulate(lo[i], ms0, lo[i], t);
+ }
+ }
+ }
+ }
+
+ // store result to shared memory (reuse sq)
+ if (sgitg == 0) {
+ for (short i = 0; i < D8; ++i) {
+ simdgroup_store(lo[i], sq + i*8, T, 0, false);
+ }
+ }
+
+ device float4 * dst4 = (device float4 *) dst;
+
+ // final rescale with 1/S and store to global memory
+ if (sgitg == 0) {
+ for (short j = 0; j < Q && iq1 + j < ne01; ++j) {
+ const float S = ss[j*TF + 0];
+
+ for (short i = tiisg; i < D4; i += NW) {
+ dst4[(iq3*ne2*ne1 + iq2 + (iq1 + j)*ne1)*D4 + i] = (float4) sq4[j*T4 + i]/S;
+ }
+ }
+ }
+}
+
+template [[host_name("kernel_flash_attn_ext_f16_h64" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<64>;
+template [[host_name("kernel_flash_attn_ext_f16_h80" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<80>;
+template [[host_name("kernel_flash_attn_ext_f16_h96" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<96>;
+template [[host_name("kernel_flash_attn_ext_f16_h112")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<112>;
+template [[host_name("kernel_flash_attn_ext_f16_h128")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<128>;
+//template [[host_name("kernel_flash_attn_ext_f16_h256")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<256>;
+
+template<int64_t D, int64_t Q = 1, int64_t C = 32> // head size, queries per threadgroup, cache items per threadgroup
+kernel void kernel_flash_attn_ext_vec_f16(
+ device const char * q,
+ device const char * k,
+ device const char * v,
+ device const char * mask,
+ device float * dst,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant uint64_t & nb21,
+ constant uint64_t & nb22,
+ constant uint64_t & nb23,
+ constant uint64_t & nb31,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant float & scale,
+ constant float & max_bias,
+ constant float & m0,
+ constant float & m1,
+ constant uint32_t & n_head_log2,
+ constant float & logit_softcap,
+ threadgroup half * shared [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]],
+ ushort tiisg[[thread_index_in_simdgroup]],
+ ushort sgitg[[simdgroup_index_in_threadgroup]]) {
+ const short nsg = ntg.y; // number of simdgroups
+
+ const short iq3 = tgpig[2];
+ const short iq2 = tgpig[1];
+ const short iq1 = tgpig[0];
+
+ const short D4 = D/4;
+ const short NW = N_SIMDWIDTH;
+ const short SH = (C + Q); // shared memory per simdgroup in (half)
+
+ const short T = D + 2*nsg*SH; // shared memory size per query in (half)
+
+ float slope = 1.0f;
+
+ // ALiBi
+ if (max_bias > 0.0f) {
+ const uint32_t h = iq2;
+
+ const float base = h < n_head_log2 ? m0 : m1;
+ const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1;
+
+ slope = pow(base, exp);
+ }
+
+ //threadgroup half * sq = (threadgroup half *) (shared + 0*D); // holds the query data
+ threadgroup half4 * sq4 = (threadgroup half4 *) (shared + 0*D); // same as above but in half4
+ threadgroup float * ss = (threadgroup float *) (shared + 2*sgitg*SH + 1*D); // scratch buffer for attention and diagonal matrix
+ threadgroup float4 * ss4 = (threadgroup float4 *) (shared + 2*sgitg*SH + 1*D); // same as above but in half4
+ threadgroup half4 * sr4 = (threadgroup half4 *) (shared + sgitg*D + 1*T); // scratch buffer for the results
+
+ // store the result for all queries in local memory in 8x8 matrices (the O matrix from the paper)
+ half4 lo[D4/NW];
+
+ // load heads from Q to shared memory
+ device const float4 * q4 = (device const float4 *) ((device const char *) q + (iq1*nb01 + iq2*nb02 + iq3*nb03));
+
+ for (short i = tiisg; i < D4; i += NW) {
+ if (iq1 < ne01) {
+ sq4[i] = (half4) q4[i];
+ } else {
+ sq4[i] = 0.0h;
+ }
+ }
+
+ // zero out lo
+ for (short i = tiisg; i < D4; i += NW) {
+ lo[i/NW] = 0.0h;
+ }
+
+ // zero out shared memory SH
+ for (short i = tiisg; i < SH/4; i += NW) {
+ ss4[i] = 0.0h;
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ {
+ float S = { 0.0h };
+ float M = { -FLT_MAX/2 };
+
+ // assume K and V are same shape
+ const short ne22 = ne12;
+ const short ne23 = ne13;
+
+ // broadcast
+ const short rk2 = ne02/ne12;
+ const short rk3 = ne03/ne13;
+
+ const short rv2 = ne02/ne22;
+ const short rv3 = ne03/ne23;
+
+ // k indices
+ const short ik2 = iq2 / rk2;
+ const short ik3 = iq3 / rk3;
+
+ // v indices
+ const short iv2 = iq2 / rv2;
+ const short iv3 = iq3 / rv3;
+
+ // load the queries from shared memory into local memory
+ float4 mq[D4];
+
+ for (short ii = 0; ii < D4; ii += NW) {
+ short i = ii + tiisg;
+ mq[i] = (float4) sq4[i];
+ }
+
+ // pointer to the mask
+ device const half4 * mp4 = (device const half4 *) (mask + iq1*nb31);
+
+ // loop over the KV cache
+ // each simdgroup handles blocks of Q rows and C columns
+ for (int ic0 = 0; ic0 < ne11; ic0 += C*nsg) {
+ const int ic = ic0 + C*sgitg;
+ if (ic >= ne11) {
+ break;
+ }
+
+ // Q*K^T
+ {
+#pragma unroll
+ for (short cc = 0; cc < C/4; ++cc) {
+ float4 mqk = { 0.0h };
+
+ device const half4 * pk4 = (device const half4 *) ((device const char *) k + ((ic + 4*cc)*nb11 + ik2*nb12 + ik3*nb13));
+
+#pragma unroll
+ for (short ii = 0; ii < D4; ii += NW) {
+ const short i = ii + tiisg;
+
+ float4x4 mk;
+ mk[0] = (float4) pk4[i + 0*(nb11/8)];
+ mk[1] = (float4) pk4[i + 1*(nb11/8)];
+ mk[2] = (float4) pk4[i + 2*(nb11/8)];
+ mk[3] = (float4) pk4[i + 3*(nb11/8)];
+
+ mqk += (float4) (mq[i] * mk);
+ }
+
+ // reduce the results from the threads in the simdgroup
+ mqk += simd_shuffle_down(mqk, 16);
+ mqk += simd_shuffle_down(mqk, 8);
+ mqk += simd_shuffle_down(mqk, 4);
+ mqk += simd_shuffle_down(mqk, 2);
+ mqk += simd_shuffle_down(mqk, 1);
+
+ // mqk = mqk*scale + mask*slope
+ if (tiisg == 0) {
+ mqk *= scale;
+
+ if (logit_softcap != 0.0f) {
+ mqk = logit_softcap*precise::tanh(mqk);
+ }
+
+ mqk += (mask != q) ? ((float4) mp4[ic/4 + cc])*slope : (float4) 0.0f;
+
+ ss4[cc] = mqk;
+ }
+ }
+ }
+
+ // online softmax
+ {
+ const short p = tiisg;
+
+ const float m = M;
+ const float s = ss[p];
+
+ M = simd_max(max(M, s));
+
+ const float ms = exp(m - M);
+ const float vs = exp(s - M);
+
+ S = S*ms + simd_sum(vs);
+
+ // the P matrix from the paper (Q rows, C columns)
+ ss[p] = vs;
+
+ // O = diag(ms)*O
+#pragma unroll
+ for (short ii = 0; ii < D4; ii += NW) {
+ const short i = ii + tiisg;
+ lo[i/NW] *= ms;
+ }
+ }
+
+ // O = O + (Q*K^T)*V
+ {
+#pragma unroll
+ for (short cc = 0; cc < C/4; ++cc) {
+ device const half4 * pv4 = (device const half4 *) ((device const char *) v + ((ic + 4*cc)*nb21 + iv2*nb22 + iv3*nb23));
+
+#pragma unroll
+ for (short ii = 0; ii < D4; ii += NW) {
+ const short i = ii + tiisg;
+
+ lo[i/NW] += pv4[i + 0*(nb21/8)] * ss[4*cc + 0];
+ lo[i/NW] += pv4[i + 1*(nb21/8)] * ss[4*cc + 1];
+ lo[i/NW] += pv4[i + 2*(nb21/8)] * ss[4*cc + 2];
+ lo[i/NW] += pv4[i + 3*(nb21/8)] * ss[4*cc + 3];
+ }
+ }
+ }
+
+ }
+
+ // these are needed for reducing the results from the simdgroups (reuse the ss buffer)
+ if (tiisg == 0) {
+ ss[0] = S;
+ ss[1] = M;
+ }
+ }
+
+ // store results to shared memory
+ for (short ii = 0; ii < D4; ii += NW) {
+ short i = ii + tiisg;
+ sr4[i] = lo[ii/NW];
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // parallel reduce
+ for (short r = nsg/2; r > 0; r >>= 1) {
+ if (sgitg < r) {
+ const float S0 = ss[ 0];
+ const float S1 = ss[r*SH + 0];
+
+ const float M0 = ss[ 1];
+ const float M1 = ss[r*SH + 1];
+
+ const float M = max(M0, M1);
+
+ const float ms0 = exp(M0 - M);
+ const float ms1 = exp(M1 - M);
+
+ const float S = S0*ms0 + S1*ms1;
+
+ if (tiisg == 0) {
+ ss[0] = S;
+ ss[1] = M;
+ }
+
+ // O_0 = diag(ms0)*O_0 + diag(ms1)*O_1
+ for (short ii = 0; ii < D4; ii += NW) {
+ short i = ii + tiisg;
+ sr4[i] = sr4[i]*ms0 + sr4[i + r*D4]*ms1;
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ device float4 * dst4 = (device float4 *) dst;
+
+ // final rescale with 1/S and store to global memory
+ if (sgitg == 0) {
+ const float S = ss[0];
+
+ for (short ii = 0; ii < D4; ii += NW) {
+ short i = ii + tiisg;
+ dst4[(iq3*ne2*ne1 + iq2 + (iq1)*ne1)*D4 + i] = (float4) sr4[i]/S;
+ }
+ }
+}
+
+template [[host_name("kernel_flash_attn_ext_vec_f16_h128")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_vec_f16<128>;
+//template [[host_name("kernel_flash_attn_ext_vec_f16_h256")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_vec_f16<256>;
+
+template<typename T0, typename T1>
+kernel void kernel_cpy(
+ device const void * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0);
+
+ device T1 * dst_data = (device T1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x; i00 < ne00; i00 += ntg.x) {
+ device const T0 * src = (device T0 *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+ dst_data[i00] = (T1) src[0];
+ }
+}
+
+typedef decltype(kernel_cpy<float, float>) kernel_cpy_t;
+
+template [[host_name("kernel_cpy_f32_f32")]] kernel kernel_cpy_t kernel_cpy<float, float>;
+template [[host_name("kernel_cpy_f32_f16")]] kernel kernel_cpy_t kernel_cpy<float, half>;
+template [[host_name("kernel_cpy_f16_f16")]] kernel kernel_cpy_t kernel_cpy<half, half>;
+template [[host_name("kernel_cpy_f16_f32")]] kernel kernel_cpy_t kernel_cpy<half, float>;
+
+kernel void kernel_cpy_f32_q8_0(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK8_0;
+
+ device block_q8_0 * dst_data = (device block_q8_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK8_0; i00 < ne00; i00 += ntg.x*QK8_0) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float amax = 0.0f; // absolute max
+
+ for (int j = 0; j < QK8_0; j++) {
+ const float v = src[j];
+ amax = MAX(amax, fabs(v));
+ }
+
+ const float d = amax / ((1 << 7) - 1);
+ const float id = d ? 1.0f/d : 0.0f;
+
+ dst_data[i00/QK8_0].d = d;
+
+ for (int j = 0; j < QK8_0; ++j) {
+ const float x0 = src[j]*id;
+
+ dst_data[i00/QK8_0].qs[j] = round(x0);
+ }
+ }
+}
+
+kernel void kernel_cpy_f32_q4_0(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_0;
+
+ device block_q4_0 * dst_data = (device block_q4_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK4_0; i00 < ne00; i00 += ntg.x*QK4_0) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float amax = 0.0f; // absolute max
+ float max = 0.0f;
+
+ for (int j = 0; j < QK4_0; j++) {
+ const float v = src[j];
+ if (amax < fabs(v)) {
+ amax = fabs(v);
+ max = v;
+ }
+ }
+
+ const float d = max / -8;
+ const float id = d ? 1.0f/d : 0.0f;
+
+ dst_data[i00/QK4_0].d = d;
+
+ for (int j = 0; j < QK4_0/2; ++j) {
+ const float x0 = src[0 + j]*id;
+ const float x1 = src[QK4_0/2 + j]*id;
+
+ const uint8_t xi0 = MIN(15, (int8_t)(x0 + 8.5f));
+ const uint8_t xi1 = MIN(15, (int8_t)(x1 + 8.5f));
+
+ dst_data[i00/QK4_0].qs[j] = xi0;
+ dst_data[i00/QK4_0].qs[j] |= xi1 << 4;
+ }
+ }
+}
+
+kernel void kernel_cpy_f32_q4_1(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_1;
+
+ device block_q4_1 * dst_data = (device block_q4_1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK4_1; i00 < ne00; i00 += ntg.x*QK4_1) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float min = FLT_MAX;
+ float max = -FLT_MAX;
+
+ for (int j = 0; j < QK4_1; j++) {
+ const float v = src[j];
+ if (min > v) min = v;
+ if (max < v) max = v;
+ }
+
+ const float d = (max - min) / ((1 << 4) - 1);
+ const float id = d ? 1.0f/d : 0.0f;
+
+ dst_data[i00/QK4_1].d = d;
+ dst_data[i00/QK4_1].m = min;
+
+ for (int j = 0; j < QK4_1/2; ++j) {
+ const float x0 = (src[0 + j] - min)*id;
+ const float x1 = (src[QK4_1/2 + j] - min)*id;
+
+ const uint8_t xi0 = MIN(15, (int8_t)(x0 + 0.5f));
+ const uint8_t xi1 = MIN(15, (int8_t)(x1 + 0.5f));
+
+ dst_data[i00/QK4_1].qs[j] = xi0;
+ dst_data[i00/QK4_1].qs[j] |= xi1 << 4;
+ }
+ }
+}
+
+kernel void kernel_cpy_f32_q5_0(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK5_0;
+
+ device block_q5_0 * dst_data = (device block_q5_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK5_0; i00 < ne00; i00 += ntg.x*QK5_0) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float amax = 0.0f; // absolute max
+ float max = 0.0f;
+
+ for (int j = 0; j < QK5_0; j++) {
+ const float v = src[j];
+ if (amax < fabs(v)) {
+ amax = fabs(v);
+ max = v;
+ }
+ }
+
+ const float d = max / -16;
+ const float id = d ? 1.0f/d : 0.0f;
+
+ dst_data[i00/QK5_0].d = d;
+
+ uint32_t qh = 0;
+ for (int j = 0; j < QK5_0/2; ++j) {
+ const float x0 = src[0 + j]*id;
+ const float x1 = src[QK5_0/2 + j]*id;
+
+ const uint8_t xi0 = MIN(31, (int8_t)(x0 + 16.5f));
+ const uint8_t xi1 = MIN(31, (int8_t)(x1 + 16.5f));
+
+ dst_data[i00/QK5_0].qs[j] = (xi0 & 0xf) | ((xi1 & 0xf) << 4);
+ qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
+ qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2);
+ }
+ thread const uint8_t * qh8 = (thread const uint8_t *)&qh;
+ for (int j = 0; j < 4; ++j) {
+ dst_data[i00/QK5_0].qh[j] = qh8[j];
+ }
+ }
+}
+
+kernel void kernel_cpy_f32_q5_1(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK5_1;
+
+ device block_q5_1 * dst_data = (device block_q5_1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK5_1; i00 < ne00; i00 += ntg.x*QK5_1) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float max = src[0];
+ float min = src[0];
+
+ for (int j = 1; j < QK5_1; j++) {
+ const float v = src[j];
+ min = v < min ? v : min;
+ max = v > max ? v : max;
+ }
+
+ const float d = (max - min) / 31;
+ const float id = d ? 1.0f/d : 0.0f;
+
+ dst_data[i00/QK5_1].d = d;
+ dst_data[i00/QK5_1].m = min;
+
+ uint32_t qh = 0;
+ for (int j = 0; j < QK5_1/2; ++j) {
+ const float x0 = (src[0 + j] - min)*id;
+ const float x1 = (src[QK5_1/2 + j] - min)*id;
+
+ const uint8_t xi0 = (uint8_t)(x0 + 0.5f);
+ const uint8_t xi1 = (uint8_t)(x1 + 0.5f);
+
+ dst_data[i00/QK5_1].qs[j] = (xi0 & 0xf) | ((xi1 & 0xf) << 4);
+ qh |= ((xi0 & 0x10u) >> 4) << (j + 0);
+ qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_1/2);
+ }
+ thread const uint8_t * qh8 = (thread const uint8_t *)&qh;
+ for (int j = 0; j < 4; ++j) {
+ dst_data[i00/QK5_1].qh[j] = qh8[j];
+ }
+ }
+}
+
+static inline int best_index_int8(int n, constant float * val, float x) {
+ if (x <= val[0]) return 0;
+ if (x >= val[n-1]) return n-1;
+ int ml = 0, mu = n-1;
+ while (mu-ml > 1) {
+ int mav = (ml+mu)/2;
+ if (x < val[mav]) mu = mav; else ml = mav;
+ }
+ return x - val[mu-1] < val[mu] - x ? mu-1 : mu;
+}
+
+constexpr constant static float kvalues_iq4nl_f[16] = {
+ -127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f
+};
+
+kernel void kernel_cpy_f32_iq4_nl(
+ device const float * src0,
+ device void * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+ const int64_t i03 = tgpig[2];
+ const int64_t i02 = tgpig[1];
+ const int64_t i01 = tgpig[0];
+
+ const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00;
+
+ const int64_t i3 = n / (ne2*ne1*ne0);
+ const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0);
+ const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0;
+ const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_NL;
+
+ device block_iq4_nl * dst_data = (device block_iq4_nl *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ for (int64_t i00 = tpitg.x*QK4_NL; i00 < ne00; i00 += ntg.x*QK4_NL) {
+ device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00);
+
+ float amax = 0.0f; // absolute max
+ float max = 0.0f;
+
+ for (int j = 0; j < QK4_0; j++) {
+ const float v = src[j];
+ if (amax < fabs(v)) {
+ amax = fabs(v);
+ max = v;
+ }
+ }
+
+ const float d = max / kvalues_iq4nl_f[0];
+ const float id = d ? 1.0f/d : 0.0f;
+
+ float sumqx = 0, sumq2 = 0;
+ for (int j = 0; j < QK4_NL/2; ++j) {
+ const float x0 = src[0 + j]*id;
+ const float x1 = src[QK4_NL/2 + j]*id;
+
+ const uint8_t xi0 = best_index_int8(16, kvalues_iq4nl_f, x0);
+ const uint8_t xi1 = best_index_int8(16, kvalues_iq4nl_f, x1);
+
+ dst_data[i00/QK4_NL].qs[j] = xi0 | (xi1 << 4);
+
+ const float v0 = kvalues_iq4nl_f[xi0];
+ const float v1 = kvalues_iq4nl_f[xi1];
+ const float w0 = src[0 + j]*src[0 + j];
+ const float w1 = src[QK4_NL/2 + j]*src[QK4_NL/2 + j];
+ sumqx += w0*v0*src[j] + w1*v1*src[QK4_NL/2 + j];
+ sumq2 += w0*v0*v0 + w1*v1*v1;
+
+ }
+
+ dst_data[i00/QK4_NL].d = sumq2 > 0 ? sumqx/sumq2 : d;
+
+ }
+}
+
+kernel void kernel_concat(
+ device const char * src0,
+ device const char * src1,
+ device char * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant int64_t & ne03,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant int64_t & ne2,
+ constant int64_t & ne3,
+ constant uint64_t & nb0,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ constant uint64_t & nb3,
+ constant int32_t & dim,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]],
+ uint3 ntg[[threads_per_threadgroup]]) {
+
+ const int64_t i3 = tgpig.z;
+ const int64_t i2 = tgpig.y;
+ const int64_t i1 = tgpig.x;
+
+ int64_t o[4] = {0, 0, 0, 0};
+ o[dim] = dim == 0 ? ne00 : (dim == 1 ? ne01 : (dim == 2 ? ne02 : ne03));
+
+ device const float * x;
+
+ for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) {
+ if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
+ x = (device const float *)(src0 + (i3 )*nb03 + (i2 )*nb02 + (i1 )*nb01 + (i0 )*nb00);
+ } else {
+ x = (device const float *)(src1 + (i3 - o[3])*nb13 + (i2 - o[2])*nb12 + (i1 - o[1])*nb11 + (i0 - o[0])*nb10);
+ }
+
+ device float * y = (device float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
+
+ *y = *x;
+ }
+}
+
+void kernel_mul_mv_q2_K_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q2_K * x = (device const block_q2_K *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int step = sizeof(block_q2_K) * nb;
+
+ const int ix = tiisg/8; // 0...3
+ const int it = tiisg%8; // 0...7
+ const int iq = it/4; // 0 or 1
+ const int ir = it%4; // 0...3
+ const int is = (8*ir)/16;// 0 or 1
+
+ device const float * y4 = y + ix * QK_K + 128 * iq + 8 * ir;
+
+ for (int ib = ix; ib < nb; ib += 4) {
+
+ float4 sumy = {0.f, 0.f, 0.f, 0.f};
+ for (int i = 0; i < 8; ++i) {
+ yl[i+ 0] = y4[i+ 0]; sumy[0] += yl[i+ 0];
+ yl[i+ 8] = y4[i+32]; sumy[1] += yl[i+ 8];
+ yl[i+16] = y4[i+64]; sumy[2] += yl[i+16];
+ yl[i+24] = y4[i+96]; sumy[3] += yl[i+24];
+ }
+
+ device const uint8_t * sc = (device const uint8_t *)x[ib].scales + 8*iq + is;
+ device const uint16_t * qs = (device const uint16_t *)x[ib].qs + 16 * iq + 4 * ir;
+ device const half * dh = &x[ib].d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ float4 acc1 = {0.f, 0.f, 0.f, 0.f};
+ float4 acc2 = {0.f, 0.f, 0.f, 0.f};
+ for (int i = 0; i < 8; i += 2) {
+ acc1[0] += yl[i+ 0] * (qs[i/2] & 0x0003);
+ acc2[0] += yl[i+ 1] * (qs[i/2] & 0x0300);
+ acc1[1] += yl[i+ 8] * (qs[i/2] & 0x000c);
+ acc2[1] += yl[i+ 9] * (qs[i/2] & 0x0c00);
+ acc1[2] += yl[i+16] * (qs[i/2] & 0x0030);
+ acc2[2] += yl[i+17] * (qs[i/2] & 0x3000);
+ acc1[3] += yl[i+24] * (qs[i/2] & 0x00c0);
+ acc2[3] += yl[i+25] * (qs[i/2] & 0xc000);
+ }
+ float dall = dh[0];
+ float dmin = dh[1] * 1.f/16.f;
+ sumf[row] += dall * ((acc1[0] + 1.f/256.f * acc2[0]) * (sc[0] & 0xF) * 1.f/ 1.f +
+ (acc1[1] + 1.f/256.f * acc2[1]) * (sc[2] & 0xF) * 1.f/ 4.f +
+ (acc1[2] + 1.f/256.f * acc2[2]) * (sc[4] & 0xF) * 1.f/16.f +
+ (acc1[3] + 1.f/256.f * acc2[3]) * (sc[6] & 0xF) * 1.f/64.f) -
+ dmin * (sumy[0] * (sc[0] & 0xF0) + sumy[1] * (sc[2] & 0xF0) + sumy[2] * (sc[4] & 0xF0) + sumy[3] * (sc[6] & 0xF0));
+
+ qs += step/2;
+ sc += step;
+ dh += step/2;
+ }
+
+ y4 += 4 * QK_K;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_q2_K_f32")]]
+kernel void kernel_mul_mv_q2_K_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_q2_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_q3_K_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+
+ const int64_t r0 = tgpig.x;
+ const int64_t r1 = tgpig.y;
+ const int64_t im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * 2;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q3_K * x = (device const block_q3_K *) src0 + first_row*nb + offset0;
+ device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+
+ //const uint16_t kmask1 = 0x3030;
+ //const uint16_t kmask2 = 0x0f0f;
+
+ const int tid = tiisg/4;
+ const int ix = tiisg%4;
+ const int ip = tid/4; // 0 or 1
+ const int il = 2*((tid%4)/2); // 0 or 2
+ const int ir = tid%2;
+ const int n = 8;
+ const int l0 = n*ir;
+
+ // One would think that the Metal compiler would figure out that ip and il can only have
+ // 4 possible states, and optimize accordingly. Well, no. It needs help, and we do it
+ // with these two tales.
+ //
+ // Possible masks for the high bit
+ const ushort4 mm[4] = {{0x0001, 0x0100, 0x0002, 0x0200}, // ip = 0, il = 0
+ {0x0004, 0x0400, 0x0008, 0x0800}, // ip = 0, il = 2
+ {0x0010, 0x1000, 0x0020, 0x2000}, // ip = 1, il = 0
+ {0x0040, 0x4000, 0x0080, 0x8000}}; // ip = 1, il = 2
+
+ // Possible masks for the low 2 bits
+ const int4 qm[2] = {{0x0003, 0x0300, 0x000c, 0x0c00}, {0x0030, 0x3000, 0x00c0, 0xc000}};
+
+ const ushort4 hm = mm[2*ip + il/2];
+
+ const int shift = 2*il;
+ const float v1 = il == 0 ? 4.f : 64.f;
+ const float v2 = 4.f * v1;
+
+ const uint16_t s_shift1 = 4*ip;
+ const uint16_t s_shift2 = s_shift1 + il;
+
+ const int q_offset = 32*ip + l0;
+ const int y_offset = 128*ip + 32*il + l0;
+
+ const int step = sizeof(block_q3_K) * nb / 2;
+
+ device const float * y1 = yy + ix*QK_K + y_offset;
+
+ uint32_t scales32, aux32;
+ thread uint16_t * scales16 = (thread uint16_t *)&scales32;
+ thread const int8_t * scales = (thread const int8_t *)&scales32;
+
+ float sumf1[2] = {0.f};
+ float sumf2[2] = {0.f};
+ for (int i = ix; i < nb; i += 4) {
+
+ for (int l = 0; l < 8; ++l) {
+ yl[l+ 0] = y1[l+ 0];
+ yl[l+ 8] = y1[l+16];
+ yl[l+16] = y1[l+32];
+ yl[l+24] = y1[l+48];
+ }
+
+ device const uint16_t * q = (device const uint16_t *)(x[i].qs + q_offset);
+ device const uint16_t * h = (device const uint16_t *)(x[i].hmask + l0);
+ device const uint16_t * a = (device const uint16_t *)(x[i].scales);
+ device const half * dh = &x[i].d;
+
+ for (int row = 0; row < 2; ++row) {
+
+ const float d_all = (float)dh[0];
+
+ scales16[0] = a[4];
+ scales16[1] = a[5];
+ aux32 = ((scales32 >> s_shift2) << 4) & 0x30303030;
+ scales16[0] = a[il+0];
+ scales16[1] = a[il+1];
+ scales32 = ((scales32 >> s_shift1) & 0x0f0f0f0f) | aux32;
+
+ float s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0;
+ for (int l = 0; l < n; l += 2) {
+ const int32_t qs = q[l/2];
+ s1 += yl[l+0] * (qs & qm[il/2][0]);
+ s2 += yl[l+1] * (qs & qm[il/2][1]);
+ s3 += ((h[l/2] & hm[0]) ? 0.f : yl[l+0]) + ((h[l/2] & hm[1]) ? 0.f : yl[l+1]);
+ s4 += yl[l+16] * (qs & qm[il/2][2]);
+ s5 += yl[l+17] * (qs & qm[il/2][3]);
+ s6 += ((h[l/2] & hm[2]) ? 0.f : yl[l+16]) + ((h[l/2] & hm[3]) ? 0.f : yl[l+17]);
+ }
+ float d1 = d_all * (s1 + 1.f/256.f * s2 - s3*v1);
+ float d2 = d_all * (s4 + 1.f/256.f * s5 - s6*v2);
+ sumf1[row] += d1 * (scales[0] - 32);
+ sumf2[row] += d2 * (scales[2] - 32);
+
+ s1 = s2 = s3 = s4 = s5 = s6 = 0;
+ for (int l = 0; l < n; l += 2) {
+ const int32_t qs = q[l/2+8];
+ s1 += yl[l+8] * (qs & qm[il/2][0]);
+ s2 += yl[l+9] * (qs & qm[il/2][1]);
+ s3 += ((h[l/2+8] & hm[0]) ? 0.f : yl[l+8]) + ((h[l/2+8] & hm[1]) ? 0.f : yl[l+9]);
+ s4 += yl[l+24] * (qs & qm[il/2][2]);
+ s5 += yl[l+25] * (qs & qm[il/2][3]);
+ s6 += ((h[l/2+8] & hm[2]) ? 0.f : yl[l+24]) + ((h[l/2+8] & hm[3]) ? 0.f : yl[l+25]);
+ }
+ d1 = d_all * (s1 + 1.f/256.f * s2 - s3*v1);
+ d2 = d_all * (s4 + 1.f/256.f * s5 - s6*v2);
+ sumf1[row] += d1 * (scales[1] - 32);
+ sumf2[row] += d2 * (scales[3] - 32);
+
+ q += step;
+ h += step;
+ a += step;
+ dh += step;
+
+ }
+
+ y1 += 4 * QK_K;
+
+ }
+
+ for (int row = 0; row < 2; ++row) {
+ const float sumf = (sumf1[row] + 0.25f * sumf2[row]) / (1 << shift);
+ sumf1[row] = simd_sum(sumf);
+ }
+ if (tiisg == 0) {
+ for (int row = 0; row < 2; ++row) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = sumf1[row];
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_q3_K_f32")]]
+kernel void kernel_mul_mv_q3_K_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_q3_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_q4_K_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const uint16_t kmask1 = 0x3f3f;
+ const uint16_t kmask2 = 0x0f0f;
+ const uint16_t kmask3 = 0xc0c0;
+
+ const int ix = tiisg/8; // 0...3
+ const int it = tiisg%8; // 0...7
+ const int iq = it/4; // 0 or 1
+ const int ir = it%4; // 0...3
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+ //const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int first_row = r0 * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q4_K * x = (device const block_q4_K *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[16];
+ float yh[16];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int step = sizeof(block_q4_K) * nb / 2;
+
+ device const float * y4 = y + ix * QK_K + 64 * iq + 8 * ir;
+
+ uint16_t sc16[4];
+ thread const uint8_t * sc8 = (thread const uint8_t *)sc16;
+
+ for (int ib = ix; ib < nb; ib += 4) {
+
+ float4 sumy = {0.f, 0.f, 0.f, 0.f};
+ for (int i = 0; i < 8; ++i) {
+ yl[i+0] = y4[i+ 0]; sumy[0] += yl[i+0];
+ yl[i+8] = y4[i+ 32]; sumy[1] += yl[i+8];
+ yh[i+0] = y4[i+128]; sumy[2] += yh[i+0];
+ yh[i+8] = y4[i+160]; sumy[3] += yh[i+8];
+ }
+
+ device const uint16_t * sc = (device const uint16_t *)x[ib].scales + iq;
+ device const uint16_t * q1 = (device const uint16_t *)x[ib].qs + 16 * iq + 4 * ir;
+ device const half * dh = &x[ib].d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ sc16[0] = sc[0] & kmask1;
+ sc16[1] = sc[2] & kmask1;
+ sc16[2] = ((sc[4] >> 0) & kmask2) | ((sc[0] & kmask3) >> 2);
+ sc16[3] = ((sc[4] >> 4) & kmask2) | ((sc[2] & kmask3) >> 2);
+
+ device const uint16_t * q2 = q1 + 32;
+
+ float4 acc1 = {0.f, 0.f, 0.f, 0.f};
+ float4 acc2 = {0.f, 0.f, 0.f, 0.f};
+ for (int i = 0; i < 8; i += 2) {
+ acc1[0] += yl[i+0] * (q1[i/2] & 0x000F);
+ acc1[1] += yl[i+1] * (q1[i/2] & 0x0F00);
+ acc1[2] += yl[i+8] * (q1[i/2] & 0x00F0);
+ acc1[3] += yl[i+9] * (q1[i/2] & 0xF000);
+ acc2[0] += yh[i+0] * (q2[i/2] & 0x000F);
+ acc2[1] += yh[i+1] * (q2[i/2] & 0x0F00);
+ acc2[2] += yh[i+8] * (q2[i/2] & 0x00F0);
+ acc2[3] += yh[i+9] * (q2[i/2] & 0xF000);
+ }
+
+ float dall = dh[0];
+ float dmin = dh[1];
+ sumf[row] += dall * ((acc1[0] + 1.f/256.f * acc1[1]) * sc8[0] +
+ (acc1[2] + 1.f/256.f * acc1[3]) * sc8[1] * 1.f/16.f +
+ (acc2[0] + 1.f/256.f * acc2[1]) * sc8[4] +
+ (acc2[2] + 1.f/256.f * acc2[3]) * sc8[5] * 1.f/16.f) -
+ dmin * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]);
+
+ q1 += step;
+ sc += step;
+ dh += step;
+ }
+
+ y4 += 4 * QK_K;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_q4_K_f32")]]
+kernel void kernel_mul_mv_q4_K_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_q4_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_q5_K_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+
+ const int64_t r0 = tgpig.x;
+ const int64_t r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * 2;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q5_K * x = (device const block_q5_K *) src0 + first_row*nb + offset0;
+ device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float sumf[2]={0.f};
+
+ const int step = sizeof(block_q5_K) * nb;
+
+ float yl[16], yh[16];
+
+ const uint16_t kmask1 = 0x3f3f;
+ const uint16_t kmask2 = 0x0f0f;
+ const uint16_t kmask3 = 0xc0c0;
+
+ const int tid = tiisg/4;
+ const int ix = tiisg%4;
+ const int iq = tid/4;
+ const int ir = tid%4;
+ const int n = 8;
+
+ const int l0 = n*ir;
+ const int q_offset = 32*iq + l0;
+ const int y_offset = 64*iq + l0;
+
+ const uint8_t hm1 = 1u << (2*iq);
+ const uint8_t hm2 = hm1 << 1;
+ const uint8_t hm3 = hm1 << 4;
+ const uint8_t hm4 = hm2 << 4;
+
+ uint16_t sc16[4];
+ thread const uint8_t * sc8 = (thread const uint8_t *)sc16;
+
+ device const float * y1 = yy + ix*QK_K + y_offset;
+
+ for (int i = ix; i < nb; i += 4) {
+
+ device const uint8_t * q1 = x[i].qs + q_offset;
+ device const uint8_t * qh = x[i].qh + l0;
+ device const half * dh = &x[i].d;
+ device const uint16_t * a = (device const uint16_t *)x[i].scales + iq;
+
+ device const float * y2 = y1 + 128;
+ float4 sumy = {0.f, 0.f, 0.f, 0.f};
+ for (int l = 0; l < 8; ++l) {
+ yl[l+0] = y1[l+ 0]; sumy[0] += yl[l+0];
+ yl[l+8] = y1[l+32]; sumy[1] += yl[l+8];
+ yh[l+0] = y2[l+ 0]; sumy[2] += yh[l+0];
+ yh[l+8] = y2[l+32]; sumy[3] += yh[l+8];
+ }
+
+ for (int row = 0; row < 2; ++row) {
+
+ device const uint8_t * q2 = q1 + 64;
+
+ sc16[0] = a[0] & kmask1;
+ sc16[1] = a[2] & kmask1;
+ sc16[2] = ((a[4] >> 0) & kmask2) | ((a[0] & kmask3) >> 2);
+ sc16[3] = ((a[4] >> 4) & kmask2) | ((a[2] & kmask3) >> 2);
+
+ float4 acc1 = {0.f};
+ float4 acc2 = {0.f};
+ for (int l = 0; l < n; ++l) {
+ uint8_t h = qh[l];
+ acc1[0] += yl[l+0] * (q1[l] & 0x0F);
+ acc1[1] += yl[l+8] * (q1[l] & 0xF0);
+ acc1[2] += yh[l+0] * (q2[l] & 0x0F);
+ acc1[3] += yh[l+8] * (q2[l] & 0xF0);
+ acc2[0] += h & hm1 ? yl[l+0] : 0.f;
+ acc2[1] += h & hm2 ? yl[l+8] : 0.f;
+ acc2[2] += h & hm3 ? yh[l+0] : 0.f;
+ acc2[3] += h & hm4 ? yh[l+8] : 0.f;
+ }
+ const float dall = dh[0];
+ const float dmin = dh[1];
+ sumf[row] += dall * (sc8[0] * (acc1[0] + 16.f*acc2[0]) +
+ sc8[1] * (acc1[1]/16.f + 16.f*acc2[1]) +
+ sc8[4] * (acc1[2] + 16.f*acc2[2]) +
+ sc8[5] * (acc1[3]/16.f + 16.f*acc2[3])) -
+ dmin * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]);
+
+ q1 += step;
+ qh += step;
+ dh += step/2;
+ a += step/2;
+
+ }
+
+ y1 += 4 * QK_K;
+
+ }
+
+ for (int row = 0; row < 2; ++row) {
+ const float tot = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = tot;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_q5_K_f32")]]
+kernel void kernel_mul_mv_q5_K_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_q5_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_q6_K_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const uint8_t kmask1 = 0x03;
+ const uint8_t kmask2 = 0x0C;
+ const uint8_t kmask3 = 0x30;
+ const uint8_t kmask4 = 0xC0;
+
+ const int nb = ne00/QK_K;
+
+ const int64_t r0 = tgpig.x;
+ const int64_t r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int row = 2 * r0 + sgitg;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_q6_K * x = (device const block_q6_K *) src0 + row * nb + offset0;
+ device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float sumf = 0;
+
+ const int tid = tiisg/2;
+ const int ix = tiisg%2;
+ const int ip = tid/8; // 0 or 1
+ const int il = tid%8;
+ const int n = 4;
+ const int l0 = n*il;
+ const int is = 8*ip + l0/16;
+
+ const int y_offset = 128*ip + l0;
+ const int q_offset_l = 64*ip + l0;
+ const int q_offset_h = 32*ip + l0;
+
+ for (int i = ix; i < nb; i += 2) {
+
+ device const uint8_t * q1 = x[i].ql + q_offset_l;
+ device const uint8_t * q2 = q1 + 32;
+ device const uint8_t * qh = x[i].qh + q_offset_h;
+ device const int8_t * sc = x[i].scales + is;
+
+ device const float * y = yy + i * QK_K + y_offset;
+
+ const float dall = x[i].d;
+
+ float4 sums = {0.f, 0.f, 0.f, 0.f};
+ for (int l = 0; l < n; ++l) {
+ sums[0] += y[l+ 0] * ((int8_t)((q1[l] & 0xF) | ((qh[l] & kmask1) << 4)) - 32);
+ sums[1] += y[l+32] * ((int8_t)((q2[l] & 0xF) | ((qh[l] & kmask2) << 2)) - 32);
+ sums[2] += y[l+64] * ((int8_t)((q1[l] >> 4) | ((qh[l] & kmask3) << 0)) - 32);
+ sums[3] += y[l+96] * ((int8_t)((q2[l] >> 4) | ((qh[l] & kmask4) >> 2)) - 32);
+ }
+
+ sumf += dall * (sums[0] * sc[0] + sums[1] * sc[2] + sums[2] * sc[4] + sums[3] * sc[6]);
+
+ }
+
+ const float tot = simd_sum(sumf);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + row] = tot;
+ }
+}
+
+[[host_name("kernel_mul_mv_q6_K_f32")]]
+kernel void kernel_mul_mv_q6_K_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_q6_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+// ======================= "True" 2-bit
+
+void kernel_mul_mv_iq2_xxs_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_iq2_xxs * x = (device const block_iq2_xxs *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values;
+ threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 256);
+ {
+ int nval = 4;
+ int pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) values[pos + i] = iq2xxs_grid[pos + i];
+ nval = 2;
+ pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq2_xxs * xr = x + ibl;
+ device const uint16_t * q2 = xr->qs + 4 * ib;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ const float db = dh[0];
+ device const uint8_t * aux8 = (device const uint8_t *)q2;
+ const uint32_t aux32 = q2[2] | (q2[3] << 16);
+ const float d = db * (0.5f + (aux32 >> 28));
+
+ float sum = 0;
+ for (int l = 0; l < 4; ++l) {
+ const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + aux8[l]);
+ const uint8_t signs = shared_signs[(aux32 >> 7*l) & 127];
+ for (int j = 0; j < 8; ++j) {
+ sum += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
+ }
+ }
+ sumf[row] += d * sum;
+
+ dh += nb*sizeof(block_iq2_xxs)/2;
+ q2 += nb*sizeof(block_iq2_xxs)/2;
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq2_xxs_f32")]]
+kernel void kernel_mul_mv_iq2_xxs_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq2_xxs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_iq2_xs_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_iq2_xs * x = (device const block_iq2_xs *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values;
+ threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 512);
+ {
+ int nval = 8;
+ int pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) values[pos + i] = iq2xs_grid[pos + i];
+ nval = 2;
+ pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq2_xs * xr = x + ibl;
+ device const uint16_t * q2 = xr->qs + 4 * ib;
+ device const uint8_t * sc = xr->scales + ib;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ const float db = dh[0];
+ const uint8_t ls1 = sc[0] & 0xf;
+ const uint8_t ls2 = sc[0] >> 4;
+ const float d1 = db * (0.5f + ls1);
+ const float d2 = db * (0.5f + ls2);
+
+ float sum1 = 0, sum2 = 0;
+ for (int l = 0; l < 2; ++l) {
+ const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + (q2[l] & 511));
+ const uint8_t signs = shared_signs[(q2[l] >> 9)];
+ for (int j = 0; j < 8; ++j) {
+ sum1 += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
+ }
+ }
+ for (int l = 2; l < 4; ++l) {
+ const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + (q2[l] & 511));
+ const uint8_t signs = shared_signs[(q2[l] >> 9)];
+ for (int j = 0; j < 8; ++j) {
+ sum2 += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
+ }
+ }
+ sumf[row] += d1 * sum1 + d2 * sum2;
+
+ dh += nb*sizeof(block_iq2_xs)/2;
+ q2 += nb*sizeof(block_iq2_xs)/2;
+ sc += nb*sizeof(block_iq2_xs);
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq2_xs_f32")]]
+kernel void kernel_mul_mv_iq2_xs_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq2_xs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_iq3_xxs_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_iq3_xxs * x = (device const block_iq3_xxs *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ threadgroup uint32_t * values = (threadgroup uint32_t *)shared_values;
+ threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 256);
+ {
+ int nval = 4;
+ int pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) values[pos + i] = iq3xxs_grid[pos + i];
+ nval = 2;
+ pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq3_xxs * xr = x + ibl;
+ device const uint8_t * q3 = xr->qs + 8 * ib;
+ device const uint16_t * gas = (device const uint16_t *)(xr->qs + QK_K/4) + 2 * ib;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ const float db = dh[0];
+ const uint32_t aux32 = gas[0] | (gas[1] << 16);
+ const float d = db * (0.5f + (aux32 >> 28));
+
+ float2 sum = {0};
+ for (int l = 0; l < 4; ++l) {
+ const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(values + q3[2*l+0]);
+ const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(values + q3[2*l+1]);
+ const uint8_t signs = shared_signs[(aux32 >> 7*l) & 127];
+ for (int j = 0; j < 4; ++j) {
+ sum[0] += yl[8*l + j + 0] * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f);
+ sum[1] += yl[8*l + j + 4] * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f);
+ }
+ }
+ sumf[row] += d * (sum[0] + sum[1]);
+
+ dh += nb*sizeof(block_iq3_xxs)/2;
+ q3 += nb*sizeof(block_iq3_xxs);
+ gas += nb*sizeof(block_iq3_xxs)/2;
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.5f;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq3_xxs_f32")]]
+kernel void kernel_mul_mv_iq3_xxs_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq3_xxs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_iq3_s_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_iq3_s * x = (device const block_iq3_s *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ threadgroup uint32_t * values = (threadgroup uint32_t *)shared_values;
+ {
+ int nval = 8;
+ int pos = (32*sgitg + tiisg)*nval;
+ for (int i = 0; i < nval; ++i) values[pos + i] = iq3s_grid[pos + i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq3_s * xr = x + ibl;
+ device const uint8_t * qs = xr->qs + 8 * ib;
+ device const uint8_t * qh = xr->qh + ib;
+ device const uint8_t * sc = xr->scales + (ib/2);
+ device const uint8_t * signs = xr->signs + 4 * ib;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ const float db = dh[0];
+ const float d = db * (1 + 2*((sc[0] >> 4*(ib%2)) & 0xf));
+
+ float2 sum = {0};
+ for (int l = 0; l < 4; ++l) {
+ const threadgroup uint32_t * table1 = qh[0] & kmask_iq2xs[2*l+0] ? values + 256 : values;
+ const threadgroup uint32_t * table2 = qh[0] & kmask_iq2xs[2*l+1] ? values + 256 : values;
+ const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(table1 + qs[2*l+0]);
+ const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(table2 + qs[2*l+1]);
+ for (int j = 0; j < 4; ++j) {
+ sum[0] += yl[8*l + j + 0] * grid1[j] * select(1, -1, signs[l] & kmask_iq2xs[j+0]);
+ sum[1] += yl[8*l + j + 4] * grid2[j] * select(1, -1, signs[l] & kmask_iq2xs[j+4]);
+ }
+ }
+ sumf[row] += d * (sum[0] + sum[1]);
+
+ dh += nb*sizeof(block_iq3_s)/2;
+ qs += nb*sizeof(block_iq3_s);
+ qh += nb*sizeof(block_iq3_s);
+ sc += nb*sizeof(block_iq3_s);
+ signs += nb*sizeof(block_iq3_s);
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq3_s_f32")]]
+kernel void kernel_mul_mv_iq3_s_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq3_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_iq2_s_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+
+ device const block_iq2_s * x = (device const block_iq2_s *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ //threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values;
+ //{
+ // int nval = 32;
+ // int pos = (32*sgitg + tiisg)*nval;
+ // for (int i = 0; i < nval; ++i) values[pos + i] = iq2s_grid[pos + i];
+ // threadgroup_barrier(mem_flags::mem_threadgroup);
+ //}
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq2_s * xr = x + ibl;
+ device const uint8_t * qs = xr->qs + 4 * ib;
+ device const uint8_t * qh = xr->qh + ib;
+ device const uint8_t * sc = xr->scales + ib;
+ device const uint8_t * signs = qs + QK_K/8;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ const float db = dh[0];
+ const float d1 = db * (0.5f + (sc[0] & 0xf));
+ const float d2 = db * (0.5f + (sc[0] >> 4));
+
+ float2 sum = {0};
+ for (int l = 0; l < 2; ++l) {
+ //const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(values + (qs[l+0] | ((qh[0] << (8-2*l)) & 0x300)));
+ //const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(values + (qs[l+2] | ((qh[0] << (4-2*l)) & 0x300)));
+ constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[l+0] | ((qh[0] << (8-2*l)) & 0x300)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[l+2] | ((qh[0] << (4-2*l)) & 0x300)));
+ for (int j = 0; j < 8; ++j) {
+ sum[0] += yl[8*l + j + 0] * grid1[j] * select(1, -1, signs[l+0] & kmask_iq2xs[j]);
+ sum[1] += yl[8*l + j + 16] * grid2[j] * select(1, -1, signs[l+2] & kmask_iq2xs[j]);
+ }
+ }
+ sumf[row] += d1 * sum[0] + d2 * sum[1];
+
+ dh += nb*sizeof(block_iq2_s)/2;
+ qs += nb*sizeof(block_iq2_s);
+ qh += nb*sizeof(block_iq2_s);
+ sc += nb*sizeof(block_iq2_s);
+ signs += nb*sizeof(block_iq2_s);
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq2_s_f32")]]
+kernel void kernel_mul_mv_iq2_s_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq2_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+void kernel_mul_mv_iq1_s_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_value,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+ device const block_iq1_s * x = (device const block_iq1_s *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ float sumy = 0;
+ for (int i = 0; i < 32; ++i) {
+ yl[i] = y4[i];
+ sumy += yl[i];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq1_s * xr = x + ibl;
+ device const uint8_t * qs = xr->qs + 4 * ib;
+ device const uint16_t * qh = xr->qh + ib;
+ device const half * dh = &xr->d;
+
+ for (int row = 0; row < N_DST; row++) {
+
+ constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 5) & 0x700)));
+ constant uint8_t * grid3 = (constant uint8_t *)(iq1s_grid_gpu + (qs[2] | ((qh[0] << 2) & 0x700)));
+ constant uint8_t * grid4 = (constant uint8_t *)(iq1s_grid_gpu + (qs[3] | ((qh[0] >> 1) & 0x700)));
+
+ float sum = 0;
+ for (int j = 0; j < 4; ++j) {
+ sum += yl[j+ 0] * (grid1[j] & 0xf) + yl[j+ 4] * (grid1[j] >> 4)
+ + yl[j+ 8] * (grid2[j] & 0xf) + yl[j+12] * (grid2[j] >> 4)
+ + yl[j+16] * (grid3[j] & 0xf) + yl[j+20] * (grid3[j] >> 4)
+ + yl[j+24] * (grid4[j] & 0xf) + yl[j+28] * (grid4[j] >> 4);
+ }
+ sumf[row] += (float)dh[0] * (sum + sumy * (qh[0] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA)) * (2*((qh[0] >> 12) & 7) + 1);
+
+ dh += nb*sizeof(block_iq1_s)/2;
+ qs += nb*sizeof(block_iq1_s);
+ qh += nb*sizeof(block_iq1_s)/2;
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+void kernel_mul_mv_iq1_m_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_value,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+
+ const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+ device const block_iq1_m * x = (device const block_iq1_m *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ float yl[32];
+ float sumf[N_DST]={0.f}, all_sum;
+
+ const int nb32 = nb * (QK_K / 32);
+
+ const int ix = tiisg;
+
+ device const float * y4 = y + 32 * ix;
+
+ iq1m_scale_t scale;
+
+ for (int ib32 = ix; ib32 < nb32; ib32 += 32) {
+
+ float4 sumy = {0.f};
+ for (int i = 0; i < 8; ++i) {
+ yl[i+ 0] = y4[i+ 0]; sumy[0] += yl[i+ 0];
+ yl[i+ 8] = y4[i+ 8]; sumy[1] += yl[i+ 8];
+ yl[i+16] = y4[i+16]; sumy[2] += yl[i+16];
+ yl[i+24] = y4[i+24]; sumy[3] += yl[i+24];
+ }
+
+ const int ibl = ib32 / (QK_K / 32);
+ const int ib = ib32 % (QK_K / 32);
+
+ device const block_iq1_m * xr = x + ibl;
+ device const uint8_t * qs = xr->qs + 4 * ib;
+ device const uint8_t * qh = xr->qh + 2 * ib;
+ device const uint16_t * sc = (device const uint16_t *)xr->scales;
+
+ for (int row = 0; row < N_DST; row++) {
+ scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
+
+ constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700)));
+ constant uint8_t * grid3 = (constant uint8_t *)(iq1s_grid_gpu + (qs[2] | ((qh[1] << 8) & 0x700)));
+ constant uint8_t * grid4 = (constant uint8_t *)(iq1s_grid_gpu + (qs[3] | ((qh[1] << 4) & 0x700)));
+
+ float2 sum = {0.f};
+ for (int j = 0; j < 4; ++j) {
+ sum[0] += yl[j+ 0] * (grid1[j] & 0xf) + yl[j+ 4] * (grid1[j] >> 4)
+ + yl[j+ 8] * (grid2[j] & 0xf) + yl[j+12] * (grid2[j] >> 4);
+ sum[1] += yl[j+16] * (grid3[j] & 0xf) + yl[j+20] * (grid3[j] >> 4)
+ + yl[j+24] * (grid4[j] & 0xf) + yl[j+28] * (grid4[j] >> 4);
+ }
+ const float delta1 = sumy[0] * (qh[0] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA) + sumy[1] * (qh[0] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA);
+ const float delta2 = sumy[2] * (qh[1] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA) + sumy[3] * (qh[1] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA);
+
+ sumf[row] += (float)scale.f16 * ((sum[0] + delta1) * (2*((sc[ib/2] >> (6*(ib%2)+0)) & 7) + 1) +
+ (sum[1] + delta2) * (2*((sc[ib/2] >> (6*(ib%2)+3)) & 7) + 1));
+
+ sc += nb*sizeof(block_iq1_m)/2;
+ qs += nb*sizeof(block_iq1_m);
+ qh += nb*sizeof(block_iq1_m);
+ }
+
+ y4 += 32 * 32;
+ }
+
+ for (int row = 0; row < N_DST; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+void kernel_mul_mv_iq4_nl_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values_i8,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ threadgroup float * shared_values = (threadgroup float *)shared_values_i8;
+ const int nb = ne00/QK4_NL;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+ const int first_row = (r0 * 2 + sgitg) * 2;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+ device const block_iq4_nl * x = (device const block_iq4_nl *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ const int ix = tiisg/2; // 0...15
+ const int it = tiisg%2; // 0 or 1
+
+ shared_values[tiisg] = kvalues_iq4nl_f[tiisg%16];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ float4 yl[4];
+ float sumf[2]={0.f}, all_sum;
+
+ device const float * yb = y + ix * QK4_NL + it * 8;
+
+ uint32_t aux32[2];
+ thread const uint8_t * q8 = (thread const uint8_t *)aux32;
+
+ float4 qf1, qf2;
+
+ for (int ib = ix; ib < nb; ib += 16) {
+
+ device const float4 * y4 = (device const float4 *)yb;
+ yl[0] = y4[0]; yl[1] = y4[4]; yl[2] = y4[1]; yl[3] = y4[5];
+
+ for (int row = 0; row < 2 && first_row + row < ne01; ++row) {
+
+ device const block_iq4_nl & xb = x[row*nb + ib];
+ device const uint16_t * q4 = (device const uint16_t *)(xb.qs + 8*it);
+
+ float4 acc1 = {0.f}, acc2 = {0.f};
+
+ aux32[0] = q4[0] | (q4[1] << 16);
+ aux32[1] = (aux32[0] >> 4) & 0x0f0f0f0f;
+ aux32[0] &= 0x0f0f0f0f;
+ qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]};
+ qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]};
+ acc1 += yl[0] * qf1;
+ acc2 += yl[1] * qf2;
+
+ aux32[0] = q4[2] | (q4[3] << 16);
+ aux32[1] = (aux32[0] >> 4) & 0x0f0f0f0f;
+ aux32[0] &= 0x0f0f0f0f;
+ qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]};
+ qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]};
+ acc1 += yl[2] * qf1;
+ acc2 += yl[3] * qf2;
+
+ acc1 += acc2;
+
+ sumf[row] += (float)xb.d * (acc1[0] + acc1[1] + acc1[2] + acc1[3]);
+
+ }
+
+ yb += 16 * QK4_NL;
+ }
+
+ for (int row = 0; row < 2 && first_row + row < ne01; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+void kernel_mul_mv_iq4_xs_f32_impl(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values_i8,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg) {
+
+ threadgroup float * shared_values = (threadgroup float *)shared_values_i8;
+ const int nb = ne00/QK_K;
+ const int r0 = tgpig.x;
+ const int r1 = tgpig.y;
+ const int im = tgpig.z;
+ const int first_row = (r0 * 2 + sgitg) * 2;
+ const int ib_row = first_row * nb;
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02);
+ device const block_iq4_xs * x = (device const block_iq4_xs *) src0 + ib_row + offset0;
+ device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1;
+
+ const int ix = tiisg/16; // 0 or 1
+ const int it = tiisg%16; // 0...15
+ const int ib = it/2;
+ const int il = it%2;
+
+ shared_values[tiisg] = kvalues_iq4nl_f[tiisg%16];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ float4 yl[4];
+ float sumf[2]={0.f}, all_sum;
+
+ device const float * yb = y + ix * QK_K + ib * 32 + il * 8;
+
+ uint32_t aux32[2];
+ thread const uint8_t * q8 = (thread const uint8_t *)aux32;
+
+ float4 qf1, qf2;
+
+ for (int ibl = ix; ibl < nb; ibl += 2) {
+
+ device const float4 * y4 = (device const float4 *)yb;
+ yl[0] = y4[0]; yl[1] = y4[4]; yl[2] = y4[1]; yl[3] = y4[5];
+
+ for (int row = 0; row < 2; ++row) {
+
+ device const block_iq4_xs & xb = x[row*nb + ibl];
+ device const uint32_t * q4 = (device const uint32_t *)(xb.qs + 16*ib + 8*il);
+
+ float4 acc1 = {0.f}, acc2 = {0.f};
+
+ aux32[0] = q4[0] & 0x0f0f0f0f;
+ aux32[1] = (q4[0] >> 4) & 0x0f0f0f0f;
+ qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]};
+ qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]};
+ acc1 += yl[0] * qf1;
+ acc2 += yl[1] * qf2;
+
+ aux32[0] = q4[1] & 0x0f0f0f0f;
+ aux32[1] = (q4[1] >> 4) & 0x0f0f0f0f;
+ qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]};
+ qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]};
+ acc1 += yl[2] * qf1;
+ acc2 += yl[3] * qf2;
+
+ acc1 += acc2;
+
+ const int ls = (((xb.scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((xb.scales_h >> 2*ib) & 3) << 4)) - 32;
+ sumf[row] += (float)xb.d * ls * (acc1[0] + acc1[1] + acc1[2] + acc1[3]);
+
+ }
+
+ yb += 2 * QK_K;
+ }
+
+ for (int row = 0; row < 2; ++row) {
+ all_sum = simd_sum(sumf[row]);
+ if (tiisg == 0) {
+ dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum;
+ }
+ }
+}
+
+[[host_name("kernel_mul_mv_iq1_s_f32")]]
+kernel void kernel_mul_mv_iq1_s_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq1_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+[[host_name("kernel_mul_mv_iq1_m_f32")]]
+kernel void kernel_mul_mv_iq1_m_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq1_m_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg);
+}
+
+[[host_name("kernel_mul_mv_iq4_nl_f32")]]
+kernel void kernel_mul_mv_iq4_nl_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq4_nl_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+[[host_name("kernel_mul_mv_iq4_xs_f32")]]
+kernel void kernel_mul_mv_iq4_xs_f32(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ kernel_mul_mv_iq4_xs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg);
+}
+
+//============================= templates and their specializations =============================
+
+// NOTE: this is not dequantizing - we are simply fitting the template
+template <typename type4x4>
+void dequantize_f32(device const float4x4 * src, short il, thread type4x4 & reg) {
+ float4x4 temp = *(((device float4x4 *)src));
+ for (int i = 0; i < 16; i++){
+ reg[i/4][i%4] = temp[i/4][i%4];
+ }
+}
+
+template <typename type4x4>
+void dequantize_f16(device const half4x4 * src, short il, thread type4x4 & reg) {
+ half4x4 temp = *(((device half4x4 *)src));
+ for (int i = 0; i < 16; i++){
+ reg[i/4][i%4] = temp[i/4][i%4];
+ }
+}
+
+#if defined(__HAVE_BFLOAT__)
+template <typename type4x4>
+void dequantize_bf16(device const bfloat4x4 * src, short il, thread type4x4 & reg) {
+ reg = (type4x4)(*src);
+}
+#endif
+
+template <typename type4x4>
+void dequantize_q4_0(device const block_q4_0 *xb, short il, thread type4x4 & reg) {
+ device const uint16_t * qs = ((device const uint16_t *)xb + 1);
+ const float d1 = il ? (xb->d / 16.h) : xb->d;
+ const float d2 = d1 / 256.f;
+ const float md = -8.h * xb->d;
+ const ushort mask0 = il ? 0x00F0 : 0x000F;
+ const ushort mask1 = mask0 << 8;
+
+ for (int i=0;i<8;i++) {
+ reg[i/2][2*(i%2)+0] = d1 * (qs[i] & mask0) + md;
+ reg[i/2][2*(i%2)+1] = d2 * (qs[i] & mask1) + md;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q4_1(device const block_q4_1 *xb, short il, thread type4x4 & reg) {
+ device const uint16_t * qs = ((device const uint16_t *)xb + 2);
+ const float d1 = il ? (xb->d / 16.h) : xb->d;
+ const float d2 = d1 / 256.f;
+ const float m = xb->m;
+ const ushort mask0 = il ? 0x00F0 : 0x000F;
+ const ushort mask1 = mask0 << 8;
+
+ for (int i=0;i<8;i++) {
+ reg[i/2][2*(i%2)+0] = ((qs[i] & mask0) * d1) + m;
+ reg[i/2][2*(i%2)+1] = ((qs[i] & mask1) * d2) + m;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q5_0(device const block_q5_0 *xb, short il, thread type4x4 & reg) {
+ device const uint16_t * qs = ((device const uint16_t *)xb + 3);
+ const float d = xb->d;
+ const float md = -16.h * xb->d;
+ const ushort mask = il ? 0x00F0 : 0x000F;
+
+ const uint32_t qh = *((device const uint32_t *)xb->qh);
+
+ const int x_mv = il ? 4 : 0;
+
+ const int gh_mv = il ? 12 : 0;
+ const int gh_bk = il ? 0 : 4;
+
+ for (int i = 0; i < 8; i++) {
+ // extract the 5-th bits for x0 and x1
+ const uint8_t xh_0 = ((qh >> (gh_mv + 2*i )) << gh_bk) & 0x10;
+ const uint8_t xh_1 = ((qh >> (gh_mv + 2*i+1)) << gh_bk) & 0x10;
+
+ // combine the 4-bits from qs with the 5th bit
+ const int32_t x0 = ((((qs[i] ) & mask) >> x_mv) | xh_0);
+ const int32_t x1 = ((((qs[i] >> 8) & mask) >> x_mv) | xh_1);
+
+ reg[i/2][2*(i%2)+0] = d * x0 + md;
+ reg[i/2][2*(i%2)+1] = d * x1 + md;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q5_1(device const block_q5_1 *xb, short il, thread type4x4 & reg) {
+ device const uint16_t * qs = ((device const uint16_t *)xb + 4);
+ const float d = xb->d;
+ const float m = xb->m;
+ const ushort mask = il ? 0x00F0 : 0x000F;
+
+ const uint32_t qh = *((device const uint32_t *)xb->qh);
+
+ const int x_mv = il ? 4 : 0;
+
+ const int gh_mv = il ? 12 : 0;
+ const int gh_bk = il ? 0 : 4;
+
+ for (int i = 0; i < 8; i++) {
+ // extract the 5-th bits for x0 and x1
+ const uint8_t xh_0 = ((qh >> (gh_mv + 2*i )) << gh_bk) & 0x10;
+ const uint8_t xh_1 = ((qh >> (gh_mv + 2*i+1)) << gh_bk) & 0x10;
+
+ // combine the 4-bits from qs with the 5th bit
+ const int32_t x0 = ((((qs[i] ) & mask) >> x_mv) | xh_0);
+ const int32_t x1 = ((((qs[i] >> 8) & mask) >> x_mv) | xh_1);
+
+ reg[i/2][2*(i%2)+0] = d * x0 + m;
+ reg[i/2][2*(i%2)+1] = d * x1 + m;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q8_0(device const block_q8_0 *xb, short il, thread type4x4 & reg) {
+ device const int8_t * qs = ((device const int8_t *)xb->qs);
+ const half d = xb->d;
+
+ for (int i = 0; i < 16; i++) {
+ reg[i/4][i%4] = (qs[i + 16*il] * d);
+ }
+}
+
+template <typename type4x4>
+void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg) {
+ const float d = xb->d;
+ const float min = xb->dmin;
+ device const uint8_t * q = (device const uint8_t *)xb->qs;
+ float dl, ml;
+ uint8_t sc = xb->scales[il];
+
+ q = q + 32*(il/8) + 16*(il&1);
+ il = (il/2)%4;
+
+ half coef = il>1 ? (il>2 ? 1/64.h : 1/16.h) : (il>0 ? 1/4.h : 1.h);
+ uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3);
+ dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4);
+ for (int i = 0; i < 16; ++i) {
+ reg[i/4][i%4] = dl * (q[i] & mask) - ml;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg) {
+ const half d_all = xb->d;
+ device const uint8_t * q = (device const uint8_t *)xb->qs;
+ device const uint8_t * h = (device const uint8_t *)xb->hmask;
+ device const int8_t * scales = (device const int8_t *)xb->scales;
+
+ q = q + 32 * (il/8) + 16 * (il&1);
+ h = h + 16 * (il&1);
+ uint8_t m = 1 << (il/2);
+ uint16_t kmask1 = (il/4)>1 ? ((il/4)>2 ? 192 : 48) : \
+ ((il/4)>0 ? 12 : 3);
+ uint16_t kmask2 = il/8 ? 0xF0 : 0x0F;
+ uint16_t scale_2 = scales[il%8], scale_1 = scales[8 + il%4];
+ int16_t dl_int = (il/4)&1 ? (scale_2&kmask2) | ((scale_1&kmask1) << 2)
+ : (scale_2&kmask2) | ((scale_1&kmask1) << 4);
+ float dl = il<8 ? d_all * (dl_int - 32.f) : d_all * (dl_int / 16.f - 32.f);
+ const float ml = 4.f * dl;
+
+ il = (il/2) & 3;
+ const half coef = il>1 ? (il>2 ? 1/64.h : 1/16.h) : (il>0 ? 1/4.h : 1.h);
+ const uint8_t mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3);
+ dl *= coef;
+
+ for (int i = 0; i < 16; ++i) {
+ reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml);
+ }
+}
+
+static inline uchar2 get_scale_min_k4_just2(int j, int k, device const uchar * q) {
+ return j < 4 ? uchar2{uchar(q[j+0+k] & 63), uchar(q[j+4+k] & 63)}
+ : uchar2{uchar((q[j+4+k] & 0xF) | ((q[j-4+k] & 0xc0) >> 2)), uchar((q[j+4+k] >> 4) | ((q[j-0+k] & 0xc0) >> 2))};
+}
+
+template <typename type4x4>
+void dequantize_q4_K(device const block_q4_K *xb, short il, thread type4x4 & reg) {
+ device const uchar * q = xb->qs;
+
+ short is = (il/4) * 2;
+ q = q + (il/4) * 32 + 16 * (il&1);
+ il = il & 3;
+ const uchar2 sc = get_scale_min_k4_just2(is, il/2, xb->scales);
+ const float d = il < 2 ? xb->d : xb->d / 16.h;
+ const float min = xb->dmin;
+ const float dl = d * sc[0];
+ const float ml = min * sc[1];
+
+ const ushort mask = il<2 ? 0x0F : 0xF0;
+ for (int i = 0; i < 16; ++i) {
+ reg[i/4][i%4] = dl * (q[i] & mask) - ml;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg) {
+ device const uint8_t * q = xb->qs;
+ device const uint8_t * qh = xb->qh;
+
+ short is = (il/4) * 2;
+ q = q + 32 * (il/4) + 16 * (il&1);
+ qh = qh + 16 * (il&1);
+ uint8_t ul = 1 << (il/2);
+ il = il & 3;
+ const uchar2 sc = get_scale_min_k4_just2(is, il/2, xb->scales);
+ const float d = il < 2 ? xb->d : xb->d / 16.f;
+ const float min = xb->dmin;
+ const float dl = d * sc[0];
+ const float ml = min * sc[1];
+
+ const ushort mask = il<2 ? 0x0F : 0xF0;
+ const float qh_val = il<2 ? 16.f : 256.f;
+ for (int i = 0; i < 16; ++i) {
+ reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml;
+ }
+}
+
+template <typename type4x4>
+void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg) {
+ const half d_all = xb->d;
+ device const uint8_t * ql = (device const uint8_t *)xb->ql;
+ device const uint8_t * qh = (device const uint8_t *)xb->qh;
+ device const int8_t * scales = (device const int8_t *)xb->scales;
+
+ ql = ql + 64*(il/8) + 32*((il/2)&1) + 16*(il&1);
+ qh = qh + 32*(il/8) + 16*(il&1);
+ float sc = scales[(il%2) + 2 * ((il/2))];
+ il = (il/2) & 3;
+
+ const uint16_t kmask1 = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3);
+ const uint16_t kmask2 = il>1 ? 0xF0 : 0x0F;
+ const float coef = il>1 ? 1.f/16.f : 1.f;
+ const float ml = d_all * sc * 32.f;
+ const float dl = d_all * sc * coef;
+ for (int i = 0; i < 16; ++i) {
+ const half q = il&1 ? ((ql[i] & kmask2) | ((qh[i] & kmask1) << 2))
+ : ((ql[i] & kmask2) | ((qh[i] & kmask1) << 4));
+ reg[i/4][i%4] = dl * q - ml;
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const float d = xb->d;
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ // each block of 32 needs 2 uint32_t's for the quants & scale, so 4 uint16_t's.
+ device const uint16_t * q2 = xb->qs + 4*ib32;
+ const uint32_t aux32_g = q2[0] | (q2[1] << 16);
+ const uint32_t aux32_s = q2[2] | (q2[3] << 16);
+ thread const uint8_t * aux8 = (thread const uint8_t *)&aux32_g;
+ const float dl = d * (0.5f + (aux32_s >> 28)) * 0.25f;
+ constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]);
+ uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127];
+ for (int i = 0; i < 8; ++i) {
+ reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
+ }
+ grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]);
+ signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127];
+ for (int i = 0; i < 8; ++i) {
+ reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const float d = xb->d;
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ device const uint16_t * q2 = xb->qs + 4*ib32;
+ const float dl = d * (0.5f + ((xb->scales[ib32] >> 4*il) & 0xf)) * 0.25f;
+ constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511));
+ uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9];
+ for (int i = 0; i < 8; ++i) {
+ reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
+ }
+ grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511));
+ signs = ksigns_iq2xs[q2[2*il+1] >> 9];
+ for (int i = 0; i < 8; ++i) {
+ reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const float d = xb->d;
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ device const uint8_t * q3 = xb->qs + 8*ib32;
+ device const uint16_t * gas = (device const uint16_t *)(xb->qs + QK_K/4) + 2*ib32;
+ const uint32_t aux32 = gas[0] | (gas[1] << 16);
+ const float dl = d * (0.5f + (aux32 >> 28)) * 0.5f;
+ constant uint8_t * grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+0]);
+ constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]);
+ uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127];
+ for (int i = 0; i < 4; ++i) {
+ reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
+ reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
+ }
+ grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]);
+ grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]);
+ signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127];
+ for (int i = 0; i < 4; ++i) {
+ reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
+ reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const float d = xb->d;
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ device const uint8_t * qs = xb->qs + 8*ib32;
+ device const uint8_t * signs = xb->signs + 4*ib32 + 2*il;
+ const uint8_t qh = xb->qh[ib32] >> 4*il;
+ const float dl = d * (1 + 2*((xb->scales[ib32/2] >> 4*(ib32%2)) & 0xf));
+ constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256)));
+ for (int i = 0; i < 4; ++i) {
+ reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]);
+ reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]);
+ }
+ grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256)));
+ grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256)));
+ for (int i = 0; i < 4; ++i) {
+ reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]);
+ reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]);
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const float d = xb->d;
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ device const uint8_t * qs = xb->qs + 4*ib32 + 2*il;
+ device const uint8_t * signs = qs + QK_K/8;
+ const uint8_t qh = xb->qh[ib32] >> 4*il;
+ const float dl = d * (0.5f + ((xb->scales[ib32] >> 4*il) & 0xf)) * 0.25f;
+ constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300)));
+ for (int i = 0; i < 8; ++i) {
+ reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]);
+ reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]);
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const int ib32 = il/2;
+ il = il%2;
+ const float d = xb->d;
+ device const uint8_t * qs = xb->qs + 4*ib32 + 2*il;
+ device const uint16_t * qh = xb->qh;
+ const float dl = d * (2*((qh[ib32] >> 12) & 7) + 1);
+ const float ml = dl * (qh[ib32] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA);
+ const uint16_t h = qh[ib32] >> 6*il;
+ constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700)));
+ for (int i = 0; i < 4; ++i) {
+ reg[0][i] = dl * (grid1[i] & 0xf) + ml;
+ reg[1][i] = dl * (grid1[i] >> 4) + ml;
+ reg[2][i] = dl * (grid2[i] & 0xf) + ml;
+ reg[3][i] = dl * (grid2[i] >> 4) + ml;
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const int ib32 = il/2;
+ il = il%2;
+ device const uint16_t * sc = (device const uint16_t *)xb->scales;
+
+ iq1m_scale_t scale;
+ scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
+ const float d = scale.f16;
+
+ device const uint8_t * qs = xb->qs + 4*ib32 + 2*il;
+ device const uint8_t * qh = xb->qh + 2*ib32 + il;
+
+ const float dl = d * (2*((sc[ib32/2] >> (6*(ib32%2)+3*il)) & 7) + 1);
+ const float ml1 = dl * (qh[0] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA);
+ const float ml2 = dl * (qh[0] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA);
+ constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700)));
+ constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700)));
+ for (int i = 0; i < 4; ++i) {
+ reg[0][i] = dl * (grid1[i] & 0xf) + ml1;
+ reg[1][i] = dl * (grid1[i] >> 4) + ml1;
+ reg[2][i] = dl * (grid2[i] & 0xf) + ml2;
+ reg[3][i] = dl * (grid2[i] >> 4) + ml2;
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4 & reg) {
+ device const uint16_t * q4 = (device const uint16_t *)xb->qs;
+ const float d = xb->d;
+ uint32_t aux32;
+ thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
+ for (int i = 0; i < 4; ++i) {
+ aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f;
+ reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
+ reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
+ reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
+ reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
+ }
+}
+
+template <typename type4x4>
+void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4 & reg) {
+ // il is 0...15 for QK_K = 256 => index of block of 32 is il/2
+ const int ib32 = il/2;
+ il = il%2;
+ // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16
+ device const uint32_t * q4 = (device const uint32_t *)xb->qs + 4*ib32;
+ const int ls = ((xb->scales_l[ib32/2] >> 4*(ib32%2)) & 0xf) | (((xb->scales_h >> 2*ib32) & 3) << 4);
+ const float d = (float)xb->d * (ls - 32);
+ uint32_t aux32;
+ thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
+ for (int i = 0; i < 4; ++i) {
+ aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f;
+ reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
+ reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
+ reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
+ reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
+ }
+}
+
+template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread float4x4 &)>
+kernel void kernel_get_rows_q(
+ device const void * src0,
+ device const void * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint3 tptg [[threads_per_threadgroup]]) {
+ const int64_t i10 = tgpig.x;
+ const int64_t i11 = tgpig.y;
+
+ const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0];
+
+ const int64_t i02 = i11;
+
+ for (int64_t ind = tiitg; ind < ne00/16; ind += tptg.x) {
+ float4x4 temp;
+ dequantize_func(((device const block_q *) ((const device char *) src0 + r*nb01 + i02*nb02)) + ind/nl, ind%nl, temp);
+ *(((device float4x4 *) ((device char *) dst + i11*nb2 + i10*nb1)) + ind) = temp;
+ }
+}
+
+template<typename T>
+kernel void kernel_get_rows_f(
+ device const void * src0,
+ device const void * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint3 tptg [[threads_per_threadgroup]]) {
+ const int64_t i10 = tgpig.x;
+ const int64_t i11 = tgpig.y;
+
+ const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0];
+
+ const int64_t i02 = i11;
+
+ for (int ind = tiitg; ind < ne00; ind += tptg.x) {
+ (( device float *) (( device char *) dst + i11*nb2 + i10*nb1))[ind] =
+ ((const device T *) ((const device char *) src0 + i02*nb02 + r*nb01))[ind];
+ }
+}
+
+kernel void kernel_get_rows_i32(
+ device const void * src0,
+ device const void * src1,
+ device int32_t * dst,
+ constant int64_t & ne00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb1,
+ constant uint64_t & nb2,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint3 tptg [[threads_per_threadgroup]]) {
+ const int64_t i10 = tgpig.x;
+ const int64_t i11 = tgpig.y;
+
+ const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0];
+
+ const int64_t i02 = i11;
+
+ for (int ind = tiitg; ind < ne00; ind += tptg.x) {
+ (( device int32_t *) (( device char *) dst + i11*nb2 + i10*nb1))[ind] =
+ ((const device int32_t *) ((const device char *) src0 + i02*nb02 + r*nb01))[ind];
+ }
+}
+
+
+#define BLOCK_SIZE_M 64 // 8 simdgroup matrices from matrix A
+#define BLOCK_SIZE_N 32 // 4 simdgroup matrices from matrix B
+#define BLOCK_SIZE_K 32
+#define THREAD_MAT_M 4 // each thread take 4 simdgroup matrices from matrix A
+#define THREAD_MAT_N 2 // each thread take 2 simdgroup matrices from matrix B
+#define THREAD_PER_BLOCK 128
+#define THREAD_PER_ROW 2 // 2 thread for each row in matrix A to load numbers
+#define THREAD_PER_COL 4 // 4 thread for each row in matrix B to load numbers
+#define SG_MAT_SIZE 64 // simdgroup matrix is of shape 8x8
+#define SG_MAT_ROW 8
+
+// each block_q contains 16*nl weights
+template<typename T, typename T4x4, typename simdgroup_T8x8, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread T4x4 &)>
+kernel void kernel_mul_mm(device const uchar * src0,
+ device const uchar * src1,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne02,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant uint64_t & nb03,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant uint64_t & nb13,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint & r2,
+ constant uint & r3,
+ threadgroup uchar * shared_memory [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ threadgroup T * sa = (threadgroup T *)(shared_memory);
+ threadgroup float * sb = (threadgroup float *)(shared_memory + 4096);
+
+ const uint r0 = tgpig.y;
+ const uint r1 = tgpig.x;
+ const uint im = tgpig.z;
+
+ // if this block is of 64x32 shape or smaller
+ short n_rows = (ne0 - r0*BLOCK_SIZE_M < BLOCK_SIZE_M) ? (ne0 - r0*BLOCK_SIZE_M) : BLOCK_SIZE_M;
+ short n_cols = (ne1 - r1*BLOCK_SIZE_N < BLOCK_SIZE_N) ? (ne1 - r1*BLOCK_SIZE_N) : BLOCK_SIZE_N;
+
+ // a thread shouldn't load data outside of the matrix
+ short thread_row = ((short)tiitg/THREAD_PER_ROW) < n_rows ? ((short)tiitg/THREAD_PER_ROW) : n_rows - 1;
+ short thread_col = ((short)tiitg/THREAD_PER_COL) < n_cols ? ((short)tiitg/THREAD_PER_COL) : n_cols - 1;
+
+ simdgroup_T8x8 ma[4];
+ simdgroup_float8x8 mb[2];
+ simdgroup_float8x8 mc[8];
+
+ for (short i = 0; i < 8; i++){
+ mc[i] = make_filled_simdgroup_matrix<float, 8>(0.f);
+ }
+
+ short il = (tiitg % THREAD_PER_ROW);
+
+ const uint i12 = im%ne12;
+ const uint i13 = im/ne12;
+
+ uint offset0 = (i12/r2)*nb02 + (i13/r3)*nb03;
+ ushort offset1 = il/nl;
+
+ device const block_q * x = (device const block_q *)(src0 + (r0*BLOCK_SIZE_M + thread_row)*nb01 + offset0) + offset1;
+ device const float * y = (device const float *)(src1
+ + nb13 * i13
+ + nb12 * i12
+ + nb11 * (r1 * BLOCK_SIZE_N + thread_col)
+ + nb10 * (BLOCK_SIZE_K / THREAD_PER_COL * (tiitg % THREAD_PER_COL)));
+
+ for (int loop_k = 0; loop_k < ne00; loop_k += BLOCK_SIZE_K) {
+ // load data and store to threadgroup memory
+ T4x4 temp_a;
+ dequantize_func(x, il, temp_a);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ #pragma unroll(16)
+ for (short i = 0; i < 16; i++) {
+ *(sa + SG_MAT_SIZE * ((tiitg/THREAD_PER_ROW/8) \
+ + (tiitg%THREAD_PER_ROW)*16 + (i/8)*8) \
+ + (tiitg/THREAD_PER_ROW)%8 + (i&7)*8) = temp_a[i/4][i%4];
+ }
+
+ *(threadgroup float2x4 *)(sb + (tiitg % THREAD_PER_COL)*8*32 + 8*(tiitg/THREAD_PER_COL)) = *((device float2x4 *) y);
+
+ il = (il + 2 < nl) ? il + 2 : il % 2;
+ x = (il < 2) ? x + (2+nl-1)/nl : x;
+ y += BLOCK_SIZE_K;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // load matrices from threadgroup memory and conduct outer products
+ threadgroup T * lsma = (sa + THREAD_MAT_M*SG_MAT_SIZE*(sgitg%2));
+ threadgroup float * lsmb = (sb + THREAD_MAT_N*SG_MAT_SIZE*(sgitg/2));
+
+ #pragma unroll(4)
+ for (short ik = 0; ik < BLOCK_SIZE_K / 8; ik++) {
+ #pragma unroll(4)
+ for (short i = 0; i < 4; i++) {
+ simdgroup_load(ma[i], lsma + SG_MAT_SIZE * i);
+ }
+ simdgroup_barrier(mem_flags::mem_none);
+ #pragma unroll(2)
+ for (short i = 0; i < 2; i++) {
+ simdgroup_load(mb[i], lsmb + SG_MAT_SIZE * i);
+ }
+
+ lsma += BLOCK_SIZE_M/SG_MAT_ROW * SG_MAT_SIZE;
+ lsmb += BLOCK_SIZE_N/SG_MAT_ROW * SG_MAT_SIZE;
+
+ #pragma unroll(8)
+ for (short i = 0; i < 8; i++){
+ simdgroup_multiply_accumulate(mc[i], mb[i/4], ma[i%4], mc[i]);
+ }
+ }
+ }
+
+ if ((r0 + 1) * BLOCK_SIZE_M <= ne0 && (r1 + 1) * BLOCK_SIZE_N <= ne1) {
+ device float * C = dst + (BLOCK_SIZE_M * r0 + 32 * (sgitg & 1)) \
+ + (BLOCK_SIZE_N * r1 + 16 * (sgitg >> 1)) * ne0 + im*ne1*ne0;
+ for (short i = 0; i < 8; i++) {
+ simdgroup_store(mc[i], C + 8 * (i%4) + 8 * ne0 * (i/4), ne0);
+ }
+ } else {
+ // block is smaller than 64x32, we should avoid writing data outside of the matrix
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ threadgroup float * temp_str = ((threadgroup float *) shared_memory) \
+ + 32 * (sgitg&1) + (16 * (sgitg>>1))*BLOCK_SIZE_M;
+ for (short i = 0; i < 8; i++) {
+ simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*BLOCK_SIZE_M*(i/4), BLOCK_SIZE_M);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (sgitg == 0) {
+ for (int j = tiitg; j < n_cols; j += BLOCK_SIZE_N) {
+ device float * D = dst + (r0*BLOCK_SIZE_M) + (r1*BLOCK_SIZE_N + j)*ne0 + im*ne1*ne0;
+ device float4 * D4 = (device float4 *) D;
+
+ threadgroup float * C = temp_str + (j*BLOCK_SIZE_M);
+ threadgroup float4 * C4 = (threadgroup float4 *) C;
+
+ int i = 0;
+ for (; i < n_rows/4; i++) {
+ *(D4 + i) = *(C4 + i);
+ }
+
+ i *= 4;
+ for (; i < n_rows; i++) {
+ *(D + i) = *(C + i);
+ }
+ }
+ }
+ }
+}
+
+// same as kernel_mul_mm_impl, but src1 and dst are accessed via indices stored in rowids
+template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread half4x4 &)>
+void kernel_mul_mm_id_impl(
+ device const uchar * src0,
+ device const uchar * src1,
+ threadgroup ushort2 * rowids,
+ device float * dst,
+ constant int64_t & ne00,
+ constant int64_t & ne02,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ int64_t ne1,
+ int64_t ne0ne1,
+ threadgroup uchar * shared_memory,
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ threadgroup half * sa = (threadgroup half *)(shared_memory);
+ threadgroup float * sb = (threadgroup float *)(shared_memory + 4096);
+
+ const uint r0 = tgpig.y;
+ const uint r1 = tgpig.x;
+
+ if (r1 * BLOCK_SIZE_N >= ne1) return;
+
+ // if this block is of 64x32 shape or smaller
+ short n_rows = (ne0 - r0 * BLOCK_SIZE_M < BLOCK_SIZE_M) ? (ne0 - r0 * BLOCK_SIZE_M) : BLOCK_SIZE_M;
+ short n_cols = (ne1 - r1 * BLOCK_SIZE_N < BLOCK_SIZE_N) ? (ne1 - r1 * BLOCK_SIZE_N) : BLOCK_SIZE_N;
+
+ // a thread shouldn't load data outside of the matrix
+ short thread_row = ((short)tiitg/THREAD_PER_ROW) < n_rows ? ((short)tiitg/THREAD_PER_ROW) : n_rows - 1;
+ short thread_col = ((short)tiitg/THREAD_PER_COL) < n_cols ? ((short)tiitg/THREAD_PER_COL) : n_cols - 1;
+
+ simdgroup_half8x8 ma[4];
+ simdgroup_float8x8 mb[2];
+ simdgroup_float8x8 c_res[8];
+ for (int i = 0; i < 8; i++){
+ c_res[i] = make_filled_simdgroup_matrix<float, 8>(0.f);
+ }
+ short il = (tiitg % THREAD_PER_ROW);
+
+ ushort offset1 = il/nl;
+
+ threadgroup const auto & id = rowids[r1 * BLOCK_SIZE_N + thread_col];
+
+ device const block_q * x = (device const block_q *)(src0 + (r0 * BLOCK_SIZE_M + thread_row) * nb01) + offset1;
+ device const float * y = (device const float *)(src1
+ + nb12 * id[1]
+ + nb11 * (id[0] % ne11)
+ + nb10 * (BLOCK_SIZE_K / THREAD_PER_COL * (tiitg % THREAD_PER_COL)));
+
+ for (int loop_k = 0; loop_k < ne00; loop_k += BLOCK_SIZE_K) {
+ // load data and store to threadgroup memory
+ half4x4 temp_a;
+ dequantize_func(x, il, temp_a);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (int i = 0; i < 16; i++) {
+ *(sa + SG_MAT_SIZE * ((tiitg / THREAD_PER_ROW / 8) \
+ + (tiitg % THREAD_PER_ROW) * 16 + (i / 8) * 8) \
+ + (tiitg / THREAD_PER_ROW) % 8 + (i & 7) * 8) = temp_a[i/4][i%4];
+ }
+
+ *(threadgroup float2x4 *)(sb + (tiitg % THREAD_PER_COL) * 8 * 32 + 8 * (tiitg / THREAD_PER_COL)) = *((device float2x4 *)y);
+
+ il = (il + 2 < nl) ? il + 2 : il % 2;
+ x = (il < 2) ? x + (2+nl-1)/nl : x;
+ y += BLOCK_SIZE_K;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // load matrices from threadgroup memory and conduct outer products
+ threadgroup half * lsma = (sa + THREAD_MAT_M * SG_MAT_SIZE * (sgitg % 2));
+ threadgroup float * lsmb = (sb + THREAD_MAT_N * SG_MAT_SIZE * (sgitg / 2));
+
+ for (int ik = 0; ik < BLOCK_SIZE_K / 8; ik++) {
+ for (int i = 0; i < 4; i++) {
+ simdgroup_load(ma[i], lsma + SG_MAT_SIZE * i);
+ }
+ simdgroup_barrier(mem_flags::mem_none);
+ for (int i = 0; i < 2; i++) {
+ simdgroup_load(mb[i], lsmb + SG_MAT_SIZE * i);
+ }
+
+ lsma += BLOCK_SIZE_M / SG_MAT_ROW * SG_MAT_SIZE;
+ lsmb += BLOCK_SIZE_N / SG_MAT_ROW * SG_MAT_SIZE;
+
+ for (int i = 0; i < 8; i++){
+ simdgroup_multiply_accumulate(c_res[i], mb[i/4], ma[i%4], c_res[i]);
+ }
+ }
+ }
+
+ {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ threadgroup float * temp_str = ((threadgroup float *)shared_memory) \
+ + 32 * (sgitg&1) + (16 * (sgitg>>1)) * BLOCK_SIZE_M;
+ for (int i = 0; i < 8; i++) {
+ simdgroup_store(c_res[i], temp_str + 8 * (i%4) + 8 * BLOCK_SIZE_M * (i/4), BLOCK_SIZE_M);
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ device float * C = dst + (BLOCK_SIZE_M * r0);
+ if (sgitg == 0) {
+ for (int j = tiitg; j < n_cols; j += BLOCK_SIZE_N) {
+ threadgroup const auto & jid = rowids[r1 * BLOCK_SIZE_N + j];
+ int joff = jid[0] * ne0 + jid[1] * ne0ne1;
+ for (int i = 0; i < n_rows; i++) {
+ *(C + i + joff) = *(temp_str + i + j * BLOCK_SIZE_M);
+ }
+ }
+ }
+ }
+}
+
+template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread half4x4 &)>
+kernel void kernel_mul_mm_id(
+ device const uchar * src0s,
+ device const uchar * src1,
+ device float * dst,
+ device const uchar * ids,
+ constant int64_t & nei0,
+ constant int64_t & nei1,
+ constant uint64_t & nbi1,
+ constant int64_t & ne00,
+ constant int64_t & ne02,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint64_t & nb1,
+ threadgroup uchar * shared_memory [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+
+ const int32_t i02 = tgpig.z;
+ tgpig.z = 0;
+
+ device const uchar * src0 = src0s + i02*nb02;
+
+ // row indices
+ threadgroup ushort2 * rowids = (threadgroup ushort2 *)(shared_memory + 8192);
+
+ // TODO: parallelize this loop
+ int64_t _ne1 = 0;
+ for (ushort ii1 = 0; ii1 < nei1; ii1++) {
+ for (ushort ii0 = 0; ii0 < nei0; ii0++) {
+ int32_t id = ((device int32_t *) (ids + ii1*nbi1))[ii0];
+ if (id == i02) {
+ //if (tiitg == 0) {
+ rowids[_ne1] = ushort2(ii0, ii1);
+ //}
+ _ne1++;
+ }
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ kernel_mul_mm_id_impl<block_q, nl, dequantize_func>(
+ src0,
+ src1,
+ rowids,
+ dst,
+ ne00,
+ ne02,
+ nb01,
+ nb02,
+ ne11,
+ ne12,
+ nb10,
+ nb11,
+ nb12,
+ ne0,
+ _ne1,
+ ne0*ne1,
+ shared_memory,
+ tgpig,
+ tiitg,
+ sgitg);
+}
+
+#define QK_NL 16
+
+//
+// get rows
+//
+
+typedef decltype(kernel_get_rows_f<float>) get_rows_f_t;
+
+template [[host_name("kernel_get_rows_f32")]] kernel get_rows_f_t kernel_get_rows_f<float>;
+template [[host_name("kernel_get_rows_f16")]] kernel get_rows_f_t kernel_get_rows_f<half>;
+#if defined(__HAVE_BFLOAT__)
+template [[host_name("kernel_get_rows_bf16")]] kernel get_rows_f_t kernel_get_rows_f<bfloat>;
+#endif
+
+typedef decltype(kernel_get_rows_q<block_q4_0, 2, dequantize_q4_0>) get_rows_q_t;
+
+template [[host_name("kernel_get_rows_q4_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_0, 2, dequantize_q4_0>;
+template [[host_name("kernel_get_rows_q4_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_1, 2, dequantize_q4_1>;
+template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_0, 2, dequantize_q5_0>;
+template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_1, 2, dequantize_q5_1>;
+template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q8_0, 2, dequantize_q8_0>;
+template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q2_K, QK_NL, dequantize_q2_K>;
+template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q3_K, QK_NL, dequantize_q3_K>;
+template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_K, QK_NL, dequantize_q4_K>;
+template [[host_name("kernel_get_rows_q5_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_K, QK_NL, dequantize_q5_K>;
+template [[host_name("kernel_get_rows_q6_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q6_K, QK_NL, dequantize_q6_K>;
+template [[host_name("kernel_get_rows_iq2_xxs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_xxs, QK_NL, dequantize_iq2_xxs>;
+template [[host_name("kernel_get_rows_iq2_xs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_xs, QK_NL, dequantize_iq2_xs>;
+template [[host_name("kernel_get_rows_iq3_xxs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq3_xxs, QK_NL, dequantize_iq3_xxs>;
+template [[host_name("kernel_get_rows_iq3_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq3_s, QK_NL, dequantize_iq3_s>;
+template [[host_name("kernel_get_rows_iq2_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_s, QK_NL, dequantize_iq2_s>;
+template [[host_name("kernel_get_rows_iq1_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq1_s, QK_NL, dequantize_iq1_s>;
+template [[host_name("kernel_get_rows_iq1_m")]] kernel get_rows_q_t kernel_get_rows_q<block_iq1_m, QK_NL, dequantize_iq1_m>;
+template [[host_name("kernel_get_rows_iq4_nl")]] kernel get_rows_q_t kernel_get_rows_q<block_iq4_nl, 2, dequantize_iq4_nl>;
+template [[host_name("kernel_get_rows_iq4_xs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq4_xs, QK_NL, dequantize_iq4_xs>;
+
+//
+// matrix-matrix multiplication
+//
+
+typedef decltype(kernel_mul_mm<half, half4x4, simdgroup_half8x8, float4x4, 1, dequantize_f32>) mat_mm_t;
+
+template [[host_name("kernel_mul_mm_f32_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, float4x4, 1, dequantize_f32>;
+template [[host_name("kernel_mul_mm_f16_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half4x4, 1, dequantize_f16>;
+#if defined(__HAVE_BFLOAT__)
+template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mat_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16>;
+#endif
+template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0>;
+template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1>;
+template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0>;
+template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1>;
+template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0>;
+template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K>;
+template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K>;
+template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K>;
+template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K>;
+template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K>;
+template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs>;
+template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs>;
+template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs>;
+template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s>;
+template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s>;
+template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s>;
+template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m>;
+template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl>;
+template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs>;
+
+//
+// indirect matrix-matrix multiplication
+//
+
+typedef decltype(kernel_mul_mm_id<float4x4, 1, dequantize_f32>) mat_mm_id_t;
+
+template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<float4x4, 1, dequantize_f32>;
+template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<half4x4, 1, dequantize_f16>;
+template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_0, 2, dequantize_q4_0>;
+template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_1, 2, dequantize_q4_1>;
+template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_0, 2, dequantize_q5_0>;
+template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_1, 2, dequantize_q5_1>;
+template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q8_0, 2, dequantize_q8_0>;
+template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q2_K, QK_NL, dequantize_q2_K>;
+template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q3_K, QK_NL, dequantize_q3_K>;
+template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_K, QK_NL, dequantize_q4_K>;
+template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_K, QK_NL, dequantize_q5_K>;
+template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q6_K, QK_NL, dequantize_q6_K>;
+template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_xxs, QK_NL, dequantize_iq2_xxs>;
+template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_xs, QK_NL, dequantize_iq2_xs>;
+template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq3_xxs, QK_NL, dequantize_iq3_xxs>;
+template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq3_s, QK_NL, dequantize_iq3_s>;
+template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_s, QK_NL, dequantize_iq2_s>;
+template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq1_s, QK_NL, dequantize_iq1_s>;
+template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq1_m, QK_NL, dequantize_iq1_m>;
+template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq4_nl, 2, dequantize_iq4_nl>;
+template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq4_xs, QK_NL, dequantize_iq4_xs>;
+
+//
+// matrix-vector multiplication
+//
+
+typedef void (kernel_mul_mv_impl_t)(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ uint64_t nb00,
+ uint64_t nb01,
+ uint64_t nb02,
+ int64_t ne10,
+ int64_t ne11,
+ int64_t ne12,
+ uint64_t nb10,
+ uint64_t nb11,
+ uint64_t nb12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ uint3 tgpig,
+ uint tiisg);
+
+typedef void (kernel_mul_mv2_impl_t)(
+ device const void * src0,
+ device const float * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ int64_t ne10,
+ int64_t ne12,
+ int64_t ne0,
+ int64_t ne1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiisg,
+ uint sgitg);
+
+template<kernel_mul_mv_impl_t impl_fn>
+void mmv_fn(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ uint64_t nb00,
+ uint64_t nb01,
+ uint64_t nb02,
+ int64_t ne10,
+ int64_t ne11,
+ int64_t ne12,
+ int64_t ne13,
+ uint64_t nb10,
+ uint64_t nb11,
+ uint64_t nb12,
+ int64_t ne0,
+ int64_t ne1,
+ uint64_t nb1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiitg,
+ uint tiisg,
+ uint sgitg) {
+ impl_fn(src0,src1,dst,ne00,ne01,ne02,nb00,nb01,nb02,ne10,ne11,ne12,nb10,nb11,nb12,ne0,ne1,r2,r3,tgpig,tiisg);
+}
+
+template<kernel_mul_mv2_impl_t impl_fn>
+void mmv_fn(
+ device const char * src0,
+ device const char * src1,
+ device float * dst,
+ int64_t ne00,
+ int64_t ne01,
+ int64_t ne02,
+ uint64_t nb00,
+ uint64_t nb01,
+ uint64_t nb02,
+ int64_t ne10,
+ int64_t ne11,
+ int64_t ne12,
+ int64_t ne13,
+ uint64_t nb10,
+ uint64_t nb11,
+ uint64_t nb12,
+ int64_t ne0,
+ int64_t ne1,
+ uint64_t nb1,
+ uint r2,
+ uint r3,
+ threadgroup int8_t * shared_values,
+ uint3 tgpig,
+ uint tiitg,
+ uint tiisg,
+ uint sgitg) {
+ impl_fn(src0,(const device float *)src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,shared_values,tgpig,tiisg,sgitg);
+}
+
+typedef decltype(mmv_fn<kernel_mul_mv_impl<half, half4, half, half4>>) mul_mv_impl_fn_t;
+
+template<mul_mv_impl_fn_t impl_fn>
+kernel void kernel_mul_mv_id(
+ device const char * src0s,
+ device const char * src1,
+ device float * dst,
+ device const char * ids,
+ constant int64_t & nei0,
+ constant int64_t & nei1,
+ constant uint64_t & nbi1,
+ constant int64_t & ne00,
+ constant int64_t & ne01,
+ constant int64_t & ne02,
+ constant uint64_t & nb00,
+ constant uint64_t & nb01,
+ constant uint64_t & nb02,
+ constant int64_t & ne10,
+ constant int64_t & ne11,
+ constant int64_t & ne12,
+ constant int64_t & ne13,
+ constant uint64_t & nb10,
+ constant uint64_t & nb11,
+ constant uint64_t & nb12,
+ constant int64_t & ne0,
+ constant int64_t & ne1,
+ constant uint64_t & nb1,
+ threadgroup int8_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint tiitg[[thread_index_in_threadgroup]],
+ uint tiisg[[thread_index_in_simdgroup]],
+ uint sgitg[[simdgroup_index_in_threadgroup]]) {
+ const int iid1 = tgpig.z/nei0;
+ const int idx = tgpig.z%nei0;
+
+ tgpig.z = 0;
+
+ const int32_t i02 = ((device const int32_t *) (ids + iid1*nbi1))[idx];
+
+ const int64_t i11 = idx % ne11;
+ const int64_t i12 = iid1;
+
+ const int64_t i1 = idx;
+ const int64_t i2 = i12;
+
+ device const char * src0_cur = src0s + i02*nb02;
+ device const char * src1_cur = src1 + i11*nb11 + i12*nb12;
+ device float * dst_cur = dst + i1*ne0 + i2*ne1*ne0;
+
+ impl_fn(
+ /* src0 */ src0_cur,
+ /* src1 */ src1_cur,
+ /* dst */ dst_cur,
+ /* ne00 */ ne00,
+ /* ne01 */ ne01,
+ /* ne02 */ 1,//ne02,
+ /* nb00 */ nb00,
+ /* nb01 */ nb01,
+ /* nb02 */ nb02,
+ /* ne10 */ ne10,
+ /* ne11 */ 1,//ne11,
+ /* ne12 */ 1,//ne12,
+ /* ne13 */ 1,//ne13,
+ /* nb10 */ nb10,
+ /* nb11 */ nb11,
+ /* nb12 */ nb12,
+ /* ne0 */ ne0,
+ /* ne1 */ 1,//ne1,
+ /* nb1 */ nb1,
+ /* r2 */ 1,
+ /* r3 */ 1,
+ shared_values,
+ tgpig,
+ tiitg,
+ tiisg,
+ sgitg);
+}
+
+typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<float, float4, float, float4>>>) kernel_mul_mv_id_t;
+
+template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<float, float4, float, float4>>>;
+template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<half, half4, float, float4>>>;
+template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q8_0_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_q4_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q4_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>;
+template [[host_name("kernel_mul_mv_id_q4_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q4_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>;
+template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>;
+template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>;
+template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q2_K_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q3_K_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_q4_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q4_K_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_q5_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q5_K_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_q6_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q6_K_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq1_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq1_s_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq1_m_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq1_m_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq2_xxs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_xxs_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq2_xs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_xs_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq3_xxs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq3_xxs_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq3_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq3_s_f32_impl>>;
+template [[host_name("kernel_mul_mv_id_iq2_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_s_f32_impl>>;
+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>>;
+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>>;
+
+kernel void kernel_pool_2d_max_f32(
+ device const float * src0,
+ device float * dst,
+ constant int32_t & k0,
+ constant int32_t & k1,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int64_t & IH,
+ constant int64_t & IW,
+ constant int64_t & OH,
+ constant int64_t & OW,
+ constant int64_t & parallel_elements,
+ uint gid[[thread_position_in_grid]]) {
+
+ if (gid >= parallel_elements) {
+ return;
+ }
+
+ const int idx = gid;
+ const int I_HW = IH * IW;
+ const int O_HW = OH * OW;
+ const int nc = idx / O_HW;
+ const int cur_oh = idx % O_HW / OW;
+ const int cur_ow = idx % O_HW % OW;
+
+ device const float * i_ptr = src0 + nc * I_HW;
+ device float * o_ptr = dst + nc * O_HW;
+
+ const int start_h = cur_oh * s1 - p1;
+ const int bh = MAX(0, start_h);
+ const int eh = MIN(IH, start_h + k1);
+ const int start_w = cur_ow * s0 - p0;
+ const int bw = MAX(0, start_w);
+ const int ew = MIN(IW, start_w + k0);
+
+ float res = -INFINITY;
+
+ for (int i = bh; i < eh; i += 1) {
+ for (int j = bw; j < ew; j += 1) {
+ res = MAX(res, i_ptr[i * IW + j]);
+ }
+ }
+
+ o_ptr[cur_oh * OW + cur_ow] = res;
+}
+
+kernel void kernel_pool_2d_avg_f32(
+ device const float * src0,
+ device float * dst,
+ constant int32_t & k0,
+ constant int32_t & k1,
+ constant int32_t & s0,
+ constant int32_t & s1,
+ constant int32_t & p0,
+ constant int32_t & p1,
+ constant int64_t & IH,
+ constant int64_t & IW,
+ constant int64_t & OH,
+ constant int64_t & OW,
+ constant int64_t & parallel_elements,
+ uint gid[[thread_position_in_grid]]) {
+
+ if (gid >= parallel_elements) {
+ return;
+ }
+
+ const int idx = gid;
+ const int I_HW = IH * IW;
+ const int O_HW = OH * OW;
+ const int nc = idx / O_HW;
+ const int cur_oh = idx % O_HW / OW;
+ const int cur_ow = idx % O_HW % OW;
+
+ device const float * i_ptr = src0 + nc * I_HW;
+ device float * o_ptr = dst + nc * O_HW;
+
+ const int start_h = cur_oh * s1 - p1;
+ const int bh = MAX(0, start_h);
+ const int eh = MIN(IH, start_h + k1);
+ const int start_w = cur_ow * s0 - p0;
+ const int bw = MAX(0, start_w);
+ const int ew = MIN(IW, start_w + k0);
+ // const float scale = 1. / ((eh - bh) * (ew - bw));
+ const float scale = 1. / (k0 * k1);
+
+ float res = 0;
+
+ for (int i = bh; i < eh; i += 1) {
+ for (int j = bw; j < ew; j += 1) {
+ float cur = i_ptr[i * IW + j];
+ res += cur * scale;
+ }
+ }
+
+ o_ptr[cur_oh * OW + cur_ow] = res;
+}
diff --git a/vendor/candle-metal-kernels/src/metal_src/random.metal b/vendor/candle-metal-kernels/src/metal_src/random.metal
new file mode 100644
index 0000000..b94ba45
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/random.metal
@@ -0,0 +1,232 @@
+#include <metal_stdlib>
+#include <metal_integer>
+#include <metal_atomic>
+
+using namespace metal;
+
+// Constants
+// 2^32 and 1/2^32. Useful for converting between float and uint.
+static constexpr constant ulong UNIF01_NORM32 = 4294967296;
+static constexpr constant float UNIF01_INV32 = 2.328306436538696289e-10;
+// 2 * pi
+static constexpr constant float TWO_PI = 2.0 * M_PI_F;
+static constexpr constant int3 S1 = {13, 19, 12};
+static constexpr constant int3 S2 = {2, 25, 4};
+static constexpr constant int3 S3 = {3, 11, 17};
+
+// Used to prevent bad seeds.
+static constexpr constant uint64_t PHI[16] = {
+ 0x9E3779B97F4A7C15,
+ 0xF39CC0605CEDC834,
+ 0x1082276BF3A27251,
+ 0xF86C6A11D0C18E95,
+ 0x2767F0B153D27B7F,
+ 0x0347045B5BF1827F,
+ 0x01886F0928403002,
+ 0xC1D64BA40F335E36,
+ 0xF06AD7AE9717877E,
+ 0x85839D6EFFBD7DC6,
+ 0x64D325D1C5371682,
+ 0xCADD0CCCFDFFBBE1,
+ 0x626E33B8D04B4331,
+ 0xBBF73C790D94F79D,
+ 0x471C4AB3ED3D82A5,
+ 0xFEC507705E4AE6E5,
+};
+
+// Combined Tausworthe and LCG Random Number Generator.
+// https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-37-efficient-random-number-generation-and-application
+// https://indico.cern.ch/event/93877/contributions/2118070/attachments/1104200/1575343/acat3_revised_final.pdf
+struct HybridTaus {
+
+ float state;
+
+ HybridTaus() thread = default;
+ HybridTaus() threadgroup = default;
+ HybridTaus() device = default;
+ HybridTaus() constant = default;
+
+ // Generate seeds for each thread.
+ METAL_FUNC static uint4 seed_per_thread(const ulong4 seeds) {
+ return uint4(ulong4(seeds) * ulong4(PHI[0], PHI[1], PHI[2], PHI[3]) * ulong4(1099087573UL));
+ }
+
+ // Tausworthe generator.
+ METAL_FUNC static uint taus(const uint z, const int3 s, const uint M) {
+ uint b = (((z << s.x) ^ z) >> s.y);
+ return (((z & M) << s.z) ^ b);
+ }
+
+ // LCG generator.
+ METAL_FUNC static uint lcg(const uint z) {
+ return (1664525 * z + 1013904223UL);
+ }
+
+ // Initialize the RNG state.
+ METAL_FUNC static HybridTaus init(const ulong4 seeds) {
+ uint4 seed = seed_per_thread(seeds);
+
+ // Seed #1
+ uint z1 = taus(seed.x, S1, 4294967294UL);
+ uint z2 = taus(seed.y, S2, 4294967288UL);
+ uint z3 = taus(seed.z, S3, 4294967280UL);
+ uint z4 = lcg(seed.x);
+
+ // Seed #2
+ uint r1 = (z1^z2^z3^z4^seed.y);
+ z1 = taus(r1, S1, 429496729UL);
+ z2 = taus(r1, S2, 4294967288UL);
+ z3 = taus(r1, S3, 429496280UL);
+ z4 = lcg(r1);
+
+ // Seed #3
+ r1 = (z1^z2^z3^z4^seed.z);
+ z1 = taus(r1, S1, 429496729UL);
+ z2 = taus(r1, S2, 4294967288UL);
+ z3 = taus(r1, S3, 429496280UL);
+ z4 = lcg(r1);
+
+ // Seed #4
+ r1 = (z1^z2^z3^z4^seed.w);
+ z1 = taus(r1, S1, 429496729UL);
+ z2 = taus(r1, S2, 4294967288UL);
+ z3 = taus(r1, S3, 429496280UL);
+ z4 = lcg(r1);
+
+ HybridTaus rng;
+ rng.state = (z1^z2^z3^z4) * UNIF01_INV32;
+ return rng;
+ }
+
+ METAL_FUNC float rand() {
+ uint seed = this->state * UNIF01_NORM32;
+ uint z1 = taus(seed, S1, 429496729UL);
+ uint z2 = taus(seed, S2, 4294967288UL);
+ uint z3 = taus(seed, S3, 429496280UL);
+ uint z4 = lcg(seed);
+
+ thread float result = this->state;
+ this->state = (z1^z2^z3^z4) * UNIF01_INV32;
+ return result;
+ }
+};
+typedef struct
+{
+ atomic_uint seed[2];
+} seed_buffer;
+
+
+METAL_FUNC ulong atomic_load_seed(device seed_buffer *sb) {
+ uint x = atomic_load_explicit(&sb->seed[0], memory_order_relaxed);
+ uint y = atomic_load_explicit(&sb->seed[1], memory_order_relaxed);
+ return static_cast<ulong>(x) << 32 | y;
+}
+
+METAL_FUNC void atomic_store_seed(device seed_buffer *sb, ulong desired) {
+ uint x = static_cast<uint>(desired >> 32);
+ uint y = static_cast<uint>(desired & 0xFFFFFFFF);
+ atomic_store_explicit(&sb->seed[0], x, memory_order_relaxed);
+ atomic_store_explicit(&sb->seed[1], y, memory_order_relaxed);
+}
+
+template<typename T> METAL_FUNC void rand_uniform(
+ constant size_t &size,
+ constant float &min,
+ constant float &max,
+ device seed_buffer *sb,
+ device T *out,
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid >= size) {
+ return;
+ }
+
+ // Evenly sized vectors need an offset when writing the mirror element.
+ uint off = 1 - size % 2;
+ float diff = abs(min - max);
+ ulong s = atomic_load_seed(sb);
+ HybridTaus rng = HybridTaus::init({s, tid, 1, 1});
+ out[tid] = static_cast<T>(rng.rand() * diff + min);
+ if (tid == 0) {
+ atomic_store_seed(sb, rng.rand() * UNIF01_NORM32);
+ // Return early if tid == 0 && off == 0, otherwise we will write to out[size].
+ if (off == 0)
+ return;
+ }
+ // Use symmetry to fill the other half of the array.
+ out[size - off - tid] = static_cast<T>(rng.rand() * diff + min);
+}
+
+// Create Gaussian normal distribution using Box-Muller transform:
+// https://en.wikipedia.org/wiki/Box–Muller_transform
+template<typename T> METAL_FUNC void normal(
+ constant size_t &size,
+ constant float &mean,
+ constant float &stddev,
+ device seed_buffer *sb,
+ device T *out,
+ uint tid [[thread_position_in_grid]]
+) {
+ if (tid >= size) {
+ return;
+ }
+ // Evenly sized vectors need an offset when writing the mirror element.
+ uint off = 1 - size % 2;
+ ulong s = atomic_load_seed(sb);
+ HybridTaus rng = HybridTaus::init({s, tid, 1, 1});
+ float u1 = rng.rand();
+ float u2 = rng.rand();
+
+ float cosval;
+ float sinval = sincos(TWO_PI * u2, cosval);
+ float mag = stddev * sqrt(-2.0 * log(u1));
+ float z0 = mag * cosval + mean;
+ float z1 = mag * sinval + mean;
+
+ out[tid] = static_cast<T>(z0);
+
+ if (tid == 0) {
+ atomic_store_seed(sb, rng.rand() * UNIF01_NORM32);
+ // Return early if tid == 0 && off == 0, otherwise we will write to out[size].
+ if (off == 0)
+ return;
+ }
+ // Use symmetry to fill the other half of the array.
+ out[size - off - tid] = static_cast<T>(z1);
+}
+
+#define UNIFORM_OP(NAME, T) \
+kernel void rand_uniform_##NAME( \
+ constant size_t &size, \
+ constant float &min, \
+ constant float &max, \
+ device seed_buffer *sb, \
+ device T *out, \
+ uint tid [[thread_position_in_grid]] \
+) { \
+ rand_uniform<T>(size, min, max, sb, out, tid); \
+} \
+
+#define NORMAL_OP(NAME, T) \
+kernel void rand_normal_##NAME( \
+ constant size_t &size, \
+ constant float &mean, \
+ constant float &stddev, \
+ device seed_buffer *sb, \
+ device T *out, \
+ uint tid [[thread_position_in_grid]] \
+) { \
+ normal<T>(size, mean, stddev, sb, out, tid); \
+} \
+
+
+#define RANDOM_OPS(NAME, T) \
+UNIFORM_OP(NAME, T) \
+NORMAL_OP(NAME, T) \
+
+RANDOM_OPS(f32, float)
+RANDOM_OPS(f16, half)
+
+#if __METAL_VERSION__ >= 310
+RANDOM_OPS(bf16, bfloat)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/reduce.metal b/vendor/candle-metal-kernels/src/metal_src/reduce.metal
new file mode 100644
index 0000000..db8668f
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/reduce.metal
@@ -0,0 +1,1554 @@
+#include <metal_stdlib>
+#include <metal_limits>
+using namespace metal;
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+METAL_FUNC uint nonzero(uint n) {
+ return n == 0 ? 1 : n;
+}
+
+template<uint N>
+constexpr uint nonzero() {
+ return N == 0 ? 1 : N;
+}
+
+template<typename T>
+constexpr ushort granularity() {
+ return nonzero<vec_elements<T>::value>();
+}
+
+METAL_FUNC uint next_p2(uint x) {
+ return 1 << (32 - clz(x - 1));
+}
+
+METAL_FUNC uint prev_p2(uint x) {
+ return 1 << (31 - clz(x));
+}
+
+constant uint MAX_SHARED_MEM = 32767;
+
+template<typename T>
+METAL_FUNC uint max_shared_mem(uint n) {
+ return min(n, div_ceil<MAX_SHARED_MEM, sizeof(T)>());
+}
+
+
+template<ushort D, typename IndexT>
+struct strided_indexer {
+ constant const IndexT *dims;
+ constant const IndexT *strides;
+ strided_indexer<D - 1, IndexT> next {dims, strides};
+
+ METAL_FUNC IndexT operator()(IndexT idx) const {
+ IndexT dim = dims[D - 1];
+ IndexT i = (idx % dim) * strides[D - 1];
+ idx /= dim;
+ return i + next(idx);
+ }
+};
+
+template<typename IndexT>
+struct strided_indexer<1, IndexT> {
+ constant const IndexT *dims;
+ constant const IndexT *strides;
+
+ METAL_FUNC IndexT operator()(IndexT idx) const {
+ return idx * strides[0];
+ }
+};
+
+template<ushort D, typename IndexT>
+METAL_FUNC IndexT get_strided_idx_fallback(
+ IndexT idx,
+ constant const IndexT &num_dims,
+ constant const IndexT *dims,
+ constant const IndexT *strides
+) {
+ strided_indexer<D, IndexT> next {dims, strides};
+
+ IndexT strided_i = 0;
+ for (IndexT d = D; d < num_dims; d++) {
+ IndexT dim_idx = num_dims - 1 - (d - D);
+ IndexT dim = dims[dim_idx];
+ strided_i += (idx % dim) * strides[dim_idx];
+ idx /= dim;
+ }
+ return strided_i + next(idx);
+}
+
+template<typename IndexT>
+METAL_FUNC IndexT get_strided_index_t(
+ IndexT idx,
+ constant const IndexT &num_dims,
+ constant const IndexT *dims,
+ constant const IndexT *strides
+) {
+ switch (num_dims) {
+ case 1: return strided_indexer<1, IndexT>{dims, strides}(idx);
+ case 2: return strided_indexer<2, IndexT>{dims, strides}(idx);
+ case 3: return strided_indexer<3, IndexT>{dims, strides}(idx);
+ case 4: return strided_indexer<4, IndexT>{dims, strides}(idx);
+ //case 5: return strided_indexer<5, IndexT>{dims, strides}(idx);
+ //case 6: return strided_indexer<6, IndexT>{dims, strides}(idx);
+ default: return get_strided_idx_fallback<4, IndexT>(idx, num_dims, dims, strides);
+ }
+}
+
+template<typename IndexT, bool STRIDED>
+struct indexer_t {
+ typedef IndexT I;
+};
+
+template<typename IndexT>
+struct indexer_t<IndexT, false> {
+ typedef IndexT I;
+
+ const IndexT last_dim = 0;
+
+ METAL_FUNC IndexT operator()(IndexT i) const {
+ return i;
+ }
+};
+
+template<typename IndexT>
+struct indexer_t<IndexT, true> {
+ typedef IndexT I;
+
+ constant const IndexT &num_dims;
+ constant const IndexT *dims;
+ constant const IndexT *strides;
+ const IndexT last_dim;
+
+ METAL_FUNC IndexT operator()(IndexT i) const {
+ return get_strided_index_t(i, num_dims, dims, strides);
+ }
+};
+
+struct Divide {
+ template<typename T>
+ METAL_FUNC T operator()(T a, T b) { return a / b; }
+ METAL_FUNC float operator()(float a, float b) { return fast::divide(a, b); }
+ METAL_FUNC half operator()(half a, half b) { return divide(a, b); }
+ #if defined(__HAVE_BFLOAT__)
+ METAL_FUNC bfloat operator()(bfloat a, bfloat b) { return static_cast<bfloat>(fast::divide(a, b)); }
+ #endif
+};
+
+struct Exp {
+ template<typename T>
+ METAL_FUNC T operator()(T a) { return fast::exp(a); }
+ METAL_FUNC float operator()(float a) { return fast::exp(a); }
+ METAL_FUNC half operator()(half a) { return exp(a); }
+ #if defined(__HAVE_BFLOAT__)
+ METAL_FUNC bfloat operator()(bfloat a) { return static_cast<bfloat>(fast::exp(a)); }
+ #endif
+};
+
+
+// Keeps track of the index of the value in the reduction operation (argmin, argmax, etc.)
+// and the value itself. The index is also used to break ties in the reduction operation.
+template <typename T>
+struct indexed {
+ uint i;
+ T val;
+
+ constexpr indexed<T>() threadgroup = default;
+};
+
+template <typename T>
+struct is_indexed_type {
+ static constant constexpr bool value = false;
+};
+
+template <typename T>
+constexpr constant bool is_indexed_t = is_indexed_type<T>::value;
+
+template <typename T>
+struct is_indexed_type<indexed<T>> {
+ static constant constexpr bool value = true;
+};
+
+template <typename T>
+constexpr constant bool not_indexed_t = !is_indexed_t<T>;
+
+template<typename T>
+constexpr METAL_FUNC bool operator<(indexed<T> lhs, indexed<T> rhs) {
+ return lhs.val < rhs.val || (lhs.val == rhs.val && lhs.i < rhs.i);
+}
+
+template<typename T>
+constexpr METAL_FUNC bool operator>(indexed<T> lhs, indexed<T> rhs) {
+ return lhs.val > rhs.val || (lhs.val == rhs.val && lhs.i < rhs.i);
+}
+
+template<typename T>
+struct _numeric_limits_impl<indexed<T>> {
+ static constexpr METAL_FUNC indexed<T> lowest() {
+ return indexed<T>{ 0, numeric_limits<T>::lowest() };
+ }
+
+ static constexpr METAL_FUNC indexed<T> max() {
+ return indexed<T>{ 0, numeric_limits<T>::max() };
+ }
+};
+
+#if __METAL_VERSION__ >= 220
+METAL_FUNC int64_t simd_shuffle_down(int64_t data, uint16_t delta) {
+ return as_type<int64_t>(simd_shuffle_down(as_type<uint2>(data), delta));
+}
+#endif
+
+
+#if defined(__HAVE_BFLOAT__)
+// Metal does not have simd_shuffle_down for bfloat16
+METAL_FUNC bfloat simd_shuffle_down(bfloat value, ushort delta) {
+ return as_type<bfloat>(simd_shuffle_down(as_type<ushort>(value), delta));
+}
+#endif
+
+template <typename T>
+METAL_FUNC indexed<T> simd_shuffle_down(indexed<T> iv, ushort delta) {
+ return indexed<T> {
+ simd_shuffle_down(iv.i, delta),
+ simd_shuffle_down(iv.val, delta)
+ };
+}
+
+template<typename T>
+struct Sum {
+ static constexpr METAL_FUNC T init() {
+ return 0;
+ }
+ static METAL_FUNC T simd_op(T a) {
+ return simd_sum(a);
+ }
+
+ template<typename V>
+ METAL_FUNC V operator()(V a, V b) {
+ return a + b;
+ }
+};
+
+template<typename T>
+struct Mul {
+ static constexpr METAL_FUNC T init() {
+ return 1;
+ }
+ static METAL_FUNC T simd_op(T a) {
+ return simd_product(a);
+ }
+
+ template<typename V>
+ METAL_FUNC V operator()(V a, V b) {
+ return a * b;
+ }
+};
+
+template<typename T>
+struct Min {
+ static constexpr METAL_FUNC T init() {
+ return numeric_limits<T>::max();
+ }
+ static METAL_FUNC T simd_op(T a) {
+ return simd_min(a);
+ }
+
+ template<typename V>
+ METAL_FUNC V operator()(V a, V b) { return a < b ? a : b; }
+
+ METAL_FUNC float operator()(float a, float b) { return fast::min(a, b); }
+ METAL_FUNC half operator()(half a, half b) { return min(a, b); }
+ METAL_FUNC uint operator()(uint a, uint b) { return min(a, b); }
+ METAL_FUNC uchar operator()(uchar a, uchar b) { return min(a, b); }
+
+ #if __METAL_VERSION__ >= 220
+ METAL_FUNC long operator()(long a, long b) { return min(a, b); }
+ #endif
+
+ #if defined(__HAVE_BFLOAT__)
+ METAL_FUNC bfloat operator()(bfloat a, bfloat b) { return static_cast<bfloat>(fast::min(static_cast<float>(a), static_cast<float>(b))); }
+ #endif
+};
+
+template<typename T>
+struct Max {
+ static constexpr METAL_FUNC T init() {
+ return numeric_limits<T>::lowest();
+ }
+ static METAL_FUNC T simd_op(T a) {
+ return simd_max(a);
+ }
+
+ template<typename V>
+ METAL_FUNC V operator()(V a, V b) { return a > b ? a : b; }
+
+ METAL_FUNC float operator()(float a, float b) { return fast::max(a, b); }
+ METAL_FUNC half operator()(half a, half b) { return max(a, b); }
+ METAL_FUNC uint operator()(uint a, uint b) { return max(a, b); }
+ METAL_FUNC uchar operator()(uchar a, uchar b) { return max(a, b); }
+
+ #if __METAL_VERSION__ >= 220
+ METAL_FUNC long operator()(long a, long b) { return max(a, b); }
+ #endif
+
+ #if defined(__HAVE_BFLOAT__)
+ METAL_FUNC bfloat operator()(bfloat a, bfloat b) { return static_cast<bfloat>(fast::max(static_cast<float>(a), static_cast<float>(b))); }
+ #endif
+};
+
+template <typename T>
+constexpr constant bool is_simd_t = __is_valid_simdgroup_type<T>::value;
+
+template <typename T, typename _E = void>
+struct is_valid_simd_type {
+ static constant constexpr bool value = false;
+};
+
+template <typename T>
+constexpr constant bool is_valid_simd_t = is_valid_simd_type<T>::value;
+
+template <typename T>
+struct is_valid_simd_type<T, typename metal::enable_if_t<is_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+template <typename T>
+struct is_valid_simd_type<indexed<T>, typename metal::enable_if_t<is_valid_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+#if __METAL_VERSION__ >= 220
+template <>
+struct is_valid_simd_type<int64_t> {
+ static constant constexpr bool value = true;
+};
+#endif
+
+#if defined(__HAVE_BFLOAT__)
+template <>
+struct is_valid_simd_type<bfloat> {
+ static constant constexpr bool value = true;
+};
+#endif
+
+template <typename T, typename _E = void>
+struct is_simd_op {
+ static constant constexpr bool value = false;
+};
+template <typename T>
+struct is_simd_op<Sum<T>, typename metal::enable_if_t<is_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+template <typename T>
+struct is_simd_op<Mul<T>, typename metal::enable_if_t<is_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+template <typename T>
+struct is_simd_op<Min<T>, typename metal::enable_if_t<is_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+template <typename T>
+struct is_simd_op<Max<T>, typename metal::enable_if_t<is_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+// Helper struct for applying operators.
+// The overloaded operator() function is used to apply an operator to two values.
+template<typename OP, typename T>
+struct operation;
+
+// Specialization for scalar values.
+template<typename OP, typename T>
+struct operation {
+ OP op;
+
+ METAL_FUNC T operator()(T a, T b) {
+ return op(a, b);
+ }
+};
+
+// Specialization for indexed values.
+template<typename OP, typename T>
+struct operation<OP, indexed<T>> {
+ OP op;
+
+ METAL_FUNC indexed<T> operator()(indexed<T> a, indexed<T> b) {
+ return op(a, b);
+ }
+ METAL_FUNC indexed<T> operator()(indexed<T> a, T b, uint idx) {
+ return this->operator()(a, indexed<T>{ idx, b });
+ }
+};
+
+// Load elements from global memory into shared memory.
+// Handles both indexed and non-indexed types by using operate.
+template<
+ typename T,
+ typename R,
+ typename OP,
+ ushort BLOCKSIZE,
+ typename Indexer,
+ typename IndexT,
+ typename _E = void
+>
+struct loader;
+
+template<
+ typename T,
+ typename R,
+ typename OP,
+ ushort BLOCKSIZE,
+ typename Indexer,
+ typename IndexT
+>
+struct loader<T, R, OP, BLOCKSIZE, Indexer, IndexT, typename metal::enable_if_t<not_indexed_t<R>>> {
+ operation<OP, R> operate;
+
+ METAL_FUNC R operator()(
+ R value,
+ Indexer indexer,
+ constant IndexT &src_numel,
+ constant IndexT &el_per_block,
+ device const T *src,
+ const IndexT offset,
+ const uint tid
+ ) {
+ const IndexT idx = tid + offset;
+ const IndexT stop_idx = min(el_per_block + offset, src_numel);
+
+ #pragma clang loop unroll(full)
+ for (IndexT i = idx; i < stop_idx; i += BLOCKSIZE) {
+ value = operate(value, src[indexer(i)]);
+ }
+ return value;
+ }
+};
+
+// Indexed
+template<
+ typename T,
+ typename R,
+ typename OP,
+ ushort BLOCKSIZE,
+ typename Indexer,
+ typename IndexT
+>
+struct loader<T, R, OP, BLOCKSIZE, Indexer, IndexT, typename metal::enable_if_t<is_indexed_t<R>>> {
+ operation<OP, R> operate;
+
+ METAL_FUNC R operator()(
+ R value,
+ Indexer indexer,
+ constant IndexT &src_numel,
+ constant IndexT &el_per_block,
+ device const T *src,
+ const IndexT offset,
+ const uint tid
+ ) {
+ const IndexT idx = tid + offset;
+ const IndexT stop_idx = min(el_per_block + offset, src_numel);
+
+ #pragma clang loop unroll(full)
+ for (IndexT i = idx; i < stop_idx; i += BLOCKSIZE) {
+ value = operate(value, src[indexer(i)], i % indexer.last_dim);
+ }
+ return value;
+ }
+};
+
+template<
+ typename OP,
+ ushort BLOCKSIZE,
+ typename T,
+ typename _E = void
+>
+struct simdgroup_reducer;
+
+// Specialization for built-in simd operations.
+template<typename OP, ushort BLOCKSIZE, typename T>
+struct simdgroup_reducer<OP, BLOCKSIZE, T, typename metal::enable_if_t<is_simd_op<OP>::value && is_valid_simd_t<T>>> {
+ METAL_FUNC T operator()(T value) {
+ return OP::simd_op(value);
+ }
+};
+
+// Specialization for custom (non-built-in) simd operations.
+template<typename OP, ushort BLOCKSIZE, typename T>
+struct simdgroup_reducer<OP, BLOCKSIZE, T, typename metal::enable_if_t<!is_simd_op<OP>::value && is_valid_simd_t<T>>> {
+ operation<OP, T> op;
+
+ METAL_FUNC T operator()(T value) {
+ if (BLOCKSIZE >= 32) value = op(value, simd_shuffle_down(value, 16));
+ if (BLOCKSIZE >= 16) value = op(value, simd_shuffle_down(value, 8));
+ if (BLOCKSIZE >= 8) value = op(value, simd_shuffle_down(value, 4));
+ if (BLOCKSIZE >= 4) value = op(value, simd_shuffle_down(value, 2));
+ if (BLOCKSIZE >= 2) value = op(value, simd_shuffle_down(value, 1));
+ return value;
+ }
+};
+
+template<typename T, typename OP, ushort BLOCKSIZE>
+struct block_reducer {
+ simdgroup_reducer<OP, BLOCKSIZE, T> simd_reduce;
+ operation<OP, T> operate;
+ threadgroup T *shared;
+
+ block_reducer(threadgroup T shared[BLOCKSIZE]) {
+ this->shared = shared;
+ }
+
+ METAL_FUNC T operator()(T value, const uint tid) {
+ if (BLOCKSIZE >= 64) {
+ // Only store in threadgroup shared memory if needed.
+ shared[tid] = value;
+ // Threadgroup barrier is needed to ensure that all threads have written to shared memory
+ threadgroup_barrier(mem_flags::mem_none);
+ }
+
+ #pragma clang loop unroll(full)
+ for (ushort s = BLOCKSIZE / 2; s >= 64; s >>= 1) {
+ if (tid < s) shared[tid] = operate(shared[tid], shared[tid + s]);
+ threadgroup_barrier(mem_flags::mem_none);
+ }
+ if (tid < 32) {
+ // Last shared memory reduce can be done without tid < s check.
+ if (BLOCKSIZE >= 64) {
+ value = operate(shared[tid], shared[tid + 32]);
+ simdgroup_barrier(mem_flags::mem_none);
+ }
+ // Remaining 32 threads can be reduced with simdgroup_reduce.
+ value = simd_reduce(value);
+ }
+ return value;
+ }
+};
+
+template<typename T, typename _E = void>
+struct storer;
+
+template<typename T>
+struct storer<T, typename metal::enable_if_t<not_indexed_t<T>>> {
+ device T *dst;
+ const uint tid;
+ const uint dst_id;
+
+ METAL_FUNC void operator()(T value) {
+ if (tid == 0) {
+ dst[dst_id] = value;
+ }
+ }
+};
+
+template<typename T>
+struct storer<T, typename metal::enable_if_t<is_indexed_t<T>>> {
+ device uint *dst;
+ const uint tid;
+ const uint dst_id;
+
+ METAL_FUNC void operator()(T value) {
+ if (tid == 0) {
+ dst[dst_id] = value.i;
+ }
+ }
+};
+
+// Inspired by "Optimizing Parallel Reduction in CUDA" by Mark Harris
+template<
+ typename T,
+ typename R,
+ typename OP,
+ ushort BLOCKSIZE,
+ typename Indexer,
+ typename IndexT = typename Indexer::IndexT
+>
+METAL_FUNC void reduce(
+ Indexer indexer,
+ constant IndexT &src_numel,
+ constant IndexT &el_per_block,
+ device const T *src,
+ device R *dst,
+ threadgroup R shared[BLOCKSIZE],
+ uint tid [[ thread_index_in_threadgroup ]],
+ uint dst_id [[ threadgroup_position_in_grid ]]
+) {
+ loader<T, R, OP, BLOCKSIZE, Indexer, IndexT> load;
+ block_reducer<R, OP, BLOCKSIZE> reduce(shared);
+ storer<R> store { dst, tid, dst_id };
+
+ // Calculate offset for the threadgroup of current thread
+ const IndexT offset = dst_id * el_per_block;
+
+ // Load with reduction from global memory into shared memory
+ auto value = load(OP::init(), indexer, src_numel, el_per_block, src, offset, tid);
+
+ // Complete reduction
+ R result = reduce(value, tid);
+
+ store(result);
+}
+
+#define reduce_switch(CASE_MACRO, OP, T, R, INDEXER) \
+ switch (max_shared_mem<T>(block_dim)) { \
+ CASE_MACRO(OP, T, R, 1024, INDEXER) \
+ CASE_MACRO(OP, T, R, 512, INDEXER) \
+ CASE_MACRO(OP, T, R, 256, INDEXER) \
+ CASE_MACRO(OP, T, R, 128, INDEXER) \
+ CASE_MACRO(OP, T, R, 64, INDEXER) \
+ CASE_MACRO(OP, T, R, 32, INDEXER) \
+ CASE_MACRO(OP, T, R, 16, INDEXER) \
+ CASE_MACRO(OP, T, R, 8, INDEXER) \
+ CASE_MACRO(OP, T, R, 4, INDEXER) \
+ CASE_MACRO(OP, T, R, 2, INDEXER) \
+ CASE_MACRO(OP, T, R, 1, INDEXER) \
+ }
+
+#define reduce_case(OP, T, R, N, INDEXER) \
+case N: { \
+ threadgroup T shared[N]; \
+ reduce<T, R, OP<R>, N>( \
+ INDEXER, src_numel, el_per_block, src, dst, shared, tid, dst_id \
+ ); \
+ break; \
+}
+
+#define impl_reduce_inner(OP, NAME, T) \
+kernel void NAME( \
+ constant uint &src_numel, \
+ constant uint &num_dims, \
+ constant uint *dims, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ indexer_t<uint, false> indexer; \
+ reduce_switch(reduce_case, OP, T, T, indexer) \
+}
+
+#define impl_reduce_strided(OP, NAME, T) \
+kernel void NAME##_strided( \
+ constant uint &src_numel, \
+ constant uint &num_dims, \
+ constant uint *dims, \
+ constant uint *strides, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ indexer_t<uint, true> indexer { \
+ num_dims, dims, strides, dims[num_dims - 1] \
+ }; \
+ reduce_switch(reduce_case, OP, T, T, indexer) \
+}
+
+#define impl_reduce(OP, NAME, T) \
+impl_reduce_inner(OP, NAME, T) \
+impl_reduce_strided(OP, NAME, T)
+
+template<
+ typename T,
+ typename ReductionOp,
+ ushort BLOCKSIZE,
+ typename Indexer,
+ typename IndexT = typename Indexer::IndexT
+>
+METAL_FUNC void reduce(
+ Indexer indexer,
+ constant IndexT &src_numel,
+ constant IndexT &el_per_block,
+ device const T *src,
+ device uint *dst,
+ threadgroup indexed<T> shared[BLOCKSIZE],
+ uint tid [[ thread_index_in_threadgroup ]],
+ uint dst_id [[ threadgroup_position_in_grid ]]
+) {
+ using I = indexed<T>;
+ loader<T, I, ReductionOp, BLOCKSIZE, Indexer, IndexT> load;
+ block_reducer<I, ReductionOp, BLOCKSIZE> reduce(shared);
+ storer<I> store { dst, tid, dst_id };
+
+ // Calculate offset for the threadgroup of current thread
+ const uint offset = dst_id * el_per_block;
+
+ // Load with reduction from global memory into shared memory
+ auto value = load(
+ ReductionOp::init(),
+ indexer,
+ src_numel,
+ el_per_block,
+ src,
+ offset,
+ tid
+ );
+
+ // Complete reduction
+ I result = reduce(value, tid);
+
+ // Return index of reduce result
+ store(result);
+}
+
+#define arg_reduce_case(OP, T, R, N, INDEXER) \
+case N: { \
+ using I = indexed<R>; \
+ threadgroup I shared[N]; \
+ reduce<T, OP<I>, N>( \
+ indexer, \
+ src_numel, \
+ el_per_block, \
+ src, \
+ dst, \
+ shared, \
+ tid, \
+ dst_id); \
+ break; \
+}
+
+#define impl_arg_reduce_inner(OP, NAME, T) \
+kernel void NAME( \
+ constant uint &src_numel, \
+ constant uint &num_dims, \
+ constant uint *dims, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device uint *dst, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ indexer_t<uint, false> indexer { \
+ dims[num_dims - 1] \
+ }; \
+ reduce_switch(arg_reduce_case, OP, T, T, indexer) \
+} \
+
+#define impl_arg_reduce_strided(OP, NAME, T) \
+kernel void NAME##_strided( \
+ constant uint &src_numel, \
+ constant uint &num_dims, \
+ constant uint *dims, \
+ constant uint *strides, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device uint *dst, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ indexer_t<uint, true> indexer { \
+ num_dims, dims, strides, dims[num_dims - 1] \
+ }; \
+ reduce_switch(arg_reduce_case, OP, T, T, indexer) \
+}
+
+#define impl_arg_reduce(OP, NAME, T) \
+impl_arg_reduce_inner(OP, NAME, T) \
+impl_arg_reduce_strided(OP, NAME, T)
+
+// Contains the intermediate results for the online softmax calculation.
+// m: max
+// d: sum of the exponentials
+template <typename T>
+struct MD {
+ T m;
+ float d;
+
+ constexpr MD<T>() = default;
+ constexpr MD<T>() threadgroup = default;
+};
+
+// Enable operations for softmax MD
+template<typename OP, typename T>
+struct operation<OP, MD<T>> {
+ OP op;
+
+ METAL_FUNC MD<T> operator()(MD<T> a, MD<T> b) {
+ return op(a, b);
+ }
+
+ METAL_FUNC MD<T> operator()(MD<T> a, T b) {
+ return this->operator()(a, MD<T>{ b, static_cast<T>(1.0) });
+ }
+};
+
+template <typename T>
+METAL_FUNC MD<T> simd_shuffle_down(MD<T> md, ushort delta) {
+ return MD<T> {
+ simd_shuffle_down(md.m, delta),
+ simd_shuffle_down(md.d, delta)
+ };
+}
+
+// Enable simd_shuffle_down for softmax MD
+template <typename T>
+struct is_valid_simd_type<MD<T>, typename metal::enable_if_t<is_valid_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+template<typename T>
+struct MDReduceOp {
+ Exp fast_exp;
+
+ static constexpr METAL_FUNC MD<T> init() {
+ return MD<T>{ numeric_limits<T>::lowest(), 0 };
+ }
+
+ METAL_FUNC MD<T> operator()(MD<T> a, MD<T> b) {
+ bool a_bigger = a.m > b.m;
+ MD<T> bigger_m = a_bigger ? a : b;
+ MD<T> smaller_m = a_bigger ? b : a;
+ MD<T> res;
+ res.d = bigger_m.d + smaller_m.d * fast_exp(smaller_m.m - bigger_m.m);
+ res.m = bigger_m.m;
+ return res;
+ }
+};
+
+template<typename T, ushort BLOCKSIZE>
+struct finalize_softmax {
+ Divide fast_divide;
+ Exp fast_exp;
+
+ METAL_FUNC void operator()(
+ device const T *src,
+ device T *dst,
+ threadgroup MD<T> &md_total,
+ const uint thread_id,
+ const uint stop_idx
+ ) {
+ const float d_total_inverse = fast_divide(1.0, md_total.d);
+ for (uint idx = thread_id; idx < stop_idx; idx += BLOCKSIZE) {
+ dst[idx] = static_cast<T>(fast_exp(src[idx] - md_total.m) * d_total_inverse);
+ }
+ }
+};
+
+
+// Welford's algorithm approach for an online softmax implementation.
+// Same as the Online normalizer calculation for softmax: https://arxiv.org/pdf/1805.02867.pdf
+template<typename T, ushort BLOCKSIZE>
+METAL_FUNC void softmax(
+ constant uint &src_numel,
+ constant uint &el_per_block,
+ device const T *src,
+ device T *dst,
+ threadgroup MD<T> shared[BLOCKSIZE],
+ threadgroup MD<T> &md_total,
+
+ uint tid [[ thread_index_in_threadgroup ]],
+ uint dst_id [[ threadgroup_position_in_grid ]]
+) {
+ using MDReduceOp = MDReduceOp<T>;
+ using Indexer = indexer_t<uint, false>;
+ Indexer indexer;
+ loader<T, MD<T>, MDReduceOp, BLOCKSIZE, Indexer, uint> load;
+ block_reducer<MD<T>, MDReduceOp, BLOCKSIZE> reduce(shared);
+ finalize_softmax<T, BLOCKSIZE> softmax_finalize;
+
+ // Calculate offset for the threadgroup of current thread;
+ const uint offset = dst_id * el_per_block;
+
+ // Calculate partial result for current thread
+ MD<T> md_partial = MD<T> { numeric_limits<T>::lowest(), 0 };
+ md_partial = load(
+ md_partial,
+ indexer,
+ src_numel,
+ el_per_block,
+ src,
+ offset,
+ tid
+ );
+
+ // Reduce in shared memory
+ MD<T> md = reduce(md_partial, tid);
+
+ if (tid == 0) md_total = md;
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Finalize softmax
+ const uint thread_id = tid + offset;
+ const uint stop_idx = min(el_per_block + offset, src_numel);
+ softmax_finalize(src, dst, md_total, thread_id, stop_idx);
+}
+
+#define softmax_case(T, N) \
+case N: { \
+ threadgroup MD<T> shared[N]; \
+ threadgroup MD<T> md_total; \
+ softmax<T, N>( \
+ src_numel, \
+ el_per_block, \
+ src, \
+ dst, \
+ shared, \
+ md_total, \
+ tid, \
+ dst_id); \
+ break; \
+}
+
+#define impl_softmax(NAME, T) \
+kernel void NAME( \
+ constant uint &src_numel, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device T *dst, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ switch (max_shared_mem<T>(block_dim)) { \
+ softmax_case(T, 1024); \
+ softmax_case(T, 512); \
+ softmax_case(T, 256); \
+ softmax_case(T, 128); \
+ softmax_case(T, 64); \
+ softmax_case(T, 32); \
+ softmax_case(T, 16); \
+ softmax_case(T, 8); \
+ softmax_case(T, 4); \
+ softmax_case(T, 2); \
+ softmax_case(T, 1); \
+ } \
+}
+
+
+template<typename T>
+METAL_FUNC void rmsnorm(
+ constant size_t &src_numel,
+ constant size_t &el_to_sum_per_block,
+ device const T *src,
+ device T *dst,
+ device const T *alpha,
+ constant float &eps,
+ uint id,
+ uint tid,
+ uint dst_id,
+ uint block_dim,
+ threadgroup float * shared_memory
+) {
+ size_t start_idx = dst_id * el_to_sum_per_block;
+ size_t stop_idx = min(start_idx + el_to_sum_per_block, src_numel);
+ size_t idx = start_idx + tid;
+
+ float tmp = 0;
+ while (idx < stop_idx) {
+ tmp = tmp + float(src[idx]) * float(src[idx]);
+ idx += block_dim;
+ }
+ shared_memory[tid] = tmp;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint s = block_dim / 2; s > 0; s >>= 1) {
+ if (tid < s) {
+ shared_memory[tid] = shared_memory[tid] + shared_memory[tid + s];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ /* wait for shared_memory[0] to be filled */
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ float norm = sqrt(shared_memory[0] / float(el_to_sum_per_block) + eps);
+ float inv_norm = 1.0f / norm;
+ idx = start_idx + tid;
+ while (idx < stop_idx) {
+ float val = float(src[idx]) * inv_norm;
+ if (alpha != nullptr) {
+ val *= float(alpha[idx - start_idx]);
+ }
+ dst[idx] = T(val);
+ idx += block_dim;
+ }
+}
+
+template<typename T>
+struct RMS {
+ uint count;
+ T sum_sq;
+
+ constexpr RMS<T>() = default;
+ constexpr RMS<T>() threadgroup = default;
+};
+
+template<typename T>
+struct RMSLoadOp {
+ static constexpr METAL_FUNC RMS<T> init() {
+ return { 0, 0 };
+ }
+
+ METAL_FUNC RMS<T> operator()(RMS<T> a, RMS<T> b) {
+ a.sum_sq += (b.sum_sq * b.sum_sq);
+ a.count += 1;
+ return a;
+ }
+};
+
+template<typename T>
+struct RMSReduceOp {
+ static constexpr METAL_FUNC RMS<T> init() {
+ return { 0, 0 };
+ }
+
+ METAL_FUNC RMS<T> operator()(RMS<T> a, RMS<T> b) {
+ a.sum_sq += b.sum_sq;
+ a.count += b.count;
+ return a;
+ }
+};
+
+template<typename OP, typename T>
+struct operation<OP, RMS<T>> {
+ OP op;
+
+ METAL_FUNC RMS<T> operator()(RMS<T> a, RMS<T> b) {
+ return op(a, b);
+ }
+
+ template<typename U>
+ METAL_FUNC RMS<T> operator()(RMS<T> a, U b) {
+ return this->operator()(a, RMS<T>{ 0, static_cast<T>(b) });
+ }
+};
+
+template <typename T>
+METAL_FUNC RMS<T> simd_shuffle_down(RMS<T> rms, ushort delta) {
+ return RMS<T> {
+ simd_shuffle_down(rms.count, delta),
+ simd_shuffle_down(rms.sum_sq, delta)
+ };
+}
+
+template <typename T>
+struct is_valid_simd_type<RMS<T>, typename metal::enable_if_t<is_valid_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+// Kernels
+template<
+ typename T,
+ ushort BLOCKSIZE
+>
+METAL_FUNC void rms_norm(
+ constant uint &src_numel,
+ constant uint &el_per_block,
+ device const T *src,
+ device T *dst,
+ device const T *alpha,
+ constant float &eps,
+ threadgroup RMS<float> shared[BLOCKSIZE],
+ threadgroup float &total,
+
+ uint tid [[ thread_index_in_threadgroup ]],
+ uint dst_id [[ threadgroup_position_in_grid ]]
+) {
+ using Indexer = indexer_t<uint, false>;
+ Indexer indexer;
+ Divide fast_divide;
+ loader<T, RMS<float>, RMSLoadOp<float>, BLOCKSIZE, Indexer, uint> load;
+ block_reducer<RMS<float>, RMSReduceOp<float>, BLOCKSIZE> reduce(shared);
+
+ // Calculate offset for the threadgroup of current thread
+ const uint offset = dst_id * el_per_block;
+ const uint stop_idx = min(el_per_block + offset, src_numel);
+ const uint idx = tid + offset;
+
+ // Load with reduction from global memory into shared memory
+ RMS<float> value = load(
+ RMSLoadOp<float>::init(),
+ indexer,
+ src_numel,
+ el_per_block,
+ src,
+ offset,
+ tid
+ );
+ RMS<float> result = RMS<float> { value.count, static_cast<float>(value.sum_sq) };
+
+ // Complete reduction
+ result = reduce(result, tid);
+ if (tid == 0) {
+ total = rsqrt(fast_divide(result.sum_sq, float(el_per_block)) + eps);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (alpha == nullptr) {
+ #pragma clang loop unroll(full)
+ for (uint i = idx; i < stop_idx; i += BLOCKSIZE) {
+ dst[i] = src[i] * static_cast<T>(total);
+ }
+ } else {
+ #pragma clang loop unroll(full)
+ for (uint i = idx; i < stop_idx; i += BLOCKSIZE) {
+ T val = src[i] * static_cast<T>(total);
+ val *= alpha[i - offset];
+ dst[i] = val;
+ }
+ }
+}
+
+
+#define rms_norm_case(T, N) \
+case N: { \
+ threadgroup RMS<float> shared[N]; \
+ threadgroup float total; \
+ rms_norm<T, N>( \
+ src_numel, \
+ el_per_block, \
+ src, \
+ dst, \
+ alpha, \
+ eps, \
+ shared, \
+ total, \
+ tid, \
+ dst_id); \
+ break; \
+}
+
+#define impl_rms_norm(NAME, T) \
+kernel void NAME( \
+ constant uint &src_numel, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device T *dst, \
+ device const T *alpha, \
+ constant float &eps, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ switch (max_shared_mem<float>(block_dim)) { \
+ rms_norm_case(T, 1024); \
+ rms_norm_case(T, 512); \
+ rms_norm_case(T, 256); \
+ rms_norm_case(T, 128); \
+ rms_norm_case(T, 64); \
+ rms_norm_case(T, 32); \
+ rms_norm_case(T, 16); \
+ rms_norm_case(T, 8); \
+ rms_norm_case(T, 4); \
+ rms_norm_case(T, 2); \
+ rms_norm_case(T, 1); \
+ } \
+}
+
+template<typename T>
+struct LayerNormValue {
+ uint count;
+ T mean;
+ T m2;
+
+ constexpr LayerNormValue<T>() = default;
+ constexpr LayerNormValue<T>() threadgroup = default;
+};
+
+template<typename T>
+struct LNLoadOp {
+ static constexpr METAL_FUNC LayerNormValue<T> init() {
+ return { 0, 0, 0 };
+ }
+
+ METAL_FUNC LayerNormValue<T> operator()(LayerNormValue<T> a, LayerNormValue<T> b) {
+ a.count += 1;
+ T delta1 = b.mean - a.mean;
+ a.mean += delta1 / a.count;
+ T delta2 = b.mean - a.mean;
+ a.m2 += delta1 * delta2;
+ return a;
+ }
+};
+
+template<typename T>
+struct LNReduceOp {
+ static constexpr METAL_FUNC LayerNormValue<T> init() {
+ return { 0, 0, 0 };
+ }
+
+ METAL_FUNC LayerNormValue<T> operator()(LayerNormValue<T> a, LayerNormValue<T> b) {
+ if (b.count == 0) {
+ return a;
+ }
+ uint new_count = a.count + b.count;
+ T nb_over_n = b.count / T(new_count);
+ T delta = b.mean - a.mean;
+ a.mean += delta * nb_over_n;
+ a.m2 += b.m2 + delta * delta * a.count * nb_over_n;
+ a.count = new_count;
+ return a;
+ }
+};
+
+template<typename OP, typename T>
+struct operation<OP, LayerNormValue<T>> {
+ OP op;
+
+ METAL_FUNC LayerNormValue<T> operator()(LayerNormValue<T> a, LayerNormValue<T> b) {
+ return op(a, b);
+ }
+
+ template<typename U>
+ METAL_FUNC LayerNormValue<T> operator()(LayerNormValue<T> a, U b) {
+ return this->operator()(a, LayerNormValue<T>{ 0, static_cast<T>(b), static_cast<T>(b) });
+ }
+};
+
+template <typename T>
+METAL_FUNC LayerNormValue<T> simd_shuffle_down(LayerNormValue<T> lnv, ushort delta) {
+ return LayerNormValue<T> {
+ simd_shuffle_down(lnv.count, delta),
+ simd_shuffle_down(lnv.mean, delta),
+ simd_shuffle_down(lnv.m2, delta)
+ };
+}
+
+template <typename T>
+struct is_valid_simd_type<LayerNormValue<T>, typename metal::enable_if_t<is_valid_simd_t<T>>> {
+ static constant constexpr bool value = true;
+};
+
+// Kernels
+template<
+ typename T,
+ ushort BLOCKSIZE
+>
+METAL_FUNC void layer_norm(
+ constant uint &src_numel,
+ constant uint &el_per_block,
+ device const T *src,
+ device T *dst,
+ device const T *alpha,
+ device const T *beta,
+ constant float &eps,
+ threadgroup LayerNormValue<float> shared[BLOCKSIZE],
+ threadgroup float &mu,
+ threadgroup float &sigma,
+
+ uint tid [[ thread_index_in_threadgroup ]],
+ uint dst_id [[ threadgroup_position_in_grid ]],
+ uint lane_id [[thread_index_in_simdgroup]]
+) {
+ using Indexer = indexer_t<uint, false>;
+ Indexer indexer;
+ Divide fast_divide;
+ loader<T, LayerNormValue<float>, LNLoadOp<float>, BLOCKSIZE, Indexer, uint> load;
+ block_reducer<LayerNormValue<float>, LNReduceOp<float>, BLOCKSIZE> reduce(shared);
+
+ // Calculate offset for the threadgroup of current thread
+ const uint offset = dst_id * el_per_block;
+ const uint stop_idx = min(el_per_block + offset, src_numel);
+ const uint idx = tid + offset;
+
+ // Load with reduction from global memory into shared memory
+ LayerNormValue<float> value = load(
+ LNReduceOp<float>::init(),
+ indexer,
+ src_numel,
+ el_per_block,
+ src,
+ offset,
+ tid
+ );
+ LayerNormValue<float> result = LayerNormValue<float> { value.count, static_cast<float>(value.mean), static_cast<float>(value.m2) };
+
+ // Complete reduction
+ result = reduce(result, tid);
+ if (tid == 0) {
+ mu = result.mean;
+ sigma = rsqrt(fast_divide(result.m2, float(result.count)) + eps);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (alpha == nullptr || beta == nullptr) {
+ if (alpha == nullptr) {
+ #pragma clang loop unroll(full)
+ for (uint i = idx; i < stop_idx; i += BLOCKSIZE) {
+ T val = src[i];
+ T normalized = (val - static_cast<T>(mu)) * static_cast<T>(sigma);
+ dst[i] = normalized + beta[i - offset];
+ }
+ } else {
+ #pragma clang loop unroll(full)
+ for (uint i = idx; i < stop_idx; i += BLOCKSIZE) {
+ T val = src[i];
+ T normalized = (val - static_cast<T>(mu)) * static_cast<T>(sigma);
+ dst[i] = normalized * alpha[i - offset];
+ }
+ }
+ } else {
+ #pragma clang loop unroll(full)
+ for (uint i = idx; i < stop_idx; i += BLOCKSIZE) {
+ T val = src[i];
+ T normalized = (val - static_cast<T>(mu)) * static_cast<T>(sigma);
+ dst[i] = static_cast<T>(fma(normalized, alpha[i - offset], beta[i - offset]));
+ }
+ }
+}
+
+#define layer_norm_case(T, N) \
+case N: { \
+ threadgroup LayerNormValue<float> shared[N]; \
+ threadgroup float mu; \
+ threadgroup float sigma; \
+ layer_norm<T, N>( \
+ src_numel, \
+ el_per_block, \
+ src, \
+ dst, \
+ alpha, \
+ beta, \
+ eps, \
+ shared, \
+ mu, \
+ sigma, \
+ tid, \
+ dst_id, \
+ lane_id); \
+ break; \
+}
+
+#define impl_layer_norm(NAME, T) \
+kernel void NAME( \
+ constant uint &src_numel, \
+ constant uint &el_per_block, \
+ device const T *src, \
+ device T *dst, \
+ device const T *alpha, \
+ device const T *beta, \
+ constant float &eps, \
+ uint tid [[ thread_index_in_threadgroup ]], \
+ uint dst_id [[ threadgroup_position_in_grid ]], \
+ uint lane_id [[thread_index_in_simdgroup]], \
+ uint block_dim [[ threads_per_threadgroup ]] \
+) { \
+ switch (max_shared_mem<float>(block_dim)) { \
+ layer_norm_case(T, 1024); \
+ layer_norm_case(T, 512); \
+ layer_norm_case(T, 256); \
+ layer_norm_case(T, 128); \
+ layer_norm_case(T, 64); \
+ layer_norm_case(T, 32); \
+ layer_norm_case(T, 16); \
+ layer_norm_case(T, 8); \
+ layer_norm_case(T, 4); \
+ layer_norm_case(T, 2); \
+ layer_norm_case(T, 1); \
+ } \
+}
+
+template<typename T>
+METAL_FUNC void ropei(
+ constant size_t &bh,
+ constant size_t &td,
+ constant size_t &stride_b,
+ device const T *src,
+ device const T *cos,
+ device const T *sin,
+ device T *dst,
+ uint tid
+) {
+ if (2 * tid >= bh * td) {
+ return;
+ }
+ size_t rope_idx = tid % (td / 2);
+ if (stride_b > 0) {
+ size_t b_idx = (2 * tid) / stride_b;
+ rope_idx += b_idx * (td / 2);
+ }
+ T c = cos[rope_idx];
+ T s = sin[rope_idx];
+ dst[2 * tid] = src[2 * tid] * c - src[2 * tid + 1] * s;
+ dst[2 * tid + 1] = src[2 * tid] * s + src[2 * tid + 1] * c;
+}
+
+template<typename T>
+METAL_FUNC void rope(
+ constant size_t &bh,
+ constant size_t &td,
+ constant size_t &d,
+ constant size_t &stride_b,
+ device const T *src,
+ device const T *cos,
+ device const T *sin,
+ device T *dst,
+ uint idx
+) {
+ if (2 * idx >= bh * td) {
+ return;
+ }
+ size_t i_bh = idx / (td / 2);
+ size_t i_td = idx - (td / 2) * i_bh;
+ size_t i_t = i_td / (d / 2);
+ size_t i_d = i_td - (d / 2) * i_t;
+ size_t i1 = i_bh * td + i_t * d + i_d;
+ size_t i2 = i1 + d / 2;
+ size_t i_cs = i_t * (d / 2) + i_d;
+ if (stride_b > 0) {
+ size_t b_idx = (2 * idx) / stride_b;
+ i_cs += b_idx * (td / 2);
+ }
+ T c = cos[i_cs];
+ T s = sin[i_cs];
+ dst[i1] = src[i1] * c - src[i2] * s;
+ dst[i2] = src[i1] * s + src[i2] * c;
+}
+
+template<typename T>
+METAL_FUNC void rope_thd(
+ constant size_t &b,
+ constant size_t &t,
+ constant size_t &h,
+ constant size_t &d,
+ constant size_t &stride_b,
+ device const T *src,
+ device const T *cos,
+ device const T *sin,
+ device T *dst,
+ uint idx
+) {
+ if (2 * idx >= b * t * h * d) {
+ return;
+ }
+ const size_t i_bth = idx / (d / 2);
+ const size_t i_d = idx - (d / 2) * i_bth;
+ const size_t i_t = (i_bth / h) % t;
+ const size_t i1 = i_bth * d + i_d;
+ const size_t i2 = i1 + d / 2;
+ size_t i_cs = i_t * (d / 2) + i_d;
+ if (stride_b > 0) {
+ const size_t b_idx = (2 * idx) / stride_b;
+ i_cs += b_idx * ((t * d) / 2);
+ }
+ T c = cos[i_cs];
+ T s = sin[i_cs];
+ dst[i1] = src[i1] * c - src[i2] * s;
+ dst[i2] = src[i1] * s + src[i2] * c;
+}
+
+#define ROPE(FN_NAME, FN_NAME_I, FN_NAME_THD, TYPENAME) \
+kernel void FN_NAME_I( \
+ constant size_t &bh, \
+ constant size_t &td, \
+ constant size_t &stride_b, \
+ device const TYPENAME *src, \
+ device const TYPENAME *cos, \
+ device const TYPENAME *sin, \
+ device TYPENAME *dst, \
+ uint tid [[ thread_position_in_grid ]] \
+) { \
+ ropei<TYPENAME>(bh, td, stride_b, src, cos, sin, dst, tid); \
+}\
+kernel void FN_NAME( \
+ constant size_t &bh, \
+ constant size_t &td, \
+ constant size_t &d, \
+ constant size_t &stride_b, \
+ device const TYPENAME *src, \
+ device const TYPENAME *cos, \
+ device const TYPENAME *sin, \
+ device TYPENAME *dst, \
+ uint idx [[ thread_position_in_grid ]] \
+) { \
+ rope<TYPENAME>(bh, td, d, stride_b, src, cos, sin, dst, idx); \
+}\
+kernel void FN_NAME_THD( \
+ constant size_t &b, \
+ constant size_t &t, \
+ constant size_t &h, \
+ constant size_t &d, \
+ constant size_t &stride_b, \
+ device const TYPENAME *src, \
+ device const TYPENAME *cos, \
+ device const TYPENAME *sin, \
+ device TYPENAME *dst, \
+ uint idx [[ thread_position_in_grid ]] \
+) { \
+ rope_thd<TYPENAME>(b, t, h, d, stride_b, src, cos, sin, dst, idx); \
+}\
+
+impl_rms_norm(rmsnorm_f32, float)
+impl_rms_norm(rmsnorm_f16, half)
+impl_layer_norm(layernorm_f32, float)
+impl_layer_norm(layernorm_f16, half)
+ROPE(rope_f32, rope_i_f32, rope_thd_f32, float)
+ROPE(rope_f16, rope_i_f16, rope_thd_f16, half)
+
+impl_reduce(Sum, fast_sum_f32, float)
+impl_reduce(Sum, fast_sum_u32, uint)
+impl_reduce(Sum, fast_sum_f16, half)
+impl_reduce(Sum, fast_sum_u8, uint8_t)
+
+impl_reduce(Mul, fast_mul_f32, float)
+impl_reduce(Mul, fast_mul_u32, uint)
+impl_reduce(Mul, fast_mul_f16, half)
+impl_reduce(Mul, fast_mul_u8, uint8_t)
+
+impl_reduce(Max, fast_max_f32, float)
+impl_reduce(Max, fast_max_u32, uint)
+impl_reduce(Max, fast_max_f16, half)
+impl_reduce(Max, fast_max_u8, uint8_t)
+
+impl_reduce(Min, fast_min_f32, float)
+impl_reduce(Min, fast_min_u32, uint)
+impl_reduce(Min, fast_min_f16, half)
+impl_reduce(Min, fast_min_u8, uint8_t)
+
+impl_arg_reduce(Min, fast_argmin_f32, float)
+impl_arg_reduce(Min, fast_argmin_f16, half)
+impl_arg_reduce(Min, fast_argmin_u32, uint)
+impl_arg_reduce(Min, fast_argmin_u8, uint8_t)
+
+impl_arg_reduce(Max, fast_argmax_f32, float)
+impl_arg_reduce(Max, fast_argmax_f16, half)
+impl_arg_reduce(Max, fast_argmax_u32, uint)
+impl_arg_reduce(Max, fast_argmax_u8, uint8_t)
+
+impl_softmax(softmax_f32, float)
+impl_softmax(softmax_f16, half)
+
+#if __METAL_VERSION__ >= 220
+impl_reduce(Sum, fast_sum_i64, int64_t)
+impl_reduce(Mul, fast_mul_i64, int64_t)
+impl_reduce(Min, fast_min_i64, int64_t)
+impl_reduce(Max, fast_max_i64, int64_t)
+
+impl_arg_reduce(Min, fast_argmin_i64, int64_t)
+impl_arg_reduce(Max, fast_argmax_i64, int64_t)
+#endif
+
+#if defined(__HAVE_BFLOAT__)
+impl_reduce(Sum, fast_sum_bf16, bfloat)
+impl_reduce(Mul, fast_mul_bf16, bfloat)
+impl_reduce(Max, fast_max_bf16, bfloat)
+impl_reduce(Min, fast_min_bf16, bfloat)
+
+impl_arg_reduce(Min, fast_argmin_bf16, bfloat)
+impl_arg_reduce(Max, fast_argmax_bf16, bfloat)
+
+impl_softmax(softmax_bf16, bfloat)
+
+impl_rms_norm(rmsnorm_bf16, bfloat)
+impl_layer_norm(layernorm_bf16, bfloat)
+ROPE(rope_bf16, rope_i_bf16, rope_thd_bf16, bfloat)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/scaled_dot_product_attention.metal b/vendor/candle-metal-kernels/src/metal_src/scaled_dot_product_attention.metal
new file mode 100644
index 0000000..eba0ba0
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/scaled_dot_product_attention.metal
@@ -0,0 +1,2402 @@
+// Updated from MLX commit has f70764a
+
+#include <metal_stdlib>
+#include <metal_simdgroup>
+
+using namespace metal;
+
+#define STEEL_CONST static constant constexpr const
+#define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")
+
+#if defined(__HAVE_BFLOAT__)
+
+typedef bfloat bfloat16_t;
+typedef half float16_t;
+
+#else
+
+/////////////////////////////////////////////////////////////////////////////
+// Helpers
+/////////////////////////////////////////////////////////////////////////////
+
+constexpr METAL_FUNC uint16_t float_to_bfloat_bits(float x) {
+ // Check for nan
+ if ((as_type<uint32_t>(x) & ~_fp_encoding_traits<float>::sign_mask) >
+ _fp_encoding_traits<float>::inf_mask) {
+ return uint16_t(as_type<uint32_t>(0x7FC0));
+ }
+ // Take bits
+ uint32_t float_bits = as_type<uint32_t>(x);
+
+ // Round to nearest even
+ float_bits += ((float_bits >> 16) & 1) + as_type<uint32_t>(0x7FFF);
+
+ // Take upper 16 bits
+ return float_bits >> 16;
+}
+
+constexpr METAL_FUNC float bfloat_bits_to_float(uint16_t x) {
+ // Upper 16 bits are the data and lower 16 bits are 0s
+ return as_type<float>((uint32_t)x << 16);
+}
+
+struct _MLX_BFloat16;
+
+template <typename T>
+static constexpr constant bool can_convert_to_bfloat =
+ !is_same_v<T, _MLX_BFloat16> && is_convertible_v<T, float>;
+
+template <typename T>
+static constexpr constant bool can_convert_from_bfloat =
+ !is_same_v<T, _MLX_BFloat16> && is_convertible_v<float, T>;
+
+/////////////////////////////////////////////////////////////////////////////
+// Bfloat struct
+/////////////////////////////////////////////////////////////////////////////
+
+struct _MLX_BFloat16 {
+ /////////////////////////////////////////////////////////////////////////////
+ // Constructors
+ uint16_t bits_;
+ _MLX_BFloat16() thread = default;
+ _MLX_BFloat16() threadgroup = default;
+ _MLX_BFloat16() device = default;
+ _MLX_BFloat16() constant = default;
+
+ struct bits_to_bfloat_struct {};
+ static constexpr METAL_FUNC bits_to_bfloat_struct bits_to_bfloat() {
+ return bits_to_bfloat_struct();
+ }
+ constexpr METAL_FUNC _MLX_BFloat16(uint16_t bits, bits_to_bfloat_struct)
+ : bits_(bits) {}
+
+ /////////////////////////////////////////////////////////////////////////////
+ // Conversions to bfloat
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_to_bfloat<T>>::type>
+ constexpr METAL_FUNC _MLX_BFloat16(T x) thread
+ : bits_(float_to_bfloat_bits(static_cast<float>(x))) {}
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_to_bfloat<T>>::type>
+ constexpr METAL_FUNC _MLX_BFloat16(T x) threadgroup
+ : bits_(float_to_bfloat_bits(static_cast<float>(x))) {}
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_to_bfloat<T>>::type>
+ constexpr METAL_FUNC _MLX_BFloat16(T x) device
+ : bits_(float_to_bfloat_bits(static_cast<float>(x))) {}
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_to_bfloat<T>>::type>
+ constexpr METAL_FUNC _MLX_BFloat16(T x) constant
+ : bits_(float_to_bfloat_bits(static_cast<float>(x))) {}
+
+ /////////////////////////////////////////////////////////////////////////////
+ // Conversions from bfloat
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_from_bfloat<T>>::type>
+ constexpr METAL_FUNC operator T() const thread {
+ return static_cast<T>(bfloat_bits_to_float(bits_));
+ }
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_from_bfloat<T>>::type>
+ constexpr METAL_FUNC operator T() const threadgroup {
+ return static_cast<T>(bfloat_bits_to_float(bits_));
+ }
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_from_bfloat<T>>::type>
+ constexpr METAL_FUNC operator T() const device {
+ return static_cast<T>(bfloat_bits_to_float(bits_));
+ }
+
+ template <
+ typename T,
+ typename = typename enable_if<can_convert_from_bfloat<T>>::type>
+ constexpr METAL_FUNC operator T() const constant {
+ return static_cast<T>(bfloat_bits_to_float(bits_));
+ }
+};
+
+/////////////////////////////////////////////////////////////////////////////
+// Bfloat operators
+/////////////////////////////////////////////////////////////////////////////
+
+/////////////////////////////////////////////////////////////////////////////
+// Unary ops
+constexpr METAL_FUNC _MLX_BFloat16 operator-(_MLX_BFloat16 x) {
+ return -static_cast<float>(x);
+}
+
+/////////////////////////////////////////////////////////////////////////////
+// Binary operators
+#define bfloat_binop_base(__op__, __operator__, otype, atype, btype, ctype) \
+ constexpr METAL_FUNC otype __operator__(atype lhs, btype rhs) { \
+ return static_cast<ctype>(lhs) __op__ static_cast<ctype>(rhs); \
+ }
+
+#define bfloat_binop_helper(__op__, __operator__, otype, itype, ctype) \
+ constexpr METAL_FUNC otype __operator__(_MLX_BFloat16 lhs, itype rhs) { \
+ return static_cast<ctype>(lhs) __op__ static_cast<ctype>(rhs); \
+ } \
+ constexpr METAL_FUNC otype __operator__(itype lhs, _MLX_BFloat16 rhs) { \
+ return static_cast<ctype>(lhs) __op__ static_cast<ctype>(rhs); \
+ }
+
+/////////////////////////////////////////////////////////////////////////////
+// Arithmetic Operators
+#define bfloat_binop(_op_, _operator_) \
+ bfloat_binop_base( \
+ _op_, _operator_, _MLX_BFloat16, _MLX_BFloat16, _MLX_BFloat16, float); \
+ bfloat_binop_helper(_op_, _operator_, float, float, float); \
+ bfloat_binop_helper(_op_, _operator_, float, half, float); \
+ bfloat_binop_helper(_op_, _operator_, _MLX_BFloat16, int32_t, float); \
+ bfloat_binop_helper(_op_, _operator_, _MLX_BFloat16, uint32_t, float); \
+ bfloat_binop_helper(_op_, _operator_, _MLX_BFloat16, int64_t, float); \
+ bfloat_binop_helper(_op_, _operator_, _MLX_BFloat16, uint64_t, float);
+
+bfloat_binop(+, operator+);
+bfloat_binop(-, operator-);
+bfloat_binop(*, operator*);
+bfloat_binop(/, operator/);
+
+/////////////////////////////////////////////////////////////////////////////
+// Comparison ops
+#define bfloat_compop(__op__, __operator__) \
+ bfloat_binop_base( \
+ __op__, __operator__, bool, _MLX_BFloat16, _MLX_BFloat16, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, float, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, half, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, int32_t, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, uint32_t, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, int64_t, float); \
+ bfloat_binop_helper(__op__, __operator__, bool, uint64_t, float);
+
+bfloat_compop(>, operator>);
+bfloat_compop(<, operator<);
+bfloat_compop(>=, operator>=);
+bfloat_compop(<=, operator<=);
+bfloat_compop(==, operator==);
+bfloat_compop(!=, operator!=);
+
+#undef bfloat_compop
+#undef bfloat_binop_base
+#undef bfloat_binop_helper
+#undef bfloat_binop
+
+/////////////////////////////////////////////////////////////////////////////
+// Inplace Operators
+#define bfloat_inplace_op_helper(__op__, __operator__, itype, addr_space) \
+ constexpr METAL_FUNC addr_space _MLX_BFloat16& __operator__( \
+ addr_space _MLX_BFloat16& lhs, itype rhs) { \
+ lhs = static_cast<float>(lhs) __op__ static_cast<float>(rhs); \
+ return lhs; \
+ } \
+ constexpr METAL_FUNC addr_space itype& __operator__( \
+ addr_space itype& lhs, _MLX_BFloat16 rhs) { \
+ lhs = static_cast<float>(lhs) __op__ static_cast<float>(rhs); \
+ return lhs; \
+ }
+
+#define bfloat_inplace_op_addr_space_helper(__op__, __operator__, itype) \
+ bfloat_inplace_op_helper(__op__, __operator__, itype, device); \
+ bfloat_inplace_op_helper(__op__, __operator__, itype, thread); \
+ bfloat_inplace_op_helper(__op__, __operator__, itype, threadgroup);
+
+#define bfloat_inplace_op(itype) \
+ bfloat_inplace_op_addr_space_helper(+, operator+=, itype); \
+ bfloat_inplace_op_addr_space_helper(-, operator-=, itype); \
+ bfloat_inplace_op_addr_space_helper(*, operator*=, itype); \
+ bfloat_inplace_op_addr_space_helper(/, operator/=, itype);
+
+bfloat_inplace_op(float);
+bfloat_inplace_op(half);
+bfloat_inplace_op(int16_t);
+bfloat_inplace_op(int32_t);
+bfloat_inplace_op(int64_t);
+bfloat_inplace_op(uint16_t);
+bfloat_inplace_op(uint32_t);
+bfloat_inplace_op(uint64_t);
+
+#undef bfloat_inplace_op_helper
+#undef bfloat_inplace_op_addr_space_helper
+#undef bfloat_inplace_op
+
+#define bfloat_inplace_op_helper(__op__, __operator__, addr_space) \
+ constexpr METAL_FUNC addr_space _MLX_BFloat16& __operator__( \
+ addr_space _MLX_BFloat16& lhs, _MLX_BFloat16 rhs) { \
+ lhs = static_cast<float>(lhs) __op__ static_cast<float>(rhs); \
+ return lhs; \
+ }
+
+#define bfloat_inplace_op_addr_space_helper(__op__, __operator__) \
+ bfloat_inplace_op_helper(__op__, __operator__, device); \
+ bfloat_inplace_op_helper(__op__, __operator__, thread); \
+ bfloat_inplace_op_helper(__op__, __operator__, threadgroup);
+
+bfloat_inplace_op_addr_space_helper(+, operator+=);
+bfloat_inplace_op_addr_space_helper(-, operator-=);
+bfloat_inplace_op_addr_space_helper(*, operator*=);
+bfloat_inplace_op_addr_space_helper(/, operator/=);
+
+#undef bfloat_inplace_op_helper
+#undef bfloat_inplace_op_addr_space_helper
+
+/////////////////////////////////////////////////////////////////////////////
+// Bfloat typedef
+/////////////////////////////////////////////////////////////////////////////
+
+typedef struct _MLX_BFloat16 bfloat16_t;
+
+#endif
+
+// ============ "mlx/backend/metal/kernels/scaled_dot_product_attention_params.h"
+
+struct MLXFastAttentionParams {
+ const int M;
+ const int N;
+ const int K;
+
+ const int ldq; // ldq == ldo
+ const int ldk;
+ const int ldv;
+ const int lds;
+ const int ldo;
+
+ const int tiles_n;
+ const int tiles_m;
+
+ const int batch_stride_q;
+ const int batch_stride_k;
+ const int batch_stride_v;
+ const int batch_stride_o;
+
+ const int swizzle_log;
+ const int gemm_n_iterations_aligned;
+ const int gemm_k_iterations_aligned;
+ const int gemm_sv_m_block_iterations;
+
+ const int batch_ndim;
+ const float alpha;
+ const float softcapping;
+};
+
+struct MLXScaledDotProductAttentionParams {
+ // Associated dimensions & transposition information
+ const uint QUERY_SEQUENCE_LENGTH = 1;
+ const uint N_Q_HEADS = 32;
+ const uint N_KV_HEADS = 32;
+ const uint KV_TILES = 1;
+ const float INV_ALPHA = 0.08838834764831843f;
+};
+
+// ============ "mlx/backend/metal/kernels/scaled_dot_product_attention_params.sdpa_vector"
+
+constant bool sdpa_vector_has_mask [[function_constant(20)]];
+
+template <typename T, int D>
+[[kernel]] void sdpa_vector(
+ const device T* queries [[buffer(0)]],
+ const device T* keys [[buffer(1)]],
+ const device T* values [[buffer(2)]],
+ device T* out [[buffer(3)]],
+ const constant int& gqa_factor,
+ const constant int& N,
+ const constant size_t& k_stride,
+ const constant size_t& v_stride,
+ const constant float& scale,
+ const constant float& softcapping,
+ const device bool* mask [[function_constant(sdpa_vector_has_mask)]],
+ const constant int& mask_seq_stride [[function_constant(sdpa_vector_has_mask)]],
+ const constant int& mask_head_stride [[function_constant(sdpa_vector_has_mask)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BN = 32;
+ constexpr int BD = 32;
+ constexpr int elem_per_thread = D / BD;
+ constexpr int stride = BN * D;
+
+ typedef float U;
+
+ thread U q[elem_per_thread];
+ thread U k[elem_per_thread];
+ thread U o[elem_per_thread];
+
+ threadgroup U outputs[BN * BD];
+ threadgroup U max_scores[BN];
+ threadgroup U sum_exp_scores[BN];
+
+ // Adjust positions
+ const int head_idx = tid.y;
+ const int kv_head_idx = head_idx / gqa_factor;
+ queries += head_idx * D + simd_lid * elem_per_thread;
+ keys += kv_head_idx * k_stride + simd_gid * D + simd_lid * elem_per_thread;
+ values += kv_head_idx * v_stride + simd_gid * D + simd_lid * elem_per_thread;
+ if (sdpa_vector_has_mask) {
+ mask += head_idx * mask_head_stride + simd_gid * mask_seq_stride;
+ }
+ out += head_idx * D + simd_gid * elem_per_thread;
+
+ // Read the query and 0 the output accumulator
+ for (int i = 0; i < elem_per_thread; i++) {
+ q[i] = static_cast<U>(scale) * queries[i];
+ }
+ for (int i = 0; i < elem_per_thread; i++) {
+ o[i] = 0;
+ }
+
+ U max_score = -INFINITY;
+ U sum_exp_score = 0;
+
+ // For each key
+ for (int i = simd_gid; i < N; i += BN) {
+ if (!sdpa_vector_has_mask || mask[0]) {
+ // Read the key
+ for (int j = 0; j < elem_per_thread; j++) {
+ k[j] = keys[j];
+ }
+
+ // Compute the i-th score
+ U score = 0;
+ for (int j = 0; j < elem_per_thread; j++) {
+ score += q[j] * k[j];
+ }
+ score = simd_sum(score);
+ if (softcapping != 1.) {
+ score = precise::tanh(score);
+ score = score * softcapping;
+ }
+
+ // Update the accumulators
+ U new_max = max(max_score, score);
+ U factor = fast::exp(max_score - new_max);
+ U exp_score = fast::exp(score - new_max);
+
+ max_score = new_max;
+ sum_exp_score = sum_exp_score * factor + exp_score;
+
+ // Update the output accumulator
+ for (int j = 0; j < elem_per_thread; j++) {
+ o[j] = o[j] * factor + exp_score * values[j];
+ }
+ }
+
+ // Move the pointers to the next kv
+ keys += stride;
+ values += stride;
+ if (sdpa_vector_has_mask) {
+ mask += BN * mask_seq_stride;
+ }
+ }
+
+ // Each thread has a partial part of the output so we need to combine them.
+
+ // First let's communicate the max and sum_exp
+ if (simd_lid == 0) {
+ max_scores[simd_gid] = max_score;
+ sum_exp_scores[simd_gid] = sum_exp_score;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ max_score = max_scores[simd_lid];
+ U new_max = simd_max(max_score);
+ U factor = fast::exp(max_score - new_max);
+ sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * factor);
+
+ // Now we need to aggregate all the outputs
+ for (int i = 0; i < elem_per_thread; i++) {
+ outputs[simd_lid * BD + simd_gid] = o[i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor) / sum_exp_score;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // And write the output
+ if (simd_lid == 0) {
+ for (int i = 0; i < elem_per_thread; i++) {
+ out[i] = static_cast<T>(o[i]);
+ }
+ }
+}
+
+template <typename T, int D>
+[[kernel]] void sdpa_vector_2pass_1(
+ const device T* queries [[buffer(0)]],
+ const device T* keys [[buffer(1)]],
+ const device T* values [[buffer(2)]],
+ device float* out [[buffer(3)]],
+ device float* sums [[buffer(4)]],
+ device float* maxs [[buffer(5)]],
+ const constant int& gqa_factor,
+ const constant int& N,
+ const constant size_t& k_stride,
+ const constant size_t& v_stride,
+ const constant float& scale,
+ const constant float& softcapping,
+ const device bool* mask [[function_constant(sdpa_vector_has_mask)]],
+ const constant int& mask_seq_stride [[function_constant(sdpa_vector_has_mask)]],
+ const constant int& mask_head_stride [[function_constant(sdpa_vector_has_mask)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BN = 8;
+ constexpr int BD = 32;
+ constexpr int elem_per_thread = D / BD;
+ constexpr int stride = BN * D;
+ constexpr int blocks = 32;
+
+ typedef float U;
+
+ thread U q[elem_per_thread];
+ thread U k[elem_per_thread];
+ thread U o[elem_per_thread];
+
+ threadgroup U outputs[BN * BD];
+ threadgroup U max_scores[BN];
+ threadgroup U sum_exp_scores[BN];
+
+ // Adjust positions
+ const int block_idx = tid.z;
+ const int head_idx = tid.y;
+ const int kv_head_idx = head_idx / gqa_factor;
+ queries += head_idx * D + simd_lid * elem_per_thread;
+ keys += kv_head_idx * k_stride + (block_idx * BN + simd_gid) * D +
+ simd_lid * elem_per_thread;
+ values += kv_head_idx * v_stride + (block_idx * BN + simd_gid) * D +
+ simd_lid * elem_per_thread;
+ out += head_idx * blocks * D + block_idx * D + simd_lid * elem_per_thread;
+ if (sdpa_vector_has_mask) {
+ mask += head_idx * mask_head_stride +
+ (block_idx * BN + simd_gid) * mask_seq_stride;
+ }
+ sums += head_idx * blocks + block_idx;
+ maxs += head_idx * blocks + block_idx;
+
+ // Read the query and 0 the output accumulator
+ for (int i = 0; i < elem_per_thread; i++) {
+ q[i] = static_cast<U>(scale) * queries[i];
+ }
+ for (int i = 0; i < elem_per_thread; i++) {
+ o[i] = 0;
+ }
+
+ U max_score = -1e9;
+ U sum_exp_score = 0;
+
+ // For each key
+ for (int i = block_idx * BN + simd_gid; i < N; i += blocks * BN) {
+ if (!sdpa_vector_has_mask || mask[0]) {
+ // Read the key
+ for (int i = 0; i < elem_per_thread; i++) {
+ k[i] = keys[i];
+ }
+
+ // Compute the i-th score
+ U score = 0;
+ for (int i = 0; i < elem_per_thread; i++) {
+ score += q[i] * k[i];
+ }
+ score = simd_sum(score);
+ if (softcapping != 1.) {
+ score = precise::tanh(score);
+ score = score * softcapping;
+ }
+
+ // Update the accumulators
+ U new_max = max(max_score, score);
+ U factor = fast::exp(max_score - new_max);
+ U exp_score = fast::exp(score - new_max);
+
+ max_score = new_max;
+ sum_exp_score = sum_exp_score * factor + exp_score;
+
+ // Update the output accumulator
+ for (int i = 0; i < elem_per_thread; i++) {
+ o[i] = o[i] * factor + exp_score * values[i];
+ }
+ }
+
+ // Move the pointers to the next kv
+ keys += blocks * stride;
+ values += blocks * stride;
+ if (sdpa_vector_has_mask) {
+ mask += BN * blocks * mask_seq_stride;
+ }
+ }
+
+ // Each thread has a partial part of the output so we need to combine them.
+
+ // First let's communicate the max and sum_exp
+ if (simd_lid == 0) {
+ max_scores[simd_gid] = max_score;
+ sum_exp_scores[simd_gid] = sum_exp_score;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ max_score = (simd_lid < BN) ? max_scores[simd_lid] : -1e9;
+ U new_max = simd_max(max_score);
+ U factor = fast::exp(max_score - new_max);
+ sum_exp_score = (simd_lid < BN) ? sum_exp_scores[simd_lid] : 0;
+ sum_exp_score = simd_sum(sum_exp_score * factor);
+
+ // Write the sum and new max
+ if (simd_gid == 0) {
+ sums[0] = sum_exp_score;
+ maxs[0] = new_max;
+ }
+
+ // Now we need to aggregate all the outputs
+ for (int i = 0; i < elem_per_thread; i++) {
+ outputs[simd_lid * BN + simd_gid] =
+ o[i] * fast::exp(max_scores[simd_gid] - new_max);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // And write the output
+ if (simd_gid == 0) {
+ U output = outputs[simd_lid * BN];
+ for (int j = 1; j < BN; j++) {
+ output += outputs[simd_lid * BN + j];
+ }
+ out[i] = static_cast<T>(output);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+}
+
+template <typename T, int D>
+[[kernel]] void sdpa_vector_2pass_2(
+ const device float* partials [[buffer(0)]],
+ const device float* sums [[buffer(1)]],
+ const device float* maxs [[buffer(2)]],
+ device T* out [[buffer(3)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BN = 32;
+ constexpr int BD = 32;
+ constexpr int elem_per_thread = D / BD;
+ constexpr int blocks = 32;
+
+ typedef float U;
+
+ thread U o[elem_per_thread];
+ threadgroup U outputs[BN * BD];
+
+ // Adjust positions
+ const int head_idx = tid.y;
+ partials += head_idx * blocks * D + simd_gid * D + simd_lid * elem_per_thread;
+ sums += head_idx * blocks;
+ maxs += head_idx * blocks;
+ out += head_idx * D + simd_gid * elem_per_thread;
+
+ // First everybody reads the max and sum_exp
+ U max_score = maxs[simd_lid];
+ U new_max = simd_max(max_score);
+ U factor = fast::exp(max_score - new_max);
+ U sum_exp_score = simd_sum(sums[simd_lid] * factor);
+
+ // Now read the block into registers and then use shared memory to transpose
+ // it
+ for (int i = 0; i < elem_per_thread; i++) {
+ o[i] = partials[i];
+ }
+ for (int i = 0; i < elem_per_thread; i++) {
+ outputs[simd_lid * BD + simd_gid] = o[i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor) / sum_exp_score;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // And write the output
+ if (simd_lid == 0) {
+ for (int i = 0; i < elem_per_thread; i++) {
+ out[i] = static_cast<T>(o[i]);
+ }
+ }
+}
+
+// ============ "mlx/backend/metal/kernels/utils.h"
+
+template <typename U>
+struct Limits {
+ static const constant U max = metal::numeric_limits<U>::max();
+ static const constant U min = metal::numeric_limits<U>::min();
+ static const constant U finite_max = metal::numeric_limits<U>::max();
+ static const constant U finite_min = metal::numeric_limits<U>::min();
+};
+
+#define instantiate_default_limit(type) \
+ template <> \
+ struct Limits<type> { \
+ static constexpr constant type max = metal::numeric_limits<type>::max(); \
+ static constexpr constant type min = metal::numeric_limits<type>::min(); \
+ static constexpr constant type finite_max = \
+ metal::numeric_limits<type>::max(); \
+ static constexpr constant type finite_min = \
+ metal::numeric_limits<type>::min(); \
+ };
+
+instantiate_default_limit(uint8_t);
+instantiate_default_limit(uint16_t);
+instantiate_default_limit(uint32_t);
+instantiate_default_limit(uint64_t);
+instantiate_default_limit(int8_t);
+instantiate_default_limit(int16_t);
+instantiate_default_limit(int32_t);
+instantiate_default_limit(int64_t);
+
+#define instantiate_float_limit(type) \
+ template <> \
+ struct Limits<type> { \
+ static constexpr constant type max = \
+ metal::numeric_limits<type>::infinity(); \
+ static constexpr constant type min = \
+ -metal::numeric_limits<type>::infinity(); \
+ static constexpr constant type finite_max = \
+ metal::numeric_limits<type>::max(); \
+ static constexpr constant type finite_min = \
+ -metal::numeric_limits<type>::max(); \
+ };
+
+instantiate_float_limit(half);
+instantiate_float_limit(float);
+instantiate_float_limit(bfloat16_t);
+
+
+// ============ "mlx/backend/metal/kernels/steel/attn/loader.h"
+
+template <
+ typename T,
+ short BROWS,
+ short BCOLS,
+ short dst_ld,
+ short reduction_dim,
+ short tgp_size,
+ short alignment = 1,
+ short n_reads = (BCOLS * BROWS) / (tgp_size),
+ short TCOLS = BCOLS / n_reads,
+ short TROWS = tgp_size / TCOLS>
+struct BlockLoader {
+ STEEL_CONST short n_rows = (BROWS + TROWS - 1) / TROWS;
+ STEEL_CONST short vec_size = n_reads;
+
+ // Leading dimension for src
+ const int src_ld;
+ const int tile_stride;
+
+ // Thread location indices
+ const short thread_idx;
+ const short bi;
+ const short bj;
+
+ // threadgroup and device memory
+ threadgroup T* dst;
+ const device T* src;
+
+ struct alignas(alignment * sizeof(T)) ReadVector {
+ uint8_t v[sizeof(T) * vec_size];
+ };
+
+ /* Constructor */
+ METAL_FUNC BlockLoader(
+ const device T* src_,
+ const int src_ld_,
+ threadgroup T* dst_,
+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],
+ ushort simd_lane_id [[thread_index_in_simdgroup]])
+ : src_ld(src_ld_),
+ tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),
+ thread_idx(simd_group_id * 32 + simd_lane_id),
+ bi(thread_idx / TCOLS),
+ bj(vec_size * (thread_idx % TCOLS)),
+ dst(dst_ + bi * dst_ld + bj),
+ src(src_ + bi * src_ld + bj) {}
+
+ /* Apply operation to threadgroup without bound checking */
+ template <typename UnaryOp>
+ METAL_FUNC void apply_inplace_op(thread const UnaryOp& op) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = op.apply(dst[i * dst_ld + j]);
+ }
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - without bound checking */
+ METAL_FUNC void load_unsafe() const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ *((threadgroup ReadVector*)(&dst[i * dst_ld])) =
+ *((const device ReadVector*)(&src[i * src_ld]));
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - with bound checking */
+ METAL_FUNC void load_safe(short2 src_tile_dim) const {
+ src_tile_dim = src_tile_dim - short2(bj, bi);
+
+ // Skip loading if thread has no valid reads
+ if (src_tile_dim.x <= 0 || src_tile_dim.y <= 0) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = T(0);
+ }
+ }
+ return;
+ }
+
+ // Use fast thread memory for bound checks
+ bool tmp_idx[vec_size];
+ T tmp_val[vec_size];
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ // Make sure tmp_idx only contains valid indices
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_idx[j] = (i < src_tile_dim.y) && (j < src_tile_dim.x);
+ }
+
+ // Read valid indices into tmp_val
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = src[(tmp_idx[j] ? i * src_ld + j : 0)];
+ }
+
+ // Zero out uneeded values
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = tmp_idx[j] ? tmp_val[j] : T(0);
+ }
+
+ // Copy values to threadgroup memory
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * dst_ld + j] = tmp_val[j];
+ }
+ }
+ }
+
+ /* Iteration helper */
+ METAL_FUNC void next() {
+ src += tile_stride;
+ }
+};
+
+template <int R, int C>
+struct CShape {
+ STEEL_CONST int kRows = R;
+ STEEL_CONST int kCols = C;
+};
+
+template <
+ typename T,
+ short BROWS,
+ short BCOLS,
+ short kDstStrRow,
+ short kDstStrCol,
+ short reduction_dim,
+ short tgp_size,
+ short n_reads = (BCOLS * BROWS) / (tgp_size),
+ short TCOLS = BCOLS / n_reads,
+ short TROWS = tgp_size / TCOLS>
+struct BlockLoaderT {
+ STEEL_CONST short n_rows = (BROWS + TROWS - 1) / TROWS;
+ STEEL_CONST short vec_size = n_reads;
+
+ // Leading dimension for src
+ const int src_ld;
+ const int tile_stride;
+
+ // Thread location indices
+ const short thread_idx;
+ const short bi;
+ const short bj;
+
+ // threadgroup and device memory
+ threadgroup T* dst;
+ const device T* src;
+
+ /* Constructor */
+ METAL_FUNC BlockLoaderT(
+ const device T* src_,
+ const int src_ld_,
+ threadgroup T* dst_,
+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],
+ ushort simd_lane_id [[thread_index_in_simdgroup]])
+ : src_ld(src_ld_),
+ tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),
+ thread_idx(simd_group_id * 32 + simd_lane_id),
+ bi(thread_idx / TCOLS),
+ bj(vec_size * (thread_idx % TCOLS)),
+ dst(dst_ + bi * kDstStrRow + bj * kDstStrCol),
+ src(src_ + bi * src_ld + bj) {}
+
+ /* Apply operation to threadgroup without bound checking */
+ template <typename UnaryOp>
+ METAL_FUNC void apply_inplace_op(thread const UnaryOp& op) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * kDstStrRow + j * kDstStrCol] =
+ op.apply(dst[i * kDstStrRow + j * kDstStrCol]);
+ }
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - without bound checking */
+ METAL_FUNC void load_unsafe() const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * kDstStrRow + j * kDstStrCol] = src[i * src_ld + j];
+ }
+ }
+ }
+
+ /* Load from device memory into threadgroup memory - with bound checking */
+ METAL_FUNC void load_safe(short2 src_tile_dim) const {
+ src_tile_dim = src_tile_dim - short2(bj, bi);
+
+ // Skip loading if thread has no valid reads
+ if (src_tile_dim.x <= 0 || src_tile_dim.y <= 0) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * kDstStrRow + j * kDstStrCol] = T(0);
+ }
+ }
+ return;
+ }
+
+ // Use fast thread memory for bound checks
+ bool tmp_idx[vec_size];
+ T tmp_val[vec_size];
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < BROWS; i += TROWS) {
+ // Make sure tmp_idx only contains valid indices
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_idx[j] = (i < src_tile_dim.y) && (j < src_tile_dim.x);
+ }
+
+ // Read valid indices into tmp_val
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = src[(tmp_idx[j] ? i * src_ld + j : 0)];
+ }
+
+ // Zero out uneeded values
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ tmp_val[j] = tmp_idx[j] ? tmp_val[j] : T(0);
+ }
+
+ // Copy values to threadgroup memory
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < vec_size; j++) {
+ dst[i * kDstStrRow + j * kDstStrCol] = tmp_val[j];
+ }
+ }
+ }
+
+ /* Iteration helper */
+ METAL_FUNC void next() {
+ src += tile_stride;
+ }
+};
+
+// ============ "mlx/backend/metal/kernels/steel/utils/type_traits.h"
+
+template <typename... Ts>
+struct make_void {
+ typedef void type;
+};
+
+template <typename... Ts>
+using void_t = typename make_void<Ts...>::type;
+
+template <typename T>
+struct pointer_element {};
+
+template <typename T>
+struct pointer_element<thread T*> {
+ using type = remove_cv_t<T>;
+};
+template <typename T>
+struct pointer_element<device T*> {
+ using type = remove_cv_t<T>;
+};
+template <typename T>
+struct pointer_element<constant T*> {
+ using type = remove_cv_t<T>;
+};
+template <typename T>
+struct pointer_element<threadgroup T*> {
+ using type = remove_cv_t<T>;
+};
+
+template <typename T>
+using pointer_element_t = typename pointer_element<remove_cv_t<T>>::type;
+
+// ============ "mlx/backend/metal/kernels/steel/utils/integral_constant.h"
+
+///////////////////////////////////////////////////////////////////////////////
+// Integral constant with casting
+///////////////////////////////////////////////////////////////////////////////
+
+template <int val>
+using Int = integral_constant<int, val>;
+
+///////////////////////////////////////////////////////////////////////////////
+// Binary Operators on Integral constants
+///////////////////////////////////////////////////////////////////////////////
+
+#define integral_const_binop(__op__, __operator__) \
+ template <typename T, T tv, typename U, U uv> \
+ METAL_FUNC constexpr auto __operator__( \
+ integral_constant<T, tv>, integral_constant<U, uv>) { \
+ constexpr auto res = tv __op__ uv; \
+ return integral_constant<decltype(res), res>{}; \
+ }
+
+integral_const_binop(+, operator+);
+integral_const_binop(-, operator-);
+integral_const_binop(*, operator*);
+integral_const_binop(/, operator/);
+
+integral_const_binop(==, operator==);
+integral_const_binop(!=, operator!=);
+integral_const_binop(<, operator<);
+integral_const_binop(>, operator>);
+integral_const_binop(<=, operator<=);
+integral_const_binop(>=, operator>=);
+
+integral_const_binop(&&, operator&&);
+integral_const_binop(||, operator||);
+
+#undef integral_const_binop
+
+///////////////////////////////////////////////////////////////////////////////
+// Reduction operators
+///////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+METAL_FUNC constexpr T sum(T x) {
+ return x;
+}
+
+template <typename T, typename... Us>
+METAL_FUNC constexpr auto sum(T x, Us... us) {
+ return x + sum(us...);
+}
+
+// ============ "mlx/backend/metal/kernels/steel/gemm/transforms.h"
+
+template <typename OutT, typename InT>
+struct TransformNone {
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ static METAL_FUNC OutT apply(InT x, OutT) {
+ return static_cast<OutT>(x);
+ }
+};
+
+template <typename OutT, typename InT>
+struct TransformAdd {
+ TransformAdd(const float, const float) {}
+
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ static METAL_FUNC OutT apply(InT x, OutT c) {
+ return static_cast<OutT>(x) + c;
+ }
+};
+
+template <typename OutT, typename InT>
+struct TransformAxpby {
+ const float alpha;
+ const float beta;
+
+ TransformAxpby(const float alpha_, const float beta_)
+ : alpha(alpha_), beta(beta_) {}
+
+ static METAL_FUNC OutT apply(InT x) {
+ return static_cast<OutT>(x);
+ }
+
+ METAL_FUNC OutT apply(InT x, OutT c) const {
+ return static_cast<OutT>(x * alpha + (beta * c));
+ }
+};
+
+template <typename T>
+struct AccumHelper {
+ typedef float accum_type;
+};
+
+struct BlockSwizzle {
+ static METAL_FUNC int2
+ swizzle(uint3 tid [[threadgroup_position_in_grid]], const int swizzle_log) {
+ const int tid_x = (tid.x) >> swizzle_log;
+ const int tid_y =
+ ((tid.y) << swizzle_log) + ((tid.x) & ((1 << swizzle_log) - 1));
+ return int2(tid_x, tid_y);
+ }
+};
+
+// ============ "mlx/backend/metal/kernels/steel/attn/mma.h"
+
+template <typename RInt, typename CInt>
+struct Shape2D {
+ RInt r;
+ CInt c;
+
+ Shape2D(RInt r_, CInt c_) : r(r_), c(c_) {}
+};
+
+template <typename Shape, typename Layout>
+struct Layout2D {
+ Shape shape;
+ Layout layout;
+};
+
+template <typename T, int kFragRows_, int kFragCols_>
+struct BaseMMAFrag {
+ static_assert(
+ kFragRows_ == 8,
+ "Only 8 x 8 fragment matrices are currently supported");
+ static_assert(
+ kFragCols_ == 8,
+ "Only 8 x 8 fragment matrices are currently supported");
+};
+
+template <typename T>
+struct BaseMMAFrag<T, 8, 8> {
+ STEEL_CONST int kFragRows = 8;
+ STEEL_CONST int kFragCols = 8;
+
+ STEEL_CONST int kElemsPerFrag = (kFragRows * kFragCols) / 32;
+
+ STEEL_CONST int kElemRows = 1;
+ STEEL_CONST int kElemCols = 2;
+
+ static_assert(
+ kElemRows * kElemCols == kElemsPerFrag,
+ "MMAFrag shape is not consistent with MMAFrag size");
+
+ typedef metal::simdgroup_matrix<T, kFragRows, kFragCols> mat_type;
+ typedef metal::vec<T, kElemsPerFrag> frag_type;
+ typedef metal::vec<T, kElemRows> row_frag_type;
+ typedef metal::vec<T, kElemCols> col_frag_type;
+
+ template <typename U>
+ using dtype_mat_t = typename metal::simdgroup_matrix<U, kFragRows, kFragCols>;
+
+ template <typename U>
+ using dtype_frag_t = typename metal::vec<U, kElemsPerFrag>;
+
+ METAL_FUNC static constexpr short2 get_coord(ushort simd_lane_id
+ [[thread_index_in_simdgroup]]) {
+ const short qid = simd_lane_id / 4;
+ const short fm = (qid & 4) + ((simd_lane_id / 2) % 4);
+ const short fn = (qid & 2) * 2 + (simd_lane_id % 2) * 2;
+ return short2{fn, fm};
+ }
+
+ template <typename SrcPtrType, typename StrX, typename StrY>
+ METAL_FUNC static constexpr void
+ load(thread frag_type& dst, SrcPtrType src, StrX str_x, StrY str_y) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kElemRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kElemCols; j++) {
+ dst[i * kElemCols + j] = static_cast<T>(src[i * str_x.value + j * str_y.value]);
+ }
+ }
+ }
+
+ template <
+ typename SrcPtrType,
+ typename StrX,
+ typename StrY,
+ typename LimX,
+ typename LimY,
+ typename OffX,
+ typename OffY>
+ METAL_FUNC static constexpr void load_safe(
+ thread frag_type& dst,
+ SrcPtrType src,
+ StrX str_x,
+ StrY str_y,
+ LimX lim_x,
+ LimY lim_y,
+ OffX off_x = Int<0>{},
+ OffY off_y = Int<0>{}) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kElemRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kElemCols; j++) {
+ if ((off_x + i) < lim_x && (off_y + j) < lim_y) {
+ dst[i * kElemCols + j] =
+ static_cast<T>(src[(off_x + i) * str_x + (off_y + j) * str_y.value]);
+ } else {
+ dst[i * kElemCols + j] = T(0);
+ }
+ }
+ }
+ }
+
+ template <typename DstPtrType, typename StrX, typename StrY>
+ METAL_FUNC static constexpr void
+ store(const thread frag_type& src, DstPtrType dst, StrX str_x, StrY str_y) {
+ using U = pointer_element_t<DstPtrType>;
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kElemRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kElemCols; j++) {
+ dst[i * str_x + j * str_y.value] = static_cast<U>(src[i * kElemCols + j]);
+ }
+ }
+ }
+
+ template <
+ typename DstPtrType,
+ typename StrX,
+ typename StrY,
+ typename LimX,
+ typename LimY,
+ typename OffX,
+ typename OffY>
+ METAL_FUNC static constexpr void store_safe(
+ const thread frag_type& src,
+ DstPtrType dst,
+ StrX str_x,
+ StrY str_y,
+ LimX lim_x,
+ LimY lim_y,
+ OffX off_x = Int<0>{},
+ OffY off_y = Int<0>{}) {
+ using U = pointer_element_t<DstPtrType>;
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kElemRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kElemCols; j++) {
+ if ((off_x + i) < lim_x && (off_y + j) < lim_y) {
+ dst[(off_x + i) * str_x + (off_y + j) * str_y.value] =
+ static_cast<U>(src[i * kElemCols + j]);
+ }
+ }
+ }
+ }
+
+ template <typename Atype, typename Btype, typename Ctype>
+ METAL_FUNC static constexpr void mma(
+ thread frag_type& D,
+ thread dtype_frag_t<Atype>& A,
+ thread dtype_frag_t<Btype>& B,
+ thread dtype_frag_t<Ctype>& C) {
+ mat_type D_mat;
+ dtype_mat_t<Atype> A_mat;
+ dtype_mat_t<Btype> B_mat;
+ dtype_mat_t<Ctype> C_mat;
+
+ reinterpret_cast<thread dtype_frag_t<Atype>&>(A_mat.thread_elements()) = A;
+ reinterpret_cast<thread dtype_frag_t<Btype>&>(B_mat.thread_elements()) = B;
+ reinterpret_cast<thread dtype_frag_t<Ctype>&>(C_mat.thread_elements()) = C;
+
+ mma(D_mat, A_mat, B_mat, C_mat);
+
+ D = reinterpret_cast<thread frag_type&>(D_mat.thread_elements());
+ }
+
+ template <typename Atype, typename Btype, typename Ctype>
+ METAL_FUNC static constexpr void mma(
+ thread mat_type& D,
+ thread dtype_mat_t<Atype>& A,
+ thread dtype_mat_t<Btype>& B,
+ thread dtype_mat_t<Ctype>& C) {
+ simdgroup_multiply_accumulate(D, A, B, C);
+ }
+
+ template <typename Op>
+ METAL_FUNC static constexpr void row_reduce(
+ thread const frag_type& inp_vals,
+ thread T* reduced_vals) {
+ T thr_reduce = Op::apply(inp_vals.x, inp_vals.y);
+
+ T qgr_reduce = simd_shuffle_xor(thr_reduce, ushort(1));
+ qgr_reduce = Op::apply(thr_reduce, qgr_reduce);
+
+ T sgr_reduce = simd_shuffle_xor(qgr_reduce, ushort(8));
+ sgr_reduce = Op::apply(qgr_reduce, sgr_reduce);
+
+ reduced_vals[0] = Op::apply(reduced_vals[0], sgr_reduce);
+ }
+
+ template <typename Op>
+ METAL_FUNC static constexpr void row_bin_op(
+ thread frag_type& inp_vals,
+ thread T* row_vals) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kElemRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kElemCols; j++) {
+ inp_vals[i * kElemCols + j] =
+ Op::apply(inp_vals[i * kElemCols + j], row_vals[i]);
+ }
+ }
+ }
+};
+
+template <
+ typename T,
+ int kTileRows_,
+ int kTileCols_,
+ class MMAFrag_ = BaseMMAFrag<T, 8, 8>>
+struct MMATile {
+ using MMAFrag_t = MMAFrag_;
+ using elem_type = T;
+ STEEL_CONST int kFragRows = MMAFrag_t::kFragRows;
+ STEEL_CONST int kFragCols = MMAFrag_t::kFragCols;
+ STEEL_CONST int kElemsPerFrag = MMAFrag_t::kElemsPerFrag;
+
+ STEEL_CONST int kTileRows = kTileRows_;
+ STEEL_CONST int kTileCols = kTileCols_;
+
+ STEEL_CONST int kRows = kTileRows * kFragRows;
+ STEEL_CONST int kCols = kTileCols * kFragCols;
+
+ STEEL_CONST int kNumFrags = kTileRows * kTileCols;
+ STEEL_CONST int kElemsPerTile = kNumFrags * kElemsPerFrag;
+
+ STEEL_CONST int kRowsPerThread = kTileRows * MMAFrag_t::kElemRows;
+ STEEL_CONST int kColsPerThread = kTileCols * MMAFrag_t::kElemCols;
+
+ typedef typename MMAFrag_t::mat_type mat_type;
+ typedef typename MMAFrag_t::frag_type frag_type;
+
+ frag_type val_frags[kNumFrags]; // = {frag_type(0)};
+
+ METAL_FUNC MMATile() thread {}
+
+ METAL_FUNC constexpr void clear() {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kNumFrags; ++i) {
+ val_frags[i] = frag_type(0);
+ }
+ }
+
+ METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) {
+ return val_frags[i * kTileCols + j];
+ }
+
+ METAL_FUNC constexpr const thread frag_type& frag_at(
+ const short i,
+ const short j) const {
+ return val_frags[i * kTileCols + j];
+ }
+
+ METAL_FUNC mat_type mat_at(const short i, const short j) {
+ mat_type val_mat;
+ STEEL_PRAGMA_UNROLL
+ for (short ii = 0; ii < kElemsPerFrag; ++ii) {
+ val_mat.thread_elements()[ii] = frag_at(i, j)[ii];
+ }
+ return val_mat;
+ }
+
+ METAL_FUNC thread elem_type* elems() {
+ return reinterpret_cast<thread elem_type*>(val_frags);
+ }
+
+ METAL_FUNC const thread elem_type* elems() const {
+ return reinterpret_cast<const thread elem_type*>(val_frags);
+ }
+
+ template <typename Op>
+ METAL_FUNC void row_reduce(thread T vals[kRowsPerThread]) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::template row_reduce<Op>(
+ frag_at(i, j), &vals[i * MMAFrag_t::kElemRows]);
+ }
+ }
+ }
+
+ template <typename Op>
+ METAL_FUNC void row_bin_op(thread T vals[kRowsPerThread]) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::template row_bin_op<Op>(
+ frag_at(i, j), &vals[i * MMAFrag_t::kElemRows]);
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y, int str_x, int str_y>
+ METAL_FUNC void load(const threadgroup U* src) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::load(
+ frag_at(i, j),
+ &(
+ src[(i * kFragRows) * w_x * str_x +
+ (j * kFragCols) * w_y * str_y]),
+ Int<str_x>{},
+ Int<str_y>{});
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y, int str_x, int str_y>
+ METAL_FUNC void store(threadgroup U* dst) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::store(
+ frag_at(i, j),
+ &(
+ dst[(i * kFragRows) * w_x * str_x +
+ (j * kFragCols) * w_y * str_y]),
+ Int<str_x>{},
+ Int<str_y>{});
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y>
+ METAL_FUNC void load(const device U* src, const int ld) {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::load(
+ frag_at(i, j),
+ &(src[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),
+ ld,
+ Int<1>{});
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y>
+ METAL_FUNC void store(device U* dst, const int ld) const {
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::store(
+ frag_at(i, j),
+ &(dst[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),
+ ld,
+ Int<1>{});
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y>
+ METAL_FUNC void
+ load_safe(const device U* src, const int ld, const short2 src_tile_dims) {
+ STEEL_PRAGMA_UNROLL
+ for (int i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (int j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::load_safe(
+ frag_at(i, j),
+ src,
+ ld,
+ Int<1>{},
+ src_tile_dims.y,
+ src_tile_dims.x,
+ (i * kFragRows) * w_x,
+ (j * kFragCols) * w_y);
+ }
+ }
+ }
+
+ template <typename U, int w_x, int w_y>
+ METAL_FUNC void
+ store_safe(device U* dst, const int ld, const short2 dst_tile_dims) const {
+ STEEL_PRAGMA_UNROLL
+ for (int i = 0; i < kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (int j = 0; j < kTileCols; ++j) {
+ MMAFrag_t::store_safe(
+ frag_at(i, j),
+ dst,
+ ld,
+ Int<1>{},
+ dst_tile_dims.y,
+ dst_tile_dims.x,
+ (i * kFragRows) * w_x,
+ (j * kFragCols) * w_y);
+ }
+ }
+ }
+};
+
+template <
+ typename Dtype,
+ typename Atype,
+ typename Btype,
+ typename Ctype,
+ int M,
+ int N,
+ int K,
+ class MMAFragD,
+ class MMAFragA,
+ class MMAFragB,
+ class MMAFragC>
+METAL_FUNC void tile_matmad(
+ thread MMATile<Dtype, M, N, MMAFragD>& D,
+ thread MMATile<Atype, M, K, MMAFragA>& A,
+ thread MMATile<Btype, K, N, MMAFragB>& B,
+ thread MMATile<Ctype, M, N, MMAFragC>& C) {
+ STEEL_PRAGMA_UNROLL
+ for (short m = 0; m < M; ++m) {
+ STEEL_PRAGMA_UNROLL
+ for (short n = 0; n < N; ++n) {
+ short m_serp = m; //(n % 2) ? (M - 1 - m) : m;
+ short n_serp = (m % 2) ? (N - 1 - n) : n;
+
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < K; ++k) {
+ MMAFragD::mma(
+ D.frag_at(m_serp, n_serp),
+ A.frag_at(m_serp, k),
+ B.frag_at(k, n_serp),
+ C.frag_at(m_serp, n_serp));
+ }
+ }
+ }
+}
+
+template <
+ typename T,
+ typename U,
+ int BM,
+ int BN,
+ int BK,
+ int WM,
+ int WN,
+ bool transpose_a,
+ bool transpose_b,
+ short lda_tgp,
+ short ldb_tgp,
+ typename AccumType = float,
+ typename Epilogue = TransformNone<U, AccumType>>
+struct BlockMMA {
+ // MMAFrag size
+ STEEL_CONST short kFragSize = 8;
+ using MMAFrag_acc_t = BaseMMAFrag<AccumType, kFragSize, kFragSize>;
+
+ // Warp tile simdgroup matrix strides along M
+ STEEL_CONST short TM_stride = kFragSize * WM;
+ // Warp tile simdgroup matrix strides along M
+ STEEL_CONST short TN_stride = kFragSize * WN;
+
+ // Warp tile size along M
+ STEEL_CONST short TM = BM / TM_stride;
+ // Warp tile size along N
+ STEEL_CONST short TN = BN / TN_stride;
+
+ // Threadgroup A strides
+ STEEL_CONST short A_str_m = transpose_a ? 1 : lda_tgp; // M
+ STEEL_CONST short A_str_k = transpose_a ? lda_tgp : 1; // K
+
+ // Threadgroup B strides
+ STEEL_CONST short B_str_k = transpose_b ? 1 : ldb_tgp; // K
+ STEEL_CONST short B_str_n = transpose_b ? ldb_tgp : 1; // N
+
+ // Threadgroup strides along K
+ STEEL_CONST short tile_stride_a = kFragSize * A_str_k;
+ STEEL_CONST short tile_stride_b = kFragSize * B_str_k;
+
+ // Simdgroup matrices
+ MMATile<AccumType, TM, 1, MMAFrag_acc_t> Atile;
+ MMATile<AccumType, 1, TN, MMAFrag_acc_t> Btile;
+ MMATile<AccumType, TM, TN, MMAFrag_acc_t> Ctile;
+
+ // Offsets within threadgroup
+ short sm;
+ short sn;
+
+ short As_offset;
+ short Bs_offset;
+
+ /* Constructor */
+ METAL_FUNC BlockMMA(
+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],
+ ushort simd_lane_id [[thread_index_in_simdgroup]]) {
+ // Determine thread position in simdgroup matrix
+ short tm = kFragSize * (simd_group_id / WN);
+ short tn = kFragSize * (simd_group_id % WN);
+
+ short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id);
+ sm = simd_coord.y;
+ sn = simd_coord.x;
+
+ // Determine thread and simdgroup offset
+ As_offset = (tm + sm) * A_str_m + (sn)*A_str_k; // M, K
+ Bs_offset = (sm)*B_str_k + (tn + sn) * B_str_n; // K, N
+
+ sm += tm;
+ sn += tn;
+ }
+
+ /* (BM, BK) X (BK, BN) multiply accumulate function */
+ METAL_FUNC void mma(const threadgroup T* As, const threadgroup T* Bs) {
+ // Adjust for simdgroup and thread location
+ As += As_offset;
+ Bs += Bs_offset;
+
+ // Iterate over BK in blocks of kFragSize
+ STEEL_PRAGMA_UNROLL
+ for (short kk = 0; kk < BK; kk += kFragSize) {
+ simdgroup_barrier(mem_flags::mem_none);
+
+ Atile.template load<T, WM, 1, A_str_m, A_str_k>(As);
+
+ simdgroup_barrier(mem_flags::mem_none);
+
+ Btile.template load<T, 1, WN, B_str_k, B_str_n>(Bs);
+
+ simdgroup_barrier(mem_flags::mem_none);
+
+ tile_matmad(Ctile, Atile, Btile, Ctile);
+
+ // Progress to next simdgroup tile
+ As += tile_stride_a;
+ Bs += tile_stride_b;
+ }
+ }
+
+ /* Store results from simdgroup_matrix results into device memory */
+ METAL_FUNC void store_result(device U* D, const int ldd) {
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {
+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);
+ }
+
+ // Adjust for simdgroup and thread location
+ D += sm * ldd + sn;
+
+ Ctile.template store<U, WM, WN>(D, ldd);
+ }
+
+ METAL_FUNC void
+ store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {
+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);
+ }
+
+ // Adjust for simdgroup and thread location
+ D += sm * ldd + sn;
+ dst_tile_dims -= short2(sn, sm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ Ctile.template store_safe<U, WM, WN>(D, ldd, dst_tile_dims);
+ }
+
+ /* Apply epilogue */
+ template <typename UnaryEpilogue>
+ METAL_FUNC void apply_epilogue(thread const UnaryEpilogue& epilogue_op) {
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {
+ Ctile.elems()[i] = epilogue_op.apply(Ctile.elems()[i]);
+ }
+ }
+
+ /* Apply epilogue */
+ template <typename BinaryEpilogue>
+ METAL_FUNC void apply_epilogue(
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ thread const BinaryEpilogue& epilogue_op) {
+ // Adjust for simdgroup and thread location
+ C += (sm)*ldc + (sn)*fdc;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread auto& accum = Ctile.frag_at(i, j);
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < decltype(Ctile)::kElemsPerFrag; k++) {
+ accum[k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]);
+ }
+ }
+ }
+ }
+
+ /* Apply epilogue */
+ template <typename BinaryEpilogue>
+ METAL_FUNC void apply_epilogue_safe(
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ short2 dst_tile_dims,
+ thread const BinaryEpilogue& epilogue_op) {
+ // Adjust for simdgroup and thread location
+ C += (sm)*ldc + (sn)*fdc;
+ dst_tile_dims -= short2(sn, sm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread auto& accum = Ctile.frag_at(i, j);
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+
+ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;
+
+ // Read C
+ U c_elems[kelems] = {0};
+
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < kelems; k++) {
+ if ((j * TN_stride + k) < dst_tile_dims.x) {
+ c_elems[k] = C[offset_c + k * fdc];
+ }
+ }
+
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < kelems; k++) {
+ accum[k] = epilogue_op.apply(accum[k], c_elems[k]);
+ }
+ }
+ }
+ }
+
+ /* Store results from simdgroup_matrix results into device memory */
+ METAL_FUNC void store_result(
+ device U* D,
+ const int ldd,
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ thread const Epilogue& epilogue_op) const {
+ // Adjust for simdgroup and thread location
+ C += (sm)*ldc + (sn)*fdc;
+ D += (sm)*ldd + sn;
+
+ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;
+
+ // Loop over all simdgroup tiles
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < TM; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = Ctile.frag_at(i, j);
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < kelems; k++) {
+ D[offset_d + k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]);
+ }
+ }
+ }
+ }
+
+ METAL_FUNC void store_result_safe(
+ device U* D,
+ const int ldd,
+ const device U* C,
+ const int ldc,
+ const int fdc,
+ short2 dst_tile_dims,
+ thread const Epilogue& epilogue_op) const {
+ // Adjust for simdgroup and thread location
+ C += (sm)*ldc + (sn)*fdc;
+ D += (sm)*ldd + sn;
+ dst_tile_dims -= short2(sn, sm);
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;
+
+ STEEL_PRAGMA_UNROLL
+ for (int i = 0; i < TM; i++) {
+ if (i * TM_stride < dst_tile_dims.y) {
+ STEEL_PRAGMA_UNROLL
+ for (int j = 0; j < TN; j++) {
+ // Get accumulated result and associated offset in C
+ thread const auto& accum = Ctile.frag_at(i, j);
+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;
+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);
+
+ // Apply epilogue
+ STEEL_PRAGMA_UNROLL
+ for (short k = 0; k < kelems; k++) {
+ if ((j * TN_stride + k) < dst_tile_dims.x) {
+ D[offset_d + k] =
+ epilogue_op.apply(accum[k], C[offset_c + k * fdc]);
+ }
+ }
+ }
+ }
+ }
+ }
+};
+
+// ============ "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h"
+
+struct AttnParams {
+ int B; ///< Batch Size
+ int H; ///< Heads
+ int D; ///< Head Dim
+
+ int qL; ///< Query Sequence Length
+ int kL; ///< Key Sequence Length
+
+ int gqa_factor; ///< Group Query factor
+ float scale; ///< Attention scale
+ float softcapping; ///< Softcapping value (1.0 = disabled)
+
+ int NQ; ///< Number of query blocks
+ int NK; ///< Number of key/value blocks
+
+ int NQ_aligned; ///< Number of full query blocks
+ int NK_aligned; ///< Number of full key/value blocks
+
+ int qL_rem; ///< Remainder in last query block
+ int kL_rem; ///< Remainder in last key/value block
+ int qL_off; ///< Offset in query sequence start
+
+ int64_t Q_strides[3]; ///< Query strides (B, H, L, D = 1)
+ int64_t K_strides[3]; ///< Key strides (B, H, L, D = 1)
+ int64_t V_strides[3]; ///< Value strides (B, H, L, D = 1)
+ int64_t O_strides[3]; ///< Output strides (B, H, L, D = 1)
+};
+
+struct AttnMaskParams {
+ int64_t M_strides[3]; ///< Mask strides (B, H, qL, kL = 1)
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// GEMM kernels
+///////////////////////////////////////////////////////////////////////////////
+
+constant bool align_Q [[function_constant(200)]];
+constant bool align_K [[function_constant(201)]];
+
+constant bool has_mask [[function_constant(300)]];
+constant bool do_causal [[function_constant(301)]];
+
+template <typename T>
+struct TransformScale {
+ T scale;
+ METAL_FUNC TransformScale(T scale_) : scale(scale_) {}
+
+ METAL_FUNC T apply(T x) const {
+ return scale * x;
+ }
+};
+
+struct MaxOp {
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return metal::max(x, y);
+ }
+};
+
+struct SumOp {
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return x + y;
+ }
+};
+
+struct MulOp {
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return x * y;
+ }
+};
+
+struct SubOp {
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return x - y;
+ }
+};
+
+struct ExpSubOp {
+ // Guard: when y (row max) is -inf, all scores in the row are -inf (entirely masked). Return 0 instead of exp2(-inf - (-inf)) = exp2(NaN).
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return (y == -metal::numeric_limits<T>::infinity())
+ ? T(0)
+ : fast::exp2(x - y);
+ }
+};
+
+struct DivOp {
+ template <typename T>
+ METAL_FUNC static constexpr T apply(T x, T y) {
+ return x / y;
+ }
+};
+
+// clang-format off
+template <
+ typename T,
+ int BQ,
+ int BK,
+ int BD,
+ int WM,
+ int WN,
+ typename MaskType = float,
+ typename AccumType = float>
+[[kernel, max_total_threads_per_threadgroup(WM * WN * 32)]] void attention(
+ const device T* Q [[buffer(0)]],
+ const device T* K [[buffer(1)]],
+ const device T* V [[buffer(2)]],
+ device T* O [[buffer(3)]],
+ const constant AttnParams* params [[buffer(4)]],
+ const constant AttnMaskParams* mask_params [[buffer(5), function_constant(has_mask)]],
+ const device MaskType* mask [[buffer(6), function_constant(has_mask)]],
+ uint simd_lane_id [[thread_index_in_simdgroup]],
+ uint simd_group_id [[simdgroup_index_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) { // clang-format on
+
+ // Pacifying compiler
+ (void)lid;
+
+ // Move to correct block
+ ulong3 tidl{tid.x, tid.y, tid.z};
+
+ Q += tidl.z * params->Q_strides[0] + // Batch
+ tidl.y * params->Q_strides[1] + // Head
+ tidl.x * BQ * params->Q_strides[2]; // Seqeunce
+
+ ulong kv_head_idx = int(tid.y) / params->gqa_factor;
+ K += tidl.z * params->K_strides[0] + // Batch
+ kv_head_idx * params->K_strides[1]; // Head
+
+ V += tidl.z * params->V_strides[0] + // Batch
+ kv_head_idx * params->V_strides[1]; // Head
+
+ O += tidl.z * params->O_strides[0] + // Batch
+ tidl.y * params->O_strides[1] + // Head
+ tidl.x * BQ * params->O_strides[2]; // Seqeunce
+
+ if (has_mask) {
+ mask += tidl.z * mask_params->M_strides[0] + // Batch
+ tidl.y * mask_params->M_strides[1]; // Head
+ }
+
+ // Prepare threadgroup memory
+ constexpr short padQ = 16 / sizeof(T);
+ constexpr short padK = 16 / sizeof(T);
+ constexpr short padV = 16 / sizeof(T);
+
+ constexpr short LDQ_tgp = BD + padQ;
+ constexpr short LDK_tgp = BK + padK;
+ constexpr short LDV_tgp = BD + padV;
+
+ constexpr short tgp_mem_0 = (BK + padK) * (BD);
+ constexpr short tgp_mem_1 = BK * (BD + padV);
+ constexpr short tgp_mem_s = tgp_mem_0 > tgp_mem_1 ? tgp_mem_0 : tgp_mem_1;
+
+ threadgroup T Q_smem[BQ * (BD + padQ)];
+ threadgroup T KV_smem[tgp_mem_s];
+
+ threadgroup T* Qs = Q_smem;
+ threadgroup T* Ks = KV_smem;
+ threadgroup T* Vs = KV_smem;
+
+ // Prepare block loaders
+ using QBlockLoader = BlockLoaderT<
+ /* typename T = */ T,
+ /* short BROWS = */ BQ,
+ /* short BCOLS = */ BD,
+ /* short kDstStrRow = */ LDQ_tgp,
+ /* short kDstStrCol = */ 1,
+ /* short reduction_dim = */ 1,
+ /* short tgp_size = */ WM * WN * 32>;
+
+ // K is loaded in transposed
+ using KBlockLoader = BlockLoaderT<
+ /* typename T = */ T,
+ /* short BROWS = */ BK,
+ /* short BCOLS = */ BD,
+ /* short kDstStrRow = */ 1,
+ /* short kDstStrCol = */ LDK_tgp,
+ /* short reduction_dim = */ 0,
+ /* short tgp_size = */ WM * WN * 32>;
+
+ using VBlockLoader = BlockLoaderT<
+ /* typename T = */ T,
+ /* short BROWS = */ BK,
+ /* short BCOLS = */ BD,
+ /* short kDstStrRow = */ LDV_tgp,
+ /* short kDstStrCol = */ 1,
+ /* short reduction_dim = */ 0,
+ /* short tgp_size = */ WM * WN * 32>;
+
+ QBlockLoader loader_q(
+ Q, params->Q_strides[2], Qs, simd_group_id, simd_lane_id);
+ KBlockLoader loader_k(
+ K, params->K_strides[2], Ks, simd_group_id, simd_lane_id);
+ VBlockLoader loader_v(
+ V, params->V_strides[2], Vs, simd_group_id, simd_lane_id);
+
+ TransformScale<T> ts(static_cast<T>(params->scale * 1.44269504089));
+
+ // Prepare MMA tiles
+ constexpr short kFragSize = 8; // MMAFrag size
+ using MMAFrag_acc_t = BaseMMAFrag<AccumType, kFragSize, kFragSize>;
+
+ constexpr int kNWarps = WM * WN;
+ static_assert(
+ BQ >= (kNWarps * kFragSize) && BQ % (kNWarps * kFragSize) == 0,
+ "Each simdgroup must host atleast 1 simdgroup matrix along Q sequence.");
+
+ // Q seq frags per warp
+ constexpr int TQ = BQ / (kNWarps * kFragSize);
+ // KV sequence frags (all warps load the same frags)
+ constexpr int TK = BK / kFragSize;
+ // HeadDim frags (all warps load the same frags)
+ constexpr int TD = BD / kFragSize;
+
+ static_assert(TQ == 1, "Check TQ");
+
+ MMATile<AccumType, TQ, 1, MMAFrag_acc_t> Qtile;
+ MMATile<AccumType, 1, TK, MMAFrag_acc_t> Ktile;
+ MMATile<AccumType, TQ, TK, MMAFrag_acc_t> Stile;
+ MMATile<AccumType, 1, 1, MMAFrag_acc_t> Vtile;
+ MMATile<AccumType, TQ, TD, MMAFrag_acc_t> Otile;
+
+ Otile.clear();
+
+ // Prepare mma tile offsets
+ const short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id);
+ const short sm = simd_coord.y;
+ const short sn = simd_coord.x;
+ const short tm = kFragSize * TQ * simd_group_id;
+
+ const short Qs_offset = (tm + sm) * LDQ_tgp + sn;
+ const short Ks_offset = sm * LDK_tgp + sn;
+ const short Vs_offset = sm * LDV_tgp + sn;
+
+ constexpr short Qs_tile_stride = kFragSize;
+ constexpr short Ks_tile_stride = kFragSize * LDK_tgp;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Load Q blocks apply scale
+ if (!align_Q && int(tid.x) == (params->NQ_aligned)) {
+ loader_q.load_safe(short2(BD, params->qL_rem));
+ } else {
+ loader_q.load_unsafe();
+ }
+ loader_q.apply_inplace_op(ts);
+
+ // Init row reduction variables
+ constexpr short kRowsPT = decltype(Stile)::kRowsPerThread;
+
+ AccumType max_score[kRowsPT];
+ AccumType sum_score[kRowsPT] = {0};
+
+ // Init to -Inf
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kRowsPT; ++i) {
+ max_score[i] = Limits<AccumType>::min;
+ }
+
+ int kb_lim = params->NK;
+
+ if (do_causal) {
+ int q_max = (tid.x + 1) * BQ + params->qL_off;
+ kb_lim = (q_max + BK - 1) / BK;
+ }
+
+ // Loop over KV seq length
+ for (int kb = 0; kb < kb_lim; kb++) {
+ // Load K block and apply scale
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (!align_K && kb == (params->NK_aligned)) {
+ loader_k.load_safe(short2(BD, params->kL_rem));
+ } else {
+ loader_k.load_unsafe();
+ }
+
+ // Do S = Q @ K.T
+ Stile.clear();
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ STEEL_PRAGMA_UNROLL
+ for (short dd = 0; dd < TD; dd++) {
+ simdgroup_barrier(mem_flags::mem_none);
+
+ Qtile.template load<T, 1, 1, LDQ_tgp, 1>(
+ &Qs[Qs_offset + dd * Qs_tile_stride]);
+ Ktile.template load<T, 1, 1, LDK_tgp, 1>(
+ &Ks[Ks_offset + dd * Ks_tile_stride]);
+
+ simdgroup_barrier(mem_flags::mem_none);
+
+ tile_matmad(Stile, Qtile, Ktile, Stile);
+ }
+
+ // Mask out length sequence
+ if (!align_K && kb == (params->NK_aligned)) {
+ using stile_t = decltype(Stile);
+ using selem_t = typename stile_t::elem_type;
+ constexpr auto neg_inf = -metal::numeric_limits<selem_t>::infinity();
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < stile_t::kTileRows; i++) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < stile_t::kTileCols; j++) {
+ short col_pos = sn + (j * stile_t::kFragCols);
+ STEEL_PRAGMA_UNROLL
+ for (short jj = 0; jj < stile_t::MMAFrag_t::kElemCols; jj++) {
+ if ((col_pos + jj) >= params->kL_rem) {
+ Stile.frag_at(i, j)[jj] = neg_inf;
+ }
+ }
+ }
+ }
+ }
+
+ // Mask out if causal
+ if (do_causal && kb >= (kb_lim - (BQ + BK - 1) / BK - int(!align_K))) {
+ using stile_t = decltype(Stile);
+ using selem_t = typename stile_t::elem_type;
+ constexpr auto neg_inf = -metal::numeric_limits<selem_t>::infinity();
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < stile_t::kTileRows; i++) {
+ const int row_pos =
+ tid.x * BQ + params->qL_off + tm + sm + (i * stile_t::kFragRows);
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < stile_t::kTileCols; j++) {
+ const int col_pos = kb * BK + sn + (j * stile_t::kFragCols);
+ STEEL_PRAGMA_UNROLL
+ for (short jj = 0; jj < stile_t::MMAFrag_t::kElemCols; jj++) {
+ if (row_pos < (col_pos + jj)) {
+ Stile.frag_at(i, j)[jj] = neg_inf;
+ }
+ }
+ }
+ }
+ }
+
+ // Other masking as needed
+ if (has_mask) {
+ using stile_t = decltype(Stile);
+ using selem_t = typename stile_t::elem_type;
+ constexpr auto neg_inf = -metal::numeric_limits<selem_t>::infinity();
+
+ constexpr bool is_bool = is_same_v<MaskType, bool>;
+ using melem_t = typename metal::conditional_t<is_bool, bool, selem_t>;
+
+ using MMAFrag_mask_t = BaseMMAFrag<melem_t, kFragSize, kFragSize>;
+ using frag_t = typename MMAFrag_mask_t::frag_type;
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < stile_t::kTileRows; i++) {
+ const int row_pos = tid.x * BQ + tm + sm + (i * stile_t::kFragRows);
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < stile_t::kTileCols; j++) {
+ const int col_pos = kb * BK + sn + (j * stile_t::kFragCols);
+
+ frag_t mfrag;
+
+ MMAFrag_mask_t::load_safe(
+ mfrag,
+ mask,
+ int(mask_params->M_strides[2]),
+ Int<1>{},
+ params->qL,
+ params->kL,
+ row_pos,
+ col_pos);
+
+ STEEL_PRAGMA_UNROLL
+ for (short jj = 0; jj < stile_t::MMAFrag_t::kElemsPerFrag; jj++) {
+ if constexpr (is_bool) {
+ Stile.frag_at(i, j)[jj] =
+ mfrag[jj] ? Stile.frag_at(i, j)[jj] : neg_inf;
+ } else {
+ Stile.frag_at(i, j)[jj] += 1.44269504089 * selem_t(mfrag[jj]);
+ }
+ }
+ }
+ }
+ }
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ // Load V blocks
+ if (!align_K && kb == (params->NK_aligned)) {
+ loader_v.load_safe(short2(BD, params->kL_rem));
+ } else {
+ loader_v.load_unsafe();
+ }
+
+ // Do softmax
+
+ // Temp variables
+ AccumType new_max[kRowsPT];
+ AccumType factor[kRowsPT];
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kRowsPT; ++i) {
+ new_max[i] = max_score[i];
+ }
+
+ // Row max
+ Stile.template row_reduce<MaxOp>(new_max);
+
+ // exp(Si - rowmax(Si))
+ Stile.template row_bin_op<ExpSubOp>(new_max);
+
+ // Factor exp(rowmax(Si) - rowmax(Si-1))
+ // Guard: when max_score == -inf (no valid K seen yet), the previous accumulation is all zeros so the correct rescaling factor is 0.
+ // Without this, -inf - (-inf) = NaN which poisons the output.
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kRowsPT; ++i) {
+ factor[i] = (max_score[i] == -metal::numeric_limits<AccumType>::infinity())
+ ? AccumType(0)
+ : fast::exp2(max_score[i] - new_max[i]);
+ }
+
+ // Save max for next iteration
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kRowsPT; ++i) {
+ max_score[i] = new_max[i];
+ }
+
+ // Row Sum
+ AccumType sum_score_tmp[kRowsPT] = {0};
+ Stile.template row_reduce<SumOp>(sum_score_tmp);
+
+ // Update norm
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < kRowsPT; ++i) {
+ sum_score[i] = sum_score[i] * factor[i] + sum_score_tmp[i];
+ }
+
+ // Update O
+ Otile.template row_bin_op<MulOp>(factor);
+
+ // Load V into registers
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ STEEL_PRAGMA_UNROLL
+ for (short iq = 0; iq < TQ; iq++) {
+ STEEL_PRAGMA_UNROLL
+ for (short id = 0; id < TD; id++) {
+ STEEL_PRAGMA_UNROLL
+ for (short ik = 0; ik < TK; ik++) {
+ if constexpr (BD == 128) {
+ simdgroup_barrier(mem_flags::mem_none);
+ }
+
+ const short kk = ik * kFragSize;
+ const short dd = id * kFragSize;
+
+ Vtile.template load<T, 1, 1, LDV_tgp, 1>(
+ &Vs[Vs_offset + kk * LDV_tgp + dd]);
+
+ if constexpr (BD == 128) {
+ simdgroup_barrier(mem_flags::mem_none);
+ }
+
+ MMAFrag_acc_t::mma(
+ Otile.frag_at(iq, id),
+ Stile.frag_at(iq, ik),
+ Vtile.frag_at(0, 0),
+ Otile.frag_at(iq, id));
+ }
+ }
+ }
+
+ // Prepare for next iteration
+ loader_k.next();
+ loader_v.next();
+ }
+
+ // Normalize output
+ Otile.template row_bin_op<DivOp>(sum_score);
+ threadgroup_barrier(mem_flags::mem_none);
+
+ // Store results
+ O += (tm + sm) * params->O_strides[2] + sn;
+
+ if (!align_Q && int(tid.x) == (params->NQ_aligned)) {
+ auto dst_tile_dims = short2(BD - sn, params->qL_rem - (tm + sm));
+
+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)
+ return;
+
+ Otile.template store_safe<T, 1, 1>(O, params->O_strides[2], dst_tile_dims);
+ } else {
+ Otile.template store<T, 1, 1>(O, params->O_strides[2]);
+ }
+}
+
+// clang-format off
+
+// SDPA full instantiations
+
+// Instantiate a templated kernel.
+// Extra args are used as template parameters:
+// e.g. instantiate_kernel(binary_int, binary, a, b) ->
+// [[host_name(binary_int)]] [kernel] binary<a, b>
+#define instantiate_kernel(name, func, ...) \
+ template [[host_name( \
+ name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+#define instantiate_attn(tname, dtype, bq, bk, bd, wm, wn, mname, mtype) \
+ instantiate_kernel( \
+ "steel_attention_" #tname "_bq" #bq "_bk" #bk "_bd" #bd \
+ "_wm" #wm "_wn" #wn "_mask" #mname, \
+ attention, dtype, bq, bk, bd, wm, wn, mtype, float)
+
+#define instantiate_attn_shapes_helper(iname, itype, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 16, 256, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 16, 128, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 32, 96, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 32, 80, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 32, 72, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 32, 64, 4, 1, mname, mtype) \
+ instantiate_attn(iname, itype, 32, 32, 32, 4, 1, mname, mtype)
+
+#define instantiate_attn_mask_helper(iname, itype) \
+ instantiate_attn_shapes_helper(iname, itype, iname, itype) \
+ instantiate_attn_shapes_helper(iname, itype, bool_, bool)
+
+instantiate_attn_mask_helper(float16, half);
+instantiate_attn_mask_helper(bfloat16, bfloat16_t);
+instantiate_attn_mask_helper(float32, float);
+
+// BD=512: reduced tiles (BQ=8, BK=8) to fit 32KB threadgroup memory.
+// Only f16/bf16 — float32 exceeds the limit.
+instantiate_attn(float16, half, 8, 8, 512, 1, 1, float16, half)
+instantiate_attn(float16, half, 8, 8, 512, 1, 1, bool_, bool)
+instantiate_attn(bfloat16, bfloat16_t, 8, 8, 512, 1, 1, bfloat16, bfloat16_t)
+instantiate_attn(bfloat16, bfloat16_t, 8, 8, 512, 1, 1, bool_, bool)
+
+// SDPA vector instantiations
+#define instantiate_sdpa_vector(type, head_dim) \
+ template [[host_name("sdpa_vector_" #type "_" #head_dim)]] \
+ [[kernel]] void sdpa_vector<type, head_dim>( \
+ const device type* queries [[buffer(0)]], \
+ const device type* keys [[buffer(1)]], \
+ const device type* values [[buffer(2)]], \
+ device type* out [[buffer(3)]], \
+ const constant int& gqa_factor, \
+ const constant int& N, \
+ const constant size_t& k_stride, \
+ const constant size_t& v_stride, \
+ const constant float& scale, \
+ const constant float& softcapping, \
+ const device bool* mask [[function_constant(sdpa_vector_has_mask)]], \
+ const constant int& mask_seq_stride [[function_constant(sdpa_vector_has_mask)]], \
+ const constant int& mask_head_stride [[function_constant(sdpa_vector_has_mask)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]); \
+ template [[host_name("sdpa_vector_2pass_1_" #type "_" #head_dim)]] \
+ [[kernel]] void sdpa_vector_2pass_1<type, head_dim>( \
+ const device type* queries [[buffer(0)]], \
+ const device type* keys [[buffer(1)]], \
+ const device type* values [[buffer(2)]], \
+ device float* out [[buffer(3)]], \
+ device float* sums [[buffer(4)]], \
+ device float* maxs [[buffer(5)]], \
+ const constant int& gqa_factor, \
+ const constant int& N, \
+ const constant size_t& k_stride, \
+ const constant size_t& v_stride, \
+ const constant float& scale, \
+ const constant float& softcapping, \
+ const device bool* mask [[function_constant(sdpa_vector_has_mask)]], \
+ const constant int& mask_seq_stride [[function_constant(sdpa_vector_has_mask)]], \
+ const constant int& mask_head_stride [[function_constant(sdpa_vector_has_mask)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]); \
+ template [[host_name("sdpa_vector_2pass_2_" #type "_" #head_dim)]] \
+ [[kernel]] void sdpa_vector_2pass_2<type, head_dim>( \
+ const device float* partials [[buffer(0)]], \
+ const device float* sums [[buffer(1)]], \
+ const device float* maxs [[buffer(2)]], \
+ device type* out [[buffer(3)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]); \
+
+#define instantiate_sdpa_vector_heads(type) \
+ instantiate_sdpa_vector(type, 32) \
+ instantiate_sdpa_vector(type, 64) \
+ instantiate_sdpa_vector(type, 72) \
+ instantiate_sdpa_vector(type, 80) \
+ instantiate_sdpa_vector(type, 96) \
+ instantiate_sdpa_vector(type, 128) \
+ instantiate_sdpa_vector(type, 256) \
+ instantiate_sdpa_vector(type, 512)
+
+instantiate_sdpa_vector_heads(float)
+instantiate_sdpa_vector_heads(bfloat16_t)
+instantiate_sdpa_vector_heads(float16_t)
+ // clang-format on
\ No newline at end of file
diff --git a/vendor/candle-metal-kernels/src/metal_src/sort.metal b/vendor/candle-metal-kernels/src/metal_src/sort.metal
new file mode 100644
index 0000000..d71ab82
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/sort.metal
@@ -0,0 +1,97 @@
+// Imported from https://github.com/ggerganov/llama.cpp/blob/master/ggml-metal.metal
+#include <metal_stdlib>
+using namespace metal;
+
+#define SWAP(x, y) { auto tmp = (x); (x) = (y); (y) = tmp; }
+#define SORT_ASC 1
+#define SORT_DESC 0
+
+template<int order, typename T>
+METAL_FUNC void argsort(
+ device const T * x,
+ device uint32_t * dst,
+ constant int64_t & ncols,
+ constant int64_t & ncols_pad,
+ threadgroup uint32_t * shared_values [[threadgroup(0)]],
+ uint3 tgpig[[threadgroup_position_in_grid]],
+ uint3 tpitg[[thread_position_in_threadgroup]]) {
+ int col = tpitg[0];
+ int row = tgpig[1];
+
+ if (col >= ncols_pad) return;
+
+ device const T * x_row = x + row * ncols;
+ threadgroup uint32_t * dst_row = shared_values;
+
+ // initialize indices
+ dst_row[col] = col;
+
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (int k = 2; k <= ncols_pad; k *= 2) {
+ for (int j = k / 2; j > 0; j /= 2) {
+ int ixj = col ^ j;
+ if (ixj > col) {
+ if ((col & k) == 0) {
+ if (dst_row[col] >= ncols ||
+ (dst_row[ixj] < ncols && (order == SORT_ASC ?
+ x_row[dst_row[col]] > x_row[dst_row[ixj]] :
+ x_row[dst_row[col]] < x_row[dst_row[ixj]]))
+ ) {
+ SWAP(dst_row[col], dst_row[ixj]);
+ }
+ } else {
+ if (dst_row[ixj] >= ncols ||
+ (dst_row[col] < ncols && (order == SORT_ASC ?
+ x_row[dst_row[col]] < x_row[dst_row[ixj]] :
+ x_row[dst_row[col]] > x_row[dst_row[ixj]]))
+ ) {
+ SWAP(dst_row[col], dst_row[ixj]);
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ }
+
+ // copy the result to dst without the padding
+ if (col < ncols) {
+ dst[row * ncols + col] = dst_row[col];
+ }
+}
+
+#define ARGSORT(T, RUST_T) \
+kernel void asort_asc_##RUST_T( \
+ device const T * x, \
+ device uint32_t * dst, \
+ constant int64_t & ncols, \
+ constant int64_t & ncols_pad, \
+ threadgroup uint32_t * shared_values [[threadgroup(0)]], \
+ uint3 tgpig[[threadgroup_position_in_grid]], \
+ uint3 tpitg[[thread_position_in_threadgroup]] \
+) { \
+ argsort<SORT_ASC, T>(x, dst, ncols, ncols_pad, shared_values, tgpig, tpitg); \
+} \
+kernel void asort_desc_##RUST_T( \
+ device const T * x, \
+ device uint32_t * dst, \
+ constant int64_t & ncols, \
+ constant int64_t & ncols_pad, \
+ threadgroup uint32_t * shared_values [[threadgroup(0)]], \
+ uint3 tgpig[[threadgroup_position_in_grid]], \
+ uint3 tpitg[[thread_position_in_threadgroup]] \
+) { \
+ argsort<SORT_DESC, T>(x, dst, ncols, ncols_pad, shared_values, tgpig, tpitg); \
+} \
+
+ARGSORT(float, f32)
+ARGSORT(half, f16)
+ARGSORT(uint8_t, u8)
+ARGSORT(uint32_t, u32)
+
+#if __METAL_VERSION__ >= 220
+ARGSORT(int64_t, i64)
+#endif
+#if defined(__HAVE_BFLOAT__)
+ARGSORT(bfloat, bf16)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/ternary.metal b/vendor/candle-metal-kernels/src/metal_src/ternary.metal
new file mode 100644
index 0000000..b78cb4a
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/ternary.metal
@@ -0,0 +1,125 @@
+#include <metal_stdlib>
+using namespace metal;
+
+constant bool IDS_CONTIGUOUS [[function_constant(0)]];
+constant bool T_CONTIGUOUS [[function_constant(1)]];
+constant bool F_CONTIGUOUS [[function_constant(2)]];
+
+
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant const size_t &num_dims,
+ constant const size_t *dims,
+ constant const size_t *strides
+) {
+ uint strided_i = 0;
+ #pragma clang loop unroll(full)
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+template<typename T, typename ID, uint W = work_per_thread<T>()>
+METAL_FUNC void where_cond(
+ constant size_t &numel,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant size_t *strides_t,
+ constant size_t *strides_f,
+ device const ID *ids,
+ device const T *t,
+ device const T *f,
+ device T *out,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ uint idx = 0;
+ uint t_idx = 0;
+ uint f_idx = 0;
+
+ const uint step = div_ceil<W>(numel);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < numel; i += step) {
+ if (IDS_CONTIGUOUS) {
+ idx = i;
+ } else {
+ idx = get_strided_index(i, num_dims, dims, strides);
+ }
+ if (T_CONTIGUOUS) {
+ t_idx = i;
+ } else {
+ t_idx = get_strided_index(i, num_dims, dims, strides_t);
+ }
+ if (F_CONTIGUOUS) {
+ f_idx = i;
+ } else {
+ f_idx = get_strided_index(i, num_dims, dims, strides_f);
+ }
+ out[i] = select(f[f_idx], t[t_idx], ids[idx]);
+ }
+
+}
+
+#define WHERE_OP(T, ID, FN_NAME) \
+kernel void FN_NAME( \
+ constant size_t &numel, \
+ constant size_t &num_dims, \
+ constant size_t *dims, \
+ constant size_t *strides, \
+ constant size_t *strides_t, \
+ constant size_t *strides_f, \
+ device const ID *ids, \
+ device const T *t, \
+ device const T *f, \
+ device T *out, \
+ uint i [[ thread_position_in_grid ]] \
+) { \
+ where_cond<T, ID>(numel, num_dims, dims, strides, strides_t, strides_f, ids, t, f, out, i); \
+} \
+
+WHERE_OP(half, uint32_t, where_u32_f16)
+WHERE_OP(float, uint32_t, where_u32_f32)
+WHERE_OP(uint8_t, uint32_t, where_u32_u8)
+WHERE_OP(uint32_t, uint32_t, where_u32_u32)
+
+WHERE_OP(half, uint8_t, where_u8_f16)
+WHERE_OP(float, uint8_t, where_u8_f32)
+WHERE_OP(uint8_t, uint8_t, where_u8_u8)
+WHERE_OP(uint32_t, uint8_t, where_u8_u32)
+
+#if __METAL_VERSION__ >= 220
+WHERE_OP(int64_t, uint8_t, where_u8_i64)
+WHERE_OP(int64_t, uint32_t, where_u32_i64)
+
+WHERE_OP(half, int64_t, where_i64_f16)
+WHERE_OP(float, int64_t, where_i64_f32)
+WHERE_OP(uint8_t, int64_t, where_i64_u8)
+WHERE_OP(uint32_t, int64_t, where_i64_u32)
+WHERE_OP(int64_t, int64_t, where_i64_i64)
+#if defined(__HAVE_BFLOAT__)
+WHERE_OP(bfloat, int64_t, where_i64_bf16)
+#endif
+#endif
+
+#if defined(__HAVE_BFLOAT__)
+WHERE_OP(bfloat, uint8_t, where_u8_bf16)
+WHERE_OP(bfloat, uint32_t, where_u32_bf16)
+#endif
diff --git a/vendor/candle-metal-kernels/src/metal_src/unary.metal b/vendor/candle-metal-kernels/src/metal_src/unary.metal
new file mode 100644
index 0000000..11e7a9a
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/unary.metal
@@ -0,0 +1,280 @@
+#include <metal_stdlib>
+#include <metal_math>
+using namespace metal;
+
+// Utils
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
+
+template<uint Y>
+constexpr uint div_ceil(uint x) {
+ return x / Y + (x % Y > 0);
+}
+
+template<uint X, uint Y>
+constexpr uint div_ceil() {
+ return X / Y + (X % Y > 0);
+}
+
+template<typename T>
+constexpr uint work_per_thread() {
+ return div_ceil<8, sizeof(T)>();
+}
+
+// Kernels
+template <typename T, typename U, typename unary, int W = work_per_thread<T>()>
+[[kernel]] void unary_kernel(
+ constant size_t &dim,
+ device const T* input,
+ device U* output,
+ uint tid [[thread_position_in_grid]]
+) {
+ unary op;
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = static_cast<U>(op(input[i]));
+ }
+}
+
+template <typename T, typename U, typename unary>
+[[kernel]] void unary_kernel_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ constant const T *input,
+ device U *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ unary op;
+ if (tid >= dim) return;
+ uint idx = get_strided_index(tid, num_dims, dims, strides);
+ output[tid] = static_cast<U>(op(input[idx]));
+}
+
+template <typename T, int W = work_per_thread<T>()>
+[[kernel]] void const_set(
+ constant size_t &dim,
+ device const T &input,
+ device T *output,
+ uint tid [[thread_position_in_grid]]
+) {
+ const uint step = div_ceil<W>(dim);
+ #pragma clang loop unroll(full)
+ for (uint i = tid; i < dim; i += step) {
+ output[i] = input;
+ }
+}
+
+template <typename T>
+[[kernel]] void const_set_strided(
+ constant size_t &dim,
+ constant size_t &num_dims,
+ constant size_t *dims,
+ constant size_t *strides,
+ device const T &input,
+ device T *output,
+ uint tid [[ thread_position_in_grid ]]
+) {
+ if (tid >= dim) return;
+ uint idx = get_strided_index(tid, num_dims, dims, strides);
+ output[idx] = input;
+}
+
+template <typename T>
+[[kernel]] void copy2d(
+ constant int64_t &d1,
+ constant int64_t &d2,
+ constant int64_t &src_s,
+ constant int64_t &dst_s,
+ device const T *input,
+ device T *output,
+ uint2 idx [[thread_position_in_grid]]
+) {
+ if (idx.x >= d1 || idx.y >= d2) return;
+ int64_t src_idx = idx.x * src_s + idx.y;
+ int64_t dst_idx = idx.x * dst_s + idx.y;
+ output[dst_idx] = input[src_idx];
+}
+
+// Unary functions
+template <typename T> METAL_FUNC T erf(T in){
+ // constants
+ constexpr const float a1 = 0.254829592;
+ constexpr const float a2 = -0.284496736;
+ constexpr const float a3 = 1.421413741;
+ constexpr const float a4 = -1.453152027;
+ constexpr const float a5 = 1.061405429;
+ constexpr const float p = 0.3275911;
+
+ float x = static_cast<float>(in);
+
+ // Save the sign of x
+ int sign = 1;
+ if (x < 0)
+ sign = -1;
+ x = fabs(x);
+
+ // A&S formula 7.1.26
+ float t = 1.0/(1.0 + p*x);
+ float y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);
+
+ return T(sign*y);
+}
+template <typename T> METAL_FUNC T id(T in) { return in; }
+template <typename T> METAL_FUNC T gelu_erf(T x) {
+ return static_cast<T>(x * (1 + erf(x * M_SQRT1_2_F)) / 2);
+}
+template <typename T> METAL_FUNC T gelu(T x) {
+ if (x > 5) {
+ return x;
+ }
+ T x_sq = x * x;
+ T x_cube = x_sq * x;
+ T alpha = x + static_cast<T>(0.044715) * x_cube;
+ T beta = (static_cast<T>(M_2_SQRTPI_F * M_SQRT1_2_F) * alpha);
+ return static_cast<T>(0.5) * x * (static_cast<T>(1.0) + T(precise::tanh(beta)));
+}
+template <typename T> METAL_FUNC T relu(T x) {
+ if (x > 5) {
+ return x;
+ }
+ T x_sq = x * x;
+ T x_cube = x_sq * x;
+ T alpha = x + static_cast<T>(0.044715) * x_cube;
+ T beta = (static_cast<T>(M_2_SQRTPI_F * M_SQRT1_2_F) * alpha);
+ return static_cast<T>(0.5) * x * (static_cast<T>(1.0) + T(precise::tanh(beta)));
+}
+template <typename T> METAL_FUNC T recip(T x) {
+ return static_cast<T>(1.0 / x);
+}
+template <typename T> METAL_FUNC T sigmoid(T x) {
+ return static_cast<T>(recip(1 + exp(-x)));
+}
+
+// Define unary ops
+#define define_unary_op(name, op) \
+struct name { \
+ template <typename T> \
+ METAL_FUNC T operator()(T x) { \
+ return static_cast<T>(op); \
+ } \
+};
+
+define_unary_op(usqr, x * x);
+define_unary_op(urecip, recip(x));
+define_unary_op(uneg, -x);
+define_unary_op(uid, x);
+define_unary_op(ugelu, gelu(x));
+define_unary_op(urelu, x < 0 ? 0 : x);
+define_unary_op(usilu, x / (1 + exp(-x)));
+define_unary_op(ugelu_erf, gelu_erf(x));
+define_unary_op(usqrt, sqrt(x));
+define_unary_op(ucos, cos(x));
+define_unary_op(usin, sin(x));
+define_unary_op(uexp, exp(x));
+define_unary_op(ulog, log(x));
+define_unary_op(uabs, abs(static_cast<float>(x)));
+define_unary_op(uceil, ceil(x));
+define_unary_op(ufloor, floor(x));
+define_unary_op(uround, round(x));
+define_unary_op(uerf, erf(x));
+define_unary_op(usign, sign(x));
+define_unary_op(usigmoid, sigmoid(x));
+// tanh may create NaN on large values, e.g. 45 rather than outputting 1.
+// This has been an issue for the encodec example.
+define_unary_op(utanh, precise::tanh(x));
+
+// Macros to help initialize kernels
+#define init_kernel(name, func, ...) \
+ template [[host_name(name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;
+
+#define init_unary(op_name, unary_op, tname, t) \
+ init_kernel(#op_name "_" #tname, unary_kernel, t, t, unary_op) \
+ init_kernel(#op_name "_" #tname "_strided", unary_kernel_strided, t, t, unary_op)
+
+#if defined(__HAVE_BFLOAT__)
+#define init_unary_float(op_name, unary_op) \
+ init_unary(op_name, unary_op, f32, float) \
+ init_unary(op_name, unary_op, f16, half) \
+ init_unary(op_name, unary_op, bf16, bfloat)
+#else
+#define init_unary_float(op_name, unary_op) \
+ init_unary(op_name, unary_op, f32, float) \
+ init_unary(op_name, unary_op, f16, half)
+#endif
+
+#define init_copy2d(tname, t) \
+ init_kernel("copy2d_" #tname, copy2d, t)
+
+#define init_const_set(tname, t) \
+ init_kernel("const_set_" #tname, const_set, t) \
+ init_kernel("const_set_" #tname "_strided", const_set_strided, t)
+
+// Initialize all unary kernels for floating point types
+init_unary_float(gelu_erf, ugelu_erf);
+init_unary_float(sqrt, usqrt);
+init_unary_float(sqr, usqr);
+init_unary_float(neg, uneg);
+init_unary_float(recip, urecip);
+init_unary_float(copy, uid);
+init_unary_float(silu, usilu);
+init_unary_float(gelu, ugelu);
+init_unary_float(relu, urelu);
+init_unary_float(cos, ucos);
+init_unary_float(sin, usin);
+init_unary_float(exp, uexp);
+init_unary_float(log, ulog);
+init_unary_float(abs, uabs);
+init_unary_float(ceil, uceil);
+init_unary_float(floor, ufloor);
+init_unary_float(round, uround);
+init_unary_float(erf, uerf);
+init_unary_float(sign, usign);
+init_unary_float(sigmoid, usigmoid);
+init_unary_float(tanh, utanh);
+
+// Initialize copy2d kernels
+init_copy2d(f32, float);
+init_copy2d(f16, half);
+
+// Initialize const_set kernels
+init_const_set(f32, float);
+init_const_set(f16, half);
+
+#if defined(__HAVE_BFLOAT__)
+init_copy2d(bf16, bfloat);
+init_const_set(bf16, bfloat);
+#endif
+
+// Initialize unary kernels for integer dtypes
+init_unary(copy, uid, u8, uint8_t);
+init_unary(copy, uid, u32, uint32_t);
+
+init_copy2d(u8, uint8_t);
+init_copy2d(u32, uint32_t);
+
+init_const_set(u8, uint8_t);
+init_const_set(u32, uint32_t);
+
+#if __METAL_VERSION__ >= 220
+init_unary(copy, uid, i64, int64_t);
+init_copy2d(i64, int64_t);
+init_const_set(i64, int64_t);
+#endif
+
+init_copy2d(i32, int32_t);
+init_copy2d(i16, int16_t);
diff --git a/vendor/candle-metal-kernels/src/metal_src/utils.metal b/vendor/candle-metal-kernels/src/metal_src/utils.metal
new file mode 100644
index 0000000..8ee6b4a
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/metal_src/utils.metal
@@ -0,0 +1,47 @@
+#pragma once
+#include <metal_stdlib>
+using namespace metal;
+
+METAL_FUNC uint nonzero(uint n) {
+ return n == 0 ? 1 : n;
+}
+
+template<uint N>
+constexpr uint nonzero() {
+ return N == 0 ? 1 : N;
+}
+
+template<typename T>
+constexpr ushort granularity() {
+ return nonzero<vec_elements<T>::value>();
+}
+
+METAL_FUNC uint next_p2(uint x) {
+ return 1 << (32 - clz(x - 1));
+}
+
+METAL_FUNC uint prev_p2(uint x) {
+ return 1 << (31 - clz(x));
+}
+
+constant uint MAX_SHARED_MEM = 32767;
+
+template<typename T>
+METAL_FUNC uint max_shared_mem(uint n) {
+ return min(n, prev_p2(MAX_SHARED_MEM / sizeof(T)));
+}
+
+METAL_FUNC uint get_strided_index(
+ uint idx,
+ constant const uint &num_dims,
+ constant const size_t *dims,
+ constant const size_t *strides
+) {
+ uint strided_i = 0;
+ for (uint d = 0; d < num_dims; d++) {
+ uint dim_idx = num_dims - 1 - d;
+ strided_i += (idx % dims[dim_idx]) * strides[dim_idx];
+ idx /= dims[dim_idx];
+ }
+ return strided_i;
+}
diff --git a/vendor/candle-metal-kernels/src/source.rs b/vendor/candle-metal-kernels/src/source.rs
new file mode 100644
index 0000000..3b37329
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/source.rs
@@ -0,0 +1,36 @@
+pub const AFFINE: &str = include_str!("metal_src/affine.metal");
+pub const BINARY: &str = include_str!("metal_src/binary.metal");
+pub const CAST: &str = include_str!("metal_src/cast.metal");
+pub const CONV: &str = include_str!("metal_src/conv.metal");
+pub const FILL: &str = include_str!("metal_src/fill.metal");
+pub const INDEXING: &str = include_str!("metal_src/indexing.metal");
+pub const GEMV: &str = include_str!("metal_src/gemv.metal");
+pub const MLX_GEMM: &str = include_str!("metal_src/mlx_gemm.metal");
+pub const MLX_SORT: &str = include_str!("metal_src/mlx_sort.metal");
+pub const QUANTIZED: &str = include_str!("metal_src/quantized.metal");
+pub const RANDOM: &str = include_str!("metal_src/random.metal");
+pub const REDUCE: &str = include_str!("metal_src/reduce.metal");
+pub const SORT: &str = include_str!("metal_src/sort.metal");
+pub const TERNARY: &str = include_str!("metal_src/ternary.metal");
+pub const UNARY: &str = include_str!("metal_src/unary.metal");
+pub const SDPA: &str = include_str!("metal_src/scaled_dot_product_attention.metal");
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Source {
+ Affine,
+ Binary,
+ Cast,
+ Conv,
+ Fill,
+ Gemm,
+ Gemv,
+ Indexing,
+ MlxSort,
+ Quantized,
+ Random,
+ Reduce,
+ Sort,
+ Ternary,
+ Unary,
+ Sdpa,
+}
diff --git a/vendor/candle-metal-kernels/src/tests.rs b/vendor/candle-metal-kernels/src/tests.rs
new file mode 100644
index 0000000..5487e24
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/tests.rs
@@ -0,0 +1,2493 @@
+use super::*;
+use crate::metal::{Commands, ResidencySet};
+use core::ffi::c_void;
+use half::{bf16, f16};
+use rand::prelude::SliceRandom;
+use rand::{rng, Rng};
+use std::sync::Arc;
+use std::thread;
+
+fn commands(device: &Device) -> Commands {
+ let queue = device.new_command_queue().unwrap();
+ let residency_set = Arc::new(ResidencySet::new(&device));
+ Commands::new(queue, &residency_set).unwrap()
+}
+
+fn read_to_vec<T: Clone>(buffer: &Buffer, n: usize) -> Vec<T> {
+ let ptr = buffer.contents() as *const T;
+ assert!(!ptr.is_null());
+ let slice = unsafe { std::slice::from_raw_parts(ptr, n) };
+ slice.to_vec()
+}
+
+fn new_buffer<T>(device: &Device, data: &[T]) -> Buffer {
+ let options = RESOURCE_OPTIONS;
+ let ptr = data.as_ptr() as *const c_void;
+ let size = std::mem::size_of_val(data);
+ device.new_buffer_with_data(ptr, size, options).unwrap()
+}
+
+fn device() -> Device {
+ Device::system_default().unwrap()
+}
+
+#[test]
+fn pipeline_cache_distinguishes_sources() {
+ let device = device();
+ let kernels = Kernels::new();
+
+ // Prime the cache with a name that is not present in the binary library.
+ kernels
+ .load_pipeline(&device, Source::Unary, "cos_f32")
+ .unwrap();
+ assert!(matches!(
+ kernels.load_pipeline(&device, Source::Binary, "cos_f32"),
+ Err(MetalKernelError::LoadFunctionError(_))
+ ));
+}
+
+fn approx(v: Vec<f32>, digits: i32) -> Vec<f32> {
+ let b = 10f32.powi(digits);
+ v.iter().map(|t| f32::round(t * b) / b).collect()
+}
+
+fn approx_f16(v: Vec<f16>, digits: i32) -> Vec<f32> {
+ let b = 10f32.powi(digits);
+ v.iter().map(|t| f32::round(t.to_f32() * b) / b).collect()
+}
+
+fn approx_bf16(v: Vec<bf16>, digits: i32) -> Vec<f32> {
+ let b = 10f32.powi(digits);
+ v.iter().map(|t| f32::round(t.to_f32() * b) / b).collect()
+}
+
+fn run<T: Clone>(v: &[T], name: unary::contiguous::Kernel) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input = new_buffer(&device, v);
+ let input = BufferOffset {
+ buffer: &input,
+ offset_in_bytes: 0,
+ };
+ let output = new_buffer(&device, v);
+ call_unary_contiguous(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ size_of::<T>(),
+ v.len(),
+ input,
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, v.len())
+}
+
+fn run_binary<T: Clone, S: ToString>(x: &[T], y: &[T], name: S) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let options = RESOURCE_OPTIONS;
+ let left = new_buffer(&device, x);
+ let right = new_buffer(&device, y);
+ let output = device
+ .new_buffer(std::mem::size_of_val(x), options)
+ .unwrap();
+ call_binary_contiguous(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ size_of::<T>(),
+ x.len(),
+ BufferOffset::zero_offset(&left),
+ BufferOffset::zero_offset(&right),
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, x.len())
+}
+
+fn run_strided<T: Clone>(
+ v: &[T],
+ kernel: unary::strided::Kernel,
+ shape: &[usize],
+ strides: &[usize],
+ offset: usize,
+) -> Vec<T> {
+ let device = device();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input = new_buffer(&device, v);
+ let input = BufferOffset {
+ buffer: &input,
+ offset_in_bytes: offset,
+ };
+ let output_b = new_buffer(&device, v);
+ let output = BufferOffset {
+ buffer: &output_b,
+ offset_in_bytes: 0,
+ };
+ let kernels = Kernels::new();
+ call_unary_strided(
+ &device, &encoder, &kernels, kernel, shape, input, strides, output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output_b, v.len())
+}
+
+#[test]
+fn cos_f32() {
+ let v = vec![1.0f32, 2.0, 3.0];
+ let results = run(&v, unary::contiguous::cos::FLOAT);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(approx(results, 4), vec![0.5403, -0.4161, -0.99]);
+ assert_eq!(approx(expected, 4), vec![0.5403, -0.4161, -0.99]);
+
+ let v = vec![1.0f32; 10_000];
+ let results = run(&v, unary::contiguous::cos::FLOAT);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(approx(results, 4), vec![0.5403; 10_000]);
+ assert_eq!(approx(expected, 4), vec![0.5403; 10_000]);
+}
+
+#[test]
+fn cos_f32_strided() {
+ let v = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let shape = vec![6];
+ let strides = vec![1];
+ let offset = 0;
+ let results = run_strided(&v, unary::strided::cos::FLOAT, &shape, &strides, offset);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(
+ approx(results, 4),
+ vec![0.5403, -0.4161, -0.99, -0.6536, 0.2837, 0.9602]
+ );
+ assert_eq!(
+ approx(expected, 4),
+ vec![0.5403, -0.4161, -0.99, -0.6536, 0.2837, 0.9602]
+ );
+
+ // Contiguous
+ let v = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let shape = vec![3, 2];
+ let strides = vec![2, 1];
+ let offset = 0;
+ let results = run_strided(&v, unary::strided::cos::FLOAT, &shape, &strides, offset);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(
+ approx(results, 4),
+ vec![0.5403, -0.4161, -0.99, -0.6536, 0.2837, 0.9602]
+ );
+ assert_eq!(
+ approx(expected, 4),
+ vec![0.5403, -0.4161, -0.99, -0.6536, 0.2837, 0.9602]
+ );
+
+ // Transposed
+ let v = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let shape = vec![3, 2];
+ let strides = vec![1, 3];
+ let offset = 0;
+ let results = run_strided(&v, unary::strided::cos::FLOAT, &shape, &strides, offset);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(
+ approx(results, 4),
+ vec![0.5403, -0.6536, -0.4161, 0.2837, -0.99, 0.9602]
+ );
+ assert_eq!(
+ approx(expected, 4),
+ vec![0.5403, -0.4161, -0.99, -0.6536, 0.2837, 0.9602]
+ );
+
+ // Very large
+ let v = vec![1.0f32; 10_000];
+ let shape = vec![2, 5_000];
+ let strides = vec![2, 1];
+ let offset = 0;
+ let results = run_strided(&v, unary::strided::cos::FLOAT, &shape, &strides, offset);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(approx(results, 4), vec![0.5403; 10_000]);
+ assert_eq!(approx(expected, 4), vec![0.5403; 10_000]);
+}
+
+#[test]
+fn cos_strided_random() {
+ let v: Vec<_> = (0..10_000).map(|_| rand::random::<f32>()).collect();
+ let shape = vec![5_000, 2];
+ let strides = vec![1, 5_000];
+ let offset = 0;
+ let results = run_strided(&v, unary::strided::cos::FLOAT, &shape, &strides, offset);
+ let expected: Vec<_> = v.iter().map(|v| v.cos()).collect();
+ assert_eq!(approx(vec![results[0]], 4), approx(vec![expected[0]], 4));
+ assert_eq!(
+ approx(vec![results[1]], 4),
+ approx(vec![expected[5_000]], 4)
+ );
+ assert_eq!(approx(vec![results[2]], 4), approx(vec![expected[1]], 4));
+ assert_eq!(
+ approx(vec![results[3]], 4),
+ approx(vec![expected[5_001]], 4)
+ );
+ assert_eq!(
+ approx(vec![results[5_000]], 4),
+ approx(vec![expected[2_500]], 4)
+ );
+}
+
+#[test]
+fn gelu_f16() {
+ let v: Vec<f16> = [-10f32, -1.0, 0., 1., 2., 3., 10.0, 20.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect();
+ let expected: Vec<f32> = vec![-0.0, -0.159, 0.0, 0.841, 1.954, 2.996, 10.0, 20.0];
+ let results = run(&v, unary::contiguous::gelu::HALF);
+ assert_eq!(approx_f16(results, 3), expected);
+}
+
+#[test]
+fn gelu_f32() {
+ let v: Vec<f32> = vec![-10f32, -1.0, 0., 1., 2., 3., 10.0, 20.0];
+ let expected: Vec<f32> = vec![-0.0, -0.159, 0.0, 0.841, 1.955, 2.996, 10.0, 20.0];
+ let results = run(&v, unary::contiguous::gelu::FLOAT);
+ assert_eq!(approx(results, 3), expected);
+}
+
+#[test]
+fn silu_f16() {
+ let v: Vec<f16> = [-10f32, -1.0, 0., 1., 2., 3., 10.0, 20.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect();
+ let expected: Vec<f32> = vec![-0.0, -0.27, 0.0, 0.73, 1.76, 2.86, 10.0, 20.0];
+ let results = run(&v, unary::contiguous::silu::HALF);
+ assert_eq!(approx_f16(results, 2), expected);
+}
+
+#[test]
+fn silu_f32() {
+ let v: Vec<f32> = vec![-10f32, -1.0, 0., 1., 2., 3., 10.0, 20.0];
+ let expected: Vec<f32> = vec![-0.0, -0.269, 0.0, 0.731, 1.762, 2.858, 10.0, 20.0];
+ let results = run(&v, unary::contiguous::silu::FLOAT);
+ assert_eq!(approx(results, 3), expected);
+}
+
+#[test]
+fn binary_add_f32() {
+ let left = vec![1.0f32, 2.0, 3.0];
+ let right = vec![2.0f32, 3.1, 4.2];
+ let results = run_binary(&left, &right, "badd_f32");
+ let expected: Vec<_> = left
+ .iter()
+ .zip(right.iter())
+ .map(|(&x, &y)| x + y)
+ .collect();
+ assert_eq!(approx(results, 4), vec![3.0f32, 5.1, 7.2]);
+ assert_eq!(approx(expected, 4), vec![3.0f32, 5.1, 7.2]);
+}
+
+#[test]
+fn binary_ops_bf16() {
+ let lhs: Vec<bf16> = [1.1f32, 2.2, 3.3].into_iter().map(bf16::from_f32).collect();
+ let rhs: Vec<bf16> = [4.2f32, 5.5f32, 6.91f32]
+ .into_iter()
+ .map(bf16::from_f32)
+ .collect();
+
+ macro_rules! binary_op {
+ ($opname:ident, $dtype:ident, $opexpr:expr) => {{
+ let results = run_binary(
+ &lhs,
+ &rhs,
+ concat!(stringify!($opname), "_", stringify!($dtype)),
+ );
+ let expected: Vec<bf16> = lhs
+ .iter()
+ .zip(rhs.iter())
+ .map(|(x, y): (&$dtype, &$dtype)| $opexpr(*x, *y))
+ .collect();
+ assert_eq!(results, expected);
+ }};
+ }
+ binary_op!(badd, bf16, |x, y| x + y);
+ binary_op!(bsub, bf16, |x, y| x - y);
+ binary_op!(bmul, bf16, |x, y| x * y);
+ binary_op!(bdiv, bf16, |x, y| x / y);
+ binary_op!(bminimum, bf16, |x: bf16, y| x.min(y));
+ binary_op!(bmaximum, bf16, |x: bf16, y| x.max(y));
+}
+
+fn run_cast<T: Clone, U: Clone>(v: &[T], name: &'static str) -> Vec<U> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input = new_buffer(&device, v);
+ let options = RESOURCE_OPTIONS;
+ let size = v.len() * std::mem::size_of::<U>();
+ let output = device.new_buffer(size, options).unwrap();
+
+ call_cast_contiguous(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ size_of::<T>(),
+ v.len(),
+ BufferOffset::zero_offset(&input),
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, v.len())
+}
+
+#[test]
+fn cast_f32() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // f32 -> f16
+ let results: Vec<half::f16> = run_cast(&v_f32, "cast_f32_f16");
+ assert_eq!(results, v_f16);
+
+ // f32 -> bf16
+ let results: Vec<bf16> = run_cast(&v_f32, "cast_f32_bf16");
+ assert_eq!(results, v_bf16);
+
+ // f32 -> u32
+ let results: Vec<u32> = run_cast(&v_f32, "cast_f32_u32");
+ assert_eq!(results, v_u32);
+
+ // f32 -> u8
+ let results: Vec<u8> = run_cast(&v_f32, "cast_f32_u8");
+ assert_eq!(results, v_u8);
+
+ // f32 -> i64
+ let results: Vec<i64> = run_cast(&v_f32, "cast_f32_i64");
+ assert_eq!(results, v_i64);
+}
+
+#[test]
+fn cast_f16() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // f16 -> f32
+ let results: Vec<f32> = run_cast(&v_f16, "cast_f16_f32");
+ assert_eq!(results, v_f32);
+
+ // f16 -> bf16
+ let results: Vec<bf16> = run_cast(&v_f16, "cast_f16_bf16");
+ assert_eq!(results, v_bf16);
+
+ // f16 -> u32
+ let results: Vec<u32> = run_cast(&v_f16, "cast_f16_u32");
+ assert_eq!(results, v_u32);
+
+ // f16 -> u8
+ let results: Vec<u8> = run_cast(&v_f16, "cast_f16_u8");
+ assert_eq!(results, v_u8);
+
+ // f16 -> i64
+ let results: Vec<i64> = run_cast(&v_f16, "cast_f16_i64");
+ assert_eq!(results, v_i64);
+}
+
+#[test]
+fn cast_bf16() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // bf16 -> f32
+ let results: Vec<f32> = run_cast(&v_bf16, "cast_bf16_f32");
+ assert_eq!(results, v_f32);
+
+ // bf16 -> f16
+ let results: Vec<f16> = run_cast(&v_bf16, "cast_bf16_f16");
+ assert_eq!(results, v_f16);
+
+ // bf16 -> u32
+ let results: Vec<u32> = run_cast(&v_bf16, "cast_bf16_u32");
+ assert_eq!(results, v_u32);
+
+ // bf16 -> u8
+ let results: Vec<u8> = run_cast(&v_bf16, "cast_bf16_u8");
+ assert_eq!(results, v_u8);
+
+ // bf16 -> i64
+ let results: Vec<i64> = run_cast(&v_bf16, "cast_bf16_i64");
+ assert_eq!(results, v_i64);
+}
+
+#[test]
+fn cast_u32() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // u32 -> f32
+ let results: Vec<f32> = run_cast(&v_u32, "cast_u32_f32");
+ assert_eq!(results, v_f32);
+
+ // u32 -> f16
+ let results: Vec<f16> = run_cast(&v_u32, "cast_u32_f16");
+ assert_eq!(results, v_f16);
+
+ // u32 -> bf16
+ let results: Vec<bf16> = run_cast(&v_u32, "cast_u32_bf16");
+ assert_eq!(results, v_bf16);
+
+ // u32 -> u8
+ let results: Vec<u8> = run_cast(&v_u32, "cast_u32_u8");
+ assert_eq!(results, v_u8);
+
+ // u32 -> i64
+ let results: Vec<i64> = run_cast(&v_u32, "cast_u32_i64");
+ assert_eq!(results, v_i64);
+}
+
+#[test]
+fn cast_u8() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // u8 -> f32
+ let results: Vec<f32> = run_cast(&v_u8, "cast_u8_f32");
+ assert_eq!(results, v_f32);
+
+ // u8 -> f16
+ let results: Vec<f16> = run_cast(&v_u8, "cast_u8_f16");
+ assert_eq!(results, v_f16);
+
+ // u8 -> bf16
+ let results: Vec<bf16> = run_cast(&v_u8, "cast_u8_bf16");
+ assert_eq!(results, v_bf16);
+
+ // u8 -> u32
+ let results: Vec<u32> = run_cast(&v_u8, "cast_u8_u32");
+ assert_eq!(results, v_u32);
+
+ // u8 -> i64
+ let results: Vec<i64> = run_cast(&v_u8, "cast_u8_i64");
+ assert_eq!(results, v_i64);
+}
+
+#[test]
+fn cast_i64() {
+ let v_f64 = [1.0f64, 2.0, 3.0];
+ let v_f32: Vec<f32> = v_f64.iter().map(|&v| v as f32).collect();
+ let v_f16: Vec<f16> = v_f64.iter().map(|&v| f16::from_f32(v as f32)).collect();
+ let v_bf16: Vec<bf16> = v_f64.iter().map(|&v| bf16::from_f32(v as f32)).collect();
+ let v_u32: Vec<u32> = v_f64.iter().map(|&v| v as u32).collect();
+ let v_u8: Vec<u8> = v_f64.iter().map(|&v| v as u8).collect();
+ let v_i64: Vec<i64> = v_f64.iter().map(|&v| v as i64).collect();
+
+ // i64 -> f32
+ let results: Vec<f32> = run_cast(&v_i64, "cast_i64_f32");
+ assert_eq!(results, v_f32);
+
+ // i64 -> f16
+ let results: Vec<f16> = run_cast(&v_i64, "cast_i64_f16");
+ assert_eq!(results, v_f16);
+
+ // i64 -> bf16
+ let results: Vec<bf16> = run_cast(&v_i64, "cast_i64_bf16");
+ assert_eq!(results, v_bf16);
+
+ // i64 -> u32
+ let results: Vec<u32> = run_cast(&v_i64, "cast_i64_u32");
+ assert_eq!(results, v_u32);
+
+ // i64 -> u8
+ let results: Vec<u8> = run_cast(&v_i64, "cast_i64_u8");
+ assert_eq!(results, v_u8);
+}
+
+fn run_affine<T: Clone>(v: &[T], mul: f64, add: f64) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+
+ let input = new_buffer(&device, v);
+ let output = new_buffer(&device, v);
+
+ let size = v.len();
+
+ call_affine(
+ &device,
+ &encoder,
+ &kernels,
+ "affine_f32",
+ size_of::<T>(),
+ size,
+ BufferOffset::zero_offset(&input),
+ &output,
+ mul as f32,
+ add as f32,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, v.len())
+}
+
+fn run_affine_strided<T: Clone>(
+ v: &[T],
+ shape: &[usize],
+ strides: &[usize],
+ mul: f64,
+ add: f64,
+) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+
+ let input = new_buffer(&device, v);
+ let output = new_buffer(&device, v);
+
+ call_affine_strided(
+ &device,
+ &encoder,
+ &kernels,
+ "affine_f32_strided",
+ shape,
+ BufferOffset::zero_offset(&input),
+ strides,
+ &output,
+ mul as f32,
+ add as f32,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ let len: usize = shape.iter().product();
+ read_to_vec(&output, len)
+}
+
+#[test]
+fn affine() {
+ let input = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
+ let mul = 1.5;
+ let add = 1.1;
+ let result = run_affine(&input, mul, add);
+ assert_eq!(result, vec![2.6, 4.1, 5.6, 7.1, 8.6, 10.1, 11.6, 13.1]);
+
+ let input = [1.0f32; 40_000];
+ let mul = 1.5;
+ let add = 1.1;
+ let result = run_affine(&input, mul, add);
+ assert_eq!(result, vec![2.6; 40_000]);
+}
+
+#[test]
+fn affine_strided() {
+ let input = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
+ let mul = 1.5;
+ let add = 1.1;
+ let shape = [4];
+ let strides = [2];
+ let result = run_affine_strided(&input, &shape, &strides, mul, add);
+ // 1 on 2
+ assert_eq!(result, vec![2.6, 5.6, 8.6, 11.6]);
+}
+
+fn run_mlx_sort<T: Clone>(v: &[T], ncols: usize) -> Vec<u32> {
+ let nrows = v.len() / ncols;
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+
+ let input = new_buffer(&device, v);
+ let indexes = vec![0u32; v.len()];
+ let output = new_buffer(&device, &indexes);
+
+ call_mlx_arg_sort(
+ &device,
+ &encoder,
+ &kernels,
+ DType::F32,
+ nrows,
+ ncols,
+ BufferOffset::zero_offset(&input),
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, v.len())
+}
+
+#[test]
+fn mlx_sort() {
+ use rand::SeedableRng;
+ use rand_distr::Distribution;
+
+ let input: Vec<_> = (0..8).map(|v| v as f32).collect();
+ let result = run_mlx_sort(&input, 4);
+ assert_eq!(result, [0, 1, 2, 3, 0, 1, 2, 3]);
+ let input: Vec<_> = (0..8).rev().map(|v| v as f32).collect();
+ let result = run_mlx_sort(&input, 4);
+ assert_eq!(result, [3, 2, 1, 0, 3, 2, 1, 0]);
+ let input: Vec<_> = (0..1000).rev().map(|v| v as f32).collect();
+ let result = run_mlx_sort(&input, 200);
+ let out: Vec<_> = (0..200).rev().collect();
+ assert_eq!(&result[..200], out);
+ assert_eq!(&result[200..400], out);
+ assert_eq!(&result[400..600], out);
+ assert_eq!(&result[600..800], out);
+ assert_eq!(&result[800..], out);
+
+ // Multi-block test
+ let ncols = 16000;
+ let mut rng = rand::rngs::StdRng::seed_from_u64(299792458);
+ let normal = rand_distr::Normal::new(0.0, 1.0).unwrap();
+ let input: Vec<f32> = (0..ncols * 16).map(|_| normal.sample(&mut rng)).collect();
+ let result = run_mlx_sort(&input, ncols);
+ for start in 0..16 {
+ let slice = &input[start * ncols..(start + 1) * ncols];
+ let result = &result[start * ncols..(start + 1) * ncols];
+ let mut perm: Vec<usize> = (0..ncols).collect();
+ perm.sort_by(|i1, i2| slice[*i1].total_cmp(&slice[*i2]));
+ let perm: Vec<_> = perm.into_iter().map(|v| v as u32).collect();
+ assert_eq!(perm, result);
+ }
+}
+
+#[test]
+fn index_select() {
+ let embedding = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u32, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_f32");
+ assert_eq!(result, vec![1.0f32, 2.0, 9.0, 10.0, 5.0, 6.0]);
+
+ let embedding = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
+ let shape = [2, 5];
+ let stride = [1, 2];
+ let ids = [0u32, 1, 0];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_f32");
+ assert_eq!(
+ result,
+ vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 1.0f32, 2.0, 3.0, 4.0, 5.0]
+ );
+}
+
+#[test]
+fn index_select_strided() {
+ let embedding = (0..16).map(|x| x as f32).collect::<Vec<_>>();
+ let shape = [2, 2];
+ let stride = [2, 4];
+ let ids = [0u32];
+ let dim = 0;
+ let result = run_index_select_strided(&embedding, &shape, &stride, &ids, dim, "is_u32_f32");
+ assert_eq!(result, vec![0.0, 4.0]);
+}
+
+#[test]
+fn index_select_f16() {
+ let embedding: Vec<_> = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u32, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_f16");
+ assert_eq!(
+ approx_f16(result, 4),
+ vec![1.0f32, 2.0, 9.0, 10.0, 5.0, 6.0]
+ );
+}
+
+#[test]
+fn index_select_is_u32_bf16() {
+ let embedding: Vec<bf16> = (1..=10).map(|x| bf16::from_f32(x as f32)).collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u32, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_bf16");
+ assert_eq!(
+ approx_bf16(result, 4),
+ vec![1.0f32, 2.0, 9.0, 10.0, 5.0, 6.0]
+ );
+}
+
+#[test]
+fn index_select_is_u8_bf16() {
+ let embedding: Vec<bf16> = (1..=10).map(|x| bf16::from_f32(x as f32)).collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u8, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u8_bf16");
+ assert_eq!(
+ approx_bf16(result, 4),
+ vec![1.0f32, 2.0, 9.0, 10.0, 5.0, 6.0]
+ );
+}
+
+#[test]
+fn index_select_is_u32_i64() {
+ let embedding: Vec<i64> = (1..=10).map(|x| x as i64).collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u32, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_i64");
+ assert_eq!(result, vec![1i64, 2, 9, 10, 5, 6]);
+}
+
+#[test]
+fn index_select_is_u8_i64() {
+ let embedding: Vec<i64> = (1..=10).map(|x| x as i64).collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u8, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u8_i64");
+ assert_eq!(result, vec![1i64, 2, 9, 10, 5, 6]);
+}
+
+#[test]
+fn index_select_is_i64_i64() {
+ let embedding: Vec<i64> = (1..=10).map(|x| x as i64).collect();
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0i64, 4, 2];
+ let dim = 0;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_i64_i64");
+ assert_eq!(result, vec![1i64, 2, 9, 10, 5, 6]);
+}
+
+#[test]
+fn index_select_dim1() {
+ let embedding = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
+ let shape = [5, 2];
+ let stride = [2, 1];
+ let ids = [0u32, 1, 0];
+ let dim = 1;
+ let result = run_index_select(&embedding, &shape, &stride, &ids, dim, "is_u32_f32");
+ assert_eq!(
+ result,
+ vec![1.0f32, 2.0, 1.0, 3.0, 4.0, 3.0, 5.0, 6.0, 5.0, 7.0, 8.0f32, 7.0, 9.0, 10.0, 9.0]
+ );
+}
+
+fn run_index_select<T: Clone, I: Clone + std::fmt::Debug>(
+ embeddings: &[T],
+ shape: &[usize],
+ stride: &[usize],
+ ids: &[I],
+ dim: usize,
+ name: &'static str,
+) -> Vec<T> {
+ let device = Device::system_default().expect("no device found");
+
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let embeddings_buffer = new_buffer(&device, embeddings);
+ let ids_buffer = new_buffer(&device, ids);
+
+ let left_size: usize = shape[..dim].iter().product();
+ let right_size: usize = shape[dim + 1..].iter().product();
+ let dst_el = ids.len() * left_size * right_size;
+ let dst_buffer = new_buffer(&device, &vec![0.0f32; dst_el]);
+
+ let kernels = Kernels::new();
+ call_index_select(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ shape,
+ ids.len(),
+ dim,
+ true,
+ shape,
+ stride,
+ BufferOffset::zero_offset(&embeddings_buffer),
+ BufferOffset::zero_offset(&ids_buffer),
+ &dst_buffer,
+ )
+ .unwrap();
+
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&dst_buffer, dst_el)
+}
+
+fn run_index_select_strided<T: Clone, I: Clone + std::fmt::Debug>(
+ embeddings: &[T],
+ shape: &[usize],
+ stride: &[usize],
+ ids: &[I],
+ dim: usize,
+ name: &'static str,
+) -> Vec<T> {
+ let device = Device::system_default().expect("no device found");
+
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let embeddings_buffer = new_buffer(&device, embeddings);
+ let ids_buffer = new_buffer(&device, ids);
+
+ let left_size: usize = shape[..dim].iter().product();
+ let right_size: usize = shape[dim + 1..].iter().product();
+ let dst_el = ids.len() * left_size * right_size;
+ let dst_buffer = new_buffer(&device, &vec![0.0f32; dst_el]);
+
+ let kernels = Kernels::new();
+ call_index_select(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ shape,
+ ids.len(),
+ dim,
+ false,
+ shape,
+ stride,
+ BufferOffset::zero_offset(&embeddings_buffer),
+ BufferOffset::zero_offset(&ids_buffer),
+ &dst_buffer,
+ )
+ .unwrap();
+
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&dst_buffer, dst_el)
+}
+
+#[test]
+fn cos_f16() {
+ let v: Vec<f16> = [1.0f32, 2.0, 3.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect();
+ let results = run(&v, unary::contiguous::cos::HALF);
+ let expected: Vec<f16> = v.iter().map(|v| f16::from_f32(v.to_f32().cos())).collect();
+ assert_eq!(approx_f16(results, 2), vec![0.54, -0.42, -0.99]);
+ assert_eq!(approx_f16(expected, 2), vec![0.54, -0.42, -0.99]);
+}
+
+fn run_reduce<T, U: Clone>(
+ v: &[T],
+ in_length: usize,
+ out_length: usize,
+ name: &'static str,
+) -> Vec<U> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input = new_buffer(&device, v);
+
+ let options = RESOURCE_OPTIONS;
+ let output = device
+ .new_buffer(out_length * core::mem::size_of::<U>(), options)
+ .unwrap();
+ let shape = vec![in_length];
+ match call_reduce_contiguous(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ &shape,
+ out_length,
+ BufferOffset::zero_offset(&input),
+ &output,
+ ) {
+ Ok(_) => {}
+ Err(e) => {
+ println!("{e}");
+ panic!();
+ }
+ }
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, out_length)
+}
+
+fn run_softmax<T: Clone + std::fmt::Debug>(v: &[T], last_dim: usize, name: &'static str) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input = new_buffer(&device, v);
+ let output = new_buffer(&device, v);
+ call_last_softmax(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ v.len(),
+ last_dim,
+ &input,
+ 0,
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, v.len())
+}
+
+const fn create_array<const N: usize>() -> [f32; N] {
+ let mut array: [f32; N] = [0.0; N];
+ let mut i = 1;
+ while i <= N {
+ array[i - 1] = i as f32;
+ i += 1;
+ }
+ array
+}
+
+const fn correct_sum<const N: usize, const D: usize>() -> [f32; D] {
+ let mut sum = 0;
+ let mut results: [f32; D] = [0.0; D];
+ let mut i = 1;
+ let mut j = 1;
+ while i <= N {
+ sum += i;
+ i += 1;
+ if i > j * N / D {
+ results[j - 1] = sum as f32;
+ j += 1;
+ sum = 0;
+ }
+ }
+ results
+}
+
+const fn correct_max<const N: usize, const D: usize>() -> [f32; D] {
+ let mut results: [f32; D] = [0.0; D];
+ let mut i = 1;
+ let mut j = 1;
+ while i <= N {
+ i += 1;
+ if i > j * (N / D) {
+ results[j - 1] = (i - 1) as f32;
+ j += 1;
+ }
+ }
+ results
+}
+
+fn correct_argmax<const N: usize, const D: usize>(arr: [f32; N]) -> [u32; D] {
+ let mut max = 0.0;
+ let mut max_index: u32 = 0;
+ let mut results: [u32; D] = [0; D];
+ let mut i = 0;
+ let mut j = 1;
+ while i <= N {
+ if i >= (j * N / D) {
+ results[j - 1] = max_index;
+ max = 0.0;
+ max_index = 0;
+ j += 1;
+ }
+ if i == N {
+ break;
+ }
+ if arr[i] > max {
+ max = arr[i];
+ max_index = i as u32;
+ }
+ i += 1;
+ }
+ results
+}
+
+fn reduce_sum_case<const N: usize, const D: usize>() {
+ let mut v = create_array::<N>();
+ if D == 1 {
+ // Hardens 1-dimensional test cases
+ v.shuffle(&mut rng());
+ }
+ let results = run_reduce(&v, N, D, "fast_sum_f32");
+ assert_eq!(approx(results, 4), correct_sum::<N, D>());
+}
+
+fn reduce_max_case<const N: usize, const D: usize>() {
+ let mut v = create_array::<N>();
+ if D == 1 {
+ // Hardens 1-dimensional test cases
+ v.shuffle(&mut rng());
+ }
+ let results = run_reduce(&v, N, D, "fast_max_f32");
+ assert_eq!(approx(results, 4), correct_max::<N, D>());
+}
+
+fn reduce_argmax_case<const N: usize, const D: usize>() {
+ let mut v = create_array::<N>();
+ if D == 1 {
+ // Hardens 1-dimensional test cases
+ v.shuffle(&mut rng());
+ }
+ let results: Vec<u32> = run_reduce(&v, N, D, "fast_argmax_f32");
+ assert_eq!(results, correct_argmax::<N, D>(v));
+}
+
+#[test]
+fn reduce_sum1() {
+ reduce_sum_case::<9, 1>();
+ reduce_sum_case::<6, 1>();
+ reduce_sum_case::<10, 1>();
+ reduce_sum_case::<64, 1>();
+ reduce_sum_case::<128, 1>();
+ reduce_sum_case::<256, 1>();
+ reduce_sum_case::<512, 1>();
+ reduce_sum_case::<1024, 1>();
+ reduce_sum_case::<2048, 1>();
+ reduce_sum_case::<4096, 1>();
+}
+
+#[test]
+fn reduce_sum2() {
+ reduce_sum_case::<6, 2>();
+ reduce_sum_case::<10, 2>();
+ reduce_sum_case::<64, 2>();
+ reduce_sum_case::<128, 2>();
+ reduce_sum_case::<256, 2>();
+ reduce_sum_case::<512, 2>();
+ reduce_sum_case::<1024, 2>();
+ reduce_sum_case::<2048, 2>();
+ reduce_sum_case::<4096, 2>();
+}
+
+#[test]
+fn reduce_max() {
+ reduce_max_case::<6, 1>();
+ reduce_max_case::<9, 1>();
+ reduce_max_case::<10, 1>();
+ reduce_max_case::<64, 1>();
+ reduce_max_case::<128, 1>();
+ reduce_max_case::<256, 1>();
+ reduce_max_case::<512, 1>();
+ reduce_max_case::<1024, 1>();
+ reduce_max_case::<2048, 1>();
+ reduce_max_case::<4096, 1>();
+
+ reduce_max_case::<6, 2>();
+ reduce_max_case::<10, 2>();
+ reduce_max_case::<64, 2>();
+ reduce_max_case::<128, 2>();
+ reduce_max_case::<256, 2>();
+ reduce_max_case::<512, 2>();
+ reduce_max_case::<1024, 2>();
+ reduce_max_case::<2048, 2>();
+ reduce_max_case::<4096, 2>();
+
+ reduce_max_case::<6, 3>();
+ reduce_max_case::<10, 3>();
+ reduce_max_case::<64, 3>();
+ reduce_max_case::<128, 3>();
+ reduce_max_case::<256, 3>();
+ reduce_max_case::<512, 3>();
+ reduce_max_case::<1024, 3>();
+ reduce_max_case::<2048, 3>();
+ reduce_max_case::<4096, 3>();
+}
+
+#[test]
+fn reduce_argmax() {
+ reduce_argmax_case::<6, 1>();
+ reduce_argmax_case::<9, 1>();
+ reduce_argmax_case::<10, 1>();
+ reduce_argmax_case::<64, 1>();
+ reduce_argmax_case::<128, 1>();
+ reduce_argmax_case::<256, 1>();
+ reduce_argmax_case::<512, 1>();
+ reduce_argmax_case::<1024, 1>();
+ reduce_argmax_case::<2048, 1>();
+}
+
+#[test]
+fn reduce_argmax2() {
+ reduce_argmax_case::<6, 2>();
+ reduce_argmax_case::<10, 2>();
+ reduce_argmax_case::<64, 2>();
+ reduce_argmax_case::<128, 2>();
+ reduce_argmax_case::<256, 2>();
+ reduce_argmax_case::<512, 2>();
+ reduce_argmax_case::<1024, 2>();
+ reduce_argmax_case::<2048, 2>();
+ reduce_argmax_case::<4096, 2>();
+}
+
+#[test]
+fn softmax() {
+ let v = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let last_dim = 6;
+ let results = run_softmax(&v, last_dim, "softmax_f32");
+ assert_eq!(
+ approx(results, 4),
+ vec![0.0043, 0.0116, 0.0315, 0.0858, 0.2331, 0.6337]
+ );
+
+ let last_dim = 4096;
+ let n = 200;
+ let mut v = vec![0.0; n * last_dim];
+ for i in 0..n {
+ v[i * last_dim] = 20.0;
+ }
+ let results = run_softmax(&v, last_dim, "softmax_f32");
+ let results = approx(results, 4);
+ assert_eq!(
+ results.iter().map(|&s| s.round() as usize).sum::<usize>(),
+ n
+ );
+ assert_eq!(results[0], 1.0);
+ assert_eq!(results[1], 0.0);
+ assert_eq!(results[last_dim], 1.0);
+ assert_eq!(results[2 * last_dim], 1.0);
+
+ let v = vec![0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0];
+ let last_dim = 6;
+ let results = run_softmax(&v, last_dim, "softmax_f32");
+ assert_eq!(
+ approx(results, 4),
+ vec![0.0043, 0.0116, 0.0315, 0.0858, 0.2331, 0.6337]
+ );
+
+ let v = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let last_dim = 3;
+ let results = run_softmax(&v, last_dim, "softmax_f32");
+ assert_eq!(
+ approx(results, 4),
+ vec![0.0900, 0.2447, 0.6652, 0.0900, 0.2447, 0.6652]
+ );
+
+ let v = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ let last_dim = 6;
+ let results = run_softmax(&v, last_dim, "softmax_f16");
+ assert_eq!(
+ approx_f16(results, 4),
+ vec![0.0043, 0.0116, 0.0315, 0.0858, 0.2332, 0.6338]
+ );
+
+ let v = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0]
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+ let last_dim = 6;
+ let results = run_softmax(&v, last_dim, "softmax_bf16");
+ assert_eq!(
+ approx_bf16(results, 4),
+ vec![0.0043, 0.0116, 0.0315, 0.0859, 0.2324, 0.6328]
+ );
+}
+
+#[allow(clippy::too_many_arguments)]
+fn run_where_cond<I: Clone, T: Clone>(
+ shape: &[usize],
+ cond: &[I],
+ (cond_stride, cond_offset): (Vec<usize>, usize),
+ left_true: &[T],
+ (left_stride, left_offset): (Vec<usize>, usize),
+ right_false: &[T],
+ (_right_stride, _right_offset): (Vec<usize>, usize),
+ name: &'static str,
+) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let options = RESOURCE_OPTIONS;
+
+ let length = cond.len();
+ let cond = device
+ .new_buffer_with_data(
+ cond.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(cond),
+ options,
+ )
+ .unwrap();
+ let left = device
+ .new_buffer_with_data(
+ left_true.as_ptr() as *const core::ffi::c_void,
+ length * core::mem::size_of::<T>(),
+ options,
+ )
+ .unwrap();
+ let right = device
+ .new_buffer_with_data(
+ right_false.as_ptr() as *const core::ffi::c_void,
+ length * core::mem::size_of::<T>(),
+ options,
+ )
+ .unwrap();
+
+ let output = device
+ .new_buffer(length * core::mem::size_of::<T>(), options)
+ .unwrap();
+ let cond = BufferOffset {
+ buffer: &cond,
+ offset_in_bytes: cond_offset,
+ };
+ let left = BufferOffset {
+ buffer: &left,
+ offset_in_bytes: left_offset,
+ };
+ let right = BufferOffset {
+ buffer: &right,
+ offset_in_bytes: cond_offset,
+ };
+ call_where_cond(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ size_of::<T>(),
+ shape,
+ cond,
+ &cond_stride,
+ true,
+ left,
+ &left_stride,
+ true,
+ right,
+ &cond_stride,
+ true,
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, length)
+}
+
+#[test]
+fn where_cond() {
+ let shape = vec![6];
+ let cond = vec![0u8, 1, 0, 0, 1, 1];
+ let cond_l = (vec![1], 0);
+ let left_true = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let left_l = (vec![1], 0);
+ let right_false = vec![-1.0f32, -2.0, -3.0, -4.0, -5.0, -6.0];
+ let right_l = (vec![1], 0);
+ let results = run_where_cond(
+ &shape,
+ &cond,
+ cond_l,
+ &left_true,
+ left_l,
+ &right_false,
+ right_l,
+ "where_u8_f32",
+ );
+ assert_eq!(approx(results, 4), vec![-1.0f32, 2.0, -3.0, -4.0, 5.0, 6.0]);
+}
+#[test]
+fn where_cond_u32_f32() {
+ let shape = vec![6];
+ let cond = vec![0u32, 1, 0, 0, 1, 1];
+ let cond_l = (vec![1], 0);
+ let left_true = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let left_l = (vec![1], 0);
+ let right_false = vec![-1.0f32, -2.0, -3.0, -4.0, -5.0, -6.0];
+ let right_l = (vec![1], 0);
+ let results = run_where_cond(
+ &shape,
+ &cond,
+ cond_l,
+ &left_true,
+ left_l,
+ &right_false,
+ right_l,
+ "where_u32_f32",
+ );
+ assert_eq!(approx(results, 4), vec![-1.0f32, 2.0, -3.0, -4.0, 5.0, 6.0]);
+}
+
+#[allow(clippy::too_many_arguments)]
+fn run_mlx_gemm<T: Clone>(
+ dtype: GemmDType,
+ (b, m, n, k): (usize, usize, usize, usize),
+ lhs: &[T],
+ lhs_stride: &[usize],
+ lhs_offset: usize,
+ rhs: &[T],
+ rhs_stride: &[usize],
+ rhs_offset: usize,
+) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let options = RESOURCE_OPTIONS;
+
+ let lhs = device
+ .new_buffer_with_data(
+ lhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(lhs),
+ options,
+ )
+ .unwrap();
+ let rhs = device
+ .new_buffer_with_data(
+ rhs.as_ptr() as *const core::ffi::c_void,
+ std::mem::size_of_val(rhs),
+ options,
+ )
+ .unwrap();
+ let length = b * m * n;
+ let output = device
+ .new_buffer(length * core::mem::size_of::<T>(), options)
+ .unwrap();
+ call_mlx_gemm(
+ &device,
+ &encoder,
+ &kernels,
+ dtype,
+ (b, m, n, k),
+ lhs_stride,
+ lhs_offset,
+ &lhs,
+ rhs_stride,
+ rhs_offset,
+ &rhs,
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, length)
+}
+
+#[test]
+fn mlx_gemm() {
+ let (b, m, n, k) = (1, 2, 4, 3);
+ let lhs: Vec<f32> = (0..b * m * k).map(|f| f as f32).collect();
+ let rhs: Vec<f32> = (0..b * n * k).map(|f| f as f32).collect();
+ let results = run_mlx_gemm(
+ GemmDType::F32,
+ (b, m, n, k),
+ &lhs,
+ &[m * k, k, 1],
+ 0,
+ &rhs,
+ &[n * k, n, 1],
+ 0,
+ );
+ assert_eq!(
+ approx(results, 4),
+ vec![20.0, 23.0, 26.0, 29.0, 56.0, 68.0, 80.0, 92.0]
+ );
+
+ let (b, m, n, k) = (2, 2, 4, 3);
+ let lhs: Vec<f32> = (0..b * m * k).map(|f| f as f32).collect();
+ let rhs: Vec<f32> = (0..b * n * k).map(|f| f as f32).collect();
+ let results = run_mlx_gemm(
+ GemmDType::F32,
+ (b, m, n, k),
+ &lhs,
+ &[m * k, k, 1],
+ 0,
+ &rhs,
+ &[n * k, n, 1],
+ 0,
+ );
+ assert_eq!(
+ approx(results, 4),
+ vec![
+ 20.0, 23.0, 26.0, 29.0, 56.0, 68.0, 80.0, 92.0, 344.0, 365.0, 386.0, 407.0, 488.0,
+ 518.0, 548.0, 578.0
+ ]
+ );
+
+ // OFFSET
+ let (b, m, n, k) = (2, 2, 4, 3);
+ let lhs: Vec<f32> = (0..b * m * k).map(|f| f as f32).collect();
+ let rhs: Vec<f32> = (0..b * n * k).map(|f| f as f32).collect();
+ // Manually set batch_size=1 and offset 12 elements * 4 the number of bytes for f32
+ let results = run_mlx_gemm(
+ GemmDType::F32,
+ (1, m, n, k),
+ &lhs,
+ &[m * k, k, 1],
+ 0,
+ &rhs,
+ &[n * k, n, 1],
+ 12 * 4,
+ );
+ assert_eq!(
+ approx(results, 4),
+ vec![56.0, 59.0, 62.0, 65.0, 200.0, 212.0, 224.0, 236.0]
+ );
+
+ // bgemm sanity test
+ {
+ let (b, m, n, k) = (1, 2, 4, 3);
+ let lhs: Vec<bf16> = (0..b * m * k).map(|f| bf16::from_f32(f as f32)).collect();
+ let rhs: Vec<bf16> = (0..b * n * k).map(|f| bf16::from_f32(f as f32)).collect();
+ let results = run_mlx_gemm(
+ GemmDType::BF16,
+ (b, m, n, k),
+ &lhs,
+ &[m * k, k, 1],
+ 0,
+ &rhs,
+ &[n * k, n, 1],
+ 0,
+ );
+ assert_eq!(
+ approx_bf16(results, 4),
+ vec![20.0, 23.0, 26.0, 29.0, 56.0, 68.0, 80.0, 92.0]
+ );
+ }
+
+ {
+ // hgemm sanity test
+ let (b, m, n, k) = (1, 2, 4, 3);
+ let lhs: Vec<f16> = (0..b * m * k).map(|f| f16::from_f32(f as f32)).collect();
+ let rhs: Vec<f16> = (0..b * n * k).map(|f| f16::from_f32(f as f32)).collect();
+ let results = run_mlx_gemm(
+ GemmDType::F16,
+ (b, m, n, k),
+ &lhs,
+ &[m * k, k, 1],
+ 0,
+ &rhs,
+ &[n * k, n, 1],
+ 0,
+ );
+ assert_eq!(
+ approx_f16(results, 4),
+ vec![20.0, 23.0, 26.0, 29.0, 56.0, 68.0, 80.0, 92.0]
+ );
+ }
+}
+
+fn run_random<T: Clone>(name: &'static str, seed: u64, length: usize, a: f32, b: f32) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+
+ let options = RESOURCE_OPTIONS;
+ let output = device
+ .new_buffer(length * core::mem::size_of::<T>(), options)
+ .unwrap();
+
+ let seed = device
+ .new_buffer_with_data(
+ &seed as *const u64 as *const core::ffi::c_void,
+ std::mem::size_of::<u64>(),
+ options,
+ )
+ .unwrap();
+
+ if name.starts_with("rand_uniform") {
+ call_random_uniform(
+ &device, &encoder, &kernels, name, a, b, length, &seed, &output,
+ )
+ .unwrap();
+ } else {
+ call_random_normal(
+ &device, &encoder, &kernels, name, a, b, length, &seed, &output,
+ )
+ .unwrap();
+ }
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, length)
+}
+
+#[test]
+fn random() {
+ fn calc_mean(data: &[f32]) -> f32 {
+ let sum = data.iter().sum::<f32>();
+ let count = data.len();
+ assert!(count > 0);
+ sum / count as f32
+ }
+
+ fn calc_stddev(data: &[f32]) -> f32 {
+ let mean = calc_mean(data);
+ let count = data.len();
+ assert!(count > 0);
+
+ let variance = data
+ .iter()
+ .map(|value| {
+ let diff = mean - *value;
+ diff * diff
+ })
+ .sum::<f32>()
+ / count as f32;
+
+ variance.sqrt()
+ }
+
+ let shape = [1024, 10];
+
+ let length = shape.iter().product::<usize>();
+ let seed = 299792458u64;
+
+ let min = -30.0;
+ let max = 30.0;
+ let mean = 100.0;
+ let stddev = 50.0;
+
+ macro_rules! validate_random {
+ ($type:ty) => {
+ let results: Vec<f32> = run_random::<$type>(
+ concat!("rand_uniform_", stringify!($type)),
+ seed,
+ length,
+ min,
+ max,
+ )
+ .into_iter()
+ .map(f32::from)
+ .collect();
+ results.iter().for_each(|v| {
+ assert!(*v >= min && *v <= max);
+ });
+ assert!(calc_mean(&results) > -1.0 && calc_mean(&results) < 1.0);
+
+ let results: Vec<f32> = run_random::<$type>(
+ concat!("rand_normal_", stringify!($type)),
+ seed,
+ length,
+ mean,
+ stddev,
+ )
+ .into_iter()
+ .map(f32::from)
+ .collect();
+ assert!((calc_mean(&results) - mean).abs() < mean / 10.0);
+ assert!((calc_stddev(&results) - stddev).abs() < stddev / 10.0);
+ };
+ }
+
+ validate_random!(f32);
+ validate_random!(f16);
+ validate_random!(bf16);
+}
+
+fn run_scatter_add<T: Clone, I: Clone + std::fmt::Debug>(
+ input: &[T],
+ ids: &[I],
+ shape: &[usize],
+ dim: usize,
+ name: &'static str,
+) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let options = RESOURCE_OPTIONS;
+ let input_buffer = new_buffer(&device, input);
+ let ids_buffer = new_buffer(&device, ids);
+ let output = device
+ .new_buffer(std::mem::size_of_val(input), options)
+ .unwrap();
+ call_scatter(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ shape,
+ shape,
+ dim,
+ BufferOffset::zero_offset(&input_buffer),
+ BufferOffset::zero_offset(&ids_buffer),
+ BufferOffset::zero_offset(&output),
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, input.len())
+}
+
+#[test]
+fn scatter_add() {
+ let ids_u8 = [0u8, 0, 1, 0, 2, 2, 3, 3];
+ let ids_u32 = [0u32, 0, 1, 0, 2, 2, 3, 3];
+ let ids_i64 = [0i64, 0, 1, 0, 2, 2, 3, 3];
+
+ let input_f32 = [5.0f32, 1.0, 7.0, 2.0, 3.0, 2.0, 1.0, 3.0];
+ let input_f16 = input_f32
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ let input_bf16 = input_f32
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+
+ let output_dim1_f32 = vec![8.0, 7.0, 5.0, 4.0, 0.0, 0.0, 0.0, 0.0];
+ let output_dim1_f16 = output_dim1_f32
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ let output_dim1_bf16 = output_dim1_f32
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+
+ let output_dim2_f32 = vec![5.0, 3.0, 7.0, 0.0, 3.0, 2.0, 1.0, 3.0];
+ let output_dim2_f16 = output_dim2_f32
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ let output_dim2_bf16 = output_dim2_f32
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+
+ for (shape, output_f32, output_f16, output_bf16) in [
+ (vec![8], output_dim1_f32, output_dim1_f16, output_dim1_bf16),
+ (
+ vec![4, 2],
+ output_dim2_f32,
+ output_dim2_f16,
+ output_dim2_bf16,
+ ),
+ ] {
+ for results in [
+ run_scatter_add(&input_f32, &ids_u8, &shape, 0, "sa_u8_f32"),
+ run_scatter_add(&input_f32, &ids_u32, &shape, 0, "sa_u32_f32"),
+ run_scatter_add(&input_f32, &ids_i64, &shape, 0, "sa_i64_f32"),
+ ] {
+ assert_eq!(results, output_f32);
+ }
+ for results in [
+ run_scatter_add(&input_f16, &ids_u8, &shape, 0, "sa_u8_f16"),
+ run_scatter_add(&input_f16, &ids_u32, &shape, 0, "sa_u32_f16"),
+ run_scatter_add(&input_f16, &ids_i64, &shape, 0, "sa_i64_f16"),
+ ] {
+ assert_eq!(results, output_f16);
+ }
+ for results in [
+ run_scatter_add(&input_bf16, &ids_u8, &shape, 0, "sa_u8_bf16"),
+ run_scatter_add(&input_bf16, &ids_u32, &shape, 0, "sa_u32_bf16"),
+ run_scatter_add(&input_bf16, &ids_i64, &shape, 0, "sa_i64_bf16"),
+ ] {
+ assert_eq!(results, output_bf16);
+ }
+ }
+}
+
+fn run_index_add<T: Clone, I: Clone + std::fmt::Debug>(
+ left: &[T],
+ right: &[T],
+ indices: &[I],
+ shape: &[usize],
+ dim: usize,
+ name: &'static str,
+) -> Vec<T> {
+ let device = device();
+ let kernels = Kernels::new();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let input_buffer = new_buffer(&device, right);
+ let output = new_buffer(&device, left);
+ let indices_buffer = new_buffer(&device, indices);
+ call_index_add(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ shape,
+ shape,
+ shape,
+ dim,
+ BufferOffset::zero_offset(&input_buffer),
+ BufferOffset::zero_offset(&indices_buffer),
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec(&output, left.len())
+}
+
+#[test]
+fn index_add() {
+ let left = vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let right = vec![1.0f32, 1.0, 1.0, 1.0, 1.0, 1.0];
+ let indices = vec![0u32, 1, 0, 1, 0, 1];
+ let shape = vec![6];
+
+ // u32, f32
+ {
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u32_f32");
+ assert_eq!(results, vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // u32, f16
+ {
+ let left = left.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u32_f16");
+ assert_eq!(approx_f16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // u32, bf16
+ {
+ let left = left.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u32_bf16");
+ assert_eq!(approx_bf16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // u8, f32
+ {
+ let indices = indices.iter().map(|v| *v as u8).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u8_f32");
+ assert_eq!(results, vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // u8, f16
+ {
+ let indices = indices.iter().map(|v| *v as u8).collect::<Vec<_>>();
+ let left = left.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u8_f16");
+ assert_eq!(approx_f16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // u8, bf16
+ {
+ let indices = indices.iter().map(|v| *v as u8).collect::<Vec<_>>();
+ let left = left.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_u8_bf16");
+ assert_eq!(approx_bf16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // i64, f32
+ {
+ let indices = indices.iter().map(|v| *v as i64).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_i64_f32");
+ assert_eq!(results, vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // i64, f16
+ {
+ let indices = indices.iter().map(|v| *v as i64).collect::<Vec<_>>();
+ let left = left.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_i64_f16");
+ assert_eq!(approx_f16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+
+ // i64, bf16
+ {
+ let indices = indices.iter().map(|v| *v as i64).collect::<Vec<_>>();
+ let left = left.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let right = right.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>();
+ let results = run_index_add(&left, &right, &indices, &shape, 0, "ia_i64_bf16");
+ assert_eq!(approx_bf16(results, 4), vec![4.0, 5.0, 3.0, 4.0, 5.0, 6.0]);
+ }
+}
+
+fn run_pool2d<T: Clone>(
+ v: &[T],
+ (w_k, h_k): (usize, usize),
+ (w_stride, h_stride): (usize, usize),
+ shape: &[usize],
+ strides: &[usize],
+ name: &'static str,
+) -> Vec<T> {
+ let device = device();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+ let out_w = (shape[2] - w_k) / w_stride + 1;
+ let out_h = (shape[3] - h_k) / h_stride + 1;
+ let dst_el = out_w * out_h * shape[0] * shape[1];
+ let input = new_buffer(&device, v);
+ let output = new_buffer(&device, &vec![0.0f32; dst_el]);
+ let kernels = Kernels::new();
+ call_pool2d(
+ &device, &encoder, &kernels, name, shape, strides, out_w, out_h, w_k, h_k, w_stride,
+ h_stride, &input, &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, dst_el)
+}
+
+#[test]
+fn max_pool2d_f32() {
+ // kernel 2 stride 1
+ let v: Vec<f32> = (0..16).map(|v| v as f32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_f32",
+ );
+ let expected = vec![5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 13.0, 14.0, 15.0];
+ assert_eq!(results, expected);
+
+ // kernel 2 stride 2
+ let v: Vec<f32> = (0..16).map(|v| v as f32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 2;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_f32",
+ );
+ let expected = vec![5.0, 7.0, 13.0, 15.0];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn max_pool2d_f16() {
+ // kernel 2 stride 1
+ let v: Vec<half::f16> = (0..16).map(|v| half::f16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_f16",
+ );
+ let expected = [5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 13.0, 14.0, 15.0]
+ .iter()
+ .map(|v| half::f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+
+ // kernel 2 stride 2
+ let v: Vec<half::f16> = (0..16).map(|v| half::f16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 2;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_f16",
+ );
+ let expected = [5.0, 7.0, 13.0, 15.0]
+ .iter()
+ .map(|v| half::f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn max_pool2d_bf16() {
+ // kernel 2 stride 1
+ let v: Vec<half::bf16> = (0..16).map(|v| half::bf16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_bf16",
+ );
+ let expected = [5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 13.0, 14.0, 15.0]
+ .iter()
+ .map(|v| half::bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+
+ // kernel 2 stride 2
+ let v: Vec<half::bf16> = (0..16).map(|v| half::bf16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 2;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_bf16",
+ );
+ let expected = [5.0, 7.0, 13.0, 15.0]
+ .iter()
+ .map(|v| half::bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn max_pool2d_u8() {
+ // kernel 2 stride 1
+ let v: Vec<u8> = (0..16).map(|v| v as u8).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_u8",
+ );
+ let expected = vec![5, 6, 7, 9, 10, 11, 13, 14, 15];
+ assert_eq!(results, expected);
+
+ // kernel 2 stride 2
+ let v: Vec<u8> = (0..16).map(|v| v as u8).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 2;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_u8",
+ );
+ let expected = vec![5, 7, 13, 15];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn max_pool2d_u32() {
+ // kernel 2 stride 1
+ let v: Vec<u32> = (0..16).map(|v| v as u32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_u32",
+ );
+ let expected = vec![5, 6, 7, 9, 10, 11, 13, 14, 15];
+ assert_eq!(results, expected);
+
+ // kernel 2 stride 2
+ let v: Vec<u32> = (0..16).map(|v| v as u32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 2;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "max_pool2d_u32",
+ );
+ let expected = vec![5, 7, 13, 15];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn avg_pool2d_f32() {
+ // kernel 2 stride 1
+ let v: Vec<f32> = (0..16).map(|v| v as f32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "avg_pool2d_f32",
+ );
+ let expected = vec![
+ 2.5000, 3.5000, 4.5000, 6.5000, 7.5000, 8.5000, 10.5000, 11.5000, 12.5000,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn avg_pool2d_f16() {
+ // kernel 2 stride 1
+ let v: Vec<f16> = (0..16).map(|v| f16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "avg_pool2d_f16",
+ );
+ let expected = [
+ 2.5000, 3.5000, 4.5000, 6.5000, 7.5000, 8.5000, 10.5000, 11.5000, 12.5000,
+ ]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn avg_pool2d_bf16() {
+ // kernel 2 stride 1
+ let v: Vec<bf16> = (0..16).map(|v| bf16::from_f32(v as f32)).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "avg_pool2d_bf16",
+ );
+ let expected = [
+ 2.5000, 3.5000, 4.5000, 6.5000, 7.5000, 8.5000, 10.5000, 11.5000, 12.5000,
+ ]
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn avg_pool2d_u8() {
+ // kernel 2 stride 1
+ let v: Vec<u8> = (0..16).map(|v| v as u8).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "avg_pool2d_u8",
+ );
+ let expected = vec![2, 3, 4, 6, 7, 8, 10, 11, 12];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn avg_pool2d_u32() {
+ // kernel 2 stride 1
+ let v: Vec<u32> = (0..16).map(|v| v as u32).collect();
+ let shape = vec![1, 1, 4, 4];
+ let strides = vec![16, 16, 4, 1];
+ let kernel = 2;
+ let stride = 1;
+ let results = run_pool2d(
+ &v,
+ (kernel, kernel),
+ (stride, stride),
+ &shape,
+ &strides,
+ "avg_pool2d_u32",
+ );
+ let expected = vec![2, 3, 4, 6, 7, 8, 10, 11, 12];
+ assert_eq!(results, expected);
+}
+
+#[allow(clippy::too_many_arguments)]
+fn run_conv_transpose1d<T: Clone>(
+ input: &[T],
+ input_shape: &[usize],
+ input_stride: &[usize],
+ kernel: &[T],
+ kernel_shape: &[usize],
+ kernel_stride: &[usize],
+ dilation: usize,
+ stride: usize,
+ padding: usize,
+ out_padding: usize,
+ name: &'static str,
+) -> Vec<T> {
+ let device = device();
+ let commands = commands(&device);
+ let encoder = commands.command_encoder().unwrap();
+
+ let c_out = kernel_shape[1];
+ let k_size = kernel_shape[2];
+ let b_size = input_shape[0];
+ let l_in = input_shape[2];
+ let l_out = (l_in - 1) * stride - 2 * padding + dilation * (k_size - 1) + out_padding + 1;
+ let dst_el = c_out * l_out * b_size;
+
+ let input = new_buffer(&device, input);
+ let kernel = new_buffer(&device, kernel);
+ let output = new_buffer(&device, &vec![0.0f32; dst_el]);
+ let kernels = Kernels::new();
+
+ call_conv_transpose1d(
+ &device,
+ &encoder,
+ &kernels,
+ name,
+ dilation,
+ stride,
+ padding,
+ out_padding,
+ c_out,
+ l_out,
+ b_size,
+ input_shape,
+ input_stride,
+ kernel_shape,
+ kernel_stride,
+ &input,
+ 0,
+ &kernel,
+ 0,
+ &output,
+ )
+ .unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+
+ read_to_vec(&output, dst_el)
+}
+
+#[test]
+fn conv_transpose1d_f32() {
+ let input = vec![1.0f32, 2.0, 3.0, 4.0];
+ let input_shape = &[1, 1, 4];
+ let input_stride = &[4, 4, 1];
+
+ let kernel = vec![1.0f32, 2.0, 3.0, 4.0];
+ let kernel_shape = &[1, 1, 4];
+ let kernel_stride = &[4, 4, 1];
+
+ let results = run_conv_transpose1d(
+ &input,
+ input_shape,
+ input_stride,
+ &kernel,
+ kernel_shape,
+ kernel_stride,
+ 1,
+ 1,
+ 0,
+ 0,
+ "conv_transpose1d_f32",
+ );
+
+ let expected = vec![1., 4., 10., 20., 25., 24., 16.];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn conv_transpose1d_f16() {
+ let input: Vec<f16> = [1.0, 2.0, 3.0, 4.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect();
+ let input_shape = &[1, 1, 4];
+ let input_stride = &[4, 4, 1];
+
+ let kernel: Vec<f16> = [1.0, 2.0, 3.0, 4.0]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect();
+ let kernel_shape = &[1, 1, 4];
+ let kernel_stride = &[4, 4, 1];
+
+ let results = run_conv_transpose1d(
+ &input,
+ input_shape,
+ input_stride,
+ &kernel,
+ kernel_shape,
+ kernel_stride,
+ 1,
+ 1,
+ 0,
+ 0,
+ "conv_transpose1d_f16",
+ );
+
+ let expected = [1., 4., 10., 20., 25., 24., 16.]
+ .iter()
+ .map(|v| f16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn conv_transpose1d_bf16() {
+ let input: Vec<bf16> = [1.0, 2.0, 3.0, 4.0]
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect();
+ let input_shape = &[1, 1, 4];
+ let input_stride = &[4, 4, 1];
+
+ let kernel: Vec<bf16> = [1.0, 2.0, 3.0, 4.0]
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect();
+ let kernel_shape = &[1, 1, 4];
+ let kernel_stride = &[4, 4, 1];
+
+ let results = run_conv_transpose1d(
+ &input,
+ input_shape,
+ input_stride,
+ &kernel,
+ kernel_shape,
+ kernel_stride,
+ 1,
+ 1,
+ 0,
+ 0,
+ "conv_transpose1d_bf16",
+ );
+
+ let expected = [1., 4., 10., 20., 25., 24., 16.]
+ .iter()
+ .map(|v| bf16::from_f32(*v))
+ .collect::<Vec<_>>();
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn conv_transpose1d_u8() {
+ let input: Vec<u8> = vec![1, 2, 3, 4];
+ let input_shape = &[1, 1, 4];
+ let input_stride = &[4, 4, 1];
+
+ let kernel: Vec<u8> = vec![1, 2, 3, 4];
+ let kernel_shape = &[1, 1, 4];
+ let kernel_stride = &[4, 4, 1];
+
+ let results = run_conv_transpose1d(
+ &input,
+ input_shape,
+ input_stride,
+ &kernel,
+ kernel_shape,
+ kernel_stride,
+ 1,
+ 1,
+ 0,
+ 0,
+ "conv_transpose1d_u8",
+ );
+
+ let expected = vec![1, 4, 10, 20, 25, 24, 16];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn conv_transpose1d_u32() {
+ let input: Vec<u32> = vec![1, 2, 3, 4];
+ let input_shape = &[1, 1, 4];
+ let input_stride = &[4, 4, 1];
+
+ let kernel: Vec<u32> = vec![1, 2, 3, 4];
+ let kernel_shape = &[1, 1, 4];
+ let kernel_stride = &[4, 4, 1];
+
+ let results = run_conv_transpose1d(
+ &input,
+ input_shape,
+ input_stride,
+ &kernel,
+ kernel_shape,
+ kernel_stride,
+ 1,
+ 1,
+ 0,
+ 0,
+ "conv_transpose1d_u32",
+ );
+
+ let expected = vec![1, 4, 10, 20, 25, 24, 16];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn const_fill() {
+ fn constant_fill<T: Clone + EncoderParam>(name: &'static str, len: usize, value: T) -> Vec<T> {
+ let dev = device();
+ let kernels = Kernels::new();
+ let commands = commands(&dev);
+ let encoder = commands.command_encoder().unwrap();
+ let buffer = dev
+ .new_buffer(len * std::mem::size_of::<T>(), RESOURCE_OPTIONS)
+ .unwrap();
+ call_const_fill(&dev, &encoder, &kernels, name, len, &buffer, value).unwrap();
+ drop(encoder);
+ commands.wait_until_completed().unwrap();
+ read_to_vec::<T>(&buffer, len)
+ }
+ fn test<T: Clone + Copy + EncoderParam + PartialEq + std::fmt::Debug, F: FnOnce(f32) -> T>(
+ name: &'static str,
+ f: F,
+ ) {
+ let len = rand::rng().random_range(2..16) * rand::rng().random_range(4..16);
+ let value = rand::rng().random_range(1. ..19.);
+ let value = f(value);
+ let v = constant_fill::<T>(name, len, value);
+ assert_eq!(v, vec![value; len])
+ }
+ test::<u8, _>("fill_u8", |v| v as u8);
+ test::<u32, _>("fill_u32", |v| v as u32);
+ test::<i64, _>("fill_i64", |v| v as i64);
+ test::<f16, _>("fill_f16", f16::from_f32);
+ test::<bf16, _>("fill_bf16", bf16::from_f32);
+ test::<f32, _>("fill_f32", |v| v);
+}
+
+#[test]
+fn commands_creation_and_encoder() {
+ let device = Device::system_default().unwrap();
+ let queue = device.new_command_queue().unwrap();
+ let residency_set = Arc::new(ResidencySet::new(&device));
+ let commands = Commands::new(queue, &residency_set).unwrap();
+
+ let encoder = commands.command_encoder().unwrap();
+ drop(encoder);
+}
+
+#[test]
+fn commands_concurrent_acquisition() {
+ std::env::set_var("CANDLE_METAL_COMPUTE_PER_BUFFER", "2");
+
+ let device = Device::system_default().unwrap();
+ let queue = device.new_command_queue().unwrap();
+ let residency_set = Arc::new(ResidencySet::new(&device));
+ let commands = Arc::new(Commands::new(queue, &residency_set).unwrap());
+
+ let mut handles = vec![];
+
+ for _ in 0..16 {
+ let c = Arc::clone(&commands);
+ handles.push(thread::spawn(move || {
+ let encoder = c.command_encoder().unwrap();
+ drop(encoder);
+ }));
+ }
+
+ for h in handles {
+ h.join().unwrap();
+ }
+
+ commands.wait_until_completed().unwrap();
+}
+
+#[test]
+fn residency_set_batch_insert_remove() {
+ use objc2_metal::MTLResidencySet;
+
+ let device = device();
+ let set = ResidencySet::new(&device);
+ let Some(raw) = set.raw() else {
+ // Residency sets are unsupported on this device/OS; the set no-ops.
+ return;
+ };
+
+ let bufs: Vec<Buffer> = (0..3).map(|i| new_buffer(&device, &[i as f32])).collect();
+ let base = raw.allocationCount();
+
+ set.insert_batch(&bufs);
+ assert_eq!(raw.allocationCount(), base + bufs.len());
+ set.remove_batch(&bufs);
+ assert_eq!(raw.allocationCount(), base);
+
+ // Empty batches are valid and leave the set untouched.
+ set.insert_batch(std::iter::empty());
+ set.remove_batch(std::iter::empty());
+ assert_eq!(raw.allocationCount(), base);
+}
diff --git a/vendor/candle-metal-kernels/src/utils.rs b/vendor/candle-metal-kernels/src/utils.rs
new file mode 100644
index 0000000..b4cd96c
--- /dev/null
+++ b/vendor/candle-metal-kernels/src/utils.rs
@@ -0,0 +1,372 @@
+use crate::metal::{Buffer, CommandsGuard, ComputeCommandEncoder, ComputePipeline};
+use crate::MTLSize;
+use std::ffi::OsStr;
+use std::ops::Deref;
+use std::sync::{RwLockReadGuard, RwLockWriteGuard};
+
+pub struct WrappedEncoder<'a> {
+ inner: &'a ComputeCommandEncoder,
+ end_encoding_on_drop: bool,
+}
+
+impl Drop for WrappedEncoder<'_> {
+ fn drop(&mut self) {
+ if self.end_encoding_on_drop {
+ self.inner.end_encoding()
+ }
+ }
+}
+
+impl AsRef<ComputeCommandEncoder> for WrappedEncoder<'_> {
+ fn as_ref(&self) -> &ComputeCommandEncoder {
+ self.inner
+ }
+}
+
+/// Most kernels apply similarly across the tensors
+/// This creates a strategy that uses the maximum amount of threads per threadgroup (capped at the
+/// actual total buffer length).
+/// Then kernels can just do their op on their single point in the buffer.
+pub(crate) fn linear_split(pipeline: &ComputePipeline, length: usize) -> (MTLSize, MTLSize) {
+ let size = length;
+ let width = std::cmp::min(pipeline.max_total_threads_per_threadgroup(), size);
+ let count = size.div_ceil(width);
+ let thread_group_count = MTLSize {
+ width: count,
+ height: 1,
+ depth: 1,
+ };
+
+ let thread_group_size = MTLSize {
+ width,
+ height: 1,
+ depth: 1,
+ };
+ (thread_group_count, thread_group_size)
+}
+
+// https://github.com/ml-explore/mlx/blob/bddf23f175726a57f0e443cd45518c0757daa166/mlx/backend/metal/utils.h#L96
+pub fn get_block_dims(dim0: usize, dim1: usize, dim2: usize) -> MTLSize {
+ let mut pows0 = 0;
+ let mut pows1 = 0;
+ let mut pows2 = 0;
+ let mut sum = 0;
+ loop {
+ let presum = sum;
+ // Check all the pows
+ if dim0 >= (1 << (pows0 + 1)) {
+ pows0 += 1;
+ sum += 1;
+ }
+ if sum == 10 {
+ break;
+ }
+ if dim1 >= (1 << (pows1 + 1)) {
+ pows1 += 1;
+ sum += 1;
+ }
+ if sum == 10 {
+ break;
+ }
+ if dim2 >= (1 << (pows2 + 1)) {
+ pows2 += 1;
+ sum += 1;
+ }
+ if sum == presum || sum == 10 {
+ break;
+ }
+ }
+ MTLSize {
+ width: 1 << pows0,
+ height: 1 << pows1,
+ depth: 1 << pows2,
+ }
+}
+
+/// Calculate preferred tile size given the size of a data type in bytes.
+/// f32 -> 2, f16 -> 4, u8 -> 8.
+#[inline(always)]
+pub fn get_tile_size(dtype_size: usize) -> usize {
+ 1.max(8 / dtype_size)
+}
+
+pub fn set_param<P: EncoderParam>(encoder: &ComputeCommandEncoder, position: usize, data: P) {
+ <P as EncoderParam>::set_param(encoder, position, data)
+}
+
+/// Helper functions to create the various objects on the compute command encoder
+/// on a single line.
+/// Prevents getting wrong some arguments number and mixing length and size in bytes.
+pub trait EncoderParam {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self);
+}
+macro_rules! primitive {
+ ($type:ty) => {
+ impl EncoderParam for $type {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_bytes(position, &data);
+ }
+ }
+ };
+}
+primitive!(bool);
+primitive!(usize);
+primitive!(i32);
+primitive!(i64);
+primitive!(u8);
+primitive!(u32);
+primitive!(u64);
+primitive!(f32);
+primitive!(f64);
+primitive!(half::bf16);
+primitive!(half::f16);
+
+pub struct BufferOffset<'a> {
+ pub buffer: &'a Buffer,
+ pub offset_in_bytes: usize,
+}
+
+impl<'a> BufferOffset<'a> {
+ pub fn zero_offset(buffer: &'a Buffer) -> Self {
+ Self {
+ buffer,
+ offset_in_bytes: 0,
+ }
+ }
+}
+
+impl<T> EncoderParam for &[T] {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_bytes_directly(position, core::mem::size_of_val(data), data.as_ptr().cast());
+ }
+}
+
+impl EncoderParam for &Buffer {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_input_buffer(position, Some(data), 0);
+ }
+}
+
+impl EncoderParam for (&Buffer, usize) {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_input_buffer(position, Some(data.0), data.1);
+ }
+}
+
+impl EncoderParam for &BufferOffset<'_> {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_input_buffer(position, Some(data.buffer), data.offset_in_bytes);
+ }
+}
+
+impl EncoderParam for &mut Buffer {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_output_buffer(position, Some(data), 0);
+ }
+}
+
+impl EncoderParam for (&mut Buffer, usize) {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_output_buffer(position, Some(data.0), data.1);
+ }
+}
+
+impl EncoderParam for () {
+ fn set_param(_: &ComputeCommandEncoder, _: usize, _: Self) {}
+}
+
+/// Marks a buffer as a read input in `set_params!` calls, enabling hazard tracking.
+///
+/// # Examples
+/// ```ignore
+/// set_params!(encoder, (length, Input::new(input), output));
+/// ```
+#[derive(Copy, Clone)]
+pub struct Input<'a> {
+ buffer: &'a Buffer,
+ offset: usize,
+}
+
+impl<'a> Input<'a> {
+ #[inline]
+ pub fn new(buffer: &'a Buffer) -> Self {
+ Self { buffer, offset: 0 }
+ }
+
+ #[inline]
+ pub fn with_offset(buffer: &'a Buffer, offset: usize) -> Self {
+ Self { buffer, offset }
+ }
+
+ #[inline]
+ pub fn from_buffer_offset(bo: &'a BufferOffset<'a>) -> Self {
+ Self {
+ buffer: bo.buffer,
+ offset: bo.offset_in_bytes,
+ }
+ }
+}
+
+impl<'a> EncoderParam for Input<'a> {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_input_buffer(position, Some(data.buffer), data.offset);
+ }
+}
+
+/// Marks a buffer as a write output in `set_params!` calls, enabling hazard tracking.
+///
+/// Use this wrapper wherever a kernel writes to a buffer so the encoder can detect
+/// read-after-write (RAW) hazards and insert barriers before concurrent dispatches.
+///
+/// # Examples
+/// ```ignore
+/// set_params!(encoder, (length, &input, Output::new(output)));
+/// set_params!(encoder, (k, m, n, Output::from_buffer_offset(dst_bo)));
+/// set_params!(encoder, (n, Output::with_offset(dst, dst_offset)));
+/// ```
+#[derive(Copy, Clone)]
+pub struct Output<'a> {
+ buffer: &'a Buffer,
+ offset: usize,
+}
+
+impl<'a> Output<'a> {
+ #[inline]
+ pub fn new(buffer: &'a Buffer) -> Self {
+ Self { buffer, offset: 0 }
+ }
+
+ #[inline]
+ pub fn with_offset(buffer: &'a Buffer, offset: usize) -> Self {
+ Self { buffer, offset }
+ }
+
+ #[inline]
+ pub fn from_buffer_offset(bo: &'a BufferOffset<'a>) -> Self {
+ Self {
+ buffer: bo.buffer,
+ offset: bo.offset_in_bytes,
+ }
+ }
+}
+
+impl<'a> EncoderParam for Output<'a> {
+ fn set_param(encoder: &ComputeCommandEncoder, position: usize, data: Self) {
+ encoder.set_output_buffer(position, Some(data.buffer), data.offset);
+ }
+}
+
+#[macro_export]
+macro_rules! set_params {
+ ($encoder:ident, ($($param:expr),+)) => (
+ let mut _index = 0;
+ $(
+ $crate::utils::set_param($encoder, _index, $param);
+ _index += 1;
+ )*
+ );
+}
+
+/// Scope a Metal debug group around the current dispatch, e.g.
+/// `debug_group!(encoder, "kernel {a}")`. The guard binds into the caller's
+/// block (like `set_params!`), so the group pops after the dispatch. Gated at
+/// the macro definition: off-feature it expands to nothing.
+#[cfg(feature = "debug-labels")]
+#[macro_export]
+macro_rules! debug_group {
+ ($enc:expr, $($arg:tt)+) => {
+ let _debug_group_guard = $enc.debug_group(&::std::format!($($arg)+));
+ };
+}
+
+#[cfg(not(feature = "debug-labels"))]
+#[macro_export]
+macro_rules! debug_group {
+ ($enc:expr, $($arg:tt)+) => {};
+}
+
+/// Apply a persistent `MTLBuffer`/queue debug label, e.g.
+/// `metal_label!(buffer, "name")`. Gated like [`debug_group!`].
+#[cfg(feature = "debug-labels")]
+#[macro_export]
+macro_rules! metal_label {
+ ($obj:expr, $($arg:tt)+) => {
+ $obj.set_label(&::std::format!($($arg)+));
+ };
+}
+
+#[cfg(not(feature = "debug-labels"))]
+#[macro_export]
+macro_rules! metal_label {
+ ($obj:expr, $($arg:tt)+) => {};
+}
+
+pub trait EncoderProvider {
+ type Encoder<'a>: AsRef<ComputeCommandEncoder>
+ where
+ Self: 'a;
+
+ fn encoder(&self) -> Self::Encoder<'_>;
+}
+
+impl EncoderProvider for &ComputeCommandEncoder {
+ type Encoder<'a>
+ = WrappedEncoder<'a>
+ where
+ Self: 'a;
+ fn encoder(&self) -> Self::Encoder<'_> {
+ WrappedEncoder {
+ inner: self,
+ end_encoding_on_drop: false,
+ }
+ }
+}
+
+impl EncoderProvider for &CommandsGuard<'_> {
+ type Encoder<'a>
+ = &'a CommandsGuard<'a>
+ where
+ Self: 'a;
+ fn encoder(&self) -> Self::Encoder<'_> {
+ self
+ }
+}
+
+pub enum RwLockGuard<'a, T> {
+ Read(RwLockReadGuard<'a, T>),
+ Write(RwLockWriteGuard<'a, T>),
+}
+
+impl<'a, T> Deref for RwLockGuard<'a, T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ match self {
+ RwLockGuard::Read(g) => g.deref(),
+ RwLockGuard::Write(g) => g.deref(),
+ }
+ }
+}
+
+impl<'a, T> From<RwLockReadGuard<'a, T>> for RwLockGuard<'a, T> {
+ fn from(g: RwLockReadGuard<'a, T>) -> Self {
+ RwLockGuard::Read(g)
+ }
+}
+
+impl<'a, T> From<RwLockWriteGuard<'a, T>> for RwLockGuard<'a, T> {
+ fn from(g: RwLockWriteGuard<'a, T>) -> Self {
+ RwLockGuard::Write(g)
+ }
+}
+
+fn is_truthy(s: String) -> bool {
+ match s.as_str() {
+ "true" | "t" | "yes" | "y" | "1" => true,
+ _ => false,
+ }
+}
+
+pub(crate) fn get_env_bool<K: AsRef<OsStr>>(key: K, default: bool) -> bool {
+ std::env::var(key).map(is_truthy).unwrap_or(default)
+}