rlx-metal 0.2.2

Metal backend for RLX — Apple Silicon GPU via Metal Performance Shaders + custom MSL kernels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// RLX — versatile ML compiler + runtime.
// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! GPU sgemm via custom MSL kernel.
//!
//! Initial impl uses our tiled MSL kernel (see kernels.rs::sgemm_tiled).
//! Future: bridge MPSMatrixMultiplication for Apple's optimized matmul
//! when matrices are large enough to amortize objc bridging cost.

use crate::cost::{SgemmVariant, hw_model};
use crate::device::metal_device;
use crate::kernels::kernels;
use metal::{Buffer, ComputeCommandEncoderRef, MTLSize};

/// C = A @ B via custom MSL kernel. Issues set_pipeline+dispatch on a shared
/// compute encoder; caller is responsible for encoder lifecycle.
pub fn metal_sgemm(
    enc: &ComputeCommandEncoderRef,
    arena: &Buffer,
    a_off: usize,
    b_off: usize,
    c_off: usize,
    m: usize,
    k: usize,
    n: usize,
) {
    let kk = kernels();
    let m_u = m as u32;
    let k_u = k as u32;
    let n_u = n as u32;
    enc.set_buffer(0, Some(arena), a_off as u64);
    enc.set_buffer(1, Some(arena), b_off as u64);
    enc.set_buffer(2, Some(arena), c_off as u64);
    enc.set_bytes(
        3,
        std::mem::size_of::<u32>() as u64,
        &m_u as *const _ as *const _,
    );
    enc.set_bytes(
        4,
        std::mem::size_of::<u32>() as u64,
        &k_u as *const _ as *const _,
    );
    enc.set_bytes(
        5,
        std::mem::size_of::<u32>() as u64,
        &n_u as *const _ as *const _,
    );

    match hw_model().pick_sgemm(m, k, n) {
        SgemmVariant::Mps => {
            // Should never be hit on the in-encoder path: encode_and_run splits
            // the encoder around MPS dispatches and routes to the cmd-buffer
            // variant directly. Fall back to simd_4x4 if a caller bypasses it.
            enc.set_compute_pipeline_state(&kk.sgemm_simd_4x4);
            let tg_count = MTLSize {
                width: n.div_ceil(32) as u64,
                height: m.div_ceil(32) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 512,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::Simd4x4 => {
            enc.set_compute_pipeline_state(&kk.sgemm_simd_4x4);
            let tg_count = MTLSize {
                width: n.div_ceil(32) as u64,
                height: m.div_ceil(32) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 512,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::Simd => {
            enc.set_compute_pipeline_state(&kk.sgemm_simd);
            let tg_count = MTLSize {
                width: n.div_ceil(8) as u64,
                height: m.div_ceil(8) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 32,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::SimdPadded => {
            enc.set_compute_pipeline_state(&kk.sgemm_simd_padded);
            let tg_count = MTLSize {
                width: n.div_ceil(8) as u64,
                height: m.div_ceil(8) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 32,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::Tiled => {
            enc.set_compute_pipeline_state(&kk.sgemm_tiled);
            let grid_w = n.div_ceil(16) * 16;
            let grid_h = m.div_ceil(16) * 16;
            let grid = MTLSize {
                width: grid_w as u64,
                height: grid_h as u64,
                depth: 1,
            };
            enc.dispatch_threads(
                grid,
                MTLSize {
                    width: 16,
                    height: 16,
                    depth: 1,
                },
            );
        }
        SgemmVariant::Naive => {
            enc.set_compute_pipeline_state(&kk.sgemm);
            let grid = MTLSize {
                width: n as u64,
                height: m as u64,
                depth: 1,
            };
            let tg_w = 16u64.min(n as u64);
            let tg_h = 16u64.min(m as u64);
            enc.dispatch_threads(
                grid,
                MTLSize {
                    width: tg_w,
                    height: tg_h,
                    depth: 1,
                },
            );
        }
    }
}

/// Activation kind passed to fused matmul kernels.
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum FusedAct {
    None = 0,
    Gelu = 1,
    Silu = 2,
}

/// C = A @ B + bias [+ activation], dispatched as a single MSL kernel.
/// Halves kernel count compared to separate sgemm + bias_add + activation.
pub fn metal_sgemm_bias(
    enc: &ComputeCommandEncoderRef,
    arena: &Buffer,
    a_off: usize,
    b_off: usize,
    bias_off: usize,
    c_off: usize,
    m: usize,
    k: usize,
    n: usize,
    act: FusedAct,
) {
    let kk = kernels();

    let m_u = m as u32;
    let k_u = k as u32;
    let n_u = n as u32;
    let act_u = act as u32;

    match hw_model().pick_sgemm(m, k, n) {
        SgemmVariant::Simd4x4 => {
            enc.set_buffer(0, Some(arena), a_off as u64);
            enc.set_buffer(1, Some(arena), b_off as u64);
            enc.set_buffer(2, Some(arena), bias_off as u64);
            enc.set_buffer(3, Some(arena), c_off as u64);
            enc.set_bytes(4, 4, &m_u as *const _ as *const _);
            enc.set_bytes(5, 4, &k_u as *const _ as *const _);
            enc.set_bytes(6, 4, &n_u as *const _ as *const _);
            enc.set_bytes(7, 4, &act_u as *const _ as *const _);
            enc.set_compute_pipeline_state(&kk.sgemm_simd_4x4_bias);
            let tg_count = MTLSize {
                width: n.div_ceil(32) as u64,
                height: m.div_ceil(32) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 512,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::Simd => {
            enc.set_buffer(0, Some(arena), a_off as u64);
            enc.set_buffer(1, Some(arena), b_off as u64);
            enc.set_buffer(2, Some(arena), bias_off as u64);
            enc.set_buffer(3, Some(arena), c_off as u64);
            enc.set_bytes(4, 4, &m_u as *const _ as *const _);
            enc.set_bytes(5, 4, &k_u as *const _ as *const _);
            enc.set_bytes(6, 4, &n_u as *const _ as *const _);
            enc.set_bytes(7, 4, &act_u as *const _ as *const _);
            enc.set_compute_pipeline_state(&kk.sgemm_simd_bias);
            let tg_count = MTLSize {
                width: n.div_ceil(8) as u64,
                height: m.div_ceil(8) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 32,
                    height: 1,
                    depth: 1,
                },
            );
        }
        SgemmVariant::SimdPadded => {
            enc.set_buffer(0, Some(arena), a_off as u64);
            enc.set_buffer(1, Some(arena), b_off as u64);
            enc.set_buffer(2, Some(arena), bias_off as u64);
            enc.set_buffer(3, Some(arena), c_off as u64);
            enc.set_bytes(4, 4, &m_u as *const _ as *const _);
            enc.set_bytes(5, 4, &k_u as *const _ as *const _);
            enc.set_bytes(6, 4, &n_u as *const _ as *const _);
            enc.set_bytes(7, 4, &act_u as *const _ as *const _);
            enc.set_compute_pipeline_state(&kk.sgemm_simd_padded_bias);
            let tg_count = MTLSize {
                width: n.div_ceil(8) as u64,
                height: m.div_ceil(8) as u64,
                depth: 1,
            };
            enc.dispatch_thread_groups(
                tg_count,
                MTLSize {
                    width: 32,
                    height: 1,
                    depth: 1,
                },
            );
        }
        // Tiled / Naive variants don't have bias-fused versions yet.
        // Fall back to plain sgemm + separate bias_add (and activation) on the
        // same encoder.
        _ => {
            metal_sgemm(enc, arena, a_off, b_off, c_off, m, k, n);
            enc.set_compute_pipeline_state(&kk.bias_add);
            enc.set_buffer(0, Some(arena), c_off as u64);
            enc.set_buffer(1, Some(arena), bias_off as u64);
            enc.set_bytes(2, 4, &m_u as *const _ as *const _);
            enc.set_bytes(3, 4, &n_u as *const _ as *const _);
            let grid = MTLSize {
                width: n as u64,
                height: m as u64,
                depth: 1,
            };
            let tg = MTLSize {
                width: 16u64.min(n as u64),
                height: 16u64.min(m as u64),
                depth: 1,
            };
            enc.dispatch_threads(grid, tg);

            if !matches!(act, FusedAct::None) {
                let pipeline = match act {
                    FusedAct::Gelu => &kk.gelu_inplace,
                    FusedAct::Silu => &kk.silu_inplace,
                    FusedAct::None => unreachable!(),
                };
                enc.set_compute_pipeline_state(pipeline);
                enc.set_buffer(0, Some(arena), c_off as u64);
                let len = (m * n) as u32;
                enc.set_bytes(1, 4, &len as *const _ as *const _);
                let tg_w = pipeline.thread_execution_width().min(len as u64);
                enc.dispatch_threads(
                    MTLSize {
                        width: len as u64,
                        height: 1,
                        depth: 1,
                    },
                    MTLSize {
                        width: tg_w,
                        height: 1,
                        depth: 1,
                    },
                );
            }
        }
    }
}

/// Half-precision matmul (no bias). Uses simdgroup_half8x8 tensor units.
/// Requires M%32==K%32==N%32==0 for the tiled variant.
/// TODO: padded f16 variants for arbitrary dims; currently undefined behavior
/// for misaligned shapes (writes past output buffer).
pub fn metal_hgemm(
    enc: &ComputeCommandEncoderRef,
    arena: &Buffer,
    a_off: usize,
    b_off: usize,
    c_off: usize,
    m: usize,
    k: usize,
    n: usize,
) {
    let kk = kernels();
    let m_u = m as u32;
    let k_u = k as u32;
    let n_u = n as u32;
    enc.set_buffer(0, Some(arena), a_off as u64);
    enc.set_buffer(1, Some(arena), b_off as u64);
    enc.set_buffer(2, Some(arena), c_off as u64);
    enc.set_bytes(3, 4, &m_u as *const _ as *const _);
    enc.set_bytes(4, 4, &k_u as *const _ as *const _);
    enc.set_bytes(5, 4, &n_u as *const _ as *const _);
    enc.set_compute_pipeline_state(&kk.hgemm_simd_4x4);
    let tg_count = MTLSize {
        width: n.div_ceil(32) as u64,
        height: m.div_ceil(32) as u64,
        depth: 1,
    };
    enc.dispatch_thread_groups(
        tg_count,
        MTLSize {
            width: 512,
            height: 1,
            depth: 1,
        },
    );
}

/// Half-precision matmul + bias + activation fused.
pub fn metal_hgemm_bias(
    enc: &ComputeCommandEncoderRef,
    arena: &Buffer,
    a_off: usize,
    b_off: usize,
    bias_off: usize,
    c_off: usize,
    m: usize,
    k: usize,
    n: usize,
    act: FusedAct,
) {
    let kk = kernels();
    let m_u = m as u32;
    let k_u = k as u32;
    let n_u = n as u32;
    let act_u = act as u32;
    enc.set_buffer(0, Some(arena), a_off as u64);
    enc.set_buffer(1, Some(arena), b_off as u64);
    enc.set_buffer(2, Some(arena), bias_off as u64);
    enc.set_buffer(3, Some(arena), c_off as u64);
    enc.set_bytes(4, 4, &m_u as *const _ as *const _);
    enc.set_bytes(5, 4, &k_u as *const _ as *const _);
    enc.set_bytes(6, 4, &n_u as *const _ as *const _);
    enc.set_bytes(7, 4, &act_u as *const _ as *const _);
    enc.set_compute_pipeline_state(&kk.hgemm_simd_4x4_bias);
    let tg_count = MTLSize {
        width: n.div_ceil(32) as u64,
        height: m.div_ceil(32) as u64,
        depth: 1,
    };
    enc.dispatch_thread_groups(
        tg_count,
        MTLSize {
            width: 512,
            height: 1,
            depth: 1,
        },
    );
}

/// Helper: create a new command buffer from the global queue.
pub fn new_command_buffer() -> metal::CommandBuffer {
    let dev = metal_device().expect("Metal device required");
    dev.queue.new_command_buffer().to_owned()
}