amarck's picture
Add files using upload-large-folder tool
e9a2b5d verified
Raw History Blame Contribute Delete
2.36 kB
"""Fused Metal kernels for the DiT attention prologue.
qk_norm_rope: per-head RMSNorm (fp32 statistics) -> bf16 weight multiply ->
interleaved-pair RoPE in fp32 -> bf16, writing [B, H, L, D] directly from the
[B, L, H, D] projection output. One read + one write instead of ~8 passes.
Rounding points mirror upstream exactly:
diffusers RMSNorm: (x.float() * rsqrt(mean(x^2)+eps)).to(bf16) * weight(bf16)
apply_rotary_emb: complex multiply in fp32, .type_as(bf16)
"""
from __future__ import annotations
import mlx.core as mx
_SRC = """
uint gid = thread_position_in_grid.x;
uint j = thread_position_in_threadgroup.x; // pair index 0..63
uint row = gid / 64; // row in [B, L, H]
uint h = row % H;
uint l = (row / H) % L;
uint b = row / (H * L);
float x0 = static_cast<float>(x[row * 128 + 2 * j]);
float x1 = static_cast<float>(x[row * 128 + 2 * j + 1]);
float ss = simd_sum(x0 * x0 + x1 * x1);
threadgroup float part[2];
if (thread_index_in_simdgroup == 0) { part[simdgroup_index_in_threadgroup] = ss; }
threadgroup_barrier(mem_flags::mem_threadgroup);
float r = metal::rsqrt((part[0] + part[1]) / 128.0f + eps[0]);
bfloat16_t n0 = static_cast<bfloat16_t>(x0 * r) * w[2 * j];
bfloat16_t n1 = static_cast<bfloat16_t>(x1 * r) * w[2 * j + 1];
float y0 = static_cast<float>(n0), y1 = static_cast<float>(n1);
float c = cosv[l * 64 + j], s = sinv[l * 64 + j];
uint o = ((b * H + h) * L + l) * 128 + 2 * j;
out[o] = static_cast<bfloat16_t>(y0 * c - y1 * s);
out[o + 1] = static_cast<bfloat16_t>(y0 * s + y1 * c);
"""
_kernel = mx.fast.metal_kernel(
name="ming_qk_norm_rope",
input_names=["x", "w", "cosv", "sinv", "eps"],
output_names=["out"],
source=_SRC,
)
def supported(x, weight):
return x.dtype == mx.bfloat16 and weight.dtype == mx.bfloat16 and x.shape[-1] == 128
def qk_norm_rope(x, weight, cos, sin, eps):
"""x: [B, L, H, 128] bf16; weight: [128] bf16; cos/sin: [L, 64] fp32 -> [B, H, L, 128] bf16."""
B, L, H, D = x.shape
return _kernel(
inputs=[x, weight, cos, sin, mx.array([eps], mx.float32)],
template=[("H", H), ("L", L)],
grid=(B * L * H * 64, 1, 1),
threadgroup=(64, 1, 1),
output_shapes=[(B, H, L, D)],
output_dtypes=[mx.bfloat16],
)[0]