Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add Inkling 2 model
Text and image input, with Metal kernels for the prefill attention and the attention residuals. The published checkpoint loads as is, and tensor and pipeline parallel work.
  • Loading branch information
jundot committed Nov 13, 2026
commit 25c8b4322c5dad4bca0887a6d878d0ffa2655928
4 changes: 4 additions & 0 deletions mlx_lm/kernels/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,25 @@

"""Fused Metal kernels, one kernel per file."""

from .depth_attention import depth_attention
from .expert_routing import expert_routing
from .norm_add_norm import norm_add_norm, pre_norm
from .post_expert_norm_combine import post_expert_norm_combine
from .qk_norm import qk_norm
from .qk_norm_rope import qk_norm_rope
from .relative_attention import relative_attention
from .rms_norm_sigmoid_gate import rms_norm_sigmoid_gate
from .sparse_mla import sparse_mla_attention

__all__ = [
"depth_attention",
"expert_routing",
"norm_add_norm",
"post_expert_norm_combine",
"pre_norm",
"qk_norm",
"qk_norm_rope",
"relative_attention",
"rms_norm_sigmoid_gate",
"sparse_mla_attention",
]
107 changes: 107 additions & 0 deletions mlx_lm/kernels/depth_attention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Copyright © 2026 Apple Inc.

"""Attention of learned queries over the depth sources of each token, in one
kernel."""

import mlx.core as mx

from ._common import row_threads, scalar

_SOURCE = """
constexpr int N = K + 1;
uint row = threadgroup_position_in_grid.x;
uint rows = threadgroups_per_grid.x;
uint tid = thread_position_in_threadgroup.x;
uint lane = thread_index_in_simdgroup;
uint sg = simdgroup_index_in_threadgroup;

float acc[N * Q];
for (int i = 0; i < N * Q; i++) {
acc[i] = 0.0f;
}
for (int d = tid; d < D; d += TG) {
float x[N];
for (int i = 0; i < K; i++) {
x[i] = blocks[(size_t(i) * rows + row) * D + d];
}
x[K] = partial[size_t(row) * D + d];
for (int j = 0; j < Q; j++) {
float qv = queries[j * D + d];
for (int i = 0; i < N; i++) {
acc[i * Q + j] += x[i] * qv;
}
}
}

threadgroup float buf[N * Q][TG / 32];
for (int i = 0; i < N * Q; i++) {
float v = simd_sum(acc[i]);
if (lane == 0) {
buf[i][sg] = v;
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);

float w[N * Q];
for (int i = 0; i < N * Q; i++) {
float t = 0.0f;
for (int s = 0; s < TG / 32; s++) {
t += buf[i][s];
}
w[i] = t * scale;
}
for (int j = 0; j < Q; j++) {
float m = -INFINITY;
for (int i = 0; i < N; i++) {
m = max(m, w[i * Q + j]);
}
float z = 0.0f;
for (int i = 0; i < N; i++) {
w[i * Q + j] = metal::exp(w[i * Q + j] - m);
z += w[i * Q + j];
}
for (int i = 0; i < N; i++) {
w[i * Q + j] /= z;
}
}

for (int d = tid; d < D; d += TG) {
float x[N];
for (int i = 0; i < K; i++) {
x[i] = blocks[(size_t(i) * rows + row) * D + d];
}
x[K] = partial[size_t(row) * D + d];
for (int j = 0; j < Q; j++) {
float o = 0.0f;
for (int i = 0; i < N; i++) {
o += w[i * Q + j] * x[i];
}
out[(size_t(row) * Q + j) * D + d] = o;
}
}
"""

_kernel = mx.fast.metal_kernel(
name="depth_attention",
input_names=["blocks", "partial", "queries", "scale"],
output_names=["out"],
source=_SOURCE,
)


def depth_attention(
blocks: mx.array, partial: mx.array, queries: mx.array, *, scale: float
) -> mx.array:
"""blocks: (K, ..., D) and partial: (..., D), float32, also the values.
queries: float32 (Q, D). Returns (..., Q, D)."""
D = partial.shape[-1]
Q = queries.shape[0]
TG = row_threads(D)
return _kernel(
inputs=[blocks, partial, queries, scalar(scale)],
template=[("K", blocks.shape[0]), ("D", D), ("Q", Q), ("TG", TG)],
grid=(partial.size // D * TG, 1, 1),
threadgroup=(TG, 1, 1),
output_shapes=[partial.shape[:-1] + (Q, D)],
output_dtypes=[mx.float32],
)[0]
214 changes: 214 additions & 0 deletions mlx_lm/kernels/relative_attention.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
# Copyright © 2026 Apple Inc.

"""Causal flash attention with a relative position bias and a sink logit per
query."""

import mlx.core as mx

from ._common import scalar

# Queries per threadgroup, 8 for each of its 4 simdgroups.
_BQ = 32
_TG = 128

# The online softmax of each row starts from its sink logit, so the zero-value
# sink needs no key.
_SOURCE = """
constexpr float LOG2E = 1.4426950408889634f;
constexpr int BK = 16;
constexpr int LDK = BK + 8;
constexpr int LDV = D + 8;
const int L = sizes[0];
const int S = sizes[1];
const uint tid = thread_position_in_threadgroup.x;
const uint sg = simdgroup_index_in_threadgroup;
const uint lane = thread_index_in_simdgroup;
const int batch = threadgroup_position_in_grid.z;
const int head = threadgroup_position_in_grid.y;
const int kv_head = head / (HQ / HKV);
const int q0 = threadgroup_position_in_grid.x * BQ;
const int start = key_start[batch];
const float qscale = scale * LOG2E;

// The lane holds row fm and columns fn, fn + 1 of each 8x8 fragment.
const short fm = ((lane / 4) & 4) + (lane / 2) % 4;
const short fn = ((lane / 4) & 2) * 2 + (lane % 2) * 2;
const int row = q0 + int(sg) * 8 + fm;
const bool row_ok = row < L;
const int diag = S - L + row;

// q and k are clipped and v has unit RMS, so half holds them.
threadgroup half Ks[D * LDK];
threadgroup half Vs[BK * LDV];

simdgroup_half8x8 q_frag[D / 8];
for (int db = 0; db < D / 8; ++db) {
half2 qv = half2(0.0h);
if (row_ok) {
const device T* qp = q + batch * q_strides[0] + head * q_strides[1]
+ row * q_strides[2] + db * 8 + fn;
qv = half2(float(qp[0]), float(qp[1]));
}
q_frag[db].thread_elements()[0] = qv.x;
q_frag[db].thread_elements()[1] = qv.y;
}
simdgroup_float8x8 acc[D / 8];
for (int db = 0; db < D / 8; ++db) {
acc[db] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
}
float row_max = row_ok ? float(sinks[(batch * L + row) * HQ + head]) * LOG2E : 0.0f;
float row_sum = 1.0f;
const int bias_row = batch * L + (row_ok ? row : 0);
const device T* bias = rel + (size_t(bias_row) * HQ + head) * R;

const int first_diag = S - L + q0;
const int last_diag = S - L + min(q0 + BQ, L) - 1;
int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0;
first_key = max(first_key, start);
const device T* k_head = k + batch * k_strides[0] + kv_head * k_strides[1];
const device T* v_head = v + batch * v_strides[0] + kv_head * v_strides[1];

for (int k0 = first_key / BK * BK; k0 <= last_diag; k0 += BK) {
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int c = tid; c < BK * D / 8; c += TG) {
const int r = c / (D / 8);
const int col = (c % (D / 8)) * 8;
const int key = k0 + r;
vec<T, 4> kv[2] = {vec<T, 4>(0), vec<T, 4>(0)};
vec<T, 4> vv[2] = {vec<T, 4>(0), vec<T, 4>(0)};
if (key < S) {
auto kp = (const device vec<T, 4>*)(k_head + key * k_strides[2] + col);
auto vp = (const device vec<T, 4>*)(v_head + key * v_strides[2] + col);
kv[0] = kp[0];
kv[1] = kp[1];
vv[0] = vp[0];
vv[1] = vp[1];
}
for (int j = 0; j < 8; ++j) {
Ks[(col + j) * LDK + r] = half(float(kv[j / 4][j % 4]));
Vs[r * LDV + col + j] = half(float(vv[j / 4][j % 4]));
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (q0 + int(sg) * 8 >= L) {
continue;
}

simdgroup_float8x8 scores[BK / 8];
for (int kb = 0; kb < BK / 8; ++kb) {
scores[kb] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
for (int db = 0; db < D / 8; ++db) {
simdgroup_half8x8 k_frag;
simdgroup_load(k_frag, Ks + db * 8 * LDK + kb * 8, LDK);
simdgroup_multiply_accumulate(scores[kb], q_frag[db], k_frag, scores[kb]);
}
}

float tile_max = -INFINITY;
for (int kb = 0; kb < BK / 8; ++kb) {
for (int e = 0; e < 2; ++e) {
const int key = k0 + kb * 8 + fn + e;
const int d = diag - key;
const bool visible = row_ok && d >= 0 && key >= start
&& (WINDOW == 0 || d < WINDOW);
float s = -INFINITY;
if (visible) {
s = scores[kb].thread_elements()[e] * qscale;
if (d < R) {
s += float(bias[d]) * LOG2E;
}
}
scores[kb].thread_elements()[e] = s;
tile_max = max(tile_max, s);
}
}
// The 4 lanes of a row are lane ^ 1 and lane ^ 8 apart.
tile_max = max(tile_max, simd_shuffle_xor(tile_max, 1));
tile_max = max(tile_max, simd_shuffle_xor(tile_max, 8));
const float new_max = max(row_max, tile_max);
const float factor = fast::exp2(row_max - new_max);
float tile_sum = 0.0f;
simdgroup_half8x8 probs[BK / 8];
for (int kb = 0; kb < BK / 8; ++kb) {
for (int e = 0; e < 2; ++e) {
const float p = fast::exp2(scores[kb].thread_elements()[e] - new_max);
probs[kb].thread_elements()[e] = half(p);
tile_sum += p;
}
}
tile_sum += simd_shuffle_xor(tile_sum, 1);
tile_sum += simd_shuffle_xor(tile_sum, 8);
row_sum = row_sum * factor + tile_sum;
row_max = new_max;
for (int db = 0; db < D / 8; ++db) {
acc[db].thread_elements()[0] *= factor;
acc[db].thread_elements()[1] *= factor;
for (int kb = 0; kb < BK / 8; ++kb) {
simdgroup_half8x8 v_frag;
simdgroup_load(v_frag, Vs + kb * 8 * LDV + db * 8, LDV);
simdgroup_multiply_accumulate(acc[db], probs[kb], v_frag, acc[db]);
}
}
}

if (row_ok) {
device T* op = out + (size_t(batch * L + row) * HQ + head) * D;
for (int db = 0; db < D / 8; ++db) {
op[db * 8 + fn] = T(acc[db].thread_elements()[0] / row_sum);
op[db * 8 + fn + 1] = T(acc[db].thread_elements()[1] / row_sum);
}
}
"""

_kernel = mx.fast.metal_kernel(
name="relative_attention",
input_names=["q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale"],
output_names=["out"],
source=_SOURCE,
ensure_row_contiguous=False,
)


def relative_attention(
q: mx.array,
k: mx.array,
v: mx.array,
rel: mx.array,
sinks: mx.array,
*,
scale: float,
window: int,
key_start: mx.array,
) -> mx.array:
"""q: (B, Hq, L, D), k and v: (B, Hkv, S, D), all bfloat16, with the queries
at the last L keys. rel: (B, L, Hq, R), the bias at distances below R.
sinks: (B, L, Hq). key_start: (B,), the first key of each row. Returns
(B, L, Hq, D)."""
B, Hq, L, D = q.shape
Hkv, S = k.shape[1], k.shape[2]
return _kernel(
inputs=[
q,
k,
v,
mx.contiguous(rel),
mx.contiguous(sinks.astype(mx.float32)),
mx.contiguous(key_start.astype(mx.int32)),
mx.array([L, S], dtype=mx.int32),
scalar(scale),
],
template=[
("T", q.dtype),
("D", D),
("HQ", Hq),
("HKV", Hkv),
("R", rel.shape[-1]),
("WINDOW", window),
("BQ", _BQ),
("TG", _TG),
],
grid=((L + _BQ - 1) // _BQ * _TG, Hq, B),
threadgroup=(_TG, 1, 1),
output_shapes=[(B, L, Hq, D)],
output_dtypes=[q.dtype],
)[0]
Loading