|
| 1 | +// Fused transformer kernels from mlx::core::fast. |
| 2 | +// |
| 3 | +// These handwritten kernels beat the defn-composed equivalents on the |
| 4 | +// transformer hot paths: RMSNorm (one kernel vs rsqrt+mean+multiply |
| 5 | +// chain), LayerNorm (same for Welford+affine), RoPE (fused trig + |
| 6 | +// interleave), and Scaled-Dot-Product Attention (QK^T → scale → mask → |
| 7 | +// softmax → V as one dispatch instead of ~5). Elixir-side they're |
| 8 | +// surfaced as `Emily.Fast.*` helpers callable from inside `defn`. |
| 9 | +// |
| 10 | +// Nullable inputs (weight/bias, the RoPE `base` override, the precomp |
| 11 | +// `freqs`, per-tensor `offset`) marshal via `std::optional` — the same |
| 12 | +// pattern `ops/random.cpp` uses for PRNG keys. |
| 13 | + |
| 14 | +#include "../emily/tensor.hpp" |
| 15 | + |
| 16 | +#include <fine.hpp> |
| 17 | +#include <mlx/fast.h> |
| 18 | +#include <mlx/mlx.h> |
| 19 | + |
| 20 | +#include <cstdint> |
| 21 | +#include <optional> |
| 22 | +#include <string> |
| 23 | +#include <variant> |
| 24 | +#include <vector> |
| 25 | + |
| 26 | +namespace mx = mlx::core; |
| 27 | +using emily::Tensor; |
| 28 | +using emily::unwrap_all; |
| 29 | +using emily::wrap; |
| 30 | + |
| 31 | +namespace { |
| 32 | + |
| 33 | +// ----------------------------------------------------------------- |
| 34 | +// Nullable tensor helper |
| 35 | +// ----------------------------------------------------------------- |
| 36 | + |
| 37 | +std::optional<mx::array> opt_array( |
| 38 | + const std::optional<fine::ResourcePtr<Tensor>> &opt) { |
| 39 | + if (opt) return (*opt)->array; |
| 40 | + return std::nullopt; |
| 41 | +} |
| 42 | + |
| 43 | +// ----------------------------------------------------------------- |
| 44 | +// fast_rms_norm/3 — mx::fast::rms_norm(x, weight?, eps) |
| 45 | +// ----------------------------------------------------------------- |
| 46 | +// |
| 47 | +// Normalises the last axis of `x` by `rsqrt(mean(x^2) + eps)` and |
| 48 | +// optionally multiplies by `weight` (vector of size last-axis). The |
| 49 | +// weight is nil-able because some models (e.g. `pre_norm=False` |
| 50 | +// variants) use unit-scale RMSNorm. |
| 51 | +fine::ResourcePtr<Tensor> fast_rms_norm( |
| 52 | + ErlNifEnv *, |
| 53 | + fine::ResourcePtr<Tensor> x, |
| 54 | + std::optional<fine::ResourcePtr<Tensor>> weight, |
| 55 | + double eps) { |
| 56 | + return wrap(mx::fast::rms_norm( |
| 57 | + x->array, opt_array(weight), static_cast<float>(eps))); |
| 58 | +} |
| 59 | +FINE_NIF(fast_rms_norm, 0); |
| 60 | + |
| 61 | +// ----------------------------------------------------------------- |
| 62 | +// fast_layer_norm/4 — mx::fast::layer_norm(x, weight?, bias?, eps) |
| 63 | +// ----------------------------------------------------------------- |
| 64 | +// |
| 65 | +// Welford-style LayerNorm over the last axis with optional affine |
| 66 | +// (weight + bias). `weight` and `bias` are independently nullable to |
| 67 | +// match MLX — e.g. `elementwise_affine=False` PyTorch modules map to |
| 68 | +// both-nil. |
| 69 | +fine::ResourcePtr<Tensor> fast_layer_norm( |
| 70 | + ErlNifEnv *, |
| 71 | + fine::ResourcePtr<Tensor> x, |
| 72 | + std::optional<fine::ResourcePtr<Tensor>> weight, |
| 73 | + std::optional<fine::ResourcePtr<Tensor>> bias, |
| 74 | + double eps) { |
| 75 | + return wrap(mx::fast::layer_norm( |
| 76 | + x->array, |
| 77 | + opt_array(weight), |
| 78 | + opt_array(bias), |
| 79 | + static_cast<float>(eps))); |
| 80 | +} |
| 81 | +FINE_NIF(fast_layer_norm, 0); |
| 82 | + |
| 83 | +// ----------------------------------------------------------------- |
| 84 | +// fast_rope/7 — mx::fast::rope(x, dims, traditional, base?, scale, offset, freqs?) |
| 85 | +// ----------------------------------------------------------------- |
| 86 | +// |
| 87 | +// Fused rotary positional embedding. `dims` is the count of trailing |
| 88 | +// dimensions that carry rotated components (typically head_dim; the |
| 89 | +// remaining trailing dims, if any, are passed through). `traditional` |
| 90 | +// selects the paired-interleave layout (`true`, per Meta / MLX) vs |
| 91 | +// the split-half layout (`false`, per HuggingFace). `base` is the |
| 92 | +// theta override (nil → use the `freqs` argument instead); `freqs` is |
| 93 | +// a pre-computed 1-D tensor of inverse frequencies to support the |
| 94 | +// Llama-3 / LongRoPE / linear / dynamic scaling strategies that |
| 95 | +// Bumblebee implements outside of MLX. |
| 96 | +// |
| 97 | +// `offset` is a scalar integer tensor (Nx's canonical rep — Bumblebee |
| 98 | +// tracks the cumulative position offset as an %Nx.Tensor{} through |
| 99 | +// iterative decode), which matches the `array`-offset overload of |
| 100 | +// MLX's `rope`. The NIF always takes a tensor here and uses the |
| 101 | +// overload with `const array&` — users pass `Nx.tensor(0)` when |
| 102 | +// there's no KV-cache offset. |
| 103 | +fine::ResourcePtr<Tensor> fast_rope( |
| 104 | + ErlNifEnv *, |
| 105 | + fine::ResourcePtr<Tensor> x, |
| 106 | + int64_t dims, |
| 107 | + bool traditional, |
| 108 | + std::optional<double> base, |
| 109 | + double scale, |
| 110 | + fine::ResourcePtr<Tensor> offset, |
| 111 | + std::optional<fine::ResourcePtr<Tensor>> freqs) { |
| 112 | + std::optional<float> base_f; |
| 113 | + if (base) base_f = static_cast<float>(*base); |
| 114 | + |
| 115 | + return wrap(mx::fast::rope( |
| 116 | + x->array, |
| 117 | + static_cast<int>(dims), |
| 118 | + traditional, |
| 119 | + base_f, |
| 120 | + static_cast<float>(scale), |
| 121 | + offset->array, |
| 122 | + opt_array(freqs))); |
| 123 | +} |
| 124 | +FINE_NIF(fast_rope, 0); |
| 125 | + |
| 126 | +// ----------------------------------------------------------------- |
| 127 | +// fast_scaled_dot_product_attention/6 — |
| 128 | +// mx::fast::scaled_dot_product_attention(Q, K, V, scale, mask_mode, mask_arrs) |
| 129 | +// ----------------------------------------------------------------- |
| 130 | +// |
| 131 | +// Computes `softmax((Q @ Kᵀ) * scale + mask) @ V` as a single fused |
| 132 | +// kernel over `[B, H, S, D]` inputs. |
| 133 | +// |
| 134 | +// `mask_mode` is the empty string, `"causal"`, or `"array"`: |
| 135 | +// - `""` — no mask. |
| 136 | +// - `"causal"` — upper-triangular -inf mask (no additional arrays). |
| 137 | +// - `"array"` — `mask_arrs` holds one broadcastable additive bias |
| 138 | +// tensor (Bumblebee's `bias = select(mask, 0, -inf)` |
| 139 | +// materialises this). |
| 140 | +// |
| 141 | +// MLX supports a handful of other modes (block-sparse etc.) — out of |
| 142 | +// scope for M11; add them when a model asks. |
| 143 | +fine::ResourcePtr<Tensor> fast_scaled_dot_product_attention( |
| 144 | + ErlNifEnv *, |
| 145 | + fine::ResourcePtr<Tensor> q, |
| 146 | + fine::ResourcePtr<Tensor> k, |
| 147 | + fine::ResourcePtr<Tensor> v, |
| 148 | + double scale, |
| 149 | + std::string mask_mode, |
| 150 | + std::vector<fine::ResourcePtr<Tensor>> mask_arrs) { |
| 151 | + return wrap(mx::fast::scaled_dot_product_attention( |
| 152 | + q->array, |
| 153 | + k->array, |
| 154 | + v->array, |
| 155 | + static_cast<float>(scale), |
| 156 | + mask_mode, |
| 157 | + unwrap_all(mask_arrs))); |
| 158 | +} |
| 159 | +FINE_NIF(fast_scaled_dot_product_attention, 0); |
| 160 | + |
| 161 | +} // namespace |
0 commit comments