Instructions to use mlx-community/FastFrames-S-bf16-mlx with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use mlx-community/FastFrames-S-bf16-mlx with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download mlx-community/FastFrames-S-bf16-mlx --local-dir FastFrames-S-bf16-mlx
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Download ff_kernels.py from mlx-community/FastFrames-S-bf16-mlx: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/mlx-community/FastFrames-S-bf16-mlx/resolve/main/ff_kernels.py
- Command line
-
hf download hf://mlx-community/FastFrames-S-bf16-mlx/ff_kernels.py
-
curl -L -o ff_kernels.py https://huggingface.co/mlx-community/FastFrames-S-bf16-mlx/resolve/main/ff_kernels.py
17.9 kB
| """Custom Metal kernels for FastFrames-S (mx.fast.metal_kernel). | |
| flash_attn: self-attention of one frame's 1560 queries against the token-major KV cache | |
| [T_max, H*D] (only the first L rows are read), output token-major [N, H*D]. fp32 maths | |
| throughout (scores, online softmax, P@V) like MLX's own SDPA; bf16 in and out. | |
| """ | |
| from __future__ import annotations | |
| import mlx.core as mx | |
| HEADS, HD = 12, 128 | |
| _SRC = r""" | |
| constexpr int D = 128; | |
| constexpr int H = HEADS_; | |
| constexpr int BK = BK_; | |
| constexpr int RB = RB_; | |
| constexpr int NSG = NSG_; | |
| constexpr int LD = D + PAD_; | |
| threadgroup float Ks[BK * LD]; | |
| threadgroup float Vs[BK * LD]; | |
| const int N = int(nq[0]); | |
| const int L = int(nk[0]); | |
| const uint sg = simdgroup_index_in_threadgroup; | |
| const uint lane = thread_index_in_simdgroup; | |
| const uint tid = thread_index_in_threadgroup; | |
| const int h = int(threadgroup_position_in_grid.y); | |
| const int qbase = int(threadgroup_position_in_grid.x) * (NSG * RB * 8) + int(sg) * RB * 8; | |
| const float scale = SCALE_ * 1.4426950408889634f; | |
| const short qid = lane / 4; | |
| const short fm = (qid & 4) + ((lane / 2) % 4); | |
| const short fn = (qid & 2) * 2 + (lane % 2) * 2; | |
| simdgroup_float8x8 qf[RB][D / 8]; | |
| simdgroup_float8x8 of[RB][D / 8]; | |
| float m[RB], l[RB]; | |
| for (int rb = 0; rb < RB; rb++) { | |
| int row = min(qbase + rb * 8 + fm, N - 1); | |
| const device bfloat16_t* qp = q + (size_t(row) * H + h) * D + fn; | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = qf[rb][d].thread_elements(); | |
| e[0] = float(qp[d * 8]) * scale; | |
| e[1] = float(qp[d * 8 + 1]) * scale; | |
| of[rb][d] = make_filled_simdgroup_matrix<float, 8, 8>(0.f); | |
| } | |
| m[rb] = -INFINITY; | |
| l[rb] = 0.f; | |
| } | |
| for (int k0 = 0; k0 < L; k0 += BK) { | |
| threadgroup_barrier(mem_flags::mem_threadgroup); | |
| for (int i = int(tid); i < BK * D / 4; i += NSG * 32) { | |
| int r = (i * 4) / D, c = (i * 4) % D; | |
| size_t off = (size_t(k0 + r) * H + h) * D + c; | |
| for (int u = 0; u < 4; u++) { | |
| Ks[r * LD + c + u] = float(k[off + u]); | |
| Vs[r * LD + c + u] = float(v[off + u]); | |
| } | |
| } | |
| threadgroup_barrier(mem_flags::mem_threadgroup); | |
| simdgroup_float8x8 s[RB][BK / 8]; | |
| for (int rb = 0; rb < RB; rb++) | |
| for (int j = 0; j < BK / 8; j++) | |
| s[rb][j] = make_filled_simdgroup_matrix<float, 8, 8>(0.f); | |
| for (int d = 0; d < D / 8; d++) { | |
| for (int j = 0; j < BK / 8; j++) { | |
| simdgroup_float8x8 kf; | |
| simdgroup_load(kf, Ks + j * 8 * LD + d * 8, LD, ulong2(0, 0), true); | |
| for (int rb = 0; rb < RB; rb++) | |
| simdgroup_multiply_accumulate(s[rb][j], qf[rb][d], kf, s[rb][j]); | |
| } | |
| } | |
| for (int rb = 0; rb < RB; rb++) { | |
| float mx_ = m[rb]; | |
| for (int j = 0; j < BK / 8; j++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| mx_ = max(mx_, max(e[0], e[1])); | |
| } | |
| mx_ = max(mx_, simd_shuffle_xor(mx_, ushort(1))); | |
| mx_ = max(mx_, simd_shuffle_xor(mx_, ushort(8))); | |
| float alpha = fast::exp2(m[rb] - mx_); | |
| m[rb] = mx_; | |
| float rs = 0.f; | |
| for (int j = 0; j < BK / 8; j++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| e[0] = fast::exp2(e[0] - mx_); | |
| e[1] = fast::exp2(e[1] - mx_); | |
| rs += e[0] + e[1]; | |
| } | |
| rs += simd_shuffle_xor(rs, ushort(1)); | |
| rs += simd_shuffle_xor(rs, ushort(8)); | |
| l[rb] = l[rb] * alpha + rs; | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = of[rb][d].thread_elements(); | |
| e[0] *= alpha; | |
| e[1] *= alpha; | |
| } | |
| } | |
| for (int j = 0; j < BK / 8; j++) { | |
| for (int d = 0; d < D / 8; d++) { | |
| simdgroup_float8x8 vf; | |
| simdgroup_load(vf, Vs + j * 8 * LD + d * 8, LD); | |
| for (int rb = 0; rb < RB; rb++) | |
| simdgroup_multiply_accumulate(of[rb][d], s[rb][j], vf, of[rb][d]); | |
| } | |
| } | |
| } | |
| for (int rb = 0; rb < RB; rb++) { | |
| int row = qbase + rb * 8 + fm; | |
| if (row >= N) continue; | |
| float inv = 1.f / l[rb]; | |
| device bfloat16_t* op = out + (size_t(row) * H + h) * D + fn; | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = of[rb][d].thread_elements(); | |
| op[d * 8] = bfloat16_t(e[0] * inv); | |
| op[d * 8 + 1] = bfloat16_t(e[1] * inv); | |
| } | |
| } | |
| """ | |
| _DW_SRC = r""" | |
| // causal depthwise 3x3x3 conv, channels-last x [T, H, W, C]; time padded (2, 0), space (1, 1) | |
| const int C = int(x_shape[3]), Wd = int(x_shape[2]), Hh = int(x_shape[1]), T = int(x_shape[0]); | |
| const uint gid = thread_position_in_grid.x; | |
| const int c = int(gid % uint(C)); | |
| uint r = gid / uint(C); | |
| const int w = int(r % uint(Wd)); r /= uint(Wd); | |
| const int hh = int(r % uint(Hh)); | |
| const int t = int(r / uint(Hh)); | |
| if (t >= T) return; | |
| float acc = 0.f; | |
| for (int kt = 0; kt < 3; kt++) { | |
| int tt = t + kt - 2; | |
| for (int kh = 0; kh < 3; kh++) { | |
| int y = hh + kh - 1; | |
| for (int kw = 0; kw < 3; kw++) { | |
| int xx = w + kw - 1; | |
| float xv = (tt >= 0 && y >= 0 && y < Hh && xx >= 0 && xx < Wd) | |
| ? float(x[((size_t(tt) * Hh + y) * Wd + xx) * C + c]) : 0.f; | |
| float p = xv * float(wt[c * 27 + kt * 9 + kh * 3 + kw]); | |
| acc = acc + p; | |
| } | |
| } | |
| } | |
| out[gid] = acc + float(bias[c]); | |
| """ | |
| _dw = None | |
| def depthwise3(x, w, b): | |
| """x [T, H, W, C] fp32, w [C, 1, 3, 3, 3], b [C] -> same as PixelDecoder's shifted-add loop.""" | |
| global _dw | |
| if _dw is None: | |
| _dw = mx.fast.metal_kernel(name="ff_dw333", input_names=["x", "wt", "bias"], output_names=["out"], | |
| source=_DW_SRC) | |
| n = x.size | |
| return _dw(inputs=[x, w, b], output_shapes=[x.shape], output_dtypes=[x.dtype], | |
| grid=(n, 1, 1), threadgroup=(256, 1, 1))[0] | |
| _cache = {} | |
| def _kernel(bk, rb, nsg, pad): | |
| key = (bk, rb, nsg, pad) | |
| if key not in _cache: | |
| src = (_SRC.replace("HEADS_", str(HEADS)).replace("BK_", str(bk)).replace("RB_", str(rb)) | |
| .replace("NSG_", str(nsg)).replace("PAD_", str(pad)) | |
| .replace("SCALE_", repr(float(HD ** -0.5)) + "f")) | |
| _cache[key] = mx.fast.metal_kernel( | |
| name=f"ff_flash_bk{bk}_rb{rb}_sg{nsg}_p{pad}", input_names=["q", "k", "v", "nq", "nk"], | |
| output_names=["out"], source=src, header="#include <metal_simdgroup_matrix>\n") | |
| return _cache[key] | |
| def flash_attn(q, kc, vc, L, bk=24, rb=1, nsg=4, pad=4): | |
| """q [N, H*D] bf16 (token-major); kc, vc [T_max, H*D]; attends to rows [0, L). -> [N, H*D].""" | |
| N = q.shape[0] | |
| assert L % bk == 0, (L, bk) | |
| bq = nsg * rb * 8 | |
| k = _kernel(bk, rb, nsg, pad) | |
| return k(inputs=[q, kc, vc, mx.array([N], dtype=mx.int32), mx.array([L], dtype=mx.int32)], | |
| output_shapes=[(N, HEADS * HD)], output_dtypes=[q.dtype], | |
| grid=(((N + bq - 1) // bq) * nsg * 32, HEADS, 1), threadgroup=(nsg * 32, 1, 1))[0] | |
| # ---------------------------------------------------------------------------- flash attention v2 | |
| # Self-attention of one frame's queries against the head-major KV cache [1, H, T_max, D] (rows | |
| # [0, L) are read; there is no mask: the frame sees all earlier frames and itself). q [1, H, N, D], | |
| # out [1, H, N, D] (or token-major [1, N, H, D] with tok=1). Q stays in registers as bf16 | |
| # fragments; K and V tiles of BK rows are staged in threadgroup memory as bf16 with 16-byte loads; | |
| # QK^T is a bf16 x bf16 -> fp32 simdgroup MMA (products exact in fp32, as MLX's fp32 MMA on | |
| # upcast inputs); scores, the online softmax and the O accumulator are fp32. PV=float keeps P in | |
| # fp32 (V upcast to fp32 fragments, like MLX); PV=bf16 rounds P to bf16 for a mixed MMA. | |
| _SRC2 = r""" | |
| constexpr int D = 128; | |
| constexpr int BK = BK_; | |
| constexpr int RB = RB_; | |
| constexpr int NSG = NSG_; | |
| constexpr int LD = D + PAD_; | |
| constexpr int NT = NSG * 32; | |
| threadgroup bfloat16_t Ks[BK * LD]; | |
| threadgroup bfloat16_t Vs[BK * LD]; | |
| const int N = int(q_shape[2]); | |
| const int L = int(nk[0]); | |
| const int TM = int(k_shape[2]); | |
| const uint sg = simdgroup_index_in_threadgroup; | |
| const uint lane = thread_index_in_simdgroup; | |
| const uint tid = thread_index_in_threadgroup; | |
| const int h = int(threadgroup_position_in_grid.y); | |
| const int qbase = int(threadgroup_position_in_grid.x) * (NSG * RB * 8) + int(sg) * RB * 8; | |
| const float scale = SCALE_ * 1.4426950408889634f; | |
| const short qid = lane / 4; | |
| const short fm = (qid & 4) + ((lane / 2) % 4); | |
| const short fn = (qid & 2) * 2 + (lane % 2) * 2; | |
| const device bfloat16_t* kh = k + size_t(h) * TM * D; | |
| const device bfloat16_t* vh = v + size_t(h) * TM * D; | |
| simdgroup_bfloat8x8 qf[RB][D / 8]; | |
| simdgroup_float8x8 of[RB][D / 8]; | |
| float m[RB], l[RB]; | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) { | |
| int row = min(qbase + rb * 8 + fm, N - 1); | |
| const device bfloat16_t* qp = q + (size_t(h) * N + row) * D + fn; | |
| _Pragma("clang loop unroll(full)") | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = qf[rb][d].thread_elements(); | |
| e[0] = qp[d * 8]; | |
| e[1] = qp[d * 8 + 1]; | |
| of[rb][d] = make_filled_simdgroup_matrix<float, 8, 8>(0.f); | |
| } | |
| m[rb] = -INFINITY; | |
| l[rb] = 0.f; | |
| } | |
| constexpr int NL = (BK * (D / 8) + NT - 1) / NT; // 16-byte chunks per thread per matrix | |
| uint4 pk[NL], pv[NL]; | |
| auto fetch = [&](int k0) { | |
| _Pragma("clang loop unroll(full)") | |
| for (int u = 0; u < NL; u++) { | |
| int i = int(tid) + u * NT; | |
| int r = i / (D / 8), c = (i % (D / 8)) * 8; | |
| bool ok = (i < BK * (D / 8)) && (k0 + r < L); | |
| pk[u] = ok ? *(const device uint4*)(kh + size_t(k0 + r) * D + c) : uint4(0); | |
| pv[u] = ok ? *(const device uint4*)(vh + size_t(k0 + r) * D + c) : uint4(0); | |
| } | |
| }; | |
| #if PF_ | |
| fetch(0); | |
| #endif | |
| for (int k0 = 0; k0 < L; k0 += BK) { | |
| const bool tail = k0 + BK > L; | |
| #if !PF_ | |
| fetch(k0); | |
| #endif | |
| threadgroup_barrier(mem_flags::mem_threadgroup); | |
| _Pragma("clang loop unroll(full)") | |
| for (int u = 0; u < NL; u++) { | |
| int i = int(tid) + u * NT; | |
| int r = i / (D / 8), c = (i % (D / 8)) * 8; | |
| if (i < BK * (D / 8)) { | |
| *(threadgroup uint4*)(Ks + r * LD + c) = pk[u]; | |
| *(threadgroup uint4*)(Vs + r * LD + c) = pv[u]; | |
| } | |
| } | |
| threadgroup_barrier(mem_flags::mem_threadgroup); | |
| #if PF_ | |
| if (k0 + BK < L) fetch(k0 + BK); | |
| #endif | |
| simdgroup_float8x8 s[RB][BK / 8]; | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) | |
| s[rb][j] = make_filled_simdgroup_matrix<float, 8, 8>(0.f); | |
| _Pragma("clang loop unroll(full)") | |
| for (int d = 0; d < D / 8; d++) { | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) { | |
| simdgroup_bfloat8x8 kf; | |
| simdgroup_load(kf, Ks + j * 8 * LD + d * 8, LD, ulong2(0, 0), true); | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) | |
| simdgroup_multiply_accumulate(s[rb][j], qf[rb][d], kf, s[rb][j]); | |
| } | |
| } | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) { | |
| float mx_ = m[rb]; | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| e[0] *= scale; | |
| e[1] *= scale; | |
| if (tail) { | |
| int col = k0 + j * 8 + fn; | |
| if (col >= L) e[0] = -INFINITY; | |
| if (col + 1 >= L) e[1] = -INFINITY; | |
| } | |
| mx_ = max(mx_, max(e[0], e[1])); | |
| } | |
| mx_ = max(mx_, simd_shuffle_xor(mx_, ushort(1))); | |
| mx_ = max(mx_, simd_shuffle_xor(mx_, ushort(8))); | |
| #if LAZY_ | |
| // keep the old max unless it grew by more than 2^8 (p stays below 256, exact in fp32 maths) | |
| bool upd = simd_any(mx_ > m[rb] + 8.f); | |
| float alpha = 1.f; | |
| if (upd) { alpha = fast::exp2(m[rb] - mx_); m[rb] = mx_; } else { mx_ = m[rb]; } | |
| #else | |
| float alpha = fast::exp2(m[rb] - mx_); | |
| m[rb] = mx_; | |
| #endif | |
| float rs = 0.f; | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| e[0] = fast::exp2(e[0] - mx_); | |
| e[1] = fast::exp2(e[1] - mx_); | |
| rs += e[0] + e[1]; | |
| } | |
| rs += simd_shuffle_xor(rs, ushort(1)); | |
| rs += simd_shuffle_xor(rs, ushort(8)); | |
| l[rb] = l[rb] * alpha + rs; | |
| #if LAZY_ | |
| if (upd) | |
| #endif | |
| _Pragma("clang loop unroll(full)") | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = of[rb][d].thread_elements(); | |
| e[0] *= alpha; | |
| e[1] *= alpha; | |
| } | |
| } | |
| #if PVBF16_ | |
| simdgroup_bfloat8x8 pf[RB][BK / 8]; | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| thread auto& p = pf[rb][j].thread_elements(); | |
| p[0] = bfloat16_t(e[0]); | |
| p[1] = bfloat16_t(e[1]); | |
| } | |
| #endif | |
| _Pragma("clang loop unroll(full)") | |
| for (int j = 0; j < BK / 8; j++) { | |
| #if SKIP_ | |
| // skip P@V for an 8-key block whose probabilities (relative to the running max, which is | |
| // <= the final max) are all below 2^-SKIP_ for every query row of this simdgroup | |
| { | |
| float pm = 0.f; | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) { | |
| thread auto& e = s[rb][j].thread_elements(); | |
| pm = max(pm, max(e[0], e[1])); | |
| } | |
| if (simd_all(pm < SKIPTHR_)) continue; | |
| } | |
| #endif | |
| _Pragma("clang loop unroll(full)") | |
| for (int d = 0; d < D / 8; d++) { | |
| simdgroup_bfloat8x8 vb; | |
| simdgroup_load(vb, Vs + j * 8 * LD + d * 8, LD); | |
| #if PVBF16_ | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) | |
| simdgroup_multiply_accumulate(of[rb][d], pf[rb][j], vb, of[rb][d]); | |
| #else | |
| simdgroup_float8x8 vf; | |
| thread auto& ve = vf.thread_elements(); | |
| thread auto& vbe = vb.thread_elements(); | |
| ve[0] = float(vbe[0]); | |
| ve[1] = float(vbe[1]); | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) | |
| simdgroup_multiply_accumulate(of[rb][d], s[rb][j], vf, of[rb][d]); | |
| #endif | |
| } | |
| } | |
| } | |
| _Pragma("clang loop unroll(full)") | |
| for (int rb = 0; rb < RB; rb++) { | |
| int row = qbase + rb * 8 + fm; | |
| if (row >= N) continue; | |
| float inv = 1.f / l[rb]; | |
| #if TOK_ | |
| device bfloat16_t* op = out + (size_t(row) * HEADS_ + h) * D + fn; | |
| #else | |
| device bfloat16_t* op = out + (size_t(h) * N + row) * D + fn; | |
| #endif | |
| _Pragma("clang loop unroll(full)") | |
| for (int d = 0; d < D / 8; d++) { | |
| thread auto& e = of[rb][d].thread_elements(); | |
| op[d * 8] = bfloat16_t(e[0] * inv); | |
| op[d * 8 + 1] = bfloat16_t(e[1] * inv); | |
| } | |
| } | |
| """ | |
| _cache2 = {} | |
| def _kernel2(bk, rb, nsg, pad, pvbf16, tok, pf=0, lazy=0, skip=0): | |
| key = (bk, rb, nsg, pad, pvbf16, tok, pf, lazy, skip) | |
| if key not in _cache2: | |
| src = (_SRC2.replace("HEADS_", str(HEADS)).replace("BK_", str(bk)).replace("RB_", str(rb)) | |
| .replace("NSG_", str(nsg)).replace("PAD_", str(pad)).replace("PVBF16_", str(int(pvbf16))) | |
| .replace("TOK_", str(int(tok))).replace("PF_", str(int(pf))).replace("LAZY_", str(int(lazy))).replace("SKIPTHR_", repr(2.0 ** -skip) + "f").replace("SKIP_", str(int(skip))) | |
| .replace("SCALE_", repr(float(HD ** -0.5)) + "f")) | |
| _cache2[key] = mx.fast.metal_kernel( | |
| name=f"ff_flash2_bk{bk}_rb{rb}_sg{nsg}_p{pad}_pv{int(pvbf16)}_t{int(tok)}_pf{int(pf)}_lz{int(lazy)}_sk{int(skip)}", | |
| input_names=["q", "k", "v", "nk"], output_names=["out"], source=src, | |
| header="#include <metal_simdgroup_matrix>\n") | |
| return _cache2[key] | |
| def flash2(q, kc, vc, L, bk=16, rb=1, nsg=4, pad=8, pvbf16=False, tok=False, pf=0, lazy=0, skip=0): | |
| """q [1, H, N, D] bf16; kc, vc [1, H, T_max, D] bf16 (rows [0, L) attended, no mask). | |
| -> [1, H, N, D] (tok=False) or [1, N, H, D] (tok=True), bf16.""" | |
| N = q.shape[2] | |
| bq = nsg * rb * 8 | |
| kern = _kernel2(bk, rb, nsg, pad, pvbf16, tok, pf, lazy, skip) | |
| shape = (1, N, HEADS, HD) if tok else (1, HEADS, N, HD) | |
| return kern(inputs=[q, kc, vc, mx.array([L], dtype=mx.int32)], output_shapes=[shape], | |
| output_dtypes=[q.dtype], grid=(((N + bq - 1) // bq) * nsg * 32, HEADS, 1), | |
| threadgroup=(nsg * 32, 1, 1))[0] | |