Download src/mps_kernels.py from Phsoft-ai/Notesoop-STT-Ko-v2: direct link, hf CLI and curl.
- Browser
- Download file 116 kB
-
https://huggingface.co/Phsoft-ai/Notesoop-STT-Ko-v2/resolve/main/src/mps_kernels.py
- Command line
-
hf download hf://Phsoft-ai/Notesoop-STT-Ko-v2/src/mps_kernels.py
-
curl -L -o mps_kernels.py https://huggingface.co/Phsoft-ai/Notesoop-STT-Ko-v2/resolve/main/src/mps_kernels.py
116 kB
"""
src/mps_kernels.py
Custom Apple Silicon Metal Compute Shaders (via torch.mps.compile_shader) for Step 3 Training:
1. 2D-Coalesced Conformer ConvModule Kernels (GLU + DepthwiseConv1d(k=15) + Shifted-Mean FP32 BN + SiLU)
2. Fused Conformer Sublayer Epilogues & Activations:
- Fused LayerNorm (BF16 I/O, FP32 mean/rstd)
- Fused Bias + Stateless Philox Dropout + Residual Scale + Residual Add + FP32 LayerNorm
- Fused Bias + GELU + Stateless Philox Dropout
- Coalesced Multi-Head Attention Split/Merge + Fused Scale/Mask/Online-FP32-Softmax/Philox-Dropout
- Zero-Allocation Flat-Buffer Linear Projection (in-place addmm_ into flat grad buffers)
3. Fused Reader Tail Kernel (Residual Scale + Mask + FP32-Accumulated L2 Normalization)
4. 100% GPU Fused CosineCTCHead + Online LogSumExp + Active-Target Gather + Custom Metal FP32 Log-CTC
+ Exact Active-Scatter Softmax Backward (0 CPU Roundtrip, 0 Per-Step Sync, Cached Spherical Bank)
5. Zero-Sync Contiguous Flat-Buffer Fused Metal GradNorm + In-Kernel Clipped AdamW (FP32 Master Weights)
"""
from __future__ import annotations
from collections import OrderedDict
import math
import random
from typing import Dict, Tuple, List, Optional, Any
import torch
import torch.nn as nn
import torch.nn.functional as F
_METAL_SHADER_SOURCE = r"""
#include <metal_stdlib>
using namespace metal;
// ============================================================================
// 0. Stateless Philox-2x32 RNG, Fast Math & Reduction Epilogues
// ============================================================================
inline float philox_keep_scale(uint seed_lo, uint seed_hi, uint idx, float drop_p, float inv_keep) {
if (drop_p <= 0.0f) return 1.0f;
uint ctr0 = idx;
uint ctr1 = seed_hi ^ 0x9E3779B9u;
uint key = seed_lo;
for (int r = 0; r < 4; ++r) {
uint hi = mulhi(0xD256D193u, ctr0);
uint lo = 0xD256D193u * ctr0;
ctr0 = hi ^ key ^ ctr1;
ctr1 = lo;
key += 0x9E3779B9u;
}
float u = float(ctr0 >> 8) * (1.0f / 16777216.0f);
return (u >= drop_p) ? inv_keep : 0.0f;
}
inline float erf_approx_fp32(float x) {
float sign = (x < 0.0f) ? -1.0f : 1.0f;
float ax = metal::min(metal::abs(x), 10.0f);
float t = 1.0f / (1.0f + 0.3275911f * ax);
float poly = (((((1.061405429f * t - 1.453152027f) * t) + 1.421413741f) * t - 0.284496736f) * t + 0.254829592f) * t;
return sign * (1.0f - poly * metal::exp(-ax * ax));
}
inline float log_add(float a, float b) {
if (a == -INFINITY) return b;
if (b == -INFINITY) return a;
float m = metal::max(a, b);
return m + metal::log(1.0f + metal::exp(-metal::abs(a - b)));
}
inline float log_add3(float a, float b, float c) {
float m = metal::max(a, metal::max(b, c));
if (m == -INFINITY) return -INFINITY;
return m + metal::log(
((a == -INFINITY) ? 0.0f : metal::exp(a - m)) +
((b == -INFINITY) ? 0.0f : metal::exp(b - m)) +
((c == -INFINITY) ? 0.0f : metal::exp(c - m))
);
}
kernel void accum_reset_fp32_to_bf16(
device float* src_fp32 [[buffer(0)]],
device bfloat* dst_bf16 [[buffer(1)]],
constant int& n [[buffer(2)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= n) return;
float v = src_fp32[gid];
src_fp32[gid] = 0.0f;
dst_bf16[gid] = bfloat(float(dst_bf16[gid]) + v);
}
kernel void copy_reset_fp32_to_bf16(
device float* src_fp32 [[buffer(0)]],
device bfloat* dst_bf16 [[buffer(1)]],
constant int& n [[buffer(2)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= n) return;
float v = src_fp32[gid];
src_fp32[gid] = 0.0f;
dst_bf16[gid] = bfloat(v);
}
kernel void accum_reset_two_bf16(
device float* src_fp32 [[buffer(0)]],
device bfloat* dst1_bf16 [[buffer(1)]],
device bfloat* dst2_bf16 [[buffer(2)]],
constant int& n1 [[buffer(3)]],
constant int& n2 [[buffer(4)]],
uint gid [[thread_position_in_grid]]
) {
int i = int(gid);
if (i >= n1 + n2) return;
float v = src_fp32[i];
src_fp32[i] = 0.0f;
if (i < n1) {
dst1_bf16[i] = bfloat(float(dst1_bf16[i]) + v);
} else {
int j = i - n1;
dst2_bf16[j] = bfloat(float(dst2_bf16[j]) + v);
}
}
kernel void accum_reset_two_fp32(
device float* src_fp32 [[buffer(0)]],
device float* dst1_fp32 [[buffer(1)]],
device float* dst2_fp32 [[buffer(2)]],
constant int& D [[buffer(3)]],
uint gid [[thread_position_in_grid]]
) {
int i = int(gid);
if (i >= 2 * D) return;
float v = src_fp32[i];
src_fp32[i] = 0.0f;
if (i < D) dst1_fp32[i] += v;
else dst2_fp32[i - D] += v;
}
kernel void copy_reset_two_fp32(
device float* src_fp32 [[buffer(0)]],
device float* dst1_fp32 [[buffer(1)]],
device float* dst2_fp32 [[buffer(2)]],
constant int& D [[buffer(3)]],
uint gid [[thread_position_in_grid]]
) {
int i = int(gid);
if (i >= 2 * D) return;
float v = src_fp32[i];
src_fp32[i] = 0.0f;
if (i < D) dst1_fp32[i] = v;
else dst2_fp32[i - D] = v;
}
// ============================================================================
// 1. 2D-Coalesced Conformer ConvModule Kernels (GLU + DWConv15 + BN + SiLU)
// ============================================================================
kernel void glu_fwd_bf16(
device const bfloat* u [[buffer(0)]],
device bfloat* glu_out [[buffer(1)]],
constant int& BT [[buffer(2)]],
constant int& D [[buffer(3)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= BT) return;
int base = bt * (2 * D) + d;
float a = float(u[base]);
float b = float(u[base + D]);
float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-b, -80.0f, 80.0f)));
glu_out[bt * D + d] = bfloat(a * sig);
}
kernel void dwconv15_stats_coalesced_fwd_bf16(
device const bfloat* glu_in [[buffer(0)]],
device const bfloat* weight [[buffer(1)]],
device const float* running_mean [[buffer(2)]],
device bfloat* dw_out [[buffer(3)]],
device atomic_float* stats_buf [[buffer(4)]], // [2 * D]: sum_delta, sum_delta2
constant int& B [[buffer(5)]],
constant int& T [[buffer(6)]],
constant int& D [[buffer(7)]],
uint2 gid [[thread_position_in_grid]],
uint2 lid [[thread_position_in_threadgroup]]
) {
int d = int(gid.x);
int bt = int(gid.y);
int BT = B * T;
int dx = int(lid.x);
int ty = int(lid.y);
threadgroup float sh_d[8][33];
threadgroup float sh_d2[8][33];
float delta = 0.0f;
float delta2 = 0.0f;
if (d < D && bt < BT) {
int b = bt / T;
int t = bt % T;
device const bfloat* x_b = glu_in + b * T * D + d;
device const bfloat* w_d = weight + d * 15;
float acc = 0.0f;
int k_start = max(0, 7 - t);
int k_end = min(15, T + 7 - t);
for (int k = k_start; k < k_end; ++k) {
acc += float(x_b[(t + k - 7) * D]) * float(w_d[k]);
}
bfloat acc_bf = bfloat(acc);
dw_out[bt * D + d] = acc_bf;
delta = float(acc_bf) - running_mean[d];
delta2 = delta * delta;
}
sh_d[ty][dx] = delta;
sh_d2[ty][dx] = delta2;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (ty == 0 && d < D) {
float sd = 0.0f, sd2 = 0.0f;
for (int i = 0; i < 8; ++i) {
sd += sh_d[i][dx];
sd2 += sh_d2[i][dx];
}
atomic_fetch_add_explicit(&stats_buf[d], sd, memory_order_relaxed);
atomic_fetch_add_explicit(&stats_buf[D + d], sd2, memory_order_relaxed);
}
}
kernel void bn_finalize_stats_fp32(
device float* stats_buf [[buffer(0)]],
device float* running_mean [[buffer(1)]],
device float* running_var [[buffer(2)]],
device float* saved_mean [[buffer(3)]],
device float* saved_rstd [[buffer(4)]],
constant int& BT [[buffer(5)]],
constant int& D [[buffer(6)]],
uint gid [[thread_position_in_grid]]
) {
int d = int(gid);
if (d >= D) return;
float sum_d = stats_buf[d];
float sum_d2 = stats_buf[D + d];
stats_buf[d] = 0.0f;
stats_buf[D + d] = 0.0f;
float fBT = float(BT);
float c = running_mean[d];
float d_mean = sum_d / fBT;
float mean = c + d_mean;
float s2 = metal::max(0.0f, sum_d2 - fBT * d_mean * d_mean);
float var = s2 / fBT;
float rstd = metal::rsqrt(var + 1e-5f);
saved_mean[d] = mean;
saved_rstd[d] = rstd;
float uvar = (BT > 1) ? (s2 / float(BT - 1)) : var;
running_mean[d] = 0.9f * c + 0.1f * mean;
running_var[d] = 0.9f * running_var[d] + 0.1f * uvar;
}
kernel void bn_silu_coalesced_fwd_bf16(
device const bfloat* dw_out [[buffer(0)]],
device const float* gamma [[buffer(1)]],
device const float* beta [[buffer(2)]],
device const float* saved_mean [[buffer(3)]],
device const float* saved_rstd [[buffer(4)]],
device bfloat* out [[buffer(5)]],
constant int& BT [[buffer(6)]],
constant int& D [[buffer(7)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= BT) return;
int idx = bt * D + d;
float v = float(dw_out[idx]);
float y = (v - saved_mean[d]) * saved_rstd[d] * gamma[d] + beta[d];
float silu_y = y / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
out[idx] = bfloat(silu_y);
}
kernel void dwconv15_bn_silu_eval_coalesced_fwd_bf16(
device const bfloat* glu_in [[buffer(0)]],
device const bfloat* weight [[buffer(1)]],
device const float* gamma [[buffer(2)]],
device const float* beta [[buffer(3)]],
device const float* running_mean [[buffer(4)]],
device const float* running_var [[buffer(5)]],
device bfloat* out [[buffer(6)]],
constant int& B [[buffer(7)]],
constant int& T [[buffer(8)]],
constant int& D [[buffer(9)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
device const bfloat* x_b = glu_in + b * T * D + d;
device const bfloat* w_d = weight + d * 15;
float acc = 0.0f;
int k_start = max(0, 7 - t);
int k_end = min(15, T + 7 - t);
for (int k = k_start; k < k_end; ++k) {
acc += float(x_b[(t + k - 7) * D]) * float(w_d[k]);
}
float v = float(bfloat(acc));
float inv_std = metal::rsqrt(running_var[d] + 1e-5f);
float y = (v - running_mean[d]) * inv_std * gamma[d] + beta[d];
float silu_y = y / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
out[bt * D + d] = bfloat(silu_y);
}
kernel void bn_silu_bwd_stats_coalesced_bf16(
device const bfloat* grad_out [[buffer(0)]],
device const bfloat* dw_out [[buffer(1)]],
device const float* gamma [[buffer(2)]],
device const float* beta [[buffer(3)]],
device const float* saved_mean [[buffer(4)]],
device const float* saved_rstd [[buffer(5)]],
device atomic_float* bwd_stats [[buffer(6)]], // [2 * D]: [0..D-1] dgamma, [D..2D-1] dbeta
constant int& BT [[buffer(7)]],
constant int& D [[buffer(8)]],
uint2 gid [[thread_position_in_grid]],
uint2 lid [[thread_position_in_threadgroup]]
) {
int d = int(gid.x);
int bt = int(gid.y);
int dx = int(lid.x);
int ty = int(lid.y);
threadgroup float sh_dy_xh[8][33];
threadgroup float sh_dy[8][33];
float dy = 0.0f;
float dy_xh = 0.0f;
if (d < D && bt < BT) {
int idx = bt * D + d;
float xv = float(dw_out[idx]);
float go = float(grad_out[idx]);
float xhat = (xv - saved_mean[d]) * saved_rstd[d];
float y = xhat * gamma[d] + beta[d];
float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
dy = go * sig * (1.0f + y * (1.0f - sig));
dy_xh = dy * xhat;
}
sh_dy_xh[ty][dx] = dy_xh;
sh_dy[ty][dx] = dy;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (ty == 0 && d < D) {
float s_xh = 0.0f, s_dy = 0.0f;
for (int i = 0; i < 8; ++i) {
s_xh += sh_dy_xh[i][dx];
s_dy += sh_dy[i][dx];
}
atomic_fetch_add_explicit(&bwd_stats[d], s_xh, memory_order_relaxed);
atomic_fetch_add_explicit(&bwd_stats[D + d], s_dy, memory_order_relaxed);
}
}
kernel void bn_bwd_dx_coalesced_bf16(
device const bfloat* grad_out [[buffer(0)]],
device const bfloat* dw_out [[buffer(1)]],
device const float* gamma [[buffer(2)]],
device const float* beta [[buffer(3)]],
device const float* saved_mean [[buffer(4)]],
device const float* saved_rstd [[buffer(5)]],
device const float* bwd_stats [[buffer(6)]],
device bfloat* grad_dw [[buffer(7)]],
constant int& BT [[buffer(8)]],
constant int& D [[buffer(9)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= BT) return;
int idx = bt * D + d;
float m = saved_mean[d];
float rstd = saved_rstd[d];
float g = gamma[d];
float xhat = (float(dw_out[idx]) - m) * rstd;
float y = xhat * g + beta[d];
float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
float dy = float(grad_out[idx]) * sig * (1.0f + y * (1.0f - sig));
float tot_dy_xh = bwd_stats[d];
float tot_dy = bwd_stats[D + d];
float scale = g * rstd / float(BT);
grad_dw[idx] = bfloat(scale * (float(BT) * dy - tot_dy - xhat * tot_dy_xh));
}
kernel void dwconv15_bwd_w_simd_bf16(
device const bfloat* grad_dw [[buffer(0)]],
device const bfloat* glu_in [[buffer(1)]],
device bfloat* dst_w_bf16 [[buffer(2)]],
constant int& B [[buffer(3)]],
constant int& T [[buffer(4)]],
constant int& D [[buffer(5)]],
constant int& accum_mode [[buffer(6)]],
uint d [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
if (int(d) >= D) return;
int BT = B * T;
float acc[15];
for (int k = 0; k < 15; ++k) acc[k] = 0.0f;
for (int bt = int(tid); bt < BT; bt += 256) {
int b = bt / T;
int t = bt % T;
float gdw = float(grad_dw[bt * D + int(d)]);
device const bfloat* x_b = glu_in + b * T * D + int(d);
int k_start = max(0, 7 - t);
int k_end = min(15, T + 7 - t);
for (int k = k_start; k < k_end; ++k) {
acc[k] += gdw * float(x_b[(t + k - 7) * D]);
}
}
threadgroup float sh[8][16];
for (int k = 0; k < 15; ++k) {
float s = simd_sum(acc[k]);
if (lane == 0) sh[sgid][k] = s;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < 15u) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh[i][tid];
uint out_idx = d * 15u + tid;
if (accum_mode != 0) {
dst_w_bf16[out_idx] = bfloat(float(dst_w_bf16[out_idx]) + tot);
} else {
dst_w_bf16[out_idx] = bfloat(tot);
}
}
}
kernel void dwconv15_glu_bwd_x_bf16(
device const bfloat* grad_dw [[buffer(0)]],
device const bfloat* weight [[buffer(1)]],
device const bfloat* u [[buffer(2)]],
device bfloat* grad_u [[buffer(3)]],
constant int& B [[buffer(4)]],
constant int& T [[buffer(5)]],
constant int& D [[buffer(6)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
device const bfloat* go_b = grad_dw + b * T * D + d;
device const bfloat* w_d = weight + d * 15;
float grad_glu = 0.0f;
int k_start = max(0, t + 7 - (T - 1));
int k_end = min(15, t + 8);
for (int k = k_start; k < k_end; ++k) {
grad_glu += float(go_b[(t - k + 7) * D]) * float(w_d[k]);
}
uint u_base = uint(bt) * uint(2 * D) + uint(d);
float a = float(u[u_base]);
float b_val = float(u[u_base + D]);
float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-b_val, -80.0f, 80.0f)));
grad_u[u_base] = bfloat(grad_glu * sig);
grad_u[u_base + D] = bfloat(grad_glu * a * sig * (1.0f - sig));
}
// ============================================================================
// 2. Fused LayerNorm, Bias+Drop+Res+LN, Bias+GELU+Drop, and Self-Attention
// ============================================================================
kernel void layernorm_fwd_bf16(
device const bfloat* x [[buffer(0)]],
device const bfloat* gamma [[buffer(1)]],
device const bfloat* beta [[buffer(2)]],
device bfloat* y [[buffer(3)]],
device float* mean_out [[buffer(4)]],
device float* rstd_out [[buffer(5)]],
constant int& D [[buffer(6)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
uint base = bt * uint(D);
float v0 = (int(tid) < D) ? float(x[base + tid]) : 0.0f;
float v1 = (int(tid) + 256 < D) ? float(x[base + tid + 256u]) : 0.0f;
float s = simd_sum(v0 + v1);
threadgroup float sh[8];
if (lane == 0) sh[sgid] = s;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_mean;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh[i];
s_mean = tot / float(D);
mean_out[bt] = s_mean;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float m = s_mean;
float d0 = (int(tid) < D) ? (v0 - m) : 0.0f;
float d1 = (int(tid) + 256 < D) ? (v1 - m) : 0.0f;
float sq = simd_sum(d0 * d0 + d1 * d1);
if (lane == 0) sh[sgid] = sq;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_rstd;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh[i];
float r = metal::rsqrt(tot / float(D) + 1e-5f);
s_rstd = r;
rstd_out[bt] = r;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float r = s_rstd;
if (int(tid) < D) {
y[base + tid] = bfloat(d0 * r * float(gamma[tid]) + float(beta[tid]));
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
y[base + c] = bfloat(d1 * r * float(gamma[c]) + float(beta[c]));
}
}
kernel void layernorm_bwd_bf16(
device const bfloat* grad_y [[buffer(0)]],
device const bfloat* x [[buffer(1)]],
device const bfloat* gamma [[buffer(2)]],
device const float* mean_in [[buffer(3)]],
device const float* rstd_in [[buffer(4)]],
device bfloat* grad_x [[buffer(5)]],
device atomic_float* scratch_grads [[buffer(6)]], // [2 * D]: dgamma, dbeta
constant int& D [[buffer(7)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
uint base = bt * uint(D);
float m = mean_in[bt];
float r = rstd_in[bt];
float gy0 = 0.0f, gy1 = 0.0f;
float xh0 = 0.0f, xh1 = 0.0f;
float dy0 = 0.0f, dy1 = 0.0f;
if (int(tid) < D) {
uint idx = base + tid;
gy0 = float(grad_y[idx]);
xh0 = (float(x[idx]) - m) * r;
dy0 = gy0 * float(gamma[tid]);
atomic_fetch_add_explicit(&scratch_grads[tid], gy0 * xh0, memory_order_relaxed);
atomic_fetch_add_explicit(&scratch_grads[uint(D) + tid], gy0, memory_order_relaxed);
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
uint idx = base + c;
gy1 = float(grad_y[idx]);
xh1 = (float(x[idx]) - m) * r;
dy1 = gy1 * float(gamma[c]);
atomic_fetch_add_explicit(&scratch_grads[c], gy1 * xh1, memory_order_relaxed);
atomic_fetch_add_explicit(&scratch_grads[uint(D) + c], gy1, memory_order_relaxed);
}
float s_dy = simd_sum(dy0 + dy1);
float s_dy_xh = simd_sum(dy0 * xh0 + dy1 * xh1);
threadgroup float sh1[8];
threadgroup float sh2[8];
if (lane == 0) {
sh1[sgid] = s_dy;
sh2[sgid] = s_dy_xh;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float tot_dy;
threadgroup float tot_dy_xh;
if (tid == 0) {
float a = 0.0f, b = 0.0f;
for (int i = 0; i < 8; ++i) { a += sh1[i]; b += sh2[i]; }
tot_dy = a;
tot_dy_xh = b;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float invD = 1.0f / float(D);
float m_dy = tot_dy * invD;
float m_dy_xh = tot_dy_xh * invD;
if (int(tid) < D) {
grad_x[base + tid] = bfloat(r * (dy0 - m_dy - xh0 * m_dy_xh));
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
grad_x[base + c] = bfloat(r * (dy1 - m_dy - xh1 * m_dy_xh));
}
}
kernel void fused_bias_drop_res_ln_fwd_bf16(
device const bfloat* x_res [[buffer(0)]],
device const bfloat* sub_nobias [[buffer(1)]],
device const bfloat* sub_bias [[buffer(2)]],
device const bfloat* gamma [[buffer(3)]],
device const bfloat* beta [[buffer(4)]],
device bfloat* x_out [[buffer(5)]],
device bfloat* normed_out [[buffer(6)]],
device float* mean_out [[buffer(7)]],
device float* rstd_out [[buffer(8)]],
constant int& D [[buffer(9)]],
constant float& res_scale [[buffer(10)]],
constant float& drop_p [[buffer(11)]],
constant float& inv_keep [[buffer(12)]],
constant uint& seed_lo [[buffer(13)]],
constant uint& seed_hi [[buffer(14)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
uint base = bt * uint(D);
float v0 = 0.0f, v1 = 0.0f;
if (int(tid) < D) {
uint idx = base + tid;
float u = float(sub_nobias[idx]) + float(sub_bias[tid]);
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
bfloat x_bf = bfloat(float(x_res[idx]) + res_scale * (u * kp));
x_out[idx] = x_bf;
v0 = float(x_bf);
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
uint idx = base + c;
float u = float(sub_nobias[idx]) + float(sub_bias[c]);
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
bfloat x_bf = bfloat(float(x_res[idx]) + res_scale * (u * kp));
x_out[idx] = x_bf;
v1 = float(x_bf);
}
float s = simd_sum(v0 + v1);
threadgroup float sh[8];
if (lane == 0) sh[sgid] = s;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_mean;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh[i];
s_mean = tot / float(D);
mean_out[bt] = s_mean;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float m = s_mean;
float d0 = (int(tid) < D) ? (v0 - m) : 0.0f;
float d1 = (int(tid) + 256 < D) ? (v1 - m) : 0.0f;
float sq = simd_sum(d0 * d0 + d1 * d1);
if (lane == 0) sh[sgid] = sq;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_rstd;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh[i];
float r = metal::rsqrt(tot / float(D) + 1e-5f);
s_rstd = r;
rstd_out[bt] = r;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float r = s_rstd;
if (int(tid) < D) {
normed_out[base + tid] = bfloat(d0 * r * float(gamma[tid]) + float(beta[tid]));
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
normed_out[base + c] = bfloat(d1 * r * float(gamma[c]) + float(beta[c]));
}
}
kernel void fused_bias_drop_res_ln_bwd_bf16(
device const bfloat* grad_normed [[buffer(0)]],
device const bfloat* grad_x_out [[buffer(1)]],
device const bfloat* x_out [[buffer(2)]],
device const bfloat* gamma [[buffer(3)]],
device const float* mean_in [[buffer(4)]],
device const float* rstd_in [[buffer(5)]],
device bfloat* grad_x_res [[buffer(6)]],
device bfloat* grad_sub_nobias [[buffer(7)]],
device atomic_float* scratch_grads [[buffer(8)]], // [3 * D]: dgamma, dbeta, dsub_bias
constant int& D [[buffer(9)]],
constant int& has_grad_normed [[buffer(10)]],
constant int& has_grad_x_out [[buffer(11)]],
constant float& res_scale [[buffer(12)]],
constant float& drop_p [[buffer(13)]],
constant float& inv_keep [[buffer(14)]],
constant uint& seed_lo [[buffer(15)]],
constant uint& seed_hi [[buffer(16)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
uint base = bt * uint(D);
float m = mean_in[bt];
float r = rstd_in[bt];
float gn0 = 0.0f, gn1 = 0.0f;
float xh0 = 0.0f, xh1 = 0.0f;
float dy0 = 0.0f, dy1 = 0.0f;
if (has_grad_normed != 0) {
if (int(tid) < D) {
uint idx = base + tid;
gn0 = float(grad_normed[idx]);
xh0 = (float(x_out[idx]) - m) * r;
dy0 = gn0 * float(gamma[tid]);
atomic_fetch_add_explicit(&scratch_grads[tid], gn0 * xh0, memory_order_relaxed);
atomic_fetch_add_explicit(&scratch_grads[uint(D) + tid], gn0, memory_order_relaxed);
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
uint idx = base + c;
gn1 = float(grad_normed[idx]);
xh1 = (float(x_out[idx]) - m) * r;
dy1 = gn1 * float(gamma[c]);
atomic_fetch_add_explicit(&scratch_grads[c], gn1 * xh1, memory_order_relaxed);
atomic_fetch_add_explicit(&scratch_grads[uint(D) + c], gn1, memory_order_relaxed);
}
}
float s_dy = simd_sum(dy0 + dy1);
float s_dy_xh = simd_sum(dy0 * xh0 + dy1 * xh1);
threadgroup float sh1[8];
threadgroup float sh2[8];
if (lane == 0) {
sh1[sgid] = s_dy;
sh2[sgid] = s_dy_xh;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float tot_dy;
threadgroup float tot_dy_xh;
if (tid == 0) {
float a = 0.0f, b = 0.0f;
for (int i = 0; i < 8; ++i) { a += sh1[i]; b += sh2[i]; }
tot_dy = a;
tot_dy_xh = b;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float invD = 1.0f / float(D);
float m_dy = tot_dy * invD;
float m_dy_xh = tot_dy_xh * invD;
if (int(tid) < D) {
uint idx = base + tid;
float dx_ln = (has_grad_normed != 0) ? (r * (dy0 - m_dy - xh0 * m_dy_xh)) : 0.0f;
float gx = dx_ln + ((has_grad_x_out != 0) ? float(grad_x_out[idx]) : 0.0f);
grad_x_res[idx] = bfloat(gx);
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
bfloat gsub_bf = bfloat(gx * res_scale * kp);
grad_sub_nobias[idx] = gsub_bf;
atomic_fetch_add_explicit(&scratch_grads[2u * uint(D) + tid], float(gsub_bf), memory_order_relaxed);
}
if (int(tid) + 256 < D) {
uint c = tid + 256u;
uint idx = base + c;
float dx_ln = (has_grad_normed != 0) ? (r * (dy1 - m_dy - xh1 * m_dy_xh)) : 0.0f;
float gx = dx_ln + ((has_grad_x_out != 0) ? float(grad_x_out[idx]) : 0.0f);
grad_x_res[idx] = bfloat(gx);
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
bfloat gsub_bf = bfloat(gx * res_scale * kp);
grad_sub_nobias[idx] = gsub_bf;
atomic_fetch_add_explicit(&scratch_grads[2u * uint(D) + c], float(gsub_bf), memory_order_relaxed);
}
}
kernel void fused_bias_gelu_drop_fwd_bf16(
device const bfloat* z_nobias [[buffer(0)]],
device const bfloat* bias [[buffer(1)]],
device bfloat* out [[buffer(2)]],
constant int& BT [[buffer(3)]],
constant int& D [[buffer(4)]],
constant float& drop_p [[buffer(5)]],
constant float& inv_keep [[buffer(6)]],
constant uint& seed_lo [[buffer(7)]],
constant uint& seed_hi [[buffer(8)]],
uint2 gid [[thread_position_in_grid]]
) {
int d = int(gid.x);
int bt = int(gid.y);
if (d >= D || bt >= BT) return;
uint idx = uint(bt) * uint(D) + uint(d);
float x = float(z_nobias[idx]) + float(bias[d]);
float cdf = 0.5f * (1.0f + erf_approx_fp32(x * 0.7071067811865475f));
float g = x * cdf;
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
out[idx] = bfloat(g * kp);
}
kernel void fused_bias_gelu_drop_bwd_bf16(
device const bfloat* grad_out [[buffer(0)]],
device const bfloat* z_nobias [[buffer(1)]],
device const bfloat* bias [[buffer(2)]],
device bfloat* grad_z [[buffer(3)]],
device atomic_float* grad_bias_fp32 [[buffer(4)]],
constant int& BT [[buffer(5)]],
constant int& D [[buffer(6)]],
constant float& drop_p [[buffer(7)]],
constant float& inv_keep [[buffer(8)]],
constant uint& seed_lo [[buffer(9)]],
constant uint& seed_hi [[buffer(10)]],
uint2 gid [[thread_position_in_grid]],
uint2 lid [[thread_position_in_threadgroup]]
) {
int d = int(gid.x);
int bt = int(gid.y);
int dx = int(lid.x);
int ty = int(lid.y);
threadgroup float sh_gb[8][33];
float gb = 0.0f;
if (d < D && bt < BT) {
uint idx = uint(bt) * uint(D) + uint(d);
float x = float(z_nobias[idx]) + float(bias[d]);
float cdf = 0.5f * (1.0f + erf_approx_fp32(x * 0.7071067811865475f));
float xc = metal::clamp(x, -14.0f, 14.0f);
float pdf = 0.3989422804014327f * metal::exp(-0.5f * xc * xc);
float dgelu = cdf + x * pdf;
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
bfloat gz_bf = bfloat(float(grad_out[idx]) * kp * dgelu);
grad_z[idx] = gz_bf;
gb = float(gz_bf);
}
sh_gb[ty][dx] = gb;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (ty == 0 && d < D) {
float s = 0.0f;
for (int i = 0; i < 8; ++i) s += sh_gb[i][dx];
atomic_fetch_add_explicit(&grad_bias_fp32[d], s, memory_order_relaxed);
}
}
kernel void qkv_split_heads_bf16(
device const bfloat* qkv [[buffer(0)]], // [B, T, 3, H, Dh]
device bfloat* q_out [[buffer(1)]], // [B*H, T, Dh]
device bfloat* k_out [[buffer(2)]], // [B*H, T, Dh]
device bfloat* v_out [[buffer(3)]], // [B*H, T, Dh]
constant int& B [[buffer(4)]],
constant int& T [[buffer(5)]],
constant int& H [[buffer(6)]],
constant int& Dh [[buffer(7)]],
uint2 gid [[thread_position_in_grid]]
) {
int hd = int(gid.x);
int bt = int(gid.y);
int HD = H * Dh;
if (hd >= HD || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
int h = hd / Dh;
int d = hd % Dh;
int in_base = bt * (3 * HD);
int out_idx = ((b * H + h) * T + t) * Dh + d;
q_out[out_idx] = qkv[in_base + hd];
k_out[out_idx] = qkv[in_base + HD + hd];
v_out[out_idx] = qkv[in_base + 2 * HD + hd];
}
kernel void qkv_merge_heads_bf16(
device const bfloat* gq [[buffer(0)]],
device const bfloat* gk [[buffer(1)]],
device const bfloat* gv [[buffer(2)]],
device bfloat* gqkv [[buffer(3)]],
constant int& B [[buffer(4)]],
constant int& T [[buffer(5)]],
constant int& H [[buffer(6)]],
constant int& Dh [[buffer(7)]],
uint2 gid [[thread_position_in_grid]]
) {
int hd = int(gid.x);
int bt = int(gid.y);
int HD = H * Dh;
if (hd >= HD || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
int h = hd / Dh;
int d = hd % Dh;
int in_idx = ((b * H + h) * T + t) * Dh + d;
int out_base = bt * (3 * HD);
gqkv[out_base + hd] = gq[in_idx];
gqkv[out_base + HD + hd] = gk[in_idx];
gqkv[out_base + 2 * HD + hd] = gv[in_idx];
}
kernel void attn_merge_ctx_bf16(
device const bfloat* ctx_bh [[buffer(0)]], // [B*H, T, Dh]
device bfloat* ctx_out [[buffer(1)]], // [B, T, H*Dh]
constant int& B [[buffer(2)]],
constant int& T [[buffer(3)]],
constant int& H [[buffer(4)]],
constant int& Dh [[buffer(5)]],
uint2 gid [[thread_position_in_grid]]
) {
int hd = int(gid.x);
int bt = int(gid.y);
int HD = H * Dh;
if (hd >= HD || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
int h = hd / Dh;
int d = hd % Dh;
ctx_out[bt * HD + hd] = ctx_bh[((b * H + h) * T + t) * Dh + d];
}
kernel void attn_split_ctx_bf16(
device const bfloat* gctx [[buffer(0)]], // [B, T, H*Dh]
device bfloat* gctx_bh [[buffer(1)]], // [B*H, T, Dh]
constant int& B [[buffer(2)]],
constant int& T [[buffer(3)]],
constant int& H [[buffer(4)]],
constant int& Dh [[buffer(5)]],
uint2 gid [[thread_position_in_grid]]
) {
int hd = int(gid.x);
int bt = int(gid.y);
int HD = H * Dh;
if (hd >= HD || bt >= B * T) return;
int b = bt / T;
int t = bt % T;
int h = hd / Dh;
int d = hd % Dh;
gctx_bh[((b * H + h) * T + t) * Dh + d] = gctx[bt * HD + hd];
}
kernel void attn_scale_mask_softmax_drop_fwd_bf16(
device const bfloat* scores [[buffer(0)]], // [B*H, T, T]
device const bool* key_mask [[buffer(1)]], // [B, T] (true = pad)
device bfloat* probs_drop [[buffer(2)]], // [B*H, T, T]
device float* lse_out [[buffer(3)]], // [B*H, T]
constant int& B [[buffer(4)]],
constant int& H [[buffer(5)]],
constant int& T [[buffer(6)]],
constant int& has_mask [[buffer(7)]],
constant float& scale [[buffer(8)]],
constant float& drop_p [[buffer(9)]],
constant float& inv_keep [[buffer(10)]],
constant uint& seed_lo [[buffer(11)]],
constant uint& seed_hi [[buffer(12)]],
uint row [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
int total_rows = B * H * T;
if (int(row) >= total_rows) return;
int bh = int(row) / T;
int b = bh / H;
uint row_base = row * uint(T);
device const bool* mask_b = key_mask + b * T;
float local_max = -1e30f;
float local_sum = 0.0f;
for (int col = int(tid); col < T; col += 256) {
float v = float(scores[row_base + uint(col)]) * scale;
if (has_mask != 0 && mask_b[col]) v += -10000.0f;
if (v > local_max) {
local_sum = local_sum * metal::exp(local_max - v) + 1.0f;
local_max = v;
} else {
local_sum += metal::exp(v - local_max);
}
}
for (ushort offset = 16; offset > 0; offset >>= 1) {
float om = simd_shuffle_down(local_max, offset);
float os = simd_shuffle_down(local_sum, offset);
if (om > local_max) {
local_sum = local_sum * metal::exp(local_max - om) + os;
local_max = om;
} else {
local_sum += os * metal::exp(om - local_max);
}
}
threadgroup float sh_m[8];
threadgroup float sh_s[8];
if (lane == 0) {
sh_m[sgid] = local_max;
sh_s[sgid] = local_sum;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_lse;
if (tid == 0) {
float m = sh_m[0], s = sh_s[0];
for (int i = 1; i < 8; ++i) {
float om = sh_m[i], os = sh_s[i];
if (om > m) { s = s * metal::exp(m - om) + os; m = om; }
else { s += os * metal::exp(om - m); }
}
s_lse = m + metal::log(metal::max(s, 1e-30f));
lse_out[row] = s_lse;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float lse = s_lse;
for (int col = int(tid); col < T; col += 256) {
uint idx = row_base + uint(col);
float v = float(scores[idx]) * scale;
if (has_mask != 0 && mask_b[col]) v += -10000.0f;
float p = metal::exp(v - lse);
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
probs_drop[idx] = bfloat(p * kp);
}
}
kernel void attn_scale_mask_softmax_drop_bwd_bf16(
device bfloat* scores_in_dscores_out [[buffer(0)]], // [B*H, T, T] in-place
device bfloat* grad_pdrop_in_pdrop_out [[buffer(1)]], // [B*H, T, T] in-place
device const bool* key_mask [[buffer(2)]], // [B, T]
device const float* lse_in [[buffer(3)]], // [B*H, T]
constant int& B [[buffer(4)]],
constant int& H [[buffer(5)]],
constant int& T [[buffer(6)]],
constant int& has_mask [[buffer(7)]],
constant float& scale [[buffer(8)]],
constant float& drop_p [[buffer(9)]],
constant float& inv_keep [[buffer(10)]],
constant uint& seed_lo [[buffer(11)]],
constant uint& seed_hi [[buffer(12)]],
uint row [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
int total_rows = B * H * T;
if (int(row) >= total_rows) return;
int bh = int(row) / T;
int b = bh / H;
uint row_base = row * uint(T);
device const bool* mask_b = key_mask + b * T;
float lse = lse_in[row];
if (T <= 1024) {
float reg_p[4];
float reg_dp[4];
float reg_pdrop[4];
float local_dot = 0.0f;
for (int k = 0; k < 4; ++k) {
int col = int(tid) + k * 256;
if (col < T) {
uint idx = row_base + uint(col);
float v = float(scores_in_dscores_out[idx]) * scale;
if (has_mask != 0 && mask_b[col]) v += -10000.0f;
float p_raw = metal::exp(v - lse);
float p = float(bfloat(p_raw));
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
float gp = float(grad_pdrop_in_pdrop_out[idx]);
float dp = gp * kp;
reg_p[k] = p;
reg_dp[k] = dp;
reg_pdrop[k] = p_raw * kp;
local_dot += p * dp;
}
}
local_dot = simd_sum(local_dot);
threadgroup float sh_dot[8];
if (lane == 0) sh_dot[sgid] = local_dot;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_dot;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh_dot[i];
s_dot = tot;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float dot = s_dot;
for (int k = 0; k < 4; ++k) {
int col = int(tid) + k * 256;
if (col < T) {
uint idx = row_base + uint(col);
scores_in_dscores_out[idx] = bfloat(scale * reg_p[k] * (reg_dp[k] - dot));
grad_pdrop_in_pdrop_out[idx] = bfloat(reg_pdrop[k]);
}
}
} else {
float local_dot = 0.0f;
for (int col = int(tid); col < T; col += 256) {
uint idx = row_base + uint(col);
float v = float(scores_in_dscores_out[idx]) * scale;
if (has_mask != 0 && mask_b[col]) v += -10000.0f;
float p = float(bfloat(metal::exp(v - lse)));
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
local_dot += p * (float(grad_pdrop_in_pdrop_out[idx]) * kp);
}
local_dot = simd_sum(local_dot);
threadgroup float sh_dot2[8];
if (lane == 0) sh_dot2[sgid] = local_dot;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_dot2;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh_dot2[i];
s_dot2 = tot;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float dot = s_dot2;
for (int col = int(tid); col < T; col += 256) {
uint idx = row_base + uint(col);
float v = float(scores_in_dscores_out[idx]) * scale;
if (has_mask != 0 && mask_b[col]) v += -10000.0f;
float p_raw = metal::exp(v - lse);
float p = float(bfloat(p_raw));
float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
float dp = float(grad_pdrop_in_pdrop_out[idx]) * kp;
scores_in_dscores_out[idx] = bfloat(scale * p * (dp - dot));
grad_pdrop_in_pdrop_out[idx] = bfloat(p_raw * kp);
}
}
}
// ============================================================================
// 3. Fused Reader Tail: Residual Scale + Mask + L2 Normalize (D = 256)
// ============================================================================
kernel void fused_res_l2norm_fwd_bf16(
device const bfloat* out_in [[buffer(0)]],
device const bfloat* res_in [[buffer(1)]],
device const float* res_scale [[buffer(2)]],
device const bool* mask [[buffer(3)]],
device bfloat* normed_out [[buffer(4)]],
device float* inv_norm_out [[buffer(5)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
if (mask[bt]) {
normed_out[bt * 256 + tid] = bfloat(0.0f);
if (tid == 0) inv_norm_out[bt] = 0.0f;
return;
}
float rs = res_scale[0];
uint idx = bt * 256 + tid;
float c = rs * float(res_in[idx]) + float(out_in[idx]);
float sq = simd_sum(c * c);
threadgroup float sh_sq[8];
if (lane == 0) sh_sq[sgid] = sq;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_inv_norm;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh_sq[i];
float inv_n = 1.0f / max(metal::sqrt(tot), 1e-5f);
s_inv_norm = inv_n;
inv_norm_out[bt] = inv_n;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
normed_out[idx] = bfloat(c * s_inv_norm);
}
kernel void fused_res_l2norm_bwd_bf16(
device const bfloat* grad_normed [[buffer(0)]],
device const bfloat* normed [[buffer(1)]],
device const bfloat* res_in [[buffer(2)]],
device const float* inv_norm [[buffer(3)]],
device bfloat* grad_out [[buffer(4)]],
device atomic_float* grad_res_scale [[buffer(5)]],
uint bt [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
float inv_n = inv_norm[bt];
uint idx = bt * 256 + tid;
if (inv_n == 0.0f) {
grad_out[idx] = bfloat(0.0f);
return;
}
float g = float(grad_normed[idx]);
float y = float(normed[idx]);
float dot = simd_sum(g * y);
threadgroup float sh_dot[8];
if (lane == 0) sh_dot[sgid] = dot;
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float s_dot;
if (tid == 0) {
float tot = 0.0f;
for (int i = 0; i < 8; ++i) tot += sh_dot[i];
s_dot = tot;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float gc = inv_n * (g - y * s_dot);
grad_out[idx] = bfloat(gc);
float grs = simd_sum(gc * float(res_in[idx]));
if (lane == 0) sh_dot[sgid] = grs;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
float tot_grs = 0.0f;
for (int i = 0; i < 8; ++i) tot_grs += sh_dot[i];
atomic_fetch_add_explicit(grad_res_scale, tot_grs, memory_order_relaxed);
}
}
// ============================================================================
// 4. Fused CosineCTCHead + Custom Metal FP32 Log-CTC + Exact Scatter Softmax Bwd
// ============================================================================
kernel void fused_lse_gather_bf16(
device const bfloat* logits [[buffer(0)]],
device const int* active_ids [[buffer(1)]],
device float* lse_out [[buffer(2)]],
device float* lp_sub_out [[buffer(3)]],
constant int& B [[buffer(4)]],
constant int& T [[buffer(5)]],
constant int& V [[buffer(6)]],
constant int& U [[buffer(7)]],
uint tgid [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
if (int(tgid) >= B * T) return;
uint b = tgid / uint(T);
uint t = tgid % uint(T);
device const bfloat* row = logits + tgid * uint(V);
float local_max = -1e30f;
float local_sum = 0.0f;
for (uint v = tid; v < uint(V); v += 256) {
float val = float(row[v]);
if (val > local_max) {
local_sum = local_sum * metal::exp(local_max - val) + 1.0f;
local_max = val;
} else {
local_sum += metal::exp(val - local_max);
}
}
for (ushort offset = 16; offset > 0; offset >>= 1) {
float other_max = simd_shuffle_down(local_max, offset);
float other_sum = simd_shuffle_down(local_sum, offset);
if (other_max > local_max) {
local_sum = local_sum * metal::exp(local_max - other_max) + other_sum;
local_max = other_max;
} else {
local_sum += other_sum * metal::exp(other_max - local_max);
}
}
threadgroup float shared_max[8];
threadgroup float shared_sum[8];
if (lane == 0) {
shared_max[sgid] = local_max;
shared_sum[sgid] = local_sum;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float final_lse;
if (tid == 0) {
float m = shared_max[0];
float s = shared_sum[0];
for (uint i = 1; i < 8; ++i) {
float om = shared_max[i];
float os = shared_sum[i];
if (om > m) {
s = s * metal::exp(m - om) + os;
m = om;
} else {
s += os * metal::exp(om - m);
}
}
final_lse = m + metal::log(s);
lse_out[tgid] = final_lse;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float row_lse = final_lse;
uint out_base = (t * uint(B) + b) * uint(U);
for (uint u = tid; u < uint(U); u += 256) {
int col = active_ids[u];
lp_sub_out[out_base + u] = float(row[col]) - row_lse;
}
}
kernel void ctc_loss_fwd_bwd_fp32(
device const float* lp_sub [[buffer(0)]], // [T, B, U]
device const int* targets [[buffer(1)]], // [total_targets] (1..U-1)
device const int* in_lens [[buffer(2)]], // [B]
device const int* tgt_lens [[buffer(3)]], // [B]
device const int* tgt_offsets [[buffer(4)]], // [B]
device float* alpha_ws [[buffer(5)]], // [B, T, S_max]
device atomic_float* g_sub_out [[buffer(6)]], // [T, B, U] (pre-zeroed)
device atomic_float* loss_accum [[buffer(7)]], // [2]
constant int& B [[buffer(8)]],
constant int& T [[buffer(9)]],
constant int& U [[buffer(10)]],
constant int& S_max [[buffer(11)]],
constant int& use_token_denom [[buffer(12)]],
constant float& grad_norm_denom [[buffer(13)]],
uint b [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]]
) {
if (int(b) >= B) return;
int T_b = min(in_lens[b], T);
int L_b = tgt_lens[b];
int t_off = tgt_offsets[b];
int S = 2 * L_b + 1;
threadgroup int sh_ext[1024];
threadgroup float sh_prev[1024];
threadgroup float sh_curr[1024];
for (int s = int(tid); s < S; s += 256) {
sh_ext[s] = ((s & 1) == 0) ? 0 : targets[t_off + (s >> 1)];
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (L_b <= 0) {
for (int t = int(tid); t < T_b; t += 256) {
uint base = uint(t * B + int(b)) * uint(U);
atomic_fetch_add_explicit(&g_sub_out[base], -1.0f / grad_norm_denom, memory_order_relaxed);
}
return;
}
threadgroup int sh_valid_flag;
if (tid == 0) {
int repeats = 0;
for (int i = 1; i < L_b; ++i) {
if (targets[t_off + i] == targets[t_off + i - 1]) repeats += 1;
}
sh_valid_flag = (T_b >= L_b + repeats && S <= 1024 && U <= 1024) ? 1 : 0;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (sh_valid_flag == 0) {
return;
}
device float* alpha_b = alpha_ws + uint(b) * uint(T) * uint(S_max);
for (int s = int(tid); s < S; s += 256) {
float val = -INFINITY;
uint lp0 = uint(b) * uint(U);
if (s == 0) val = lp_sub[lp0 + 0];
else if (s == 1) val = lp_sub[lp0 + uint(sh_ext[1])];
sh_prev[s] = val;
alpha_b[s] = val;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int t = 1; t < T_b; ++t) {
uint lp_base = uint(t * B + int(b)) * uint(U);
int s_min = max(0, S - 2 * (T_b - t));
int s_max_t = min(S - 1, 2 * t + 1);
for (int s = int(tid); s < S; s += 256) {
float val = -INFINITY;
if (s >= s_min && s <= s_max_t) {
float a0 = sh_prev[s];
float a1 = (s >= 1) ? sh_prev[s - 1] : -INFINITY;
bool skip_ok = (s >= 2) && ((s & 1) == 1) && (sh_ext[s] != sh_ext[s - 2]);
float a2 = skip_ok ? sh_prev[s - 2] : -INFINITY;
float m3 = log_add3(a0, a1, a2);
if (m3 > -INFINITY) val = m3 + lp_sub[lp_base + uint(sh_ext[s])];
}
sh_curr[s] = val;
alpha_b[uint(t) * uint(S_max) + uint(s)] = val;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int s = int(tid); s < S; s += 256) sh_prev[s] = sh_curr[s];
threadgroup_barrier(mem_flags::mem_threadgroup);
}
threadgroup float s_ll;
if (tid == 0) {
s_ll = log_add(sh_prev[S - 1], sh_prev[S - 2]);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float ll = s_ll;
if (!(ll > -INFINITY && ll < INFINITY)) {
return;
}
if (tid == 0) {
if (use_token_denom != 0) {
atomic_fetch_add_explicit(&loss_accum[0], -ll, memory_order_relaxed);
atomic_fetch_add_explicit(&loss_accum[1], float(L_b), memory_order_relaxed);
} else {
atomic_fetch_add_explicit(&loss_accum[0], (-ll) / float(L_b), memory_order_relaxed);
atomic_fetch_add_explicit(&loss_accum[1], 1.0f, memory_order_relaxed);
}
}
float g_scale = (use_token_denom != 0)
? (1.0f / grad_norm_denom)
: (1.0f / (float(L_b) * grad_norm_denom));
{
int t = T_b - 1;
uint lp_base = uint(t * B + int(b)) * uint(U);
device const float* a_row = alpha_b + uint(t) * uint(S_max);
for (int s = int(tid); s < S; s += 256) {
float beta_val = (s >= S - 2) ? 0.0f : -INFINITY;
float a_val = a_row[s];
if (a_val > -INFINITY && beta_val > -INFINITY) {
float post = -g_scale * metal::exp(metal::min(0.0f, a_val + beta_val - ll));
atomic_fetch_add_explicit(&g_sub_out[lp_base + uint(sh_ext[s])], post, memory_order_relaxed);
}
sh_prev[s] = (beta_val > -INFINITY) ? (beta_val + lp_sub[lp_base + uint(sh_ext[s])]) : -INFINITY;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (int t = T_b - 2; t >= 0; --t) {
uint lp_base = uint(t * B + int(b)) * uint(U);
device const float* a_row = alpha_b + uint(t) * uint(S_max);
int s_min = max(0, S - 2 * (T_b - t));
int s_max_t = min(S - 1, 2 * t + 1);
for (int s = int(tid); s < S; s += 256) {
float beta_val = -INFINITY;
if (s >= s_min && s <= s_max_t) {
float b0 = sh_prev[s];
float b1 = (s + 1 < S) ? sh_prev[s + 1] : -INFINITY;
bool skip_ok = (s + 2 < S) && ((s & 1) == 1) && (sh_ext[s + 2] != sh_ext[s]);
float b2 = skip_ok ? sh_prev[s + 2] : -INFINITY;
beta_val = log_add3(b0, b1, b2);
}
float a_val = a_row[s];
if (a_val > -INFINITY && beta_val > -INFINITY) {
float post = -g_scale * metal::exp(metal::min(0.0f, a_val + beta_val - ll));
atomic_fetch_add_explicit(&g_sub_out[lp_base + uint(sh_ext[s])], post, memory_order_relaxed);
}
sh_curr[s] = (beta_val > -INFINITY) ? (beta_val + lp_sub[lp_base + uint(sh_ext[s])]) : -INFINITY;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int s = int(tid); s < S; s += 256) {
sh_prev[s] = sh_curr[s];
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
}
kernel void fused_softmax_scatter_bwd_bf16(
device bfloat* logits_in_dZ_out [[buffer(0)]],
device const float* lse [[buffer(1)]],
device const float* g_sub [[buffer(2)]],
device const int* active_ids [[buffer(3)]],
constant int& B [[buffer(4)]],
constant int& T [[buffer(5)]],
constant int& V [[buffer(6)]],
constant int& U [[buffer(7)]],
uint tgid [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]
) {
if (int(tgid) >= B * T) return;
uint b = tgid / uint(T);
uint t = tgid % uint(T);
device bfloat* row = logits_in_dZ_out + tgid * uint(V);
device const float* g_row = g_sub + (t * uint(B) + b) * uint(U);
float saved_logits[4];
int saved_cols[4];
float saved_g[4];
float local_g_sum = 0.0f;
for (uint k = 0; k < 4; ++k) {
uint u = tid + k * 256;
if (int(u) < U) {
int col = active_ids[u];
float gv = g_row[u];
saved_cols[k] = col;
saved_logits[k] = float(row[col]);
saved_g[k] = gv;
local_g_sum += gv;
}
}
local_g_sum = simd_sum(local_g_sum);
threadgroup float shared_g_sum[8];
if (lane == 0) {
shared_g_sum[sgid] = local_g_sum;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
threadgroup float row_g_sum;
if (tid == 0) {
float s = 0.0f;
for (uint i = 0; i < 8; ++i) s += shared_g_sum[i];
row_g_sum = s;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
float gsum = row_g_sum;
float row_lse = lse[tgid];
float neg_gsum = -gsum;
if (gsum == 0.0f) {
for (uint v = tid; v < uint(V); v += 256) {
row[v] = bfloat(0.0f);
}
} else {
for (uint v = tid; v < uint(V); v += 256) {
float p = metal::exp(float(row[v]) - row_lse);
row[v] = bfloat(p * neg_gsum);
}
}
threadgroup_barrier(mem_flags::mem_device);
for (uint k = 0; k < 4; ++k) {
uint u = tid + k * 256;
if (int(u) < U) {
float p = (gsum == 0.0f) ? 0.0f : metal::exp(saved_logits[k] - row_lse);
row[saved_cols[k]] = bfloat(p * neg_gsum + saved_g[k]);
}
}
}
// ============================================================================
// 5. Zero-Sync Flat-Buffer Metal GradNorm + In-Kernel Clipped AdamW
// ============================================================================
kernel void grad_norm_sq_bf16(
device const bfloat* grad [[buffer(0)]],
device atomic_float* total_sq [[buffer(1)]],
constant int& numel [[buffer(2)]],
uint tgid [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]],
uint num_tgs [[threadgroups_per_grid]]
) {
float acc = 0.0f;
uint stride = num_tgs * 256u;
for (uint i = tgid * 256u + tid; i < uint(numel); i += stride) {
float g = float(grad[i]);
acc += g * g;
}
acc = simd_sum(acc);
threadgroup float sh[8];
if (lane == 0) sh[sgid] = acc;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
float s = 0.0f;
for (uint i = 0; i < 8; ++i) s += sh[i];
atomic_fetch_add_explicit(total_sq, s, memory_order_relaxed);
}
}
kernel void grad_norm_sq_fp32(
device const float* grad [[buffer(0)]],
device atomic_float* total_sq [[buffer(1)]],
constant int& numel [[buffer(2)]],
uint tgid [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint sgid [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]],
uint num_tgs [[threadgroups_per_grid]]
) {
float acc = 0.0f;
uint stride = num_tgs * 256u;
for (uint i = tgid * 256u + tid; i < uint(numel); i += stride) {
float g = grad[i];
acc += g * g;
}
acc = simd_sum(acc);
threadgroup float sh[8];
if (lane == 0) sh[sgid] = acc;
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
float s = 0.0f;
for (int i = 0; i < 8; ++i) s += sh[i];
atomic_fetch_add_explicit(total_sq, s, memory_order_relaxed);
}
}
kernel void fused_adamw_master_bf16(
device bfloat* param_bf16 [[buffer(0)]],
device float* master_fp32 [[buffer(1)]],
device bfloat* grad_bf16 [[buffer(2)]],
device float* exp_avg [[buffer(3)]],
device float* exp_avg_sq [[buffer(4)]],
device const float* total_sq_buf [[buffer(5)]],
constant int& numel [[buffer(6)]],
constant float& lr [[buffer(7)]],
constant float& beta1 [[buffer(8)]],
constant float& beta2 [[buffer(9)]],
constant float& eps [[buffer(10)]],
constant float& wd [[buffer(11)]],
constant float& bc1 [[buffer(12)]],
constant float& bc2_sqrt [[buffer(13)]],
constant float& max_norm [[buffer(14)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= numel) return;
float tot_sq = total_sq_buf[0];
if (!(tot_sq >= 0.0f && tot_sq < INFINITY)) {
grad_bf16[gid] = bfloat(0.0f);
return;
}
float norm_val = metal::sqrt(tot_sq);
float clip_coef = metal::min(1.0f, max_norm / (norm_val + 1e-6f));
float g = float(grad_bf16[gid]) * clip_coef;
grad_bf16[gid] = bfloat(0.0f);
float p = master_fp32[gid];
if (wd != 0.0f) {
p -= lr * wd * p;
}
float m = beta1 * exp_avg[gid] + (1.0f - beta1) * g;
float v = beta2 * exp_avg_sq[gid] + (1.0f - beta2) * g * g;
exp_avg[gid] = m;
exp_avg_sq[gid] = v;
float denom = (metal::sqrt(v) / bc2_sqrt) + eps;
p -= (lr / bc1) * (m / denom);
master_fp32[gid] = p;
param_bf16[gid] = bfloat(p);
}
kernel void fused_adamw_fp32(
device float* param_fp32 [[buffer(0)]],
device float* grad_fp32 [[buffer(1)]],
device float* exp_avg [[buffer(2)]],
device float* exp_avg_sq [[buffer(3)]],
device const float* total_sq_buf [[buffer(4)]],
constant int& numel [[buffer(5)]],
constant float& lr [[buffer(6)]],
constant float& beta1 [[buffer(7)]],
constant float& beta2 [[buffer(8)]],
constant float& eps [[buffer(9)]],
constant float& wd [[buffer(10)]],
constant float& bc1 [[buffer(11)]],
constant float& bc2_sqrt [[buffer(12)]],
constant float& max_norm [[buffer(13)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= numel) return;
float tot_sq = total_sq_buf[0];
if (!(tot_sq >= 0.0f && tot_sq < INFINITY)) {
grad_fp32[gid] = 0.0f;
return;
}
float norm_val = metal::sqrt(tot_sq);
float clip_coef = metal::min(1.0f, max_norm / (norm_val + 1e-6f));
float g = grad_fp32[gid] * clip_coef;
grad_fp32[gid] = 0.0f;
float p = param_fp32[gid];
if (wd != 0.0f) {
p -= lr * wd * p;
}
float m = beta1 * exp_avg[gid] + (1.0f - beta1) * g;
float v = beta2 * exp_avg_sq[gid] + (1.0f - beta2) * g * g;
exp_avg[gid] = m;
exp_avg_sq[gid] = v;
float denom = (metal::sqrt(v) / bc2_sqrt) + eps;
p -= (lr / bc1) * (m / denom);
param_fp32[gid] = p;
}
"""
_SHADER_LIB = None
_DIMS_CACHE: "OrderedDict[Tuple[int, ...], torch.Tensor]" = OrderedDict()
_DIMS_CACHE_MAX = 256
_SCRATCH_CACHE: Dict[Tuple[str, int, str], torch.Tensor] = {}
_BOOL_DUMMY_CACHE: Dict[str, torch.Tensor] = {}
def get_metal_lib():
global _SHADER_LIB
if _SHADER_LIB is None:
if hasattr(torch.mps, "compile_shader") and torch.backends.mps.is_available():
_SHADER_LIB = torch.mps.compile_shader(_METAL_SHADER_SOURCE)
return _SHADER_LIB
def get_dims_tensor(shape_tuple: Tuple[int, ...], device: torch.device) -> torch.Tensor:
"""Bounded LRU helper preserved for backward compatibility."""
t = _DIMS_CACHE.get(shape_tuple)
if t is not None and t.device == device:
_DIMS_CACHE.move_to_end(shape_tuple)
return t
t = torch.tensor(list(shape_tuple), device=device, dtype=torch.int32)
_DIMS_CACHE[shape_tuple] = t
if len(_DIMS_CACHE) > _DIMS_CACHE_MAX:
_DIMS_CACHE.popitem(last=False)
return t
def get_zeroed_scratch(name: str, numel: int, device: torch.device) -> torch.Tensor:
"""Returns a persistent pre-zeroed FP32 scratch buffer (reset inside each epilogue kernel)."""
key = (name, numel, str(device))
buf = _SCRATCH_CACHE.get(key)
if buf is None or buf.device != device or buf.numel() < numel:
buf = torch.zeros((numel,), device=device, dtype=torch.float32)
_SCRATCH_CACHE[key] = buf
return buf[:numel]
def _get_dummy_bool(device: torch.device) -> torch.Tensor:
key = str(device)
buf = _BOOL_DUMMY_CACHE.get(key)
if buf is None or buf.device != device:
buf = torch.zeros((1,), device=device, dtype=torch.bool)
_BOOL_DUMMY_CACHE[key] = buf
return buf
def _next_philox_seeds(active: bool) -> Tuple[int, int]:
if not active:
return 0, 0
s64 = random.getrandbits(64)
return int(s64 & 0xFFFFFFFF), int((s64 >> 32) & 0xFFFFFFFF)
# ==============================================================================
# 1. Autograd Functions for Fused Conformer Building Blocks & Reader Tail
# ==============================================================================
class MetalFlatLinearFunction(torch.autograd.Function):
"""
Zero-allocation Linear projection for BF16 parameters packed in FlatBufferMetalAdamW.
Accumulates weight gradients directly into `w_grad_buf` via in-place `addmm_` and
optional bias gradients into `b_grad_buf`, avoiding temporary grad tensor allocations
and AccumulateGrad copies across all 62 Linear / Pointwise layers.
"""
@staticmethod
def forward(
ctx,
x: torch.Tensor,
w: torch.Tensor,
b: Optional[torch.Tensor] = None,
w_grad_buf: Optional[torch.Tensor] = None,
b_grad_buf: Optional[torch.Tensor] = None,
) -> torch.Tensor:
if any(ctx.needs_input_grad):
ctx.save_for_backward(x, w)
ctx.has_bias = b is not None
ctx.w_grad_buf = w_grad_buf
ctx.b_grad_buf = b_grad_buf
return F.linear(x, w, b)
@staticmethod
def backward(ctx, grad_out: torch.Tensor):
x, w = ctx.saved_tensors
go_2d = grad_out.reshape(-1, grad_out.size(-1))
x_2d = x.reshape(-1, x.size(-1))
grad_x = torch.matmul(go_2d, w).view_as(x) if ctx.needs_input_grad[0] else None
if ctx.w_grad_buf is not None:
ctx.w_grad_buf.addmm_(go_2d.t(), x_2d)
grad_w = None
else:
grad_w = torch.matmul(go_2d.t(), x_2d)
grad_b = None
if ctx.has_bias:
gb = go_2d.sum(dim=0)
if ctx.b_grad_buf is not None:
ctx.b_grad_buf.add_(gb)
else:
grad_b = gb
return grad_x, grad_w, grad_b, None, None
# Backward-compatible alias for QKV fused linear
MetalFusedQKVLinearFunction = MetalFlatLinearFunction
class MetalLayerNormFunction(torch.autograd.Function):
"""Single-kernel FP32-accumulated BF16 LayerNorm (D <= 512) with direct flat-grad writeback."""
@staticmethod
def forward(
ctx,
x: torch.Tensor,
gamma: torch.Tensor,
beta: torch.Tensor,
wb_grad_buf: Optional[torch.Tensor] = None,
) -> torch.Tensor:
D = x.size(-1)
x_c = x.contiguous()
BT = x_c.numel() // D
lib = get_metal_lib()
y = torch.empty_like(x_c)
mean = torch.empty((BT,), device=x.device, dtype=torch.float32)
rstd = torch.empty((BT,), device=x.device, dtype=torch.float32)
lib.layernorm_fwd_bf16(
x_c, gamma, beta, y, mean, rstd, D,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(x_c, gamma, mean, rstd)
ctx.wb_grad_buf = wb_grad_buf
return y
@staticmethod
def backward(ctx, grad_y: torch.Tensor):
x_c, gamma, mean, rstd = ctx.saved_tensors
D = x_c.size(-1)
BT = x_c.numel() // D
lib = get_metal_lib()
gy_c = grad_y.contiguous()
grad_x = torch.empty_like(x_c)
scratch = get_zeroed_scratch("ln_bwd", 2 * D, x_c.device)
lib.layernorm_bwd_bf16(
gy_c, x_c, gamma, mean, rstd, grad_x, scratch, D,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
if ctx.wb_grad_buf is not None:
lib.accum_reset_fp32_to_bf16(
scratch, ctx.wb_grad_buf, 2 * D,
threads=(2 * D, 1, 1), group_size=(256, 1, 1)
)
return grad_x, None, None, None
grad_wb = torch.empty((2 * D,), device=x_c.device, dtype=torch.bfloat16)
lib.copy_reset_fp32_to_bf16(
scratch, grad_wb, 2 * D,
threads=(2 * D, 1, 1), group_size=(256, 1, 1)
)
return grad_x, grad_wb[:D], grad_wb[D:], None
class MetalFusedBiasDropResLayerNormFunction(torch.autograd.Function):
"""
Fuses 5 Conformer sublayer boundary operations into 1 Metal kernel:
x_out = x_res + res_scale * PhiloxDropout(sub_nobias + sub_bias, p=drop_p)
normed_out = LayerNorm_FP32(x_out, ln_gamma, ln_beta)
Returns (x_out, normed_out). Uses set_materialize_grads(False) so unused x_out
at the end of ConformerBlock incurs zero zero-tensor allocation in backward.
"""
@staticmethod
def forward(
ctx,
x_res: torch.Tensor,
sub_nobias: torch.Tensor,
sub_bias: torch.Tensor,
ln_gamma: torch.Tensor,
ln_beta: torch.Tensor,
res_scale: float,
drop_p: float,
training: bool,
sub_b_grad_buf: Optional[torch.Tensor] = None,
ln_wb_grad_buf: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
ctx.set_materialize_grads(False)
D = x_res.size(-1)
xr_c = x_res.contiguous()
sub_c = sub_nobias.contiguous()
BT = xr_c.numel() // D
eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)
lib = get_metal_lib()
x_out = torch.empty_like(xr_c)
normed_out = torch.empty_like(xr_c)
mean = torch.empty((BT,), device=xr_c.device, dtype=torch.float32)
rstd = torch.empty((BT,), device=xr_c.device, dtype=torch.float32)
lib.fused_bias_drop_res_ln_fwd_bf16(
xr_c, sub_c, sub_bias, ln_gamma, ln_beta,
x_out, normed_out, mean, rstd,
D, float(res_scale), eff_p, inv_keep, seed_lo, seed_hi,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(x_out, ln_gamma, mean, rstd)
ctx.res_scale = float(res_scale)
ctx.eff_p = eff_p
ctx.inv_keep = inv_keep
ctx.seed_lo = seed_lo
ctx.seed_hi = seed_hi
ctx.sub_b_grad_buf = sub_b_grad_buf
ctx.ln_wb_grad_buf = ln_wb_grad_buf
return x_out, normed_out
@staticmethod
def backward(ctx, grad_x_out: Optional[torch.Tensor], grad_normed: Optional[torch.Tensor]):
x_out, ln_gamma, mean, rstd = ctx.saved_tensors
if grad_x_out is None and grad_normed is None:
return (None,) * 10
D = x_out.size(-1)
BT = x_out.numel() // D
lib = get_metal_lib()
has_gn = 1 if grad_normed is not None else 0
has_gx = 1 if grad_x_out is not None else 0
gn_c = grad_normed.contiguous() if has_gn else x_out
gx_c = grad_x_out.contiguous() if has_gx else x_out
grad_xr = torch.empty_like(x_out)
grad_sub = torch.empty_like(x_out)
scratch = get_zeroed_scratch("res_ln_bwd", 3 * D, x_out.device)
lib.fused_bias_drop_res_ln_bwd_bf16(
gn_c, gx_c, x_out, ln_gamma, mean, rstd,
grad_xr, grad_sub, scratch,
D, has_gn, has_gx, ctx.res_scale, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
if ctx.ln_wb_grad_buf is not None and ctx.sub_b_grad_buf is not None:
lib.accum_reset_two_bf16(
scratch, ctx.ln_wb_grad_buf, ctx.sub_b_grad_buf, 2 * D, D,
threads=(3 * D, 1, 1), group_size=(256, 1, 1)
)
return grad_xr, grad_sub, None, None, None, None, None, None, None, None
grad_all = torch.empty((3 * D,), device=x_out.device, dtype=torch.bfloat16)
lib.copy_reset_fp32_to_bf16(
scratch, grad_all, 3 * D,
threads=(3 * D, 1, 1), group_size=(256, 1, 1)
)
g_gamma = grad_all[:D] if has_gn else None
g_beta = grad_all[D : 2 * D] if has_gn else None
g_sub_b = grad_all[2 * D :]
return grad_xr, grad_sub, g_sub_b, g_gamma, g_beta, None, None, None, None, None
class MetalFusedBiasGELUDropFunction(torch.autograd.Function):
"""Fuses Linear bias + exact erf-poly GELU + stateless Philox dropout in 1 coalesced 2D kernel."""
@staticmethod
def forward(
ctx,
z_nobias: torch.Tensor,
bias: torch.Tensor,
drop_p: float,
training: bool,
bias_grad_buf: Optional[torch.Tensor] = None,
) -> torch.Tensor:
z_c = z_nobias.contiguous()
D = z_c.size(-1)
BT = z_c.numel() // D
eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)
lib = get_metal_lib()
out = torch.empty_like(z_c)
lib.fused_bias_gelu_drop_fwd_bf16(
z_c, bias, out, BT, D, eff_p, inv_keep, seed_lo, seed_hi,
threads=(D, BT, 1), group_size=(64, 4, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(z_c, bias)
ctx.eff_p = eff_p
ctx.inv_keep = inv_keep
ctx.seed_lo = seed_lo
ctx.seed_hi = seed_hi
ctx.bias_grad_buf = bias_grad_buf
return out
@staticmethod
def backward(ctx, grad_out: torch.Tensor):
z_c, bias = ctx.saved_tensors
D = z_c.size(-1)
BT = z_c.numel() // D
go_c = grad_out.contiguous()
lib = get_metal_lib()
grad_z = torch.empty_like(z_c)
scratch = get_zeroed_scratch("gelu_bwd", D, z_c.device)
gx_32 = ((D + 31) // 32) * 32
gy_8 = ((BT + 7) // 8) * 8
lib.fused_bias_gelu_drop_bwd_bf16(
go_c, z_c, bias, grad_z, scratch,
BT, D, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
)
if ctx.bias_grad_buf is not None:
lib.accum_reset_fp32_to_bf16(
scratch, ctx.bias_grad_buf, D,
threads=(D, 1, 1), group_size=(256, 1, 1)
)
return grad_z, None, None, None, None
grad_b = torch.empty_like(bias)
lib.copy_reset_fp32_to_bf16(
scratch, grad_b, D,
threads=(D, 1, 1), group_size=(256, 1, 1)
)
return grad_z, grad_b, None, None, None
class MetalFusedSelfAttentionFunction(torch.autograd.Function):
"""
Fused Multi-Head Self-Attention core on MPS BF16:
- Coalesced QKV split -> hardware torch.bmm -> fused Scale + Mask + Online FP32 Softmax + Philox Dropout
-> hardware torch.bmm -> coalesced head merge.
- Eliminates FP32 (B, H, T, T) softmax casts and cuts saved attention matrix memory by 50%
via in-place backward softmax/dropout regeneration.
"""
@staticmethod
def forward(
ctx,
qkv: torch.Tensor,
key_padding_mask: Optional[torch.Tensor],
num_heads: int,
scale: float,
drop_p: float,
training: bool,
) -> torch.Tensor:
B, T, threeD = qkv.shape
H = int(num_heads)
Dh = (threeD // 3) // H
BT = B * T
HD = H * Dh
qkv_c = qkv.contiguous()
eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)
has_mask = 1 if key_padding_mask is not None else 0
mask_c = key_padding_mask.contiguous() if has_mask else _get_dummy_bool(qkv.device)
lib = get_metal_lib()
q_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
k_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
v_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
lib.qkv_split_heads_bf16(
qkv_c, q_m, k_m, v_m, B, T, H, Dh,
threads=(HD, BT, 1), group_size=(64, 4, 1)
)
scores = torch.bmm(q_m, k_m.transpose(1, 2))
probs_drop = torch.empty_like(scores)
lse = torch.empty((B * H, T), device=qkv.device, dtype=torch.float32)
lib.attn_scale_mask_softmax_drop_fwd_bf16(
scores, mask_c, probs_drop, lse,
B, H, T, has_mask, float(scale), eff_p, inv_keep, seed_lo, seed_hi,
threads=(B * H * T * 256, 1, 1), group_size=(256, 1, 1)
)
ctx_bh = torch.bmm(probs_drop, v_m)
ctx_out = torch.empty((B, T, HD), device=qkv.device, dtype=torch.bfloat16)
lib.attn_merge_ctx_bf16(
ctx_bh, ctx_out, B, T, H, Dh,
threads=(HD, BT, 1), group_size=(64, 4, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(q_m, k_m, v_m, scores, lse, mask_c)
ctx.B = B
ctx.T = T
ctx.H = H
ctx.Dh = Dh
ctx.has_mask = has_mask
ctx.scale = float(scale)
ctx.eff_p = eff_p
ctx.inv_keep = inv_keep
ctx.seed_lo = seed_lo
ctx.seed_hi = seed_hi
return ctx_out
@staticmethod
def backward(ctx, grad_ctx: torch.Tensor):
q_m, k_m, v_m, scores, lse, mask_c = ctx.saved_tensors
B, T, H, Dh = ctx.B, ctx.T, ctx.H, ctx.Dh
BT = B * T
HD = H * Dh
lib = get_metal_lib()
gctx_bh = torch.empty((B * H, T, Dh), device=grad_ctx.device, dtype=torch.bfloat16)
lib.attn_split_ctx_bf16(
grad_ctx.contiguous(), gctx_bh, B, T, H, Dh,
threads=(HD, BT, 1), group_size=(64, 4, 1)
)
gpdrop = torch.bmm(gctx_bh, v_m.transpose(1, 2))
# In-place regeneration: overwrites `scores` with d_scores and `gpdrop` with probs_drop
lib.attn_scale_mask_softmax_drop_bwd_bf16(
scores, gpdrop, mask_c, lse,
B, H, T, ctx.has_mask, ctx.scale, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
threads=(B * H * T * 256, 1, 1), group_size=(256, 1, 1)
)
gv = torch.bmm(gpdrop.transpose(1, 2), gctx_bh)
gq = torch.bmm(scores, k_m)
gk = torch.bmm(scores.transpose(1, 2), q_m)
gqkv = torch.empty((B, T, 3 * HD), device=grad_ctx.device, dtype=torch.bfloat16)
lib.qkv_merge_heads_bf16(
gq, gk, gv, gqkv, B, T, H, Dh,
threads=(HD, BT, 1), group_size=(64, 4, 1)
)
return gqkv, None, None, None, None, None
class MetalFusedConvMidFunction(torch.autograd.Function):
"""
2D-Coalesced Fused Conformer Convolution Mid-Block:
u (B, T, 2D) -> GLU -> DepthwiseConv1d(k=15, pad=7) -> Shifted-Mean FP32 BatchNorm1d -> SiLU -> (B, T, D)
Achieves 100% SIMD-coalesced memory reads/writes across channels D and writes parameter
gradients directly into flat gradient buffers when provided.
"""
@staticmethod
def forward(
ctx,
u: torch.Tensor,
conv_w: torch.Tensor,
bn_w: torch.Tensor,
bn_b: torch.Tensor,
running_mean: torch.Tensor,
running_var: torch.Tensor,
training: bool,
conv_w_grad_buf: Optional[torch.Tensor] = None,
bn_w_grad_buf: Optional[torch.Tensor] = None,
bn_b_grad_buf: Optional[torch.Tensor] = None,
) -> torch.Tensor:
B, T, twoD = u.shape
D = twoD // 2
BT = B * T
lib = get_metal_lib()
u_c = u.contiguous()
glu_out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)
out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)
lib.glu_fwd_bf16(u_c, glu_out, BT, D, threads=(D, BT, 1), group_size=(64, 4, 1))
if training:
dw_out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)
saved_mean = torch.empty((D,), device=u.device, dtype=torch.float32)
saved_rstd = torch.empty((D,), device=u.device, dtype=torch.float32)
stats_buf = get_zeroed_scratch("bn_fwd_stats", 2 * D, u.device)
gx_32 = ((D + 31) // 32) * 32
gy_8 = ((BT + 7) // 8) * 8
lib.dwconv15_stats_coalesced_fwd_bf16(
glu_out, conv_w, running_mean, dw_out, stats_buf,
B, T, D, threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
)
lib.bn_finalize_stats_fp32(
stats_buf, running_mean, running_var, saved_mean, saved_rstd,
BT, D, threads=(D, 1, 1), group_size=(128, 1, 1)
)
lib.bn_silu_coalesced_fwd_bf16(
dw_out, bn_w, bn_b, saved_mean, saved_rstd, out,
BT, D, threads=(D, BT, 1), group_size=(64, 4, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(u_c, glu_out, dw_out, conv_w, bn_w, bn_b, saved_mean, saved_rstd)
ctx.conv_w_grad_buf = conv_w_grad_buf
ctx.bn_w_grad_buf = bn_w_grad_buf
ctx.bn_b_grad_buf = bn_b_grad_buf
else:
lib.dwconv15_bn_silu_eval_coalesced_fwd_bf16(
glu_out, conv_w, bn_w, bn_b, running_mean, running_var, out,
B, T, D, threads=(D, BT, 1), group_size=(64, 4, 1)
)
return out
@staticmethod
def backward(ctx, grad_out: torch.Tensor):
u_c, glu_out, dw_out, conv_w, bn_w, bn_b, saved_mean, saved_rstd = ctx.saved_tensors
B, T, D = dw_out.shape
BT = B * T
lib = get_metal_lib()
go_c = grad_out.contiguous()
bwd_stats = get_zeroed_scratch("bn_bwd_stats", 2 * D, u_c.device)
grad_dw = torch.empty_like(dw_out)
grad_u = torch.empty_like(u_c)
gx_32 = ((D + 31) // 32) * 32
gy_8 = ((BT + 7) // 8) * 8
lib.bn_silu_bwd_stats_coalesced_bf16(
go_c, dw_out, bn_w, bn_b, saved_mean, saved_rstd, bwd_stats,
BT, D, threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
)
lib.bn_bwd_dx_coalesced_bf16(
go_c, dw_out, bn_w, bn_b, saved_mean, saved_rstd, bwd_stats,
grad_dw, BT, D, threads=(D, BT, 1), group_size=(64, 4, 1)
)
lib.dwconv15_glu_bwd_x_bf16(
grad_dw, conv_w, u_c, grad_u,
B, T, D, threads=(D, BT, 1), group_size=(64, 4, 1)
)
if ctx.conv_w_grad_buf is not None:
lib.dwconv15_bwd_w_simd_bf16(
grad_dw, glu_out, ctx.conv_w_grad_buf,
B, T, D, 1, threads=(D * 256, 1, 1), group_size=(256, 1, 1)
)
grad_conv_w = None
else:
grad_conv_w = torch.empty_like(conv_w)
lib.dwconv15_bwd_w_simd_bf16(
grad_dw, glu_out, grad_conv_w,
B, T, D, 0, threads=(D * 256, 1, 1), group_size=(256, 1, 1)
)
if ctx.bn_w_grad_buf is not None and ctx.bn_b_grad_buf is not None:
lib.accum_reset_two_fp32(
bwd_stats, ctx.bn_w_grad_buf, ctx.bn_b_grad_buf, D,
threads=(2 * D, 1, 1), group_size=(256, 1, 1)
)
grad_gamma, grad_beta = None, None
else:
grad_gamma = torch.empty_like(bn_w)
grad_beta = torch.empty_like(bn_b)
lib.copy_reset_two_fp32(
bwd_stats, grad_gamma, grad_beta, D,
threads=(2 * D, 1, 1), group_size=(256, 1, 1)
)
return grad_u, grad_conv_w, grad_gamma, grad_beta, None, None, None, None, None, None
class MetalFusedResL2NormFunction(torch.autograd.Function):
"""
Fuses AudioToVectorReader tail:
combined = masked_fill(res_scale * res + out, mask, 0.0)
normed = masked_fill(F.normalize(combined.float(), p=2, dim=-1, eps=1e-5).bfloat16(), mask, 0.0)
"""
@staticmethod
def forward(
ctx,
out: torch.Tensor,
res: torch.Tensor,
res_scale: torch.Tensor,
mask: torch.Tensor
) -> torch.Tensor:
B, T, D = out.shape
BT = B * T
lib = get_metal_lib()
out_c = out.contiguous()
res_c = res.contiguous()
mask_c = mask.contiguous()
normed = torch.empty_like(out_c)
inv_norm = torch.empty((BT,), device=out.device, dtype=torch.float32)
lib.fused_res_l2norm_fwd_bf16(
out_c, res_c, res_scale, mask_c, normed, inv_norm,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
if any(ctx.needs_input_grad):
ctx.save_for_backward(normed, res_c, inv_norm)
ctx.res_scale_shape = res_scale.shape
return normed
@staticmethod
def backward(ctx, grad_normed: torch.Tensor):
normed, res_c, inv_norm = ctx.saved_tensors
B, T, _ = normed.shape
BT = B * T
lib = get_metal_lib()
gn_c = grad_normed.contiguous()
grad_out = torch.empty_like(normed)
grad_rs = torch.zeros((1,), device=normed.device, dtype=torch.float32)
lib.fused_res_l2norm_bwd_bf16(
gn_c, normed, res_c, inv_norm, grad_out, grad_rs,
threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
)
return grad_out, None, grad_rs.view(ctx.res_scale_shape), None
# ==============================================================================
# 2. 100% GPU Fused Metal CosineCTCHead + Log-CTC + Analytical Spherical Bank
# ==============================================================================
def _spherical_normalize_backward(
grad_norm_w: torch.Tensor,
norm_w: torch.Tensor,
inv_norm_w: torch.Tensor,
clamped_mask: torch.Tensor
) -> torch.Tensor:
"""Exact analytical Jacobian of F.normalize(w, p=2, dim=-1, eps=1e-5) without autograd overhead."""
dot = (grad_norm_w * norm_w).sum(dim=-1, keepdim=True)
proj = inv_norm_w * (grad_norm_w - norm_w * dot)
return torch.where(clamped_mask, grad_norm_w * inv_norm_w, proj)
class FusedMetalCosineCTCLoss:
"""
100% GPU-Resident CosineCTCHead + Online LogSumExp + Active-Gather + Metal FP32 Log-CTC Engine:
- Caches normalized spherical Vector Bank across micro-steps (`mark_weights_dirty()` on step)
- Eliminates CPU roundtrip (`lp_sub.to("cpu")`, `g_sub.to("mps")`) via `ctc_loss_fwd_bwd_fp32`
- Fixes V2 active-gather softmax-backward `1 - P_active` gradient attenuation bug
- Fixes missing `logit_scale` gradient accumulation and eliminates `logit_scale.item()` sync
- Supports zero-sync loss accumulation (`sync_loss=False`) and unbiased dynamic-batch token scaling
"""
def __init__(
self,
ctc_head: nn.Module,
ctc_loss_fn: nn.Module,
device: torch.device,
accum_steps: int = 1,
target_batch_tokens: Optional[float] = None,
):
self.ctc_head = ctc_head
self.ctc_loss_fn = ctc_loss_fn
self.device = device
self.accum_steps = max(1, int(accum_steps))
self.target_batch_tokens = float(target_batch_tokens) if (target_batch_tokens is not None and target_batch_tokens > 0) else None
vb = ctc_head.vector_bank
self.D = vb.size(1)
self.is_full_bank = (vb.size(0) == 2048)
self.V = vb.size(0) if self.is_full_bank else (vb.size(0) + 1)
self.W_all_bf16 = torch.empty((self.V, self.D), device=device, dtype=torch.bfloat16)
self.b_all_bf16 = torch.zeros((self.V,), device=device, dtype=torch.bfloat16)
self.loss_accum_buf = torch.zeros((2,), device=device, dtype=torch.float32)
self._alpha_ws = torch.empty((0,), device=device, dtype=torch.float32)
self._cached_norm_vb: Optional[torch.Tensor] = None
self._cached_inv_norm_vb: Optional[torch.Tensor] = None
self._cached_clamped_vb: Optional[torch.Tensor] = None
self._cached_norm_blank: Optional[torch.Tensor] = None
self._cached_inv_norm_blank: Optional[torch.Tensor] = None
self._cached_clamped_blank: Optional[torch.Tensor] = None
self._cached_scale: Optional[torch.Tensor] = None
self._cached_in_bounds: Optional[torch.Tensor] = None
self._weights_dirty = True
if not ctc_head.trainable_vector_bank:
vb_f32 = vb.to(device=device, dtype=torch.float32)
norm_vb = F.normalize(vb_f32, p=2, dim=-1, eps=1e-5)
if self.is_full_bank:
self.W_all_bf16.copy_(norm_vb.to(torch.bfloat16))
else:
self.W_all_bf16[1:].copy_(norm_vb.to(torch.bfloat16))
def mark_weights_dirty(self) -> None:
self._weights_dirty = True
@torch.no_grad()
def _refresh_head_cache(self) -> None:
if self.is_full_bank:
if self.ctc_head.trainable_vector_bank:
vb_f32 = self.ctc_head.vector_bank.float()
raw_n = vb_f32.norm(p=2, dim=-1, keepdim=True)
self._cached_clamped_vb = (raw_n <= 1e-5)
self._cached_inv_norm_vb = 1.0 / raw_n.clamp(min=1e-5)
self._cached_norm_vb = vb_f32 * self._cached_inv_norm_vb
self.W_all_bf16.copy_(self._cached_norm_vb.to(torch.bfloat16))
if hasattr(self.ctc_head, "vocab_bias") and self.ctc_head.vocab_bias is not None:
self.b_all_bf16.copy_(self.ctc_head.vocab_bias.to(torch.bfloat16))
else:
bvec_f32 = self.ctc_head.blank_vec.float()
raw_nb = bvec_f32.norm(p=2, dim=-1, keepdim=True)
self._cached_clamped_blank = (raw_nb <= 1e-5)
self._cached_inv_norm_blank = 1.0 / raw_nb.clamp(min=1e-5)
self._cached_norm_blank = bvec_f32 * self._cached_inv_norm_blank
self.W_all_bf16[0].copy_(self._cached_norm_blank.squeeze(0).to(torch.bfloat16))
if self.ctc_head.trainable_vector_bank:
vb_f32 = self.ctc_head.vector_bank.float()
raw_n = vb_f32.norm(p=2, dim=-1, keepdim=True)
self._cached_clamped_vb = (raw_n <= 1e-5)
self._cached_inv_norm_vb = 1.0 / raw_n.clamp(min=1e-5)
self._cached_norm_vb = vb_f32 * self._cached_inv_norm_vb
self.W_all_bf16[1:].copy_(self._cached_norm_vb.to(torch.bfloat16))
self.b_all_bf16[0] = self.ctc_head.blank_bias.squeeze(0).to(torch.bfloat16)
self.b_all_bf16[1:].copy_(self.ctc_head.vocab_bias.to(torch.bfloat16))
ls = self.ctc_head.logit_scale
clamped_log = torch.clamp(ls, min=-5.0, max=5.2983)
self._cached_scale = torch.exp(clamped_log)
self._cached_in_bounds = ((ls >= -5.0) & (ls <= 5.2983)).to(torch.float32)
self._weights_dirty = False
@torch.no_grad()
def pop_accumulated_loss(self) -> Tuple[float, float]:
"""Reads accumulated [sum_loss, count_or_tokens] from GPU in a single 8-byte sync and resets it."""
vals = self.loss_accum_buf.cpu()
self.loss_accum_buf.zero_()
num = float(vals[0].item())
den = float(vals[1].item())
if den <= 0.0:
return 0.0, 0.0
return num / den, den
@torch.no_grad()
def forward_and_backward_head(
self,
embeddings: torch.Tensor,
flat_targets: torch.Tensor,
input_lengths: torch.Tensor,
target_lengths: torch.Tensor,
active_ids_cpu: Optional[torch.Tensor] = None,
compact_targets: Optional[torch.Tensor] = None,
packed_ctc_meta: Optional[torch.Tensor] = None,
packed_ctc_sizes: Optional[Tuple[int, int, int, int]] = None,
sync_loss: bool = True,
) -> Tuple[Optional[float], torch.Tensor]:
lib = get_metal_lib()
B, T, D = embeddings.shape
V = self.V
if self._weights_dirty or self._cached_scale is None:
self._refresh_head_cache()
# 1. Single-DMA H2D transfer when PadCollate provides packed_ctc_meta
if packed_ctc_meta is not None and packed_ctc_sizes is not None:
U, sum_L, max_L, tot_toks = packed_ctc_sizes
meta_mps = packed_ctc_meta.to(self.device)
active_ids_mps = meta_mps[:U]
compact_t_mps = meta_mps[U : U + sum_L]
in_lens_mps = meta_mps[U + sum_L : U + sum_L + B]
tgt_lens_mps = meta_mps[U + sum_L + B : U + sum_L + 2 * B]
tgt_offs_mps = meta_mps[U + sum_L + 2 * B : U + sum_L + 3 * B]
else:
if active_ids_cpu is None or compact_targets is None:
uniq_t, inv_idx = torch.unique(flat_targets, sorted=True, return_inverse=True)
active_ids_cpu = torch.cat([torch.zeros(1, dtype=torch.int32), uniq_t.to(torch.int32)])
compact_targets = inv_idx + 1
U = int(active_ids_cpu.numel())
sum_L = int(compact_targets.numel())
max_L = int(target_lengths.max().item()) if target_lengths.numel() > 0 else 0
tot_toks = int(target_lengths.sum().item())
t_offs_cpu = torch.zeros((B,), dtype=torch.int32)
if B > 1:
t_offs_cpu[1:] = torch.cumsum(target_lengths[:-1].to(torch.int32), dim=0)
packed_cpu = torch.cat([
active_ids_cpu.to(torch.int32),
compact_targets.to(torch.int32),
input_lengths.to(torch.int32),
target_lengths.to(torch.int32),
t_offs_cpu,
], dim=0)
meta_mps = packed_cpu.to(self.device)
active_ids_mps = meta_mps[:U]
compact_t_mps = meta_mps[U : U + sum_L]
in_lens_mps = meta_mps[U + sum_L : U + sum_L + B]
tgt_lens_mps = meta_mps[U + sum_L + B : U + sum_L + 2 * B]
tgt_offs_mps = meta_mps[U + sum_L + 2 * B : U + sum_L + 3 * B]
scale = self._cached_scale
emb_f32 = embeddings.detach().float()
scaled_emb_bf16 = (emb_f32 * scale).to(torch.bfloat16)
# 2. Cosine similarity GEMM in BF16: (B, T, V)
logits = F.linear(scaled_emb_bf16, self.W_all_bf16, self.b_all_bf16)
# 3. Fused Online FP32 LogSumExp + Active-Column Gather -> (T, B, U)
lse_out = torch.empty((B * T,), device=self.device, dtype=torch.float32)
lp_sub_mps = torch.empty((T, B, U), device=self.device, dtype=torch.float32)
lib.fused_lse_gather_bf16(
logits, active_ids_mps, lse_out, lp_sub_mps,
B, T, V, U,
threads=(B * T * 256, 1, 1), group_size=(256, 1, 1)
)
# 4. 100% GPU Custom Metal FP32 Log-CTC Forward + Backward (with CPU fallback if S_max > 1024)
S_max = 2 * max_L + 1
use_token_denom = 1 if self.target_batch_tokens is not None else 0
if use_token_denom:
grad_norm_denom = max(float(self.target_batch_tokens), 0.4 * float(max(tot_toks, 1))) * float(self.accum_steps)
else:
grad_norm_denom = float(max(B, 1) * self.accum_steps)
if S_max <= 1024 and U <= 1024 and sum_L > 0:
req_ws = B * T * max(S_max, 1)
if self._alpha_ws.numel() < req_ws:
self._alpha_ws = torch.empty((int(req_ws * 1.25),), device=self.device, dtype=torch.float32)
alpha_ws = self._alpha_ws[:req_ws]
g_sub_mps = torch.zeros((T, B, U), device=self.device, dtype=torch.float32)
lib.ctc_loss_fwd_bwd_fp32(
lp_sub_mps, compact_t_mps, in_lens_mps, tgt_lens_mps, tgt_offs_mps,
alpha_ws, g_sub_mps, self.loss_accum_buf,
B, T, U, S_max, use_token_denom, float(grad_norm_denom),
threads=(B * 256, 1, 1), group_size=(256, 1, 1)
)
loss_val: Optional[float] = None
if sync_loss:
loss_val, _ = self.pop_accumulated_loss()
else:
# Rare fallback (>511 tokens in a single utterance or >1023 active tokens)
lp_sub_cpu = lp_sub_mps.to("cpu")
ct_cpu = compact_targets if compact_targets is not None else compact_t_mps.to("cpu", dtype=torch.long)
with torch.enable_grad():
lp_leaf = lp_sub_cpu.requires_grad_(True)
if use_token_denom:
loss_sum = F.ctc_loss(
lp_leaf, ct_cpu.long(), input_lengths.long(), target_lengths.long(),
blank=0, reduction="sum", zero_infinity=True
)
loss_val_f = float(loss_sum.detach().item()) / max(tot_toks, 1)
(loss_sum / grad_norm_denom).backward()
in_mask = (torch.arange(T).unsqueeze(1) < input_lengths.view(1, B)).unsqueeze(-1).float()
pure_g = lp_leaf.grad - (1.0 / grad_norm_denom) * lp_sub_cpu.exp() * in_mask
self.loss_accum_buf[0] += float(loss_sum.detach().item())
self.loss_accum_buf[1] += float(max(tot_toks, 1))
else:
loss_m = self.ctc_loss_fn(lp_leaf, ct_cpu.long(), input_lengths.long(), target_lengths.long())
loss_val_f = float(loss_m.detach().item())
(loss_m / self.accum_steps).backward()
in_mask = (torch.arange(T).unsqueeze(1) < input_lengths.view(1, B)).unsqueeze(-1).float()
wb = (1.0 / (target_lengths.float().clamp(min=1.0).view(1, B, 1) * grad_norm_denom)) * in_mask
pure_g = lp_leaf.grad - wb * lp_sub_cpu.exp()
self.loss_accum_buf[0] += loss_val_f
self.loss_accum_buf[1] += 1.0
g_sub_mps = pure_g.to(self.device)
loss_val = self.pop_accumulated_loss()[0] if sync_loss else None
# 5. Exact Fused Softmax Backward + Active Scatter in-place into logits -> dZ_bf16
lib.fused_softmax_scatter_bwd_bf16(
logits, lse_out, g_sub_mps, active_ids_mps,
B, T, V, U,
threads=(B * T * 256, 1, 1), group_size=(256, 1, 1)
)
dZ_bf16 = logits
# 6. CosineCTCHead Parameter Gradients & Analytical Spherical Jacobian (0 CPU Sync!)
grad_bias_all = dZ_bf16.sum(dim=(0, 1)).float()
grad_scaled_emb = torch.matmul(dZ_bf16, self.W_all_bf16).float()
grad_emb = (grad_scaled_emb * scale).to(embeddings.dtype)
grad_scale = (
(grad_scaled_emb * emb_f32).sum().view_as(self.ctc_head.logit_scale)
* scale
* self._cached_in_bounds
)
self._accum_grad(self.ctc_head.logit_scale, grad_scale)
if self.is_full_bank:
if hasattr(self.ctc_head, "vocab_bias") and self.ctc_head.vocab_bias is not None:
self._accum_grad(self.ctc_head.vocab_bias, grad_bias_all)
if self.ctc_head.trainable_vector_bank and self.ctc_head.vector_bank.requires_grad:
grad_norm_vb = torch.matmul(dZ_bf16.reshape(-1, V).t(), scaled_emb_bf16.reshape(-1, D)).float()
grad_vb = _spherical_normalize_backward(
grad_norm_vb, self._cached_norm_vb, self._cached_inv_norm_vb, self._cached_clamped_vb
)
self._accum_grad(self.ctc_head.vector_bank, grad_vb)
else:
grad_norm_blank = torch.matmul(dZ_bf16[:, :, 0:1].transpose(1, 2), scaled_emb_bf16).sum(dim=0).float()
grad_bvec = _spherical_normalize_backward(
grad_norm_blank, self._cached_norm_blank, self._cached_inv_norm_blank, self._cached_clamped_blank
)
self._accum_grad(self.ctc_head.blank_vec, grad_bvec)
self._accum_grad(self.ctc_head.blank_bias, grad_bias_all[0:1])
self._accum_grad(self.ctc_head.vocab_bias, grad_bias_all[1:])
if self.ctc_head.trainable_vector_bank and self.ctc_head.vector_bank.requires_grad:
grad_norm_vb = torch.matmul(dZ_bf16[:, :, 1:].reshape(-1, V - 1).t(), scaled_emb_bf16.reshape(-1, D)).float()
grad_vb = _spherical_normalize_backward(
grad_norm_vb, self._cached_norm_vb, self._cached_inv_norm_vb, self._cached_clamped_vb
)
self._accum_grad(self.ctc_head.vector_bank, grad_vb)
return loss_val, grad_emb
@staticmethod
def _accum_grad(param: nn.Parameter, g: torch.Tensor) -> None:
if not param.requires_grad:
return
if param.grad is None:
param.grad = g.to(dtype=param.dtype)
else:
param.grad.add_(g.to(dtype=param.dtype))
# ==============================================================================
# 3. Zero-Sync Contiguous Flat-Buffer Metal AdamW + In-Kernel Grad Clipping
# ==============================================================================
class FlatBufferMetalAdamW(torch.optim.Optimizer):
"""
Packs all model parameters and gradients into 3 contiguous flat buffers on MPS:
1. BF16 Decay Group (Conformer Linear/Conv weights) with FP32 Master Weights
2. BF16 No-Decay Group (Conformer LayerNorm weights/biases & Linear/Conv biases) with FP32 Master Weights
3. FP32 No-Decay Group (BatchNorm1d weights/biases, res_scale, CosineCTCHead parameters)
Eliminates per-step `total_sq_buf.item()` GPU->CPU sync by computing `clip_coef` and
`isfinite` guards directly inside the Metal AdamW shaders.
"""
def __init__(
self,
model: nn.Module,
lr: float = 2e-4,
betas: Tuple[float, float] = (0.9, 0.98),
eps: float = 1e-8,
weight_decay: float = 1e-2,
fp32_init: Optional[Dict[str, torch.Tensor]] = None
):
self.model = model
self.device = next(model.parameters()).device
self.betas = betas
self.eps = eps
self.step_count = 0
self.ctc_engine: Optional[FusedMetalCosineCTCLoss] = None
self.bf16_decay_list: List[Tuple[str, nn.Parameter]] = []
self.bf16_nodecay_list: List[Tuple[str, nn.Parameter]] = []
self.fp32_nodecay_list: List[Tuple[str, nn.Parameter]] = []
for name, param in model.named_parameters():
if not param.requires_grad:
continue
is_no_decay = (
"ctc_head" in name
or name.endswith(".bias")
or "norm" in name.lower()
or "bn" in name.lower()
or "res_scale" in name
)
if param.dtype == torch.bfloat16:
if is_no_decay:
self.bf16_nodecay_list.append((name, param))
else:
self.bf16_decay_list.append((name, param))
else:
self.fp32_nodecay_list.append((name, param))
self.g1_numel, self.g1_param_buf, self.g1_master_buf, self.g1_grad_buf, self.g1_m, self.g1_v, self.g1_slices = (
self._pack_bf16_group(self.bf16_decay_list, fp32_init)
)
self.g2_numel, self.g2_param_buf, self.g2_master_buf, self.g2_grad_buf, self.g2_m, self.g2_v, self.g2_slices = (
self._pack_bf16_group(self.bf16_nodecay_list, fp32_init)
)
self.g3_numel, self.g3_param_buf, self.g3_grad_buf, self.g3_m, self.g3_v, self.g3_slices = (
self._pack_fp32_group(self.fp32_nodecay_list)
)
self.total_sq_buf = torch.zeros((1,), device=self.device, dtype=torch.float32)
param_groups = [
{"params": [p for _, p in self.bf16_decay_list], "lr": lr, "initial_lr": lr, "weight_decay": weight_decay, "betas": betas, "eps": eps},
{"params": [p for _, p in self.bf16_nodecay_list] + [p for _, p in self.fp32_nodecay_list], "lr": lr, "initial_lr": lr, "weight_decay": 0.0, "betas": betas, "eps": eps},
]
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
super().__init__(param_groups, defaults)
self._bind_fused_views()
def _bind_fused_views(self) -> None:
"""
Binds contiguous parameter & gradient views from flat buffers onto all
Linear, Conv1d, LayerNorm, BatchNorm1d, and MultiHeadAttention modules so
forward/backward kernels accumulate gradients directly into flat buffers.
"""
for mod_name, mod in self.model.named_modules():
prefix = f"{mod_name}." if mod_name else ""
# 1. Fused QKV views on ExplicitMultiHeadAttention
if all(hasattr(mod, attr) for attr in ("q_proj", "k_proj", "v_proj", "embed_dim")):
qw_k, kw_k, vw_k = f"{prefix}q_proj.weight", f"{prefix}k_proj.weight", f"{prefix}v_proj.weight"
qb_k, kb_k, vb_k = f"{prefix}q_proj.bias", f"{prefix}k_proj.bias", f"{prefix}v_proj.bias"
if (
qw_k in self.g1_slices and kw_k in self.g1_slices and vw_k in self.g1_slices
and qb_k in self.g2_slices and kb_k in self.g2_slices and vb_k in self.g2_slices
):
sq, eq, _ = self.g1_slices[qw_k]
sk, ek, _ = self.g1_slices[kw_k]
sv, ev, _ = self.g1_slices[vw_k]
sqb, eqb, _ = self.g2_slices[qb_k]
skb, ekb, _ = self.g2_slices[kb_k]
svb, evb, _ = self.g2_slices[vb_k]
d = mod.embed_dim
if eq == sk and ek == sv and eqb == skb and ekb == svb:
mod._qkv_w_view = self.g1_param_buf[sq:ev].view(3 * d, d)
mod._qkv_w_grad_view = self.g1_grad_buf[sq:ev].view(3 * d, d)
mod._qkv_b_view = self.g2_param_buf[sqb:evb].view(3 * d)
mod._qkv_b_grad_view = self.g2_grad_buf[sqb:evb].view(3 * d)
# 2. Individual Linear & Conv1d flat grad views
if isinstance(mod, (nn.Linear, nn.Conv1d)):
wk = f"{prefix}weight"
bk = f"{prefix}bias"
if wk in self.g1_slices:
sw, ew, sh_w = self.g1_slices[wk]
if isinstance(mod, nn.Conv1d) and len(sh_w) == 3 and sh_w[2] == 1:
mod._flat_w_2d = self.g1_param_buf[sw:ew].view(sh_w[0], sh_w[1])
mod._flat_w_grad = self.g1_grad_buf[sw:ew].view(sh_w[0], sh_w[1])
else:
mod._flat_w_grad = self.g1_grad_buf[sw:ew].view(sh_w)
if bk in self.g2_slices:
sb, eb, sh_b = self.g2_slices[bk]
mod._flat_b_grad = self.g2_grad_buf[sb:eb].view(sh_b)
# 3. LayerNorm contiguous [gamma, beta] 2D grad view
elif isinstance(mod, nn.LayerNorm):
wk, bk = f"{prefix}weight", f"{prefix}bias"
if wk in self.g2_slices and bk in self.g2_slices:
sw, ew, _ = self.g2_slices[wk]
sb, eb, _ = self.g2_slices[bk]
if ew == sb:
mod._flat_wb_grad = self.g2_grad_buf[sw:eb]
# 4. BatchNorm1d FP32 grad views
elif isinstance(mod, nn.BatchNorm1d):
wk, bk = f"{prefix}weight", f"{prefix}bias"
if wk in self.g3_slices and bk in self.g3_slices:
sw, ew, sh_w = self.g3_slices[wk]
sb, eb, sh_b = self.g3_slices[bk]
mod._flat_w_grad = self.g3_grad_buf[sw:ew].view(sh_w)
mod._flat_b_grad = self.g3_grad_buf[sb:eb].view(sh_b)
# Alias preserved for backward compatibility
_bind_fused_qkv_views = _bind_fused_views
def _pack_bf16_group(
self,
named_params: List[Tuple[str, nn.Parameter]],
fp32_init: Optional[Dict[str, torch.Tensor]] = None
):
total_n = sum(p.numel() for _, p in named_params)
if total_n == 0:
empty_bf = torch.empty((0,), device=self.device, dtype=torch.bfloat16)
empty_fp = torch.empty((0,), device=self.device, dtype=torch.float32)
return 0, empty_bf, empty_fp, empty_bf, empty_fp, empty_fp, {}
param_buf = torch.empty((total_n,), device=self.device, dtype=torch.bfloat16)
master_buf = torch.empty((total_n,), device=self.device, dtype=torch.float32)
grad_buf = torch.zeros((total_n,), device=self.device, dtype=torch.bfloat16)
m_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
v_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
slices: Dict[str, Tuple[int, int, torch.Size]] = {}
offset = 0
for name, p in named_params:
n = p.numel()
shape = p.shape
src_fp32 = fp32_init[name] if (fp32_init is not None and name in fp32_init) else p.data.float()
master_buf[offset : offset + n].copy_(src_fp32.view(-1))
param_buf[offset : offset + n].copy_(src_fp32.to(torch.bfloat16).view(-1))
p.data = param_buf[offset : offset + n].view(shape)
p.grad = grad_buf[offset : offset + n].view(shape)
slices[name] = (offset, offset + n, shape)
offset += n
return total_n, param_buf, master_buf, grad_buf, m_buf, v_buf, slices
def _pack_fp32_group(self, named_params: List[Tuple[str, nn.Parameter]]):
total_n = sum(p.numel() for _, p in named_params)
if total_n == 0:
empty_fp = torch.empty((0,), device=self.device, dtype=torch.float32)
return 0, empty_fp, empty_fp, empty_fp, empty_fp, {}
param_buf = torch.empty((total_n,), device=self.device, dtype=torch.float32)
grad_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
m_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
v_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
slices: Dict[str, Tuple[int, int, torch.Size]] = {}
offset = 0
for name, p in named_params:
n = p.numel()
shape = p.shape
param_buf[offset : offset + n].copy_(p.data.float().view(-1))
p.data = param_buf[offset : offset + n].view(shape)
p.grad = grad_buf[offset : offset + n].view(shape)
slices[name] = (offset, offset + n, shape)
offset += n
return total_n, param_buf, grad_buf, m_buf, v_buf, slices
def step(self, closure=None):
"""Hook called by clip_grad_and_step so PyTorch LRScheduler step-order tracking is satisfied."""
pass
@torch.no_grad()
def clip_grad_and_step(self, max_norm: float = 1.0, sync_norm: bool = True) -> Optional[float]:
"""
Zero-sync global L2 GradNorm + In-Kernel Clipped AdamW + FP32->BF16 writeback + zero_grad.
When `sync_norm=False`, executes 100% asynchronously on MPS with zero CPU stalls; any
non-finite gradient norm is caught inside the Metal shader itself (skipping the update
while zeroing gradients). When `sync_norm=True`, returns the scalar global grad norm.
"""
lib = get_metal_lib()
self.total_sq_buf.zero_()
if self.g1_numel > 0:
lib.grad_norm_sq_bf16(
self.g1_grad_buf, self.total_sq_buf, int(self.g1_numel),
threads=(1024 * 256, 1, 1), group_size=(256, 1, 1)
)
if self.g2_numel > 0:
lib.grad_norm_sq_bf16(
self.g2_grad_buf, self.total_sq_buf, int(self.g2_numel),
threads=(256 * 256, 1, 1), group_size=(256, 1, 1)
)
if self.g3_numel > 0:
lib.grad_norm_sq_fp32(
self.g3_grad_buf, self.total_sq_buf, int(self.g3_numel),
threads=(256 * 256, 1, 1), group_size=(256, 1, 1)
)
next_step = self.step_count + 1
beta1, beta2 = self.betas
bc1 = float(1.0 - (beta1 ** next_step))
bc2_sqrt = float(math.sqrt(1.0 - (beta2 ** next_step)))
lr1 = float(self.param_groups[0]["lr"])
wd1 = float(self.param_groups[0]["weight_decay"])
lr2 = float(self.param_groups[1]["lr"])
eps_f = float(self.eps)
max_n = float(max_norm)
if self.g1_numel > 0:
lib.fused_adamw_master_bf16(
self.g1_param_buf, self.g1_master_buf, self.g1_grad_buf, self.g1_m, self.g1_v,
self.total_sq_buf, int(self.g1_numel),
lr1, float(beta1), float(beta2), eps_f, wd1, bc1, bc2_sqrt, max_n,
threads=(self.g1_numel, 1, 1), group_size=(256, 1, 1)
)
if self.g2_numel > 0:
lib.fused_adamw_master_bf16(
self.g2_param_buf, self.g2_master_buf, self.g2_grad_buf, self.g2_m, self.g2_v,
self.total_sq_buf, int(self.g2_numel),
lr2, float(beta1), float(beta2), eps_f, 0.0, bc1, bc2_sqrt, max_n,
threads=(self.g2_numel, 1, 1), group_size=(256, 1, 1)
)
if self.g3_numel > 0:
lib.fused_adamw_fp32(
self.g3_param_buf, self.g3_grad_buf, self.g3_m, self.g3_v,
self.total_sq_buf, int(self.g3_numel),
lr2, float(beta1), float(beta2), eps_f, 0.0, bc1, bc2_sqrt, max_n,
threads=(self.g3_numel, 1, 1), group_size=(256, 1, 1)
)
if self.ctc_engine is not None:
self.ctc_engine.mark_weights_dirty()
if sync_norm:
total_sq = float(self.total_sq_buf.item())
if math.isnan(total_sq) or math.isinf(total_sq) or total_sq < 0.0:
return float("nan")
self.step_count = next_step
self.step()
return math.sqrt(total_sq)
self.step_count = next_step
self.step()
return None
@torch.no_grad()
def zero_grad(self, set_to_none: bool = False) -> None:
if self.g1_numel > 0:
self.g1_grad_buf.zero_()
if self.g2_numel > 0:
self.g2_grad_buf.zero_()
if self.g3_numel > 0:
self.g3_grad_buf.zero_()
@torch.no_grad()
def sync_master_from_model(self) -> None:
for name, p in self.bf16_decay_list:
s, e, shape = self.g1_slices[name]
self.g1_master_buf[s:e].copy_(p.data.float().view(-1))
self.g1_param_buf[s:e].copy_(p.data.to(torch.bfloat16).view(-1))
p.data = self.g1_param_buf[s:e].view(shape)
p.grad = self.g1_grad_buf[s:e].view(shape)
for name, p in self.bf16_nodecay_list:
s, e, shape = self.g2_slices[name]
self.g2_master_buf[s:e].copy_(p.data.float().view(-1))
self.g2_param_buf[s:e].copy_(p.data.to(torch.bfloat16).view(-1))
p.data = self.g2_param_buf[s:e].view(shape)
p.grad = self.g2_grad_buf[s:e].view(shape)
for name, p in self.fp32_nodecay_list:
s, e, shape = self.g3_slices[name]
self.g3_param_buf[s:e].copy_(p.data.float().view(-1))
p.data = self.g3_param_buf[s:e].view(shape)
p.grad = self.g3_grad_buf[s:e].view(shape)
self._bind_fused_views()
@torch.no_grad()
def get_fp32_model_state_dict(self) -> Dict[str, torch.Tensor]:
"""Returns a full FP32 model_state_dict using the exact FP32 master weights for lossless checkpoint saving."""
sd = self.model.state_dict()
out_sd: Dict[str, torch.Tensor] = {}
for k, v in sd.items():
if k in self.g1_slices:
s, e, shape = self.g1_slices[k]
out_sd[k] = self.g1_master_buf[s:e].view(shape).cpu().clone()
elif k in self.g2_slices:
s, e, shape = self.g2_slices[k]
out_sd[k] = self.g2_master_buf[s:e].view(shape).cpu().clone()
else:
out_sd[k] = v.float().cpu().clone() if v.is_floating_point() else v.cpu().clone()
return out_sd
def state_dict(self, include_master: bool = False) -> Dict[str, Any]:
"""
When saved alongside `get_fp32_model_state_dict()`, omitting `g1_master` / `g2_master`
eliminates ~84 MB of duplicate FP32 weights per checkpoint while remaining 100% lossless.
"""
sd: Dict[str, Any] = {
"flat_metal_adamw": True,
"step_count": self.step_count,
"lr0": self.param_groups[0]["lr"],
"lr1": self.param_groups[1]["lr"],
"g1_m": self.g1_m.cpu(),
"g1_v": self.g1_v.cpu(),
"g2_m": self.g2_m.cpu(),
"g2_v": self.g2_v.cpu(),
"g3_m": self.g3_m.cpu(),
"g3_v": self.g3_v.cpu(),
}
if include_master:
sd["g1_master"] = self.g1_master_buf.cpu()
sd["g2_master"] = self.g2_master_buf.cpu()
return sd
def load_state_dict(self, sd: Dict[str, Any]) -> None:
if not sd.get("flat_metal_adamw", False):
return
self.step_count = int(sd.get("step_count", 0))
if "lr0" in sd:
self.param_groups[0]["lr"] = float(sd["lr0"])
if "lr1" in sd:
self.param_groups[1]["lr"] = float(sd["lr1"])
if "g1_master" in sd and sd["g1_master"].numel() == self.g1_numel:
self.g1_master_buf.copy_(sd["g1_master"].to(self.device))
self.g1_param_buf.copy_(self.g1_master_buf.to(torch.bfloat16))
if "g1_m" in sd and sd["g1_m"].numel() == self.g1_numel:
self.g1_m.copy_(sd["g1_m"].to(self.device))
self.g1_v.copy_(sd["g1_v"].to(self.device))
if "g2_master" in sd and sd["g2_master"].numel() == self.g2_numel:
self.g2_master_buf.copy_(sd["g2_master"].to(self.device))
self.g2_param_buf.copy_(self.g2_master_buf.to(torch.bfloat16))
if "g2_m" in sd and sd["g2_m"].numel() == self.g2_numel:
self.g2_m.copy_(sd["g2_m"].to(self.device))
self.g2_v.copy_(sd["g2_v"].to(self.device))
if "g3_m" in sd and sd["g3_m"].numel() == self.g3_numel:
self.g3_m.copy_(sd["g3_m"].to(self.device))
self.g3_v.copy_(sd["g3_v"].to(self.device))
if self.ctc_engine is not None:
self.ctc_engine.mark_weights_dirty()
"""
src/mps_kernels.py
Custom Apple Silicon Metal Compute Shaders (via torch.mps.compile_shader) for Step 3 Training:
1. 2D-Coalesced Conformer ConvModule Kernels (GLU + DepthwiseConv1d(k=15) + Shifted-Mean FP32 BN + SiLU)
2. Fused Conformer Sublayer Epilogues & Activations:
- Fused LayerNorm (BF16 I/O, FP32 mean/rstd)
- Fused Bias + Stateless Philox Dropout + Residual Scale + Residual Add + FP32 LayerNorm
- Fused Bias + GELU + Stateless Philox Dropout
- Coalesced Multi-Head Attention Split/Merge + Fused Scale/Mask/Online-FP32-Softmax/Philox-Dropout
- Zero-Allocation Flat-Buffer Linear Projection (in-place addmm_ into flat grad buffers)
3. Fused Reader Tail Kernel (Residual Scale + Mask + FP32-Accumulated L2 Normalization)
4. 100% GPU Fused CosineCTCHead + Online LogSumExp + Active-Target Gather + Custom Metal FP32 Log-CTC
+ Exact Active-Scatter Softmax Backward (0 CPU Roundtrip, 0 Per-Step Sync, Cached Spherical Bank)
5. Zero-Sync Contiguous Flat-Buffer Fused Metal GradNorm + In-Kernel Clipped AdamW (FP32 Master Weights)
"""
from __future__ import annotations
from collections import OrderedDict
import math
import random
from typing import Dict, Tuple, List, Optional, Any
import torch
import torch.nn as nn
import torch.nn.functional as F
_METAL_SHADER_SOURCE = r"""
#include <metal_stdlib>
using namespace metal;
// ============================================================================
// 0. Stateless Philox-2x32 RNG, Fast Math & Reduction Epilogues
// ============================================================================
inline float philox_keep_scale(uint seed_lo, uint seed_hi, uint idx, float drop_p, float inv_keep) {
if (drop_p <= 0.0f) return 1.0f;
uint ctr0 = idx;
uint ctr1 = seed_hi ^ 0x9E3779B9u;
uint key = seed_lo;
for (int r = 0; r < 4; ++r) {
uint hi = mulhi(0xD256D193u, ctr0);
uint lo = 0xD256D193u * ctr0;
ctr0 = hi ^ key ^ ctr1;
ctr1 = lo;
key += 0x9E3779B9u;
}
float u = float(ctr0 >> 8) * (1.0f / 16777216.0f);
return (u >= drop_p) ? inv_keep : 0.0f;
}
inline float erf_approx_fp32(float x) {
float sign = (x < 0.0f) ? -1.0f : 1.0f;
float ax = metal::min(metal::abs(x), 10.0f);
float t = 1.0f / (1.0f + 0.3275911f * ax);
float poly = (((((1.061405429f * t - 1.453152027f) * t) + 1.421413741f) * t - 0.284496736f) * t + 0.254829592f) * t;
return sign * (1.0f - poly * metal::exp(-ax * ax));
}
inline float log_add(float a, float b) {
if (a == -INFINITY) return b;
if (b == -INFINITY) return a;
float m = metal::max(a, b);
return m + metal::log(1.0f + metal::exp(-metal::abs(a - b)));
}
inline float log_add3(float a, float b, float c) {
float m = metal::max(a, metal::max(b, c));
if (m == -INFINITY) return -INFINITY;
return m + metal::log(
((a == -INFINITY) ? 0.0f : metal::exp(a - m)) +
((b == -INFINITY) ? 0.0f : metal::exp(b - m)) +
((c == -INFINITY) ? 0.0f : metal::exp(c - m))
);
}
kernel void accum_reset_fp32_to_bf16(
device float* src_fp32 [[buffer(0)]],
device bfloat* dst_bf16 [[buffer(1)]],
constant int& n [[buffer(2)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= n) return;
float v = src_fp32[gid];
src_fp32[gid] = 0.0f;
dst_bf16[gid] = bfloat(float(dst_bf16[gid]) + v);
}
kernel void copy_reset_fp32_to_bf16(
device float* src_fp32 [[buffer(0)]],
device bfloat* dst_bf16 [[buffer(1)]],
constant int& n [[buffer(2)]],
uint gid [[thread_position_in_grid]]
) {
if (int(gid) >= n) return;
float v = src_fp32[gid];
src_fp32[gid] = 0.0f;
dst_bf16[gid] = bfloat(v);
}