maurograd-mlx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 68962c92d0506a93b0fa0ac2227fec011f35530f830731c22916b0b90c48e11a
4
+ data.tar.gz: 0b1bd6df9822c79e3cd424a8b24d25b96549e60dcee588a18c6a4345325125f1
5
+ SHA512:
6
+ metadata.gz: ccce90e8017c0bb1471a351d18843c75ff25c35cd7a92fba2eee49d87676514ec2e6269007eb6a9362a018506c06a4abf5d8defb8df2b28445a81d5ecc51a118
7
+ data.tar.gz: e7accadef9bb9202d442a27b9886ed2719aec3de6b1f19e9b9939771b44330bb457365193eed5c239c7bb822f545c1165fcb8d6bd0cf02ebd103e46189229aec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Mauro Tortonesi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,44 @@
1
+ require "mkmf"
2
+ require "rubygems"
3
+
4
+ # Optional extension: Ruby bindings for mlx-c, used by the MLX backend
5
+ # (lib/maurograd/backends/mlx.rb). Only buildable where mlx-c is installed
6
+ # (macOS: `brew install mlx-c`); bin/build_ext skips it otherwise.
7
+
8
+ extension_name = "maurograd_mlx"
9
+
10
+ # Numo NArray headers (same lookup as maurograd_ext).
11
+ begin
12
+ spec = Gem::Specification.find_by_name("numo-narray-alt")
13
+ rescue Gem::LoadError => e
14
+ abort "numo-narray-alt not found, and its headers are needed to compile (#{e.class}: #{e.message}; gem search path: #{Gem.path.join(File::PATH_SEPARATOR)})"
15
+ end
16
+ hdr = Dir[File.join(spec.full_gem_path, "**", "numo", "narray.h")].then do |c|
17
+ c.find { |p| p.include?("/ext/") } || c.first
18
+ end
19
+ abort "Could not locate numo/narray.h inside #{spec.full_gem_path}" unless hdr
20
+ $INCFLAGS << " -I#{File.dirname(hdr, 2)}"
21
+ have_header("numo/narray.h") or abort "numo/narray.h not found even after adding include path"
22
+
23
+ # mlx-c: MLX_C_DIR=<prefix> selects it explicitly; otherwise ask Homebrew.
24
+ mlx_c_dir = ENV["MLX_C_DIR"]
25
+ if mlx_c_dir.nil?
26
+ brew = begin
27
+ `brew --prefix mlx-c 2>/dev/null`.strip
28
+ rescue
29
+ ""
30
+ end
31
+ mlx_c_dir = brew unless brew.empty?
32
+ end
33
+ abort "mlx-c not found (install it with `brew install mlx-c`, or set MLX_C_DIR)" unless mlx_c_dir && File.directory?(mlx_c_dir)
34
+
35
+ mlx_inc = File.join(mlx_c_dir, "include")
36
+ mlx_lib = File.join(mlx_c_dir, "lib")
37
+ $INCFLAGS << " -I#{mlx_inc}"
38
+ $LDFLAGS << " -L#{mlx_lib} -Wl,-rpath,#{mlx_lib}"
39
+ $CFLAGS << " -O2 -std=c11"
40
+
41
+ have_header("mlx/c/mlx.h") or abort "mlx/c/mlx.h not found under #{mlx_inc}"
42
+ have_library("mlxc") or abort "libmlxc not found under #{mlx_lib}"
43
+
44
+ create_makefile(extension_name)
@@ -0,0 +1,673 @@
1
+ /*
2
+ * maurograd_mlx: Ruby bindings for the subset of mlx-c (the C API of Apple's
3
+ * MLX array framework) that Maurograd's MLX backend needs.
4
+ *
5
+ * - Maurograd::MLX::Array wraps one mlx_array. Ruby's GC owns the wrapper
6
+ * and releases the mlx_array when the wrapper is collected. Arithmetic
7
+ * operators (+ - * / ** and unary -) work between arrays and with Ruby
8
+ * Numerics on either side, as the backend contract requires.
9
+ * - Module functions on Maurograd::MLX expose the MLX primitives used by
10
+ * lib/maurograd/backends/mlx.rb, plus conversion to/from Numo arrays,
11
+ * evaluation, and vjp (vector-Jacobian product) of a Ruby block.
12
+ *
13
+ * MLX is lazy: operations only record a graph, and computation happens
14
+ * when an array is evaluated (MLX.eval, or reading it back with to_numo).
15
+ *
16
+ * Errors: MLX reports failures through an error handler plus a non-zero
17
+ * return code. We install a handler that only records the message; every
18
+ * call checks the code and raises Maurograd::MLX::Error from plain C. We
19
+ * never raise (longjmp) from inside a callback MLX's C++ code is running.
20
+ */
21
+ #include "ruby.h"
22
+ #include "numo/narray.h"
23
+ #include "mlx/c/mlx.h"
24
+
25
+ #include <stdio.h>
26
+ #include <string.h>
27
+
28
+ static VALUE mMaurograd, mMLX, cArray, eMLXError;
29
+ static VALUE cSFloat, cInt32;
30
+
31
+ static mlx_stream g_stream; /* stream of the current device */
32
+ static int g_gpu; /* 1 if the current device is the GPU */
33
+
34
+ /* ---------- error handling ---------- */
35
+
36
+ static char g_err[2048];
37
+ static int g_err_set;
38
+
39
+ static void on_mlx_error(const char *msg, void *data)
40
+ {
41
+ (void)data;
42
+ snprintf(g_err, sizeof(g_err), "%s", msg ? msg : "unknown MLX error");
43
+ g_err_set = 1;
44
+ }
45
+
46
+ NORETURN(static void raise_mlx(const char *what));
47
+ static void raise_mlx(const char *what)
48
+ {
49
+ if (g_err_set) {
50
+ g_err_set = 0;
51
+ rb_raise(eMLXError, "%s: %s", what, g_err);
52
+ }
53
+ rb_raise(eMLXError, "%s failed", what);
54
+ }
55
+
56
+ /* ---------- Array wrapper ---------- */
57
+
58
+ typedef struct {
59
+ mlx_array a;
60
+ size_t accounted; /* bytes reported to Ruby's GC */
61
+ } mg_array;
62
+
63
+ static void array_free(void *p)
64
+ {
65
+ mg_array *w = (mg_array *)p;
66
+ if (w->a.ctx) mlx_array_free(w->a);
67
+ if (w->accounted) rb_gc_adjust_memory_usage(-(ssize_t)w->accounted);
68
+ xfree(w);
69
+ }
70
+
71
+ static size_t array_memsize(const void *p)
72
+ {
73
+ const mg_array *w = (const mg_array *)p;
74
+ return sizeof(*w) + w->accounted;
75
+ }
76
+
77
+ static const rb_data_type_t array_type = {
78
+ "Maurograd::MLX::Array",
79
+ { 0, array_free, array_memsize, },
80
+ 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
81
+ };
82
+
83
+ static VALUE array_alloc(VALUE klass)
84
+ {
85
+ mg_array *w;
86
+ VALUE obj = TypedData_Make_Struct(klass, mg_array, &array_type, w);
87
+ w->a = mlx_array_new();
88
+ w->accounted = 0;
89
+ return obj;
90
+ }
91
+
92
+ /* Wraps `a`, taking ownership of it. Tells Ruby's GC about the memory the
93
+ * array will use, so that GC runs often enough to release device buffers
94
+ * (Ruby can't see them otherwise and would let them pile up). */
95
+ static VALUE wrap(mlx_array a)
96
+ {
97
+ VALUE obj = array_alloc(cArray);
98
+ mg_array *w;
99
+ TypedData_Get_Struct(obj, mg_array, &array_type, w);
100
+ w->a = a;
101
+ w->accounted = mlx_array_nbytes(a);
102
+ if (w->accounted) rb_gc_adjust_memory_usage((ssize_t)w->accounted);
103
+ return obj;
104
+ }
105
+
106
+ static int is_array(VALUE v)
107
+ {
108
+ return rb_typeddata_is_kind_of(v, &array_type);
109
+ }
110
+
111
+ /* Borrowed mlx_array of a wrapper (raises TypeError otherwise). */
112
+ static mlx_array get(VALUE v)
113
+ {
114
+ mg_array *w;
115
+ TypedData_Get_Struct(v, mg_array, &array_type, w);
116
+ return w->a;
117
+ }
118
+
119
+ /* Array or Numeric argument. Sets *out; returns 1 if the caller owns (and
120
+ * must free) it, i.e. if it was created from a Numeric. Scalars become
121
+ * float32, so they never promote float32 arrays to float64. */
122
+ static int arg_array(VALUE v, mlx_array *out)
123
+ {
124
+ if (is_array(v)) {
125
+ *out = get(v);
126
+ return 0;
127
+ }
128
+ if (RB_FLOAT_TYPE_P(v) || RB_INTEGER_TYPE_P(v)) {
129
+ *out = mlx_array_new_float((float)NUM2DBL(v));
130
+ return 1;
131
+ }
132
+ rb_raise(rb_eTypeError, "expected Maurograd::MLX::Array or Numeric, got %s", rb_obj_classname(v));
133
+ return 0;
134
+ }
135
+
136
+ /* Converts a Ruby Array of Integers into a C int array (max 16 entries). */
137
+ static size_t int_list(VALUE ary, int *out, size_t cap, const char *what)
138
+ {
139
+ Check_Type(ary, T_ARRAY);
140
+ size_t n = (size_t)RARRAY_LEN(ary);
141
+ if (n > cap) rb_raise(rb_eArgError, "too many %s (max %zu)", what, cap);
142
+ for (size_t i = 0; i < n; i++) out[i] = NUM2INT(rb_ary_entry(ary, (long)i));
143
+ return n;
144
+ }
145
+
146
+ typedef int (*binary_fn)(mlx_array *, const mlx_array, const mlx_array, const mlx_stream);
147
+ typedef int (*unary_fn)(mlx_array *, const mlx_array, const mlx_stream);
148
+
149
+ static VALUE binary(VALUE va, VALUE vb, binary_fn f, const char *what)
150
+ {
151
+ mlx_array a, b;
152
+ int own_a = arg_array(va, &a);
153
+ int own_b = arg_array(vb, &b);
154
+ mlx_array r = mlx_array_new();
155
+ int rc = f(&r, a, b, g_stream);
156
+ if (own_a) mlx_array_free(a);
157
+ if (own_b) mlx_array_free(b);
158
+ if (rc) { mlx_array_free(r); raise_mlx(what); }
159
+ return wrap(r);
160
+ }
161
+
162
+ static VALUE unary(VALUE va, unary_fn f, const char *what)
163
+ {
164
+ mlx_array r = mlx_array_new();
165
+ if (f(&r, get(va), g_stream)) { mlx_array_free(r); raise_mlx(what); }
166
+ return wrap(r);
167
+ }
168
+
169
+ static VALUE astype(mlx_array a, mlx_dtype dt)
170
+ {
171
+ mlx_array r = mlx_array_new();
172
+ if (mlx_astype(&r, a, dt, g_stream)) { mlx_array_free(r); raise_mlx("astype"); }
173
+ return wrap(r);
174
+ }
175
+
176
+ /* Comparison results are bool in MLX; the backend wants float 0/1. */
177
+ static VALUE compare_as_float(VALUE va, VALUE vb, binary_fn f, const char *what)
178
+ {
179
+ VALUE b = binary(va, vb, f, what);
180
+ return astype(get(b), MLX_FLOAT32);
181
+ }
182
+
183
+ /* ---------- Array methods ---------- */
184
+
185
+ static VALUE arr_add(VALUE self, VALUE o) { return binary(self, o, mlx_add, "add"); }
186
+ static VALUE arr_sub(VALUE self, VALUE o) { return binary(self, o, mlx_subtract, "subtract"); }
187
+ static VALUE arr_mul(VALUE self, VALUE o) { return binary(self, o, mlx_multiply, "multiply"); }
188
+ static VALUE arr_div(VALUE self, VALUE o) { return binary(self, o, mlx_divide, "divide"); }
189
+ static VALUE arr_pow(VALUE self, VALUE o) { return binary(self, o, mlx_power, "power"); }
190
+ static VALUE arr_neg(VALUE self) { return unary(self, mlx_negative, "negative"); }
191
+
192
+ /* `2.0 * arr`: Float#* calls arr.coerce(2.0) and retries as scalar * arr. */
193
+ static VALUE arr_coerce(VALUE self, VALUE other)
194
+ {
195
+ mlx_array s;
196
+ arg_array(other, &s); /* Numeric -> new float32 scalar array */
197
+ return rb_assoc_new(wrap(s), self);
198
+ }
199
+
200
+ static VALUE arr_shape(VALUE self)
201
+ {
202
+ mlx_array a = get(self);
203
+ size_t nd = mlx_array_ndim(a);
204
+ const int *sh = mlx_array_shape(a);
205
+ VALUE ary = rb_ary_new_capa((long)nd);
206
+ for (size_t i = 0; i < nd; i++) rb_ary_push(ary, INT2NUM(sh[i]));
207
+ return ary;
208
+ }
209
+
210
+ static VALUE arr_size(VALUE self) { return SIZET2NUM(mlx_array_size(get(self))); }
211
+
212
+ static VALUE arr_dtype(VALUE self)
213
+ {
214
+ switch (mlx_array_dtype(get(self))) {
215
+ case MLX_FLOAT32: return ID2SYM(rb_intern("float32"));
216
+ case MLX_INT32: return ID2SYM(rb_intern("int32"));
217
+ case MLX_BOOL: return ID2SYM(rb_intern("bool"));
218
+ default: return ID2SYM(rb_intern("other"));
219
+ }
220
+ }
221
+
222
+ /* ---------- conversion ---------- */
223
+
224
+ static VALUE mlx_from_numo(VALUE self, VALUE vna)
225
+ {
226
+ mlx_dtype dt;
227
+ if (rb_obj_is_kind_of(vna, cSFloat)) dt = MLX_FLOAT32;
228
+ else if (rb_obj_is_kind_of(vna, cInt32)) dt = MLX_INT32;
229
+ else rb_raise(rb_eTypeError, "from_numo needs a Numo::SFloat or Numo::Int32");
230
+ if (!RTEST(na_check_contiguous(vna))) rb_raise(rb_eArgError, "from_numo needs a contiguous array");
231
+
232
+ narray_t *na;
233
+ GetNArray(vna, na);
234
+ int shape[16];
235
+ if (na->ndim > 16) rb_raise(rb_eArgError, "too many dimensions");
236
+ for (int i = 0; i < na->ndim; i++) shape[i] = (int)na->shape[i];
237
+
238
+ const void *ptr = na_get_pointer_for_read(vna);
239
+ /* mlx_array_new_data copies the buffer, so the Numo array can go away. */
240
+ mlx_array a = mlx_array_new_data(ptr, shape, na->ndim, dt);
241
+ RB_GC_GUARD(vna);
242
+ return wrap(a);
243
+ }
244
+
245
+ /* Evaluates `va` and copies it into a new Numo array (SFloat, or Int32 for
246
+ * int32 arrays). Other dtypes are converted to float32 first. */
247
+ static VALUE mlx_to_numo(VALUE self, VALUE va)
248
+ {
249
+ mlx_array a = get(va);
250
+ mlx_dtype dt = mlx_array_dtype(a);
251
+ VALUE keep = Qnil;
252
+ if (dt != MLX_FLOAT32 && dt != MLX_INT32) {
253
+ keep = astype(a, MLX_FLOAT32);
254
+ a = get(keep);
255
+ dt = MLX_FLOAT32;
256
+ }
257
+
258
+ /* Results can be strided views (e.g. after a transpose): make the
259
+ * buffer row-major before reading it. */
260
+ mlx_array c = mlx_array_new();
261
+ if (mlx_contiguous(&c, a, false, g_stream)) { mlx_array_free(c); raise_mlx("contiguous"); }
262
+ VALUE vc = wrap(c);
263
+ if (mlx_array_eval(c)) raise_mlx("eval");
264
+
265
+ size_t nd = mlx_array_ndim(c);
266
+ const int *sh = mlx_array_shape(c);
267
+ size_t shape[16];
268
+ if (nd > 16) rb_raise(rb_eArgError, "too many dimensions");
269
+ for (size_t i = 0; i < nd; i++) shape[i] = (size_t)sh[i];
270
+
271
+ VALUE out = nary_new(dt == MLX_FLOAT32 ? cSFloat : cInt32, (int)nd, shape);
272
+ size_t n = mlx_array_size(c);
273
+ void *dst = na_get_pointer_for_write(out);
274
+ const void *src = (dt == MLX_FLOAT32) ? (const void *)mlx_array_data_float32(c)
275
+ : (const void *)mlx_array_data_int32(c);
276
+ if (n && !src) rb_raise(eMLXError, "could not read array data");
277
+ if (n) memcpy(dst, src, n * 4);
278
+
279
+ RB_GC_GUARD(vc);
280
+ RB_GC_GUARD(keep);
281
+ RB_GC_GUARD(va);
282
+ return out;
283
+ }
284
+
285
+ static VALUE arr_to_numo(VALUE self) { return mlx_to_numo(Qnil, self); }
286
+
287
+ /* ---------- creation, randomness ---------- */
288
+
289
+ static VALUE filled(VALUE vshape, int ones)
290
+ {
291
+ int shape[16];
292
+ size_t n = int_list(vshape, shape, 16, "dimensions");
293
+ mlx_array r = mlx_array_new();
294
+ int rc = ones ? mlx_ones(&r, shape, n, MLX_FLOAT32, g_stream)
295
+ : mlx_zeros(&r, shape, n, MLX_FLOAT32, g_stream);
296
+ if (rc) { mlx_array_free(r); raise_mlx(ones ? "ones" : "zeros"); }
297
+ return wrap(r);
298
+ }
299
+
300
+ static VALUE mlx_zeros_rb(VALUE self, VALUE shape) { return filled(shape, 0); }
301
+ static VALUE mlx_ones_rb(VALUE self, VALUE shape) { return filled(shape, 1); }
302
+
303
+ static VALUE mlx_bernoulli_rb(VALUE self, VALUE vshape, VALUE vp)
304
+ {
305
+ int shape[16];
306
+ size_t n = int_list(vshape, shape, 16, "dimensions");
307
+ mlx_array p = mlx_array_new_float((float)NUM2DBL(vp));
308
+ mlx_array key = { 0 }; /* null: use the global key (see seed) */
309
+ mlx_array r = mlx_array_new();
310
+ int rc = mlx_random_bernoulli(&r, p, shape, n, key, g_stream);
311
+ mlx_array_free(p);
312
+ if (rc) { mlx_array_free(r); raise_mlx("bernoulli"); }
313
+ VALUE b = wrap(r);
314
+ return astype(get(b), MLX_FLOAT32);
315
+ }
316
+
317
+ static VALUE mlx_seed_rb(VALUE self, VALUE n)
318
+ {
319
+ if (mlx_random_seed(NUM2ULL(n))) raise_mlx("seed");
320
+ return n;
321
+ }
322
+
323
+ /* ---------- shape ---------- */
324
+
325
+ static VALUE mlx_reshape_rb(VALUE self, VALUE va, VALUE vshape)
326
+ {
327
+ int shape[16];
328
+ size_t n = int_list(vshape, shape, 16, "dimensions");
329
+ mlx_array r = mlx_array_new();
330
+ if (mlx_reshape(&r, get(va), shape, n, g_stream)) { mlx_array_free(r); raise_mlx("reshape"); }
331
+ return wrap(r);
332
+ }
333
+
334
+ static VALUE mlx_transpose_rb(VALUE self, VALUE va, VALUE vaxes)
335
+ {
336
+ int axes[16];
337
+ size_t n = int_list(vaxes, axes, 16, "axes");
338
+ mlx_array r = mlx_array_new();
339
+ if (mlx_transpose_axes(&r, get(va), axes, n, g_stream)) { mlx_array_free(r); raise_mlx("transpose"); }
340
+ return wrap(r);
341
+ }
342
+
343
+ /* x[start:stop:strides] along every axis. */
344
+ static VALUE mlx_slice_rb(VALUE self, VALUE va, VALUE vstart, VALUE vstop, VALUE vstrides)
345
+ {
346
+ int start[16], stop[16], strides[16];
347
+ size_t n0 = int_list(vstart, start, 16, "start");
348
+ size_t n1 = int_list(vstop, stop, 16, "stop");
349
+ size_t n2 = int_list(vstrides, strides, 16, "strides");
350
+ mlx_array r = mlx_array_new();
351
+ if (mlx_slice(&r, get(va), start, n0, stop, n1, strides, n2, g_stream)) { mlx_array_free(r); raise_mlx("slice"); }
352
+ return wrap(r);
353
+ }
354
+
355
+ /* Stacks a Ruby Array of arrays along a new leading axis. */
356
+ static VALUE mlx_stack_rb(VALUE self, VALUE vlist)
357
+ {
358
+ Check_Type(vlist, T_ARRAY);
359
+ mlx_vector_array v = mlx_vector_array_new();
360
+ for (long i = 0; i < RARRAY_LEN(vlist); i++) mlx_vector_array_append_value(v, get(rb_ary_entry(vlist, i)));
361
+ mlx_array r = mlx_array_new();
362
+ int rc = mlx_stack(&r, v, g_stream);
363
+ mlx_vector_array_free(v);
364
+ if (rc) { mlx_array_free(r); raise_mlx("stack"); }
365
+ return wrap(r);
366
+ }
367
+
368
+ /* Constant padding of the given axes. */
369
+ static VALUE mlx_pad_rb(VALUE self, VALUE va, VALUE vaxes, VALUE vlow, VALUE vhigh, VALUE vvalue)
370
+ {
371
+ int axes[16], low[16], high[16];
372
+ size_t n0 = int_list(vaxes, axes, 16, "axes");
373
+ size_t n1 = int_list(vlow, low, 16, "low");
374
+ size_t n2 = int_list(vhigh, high, 16, "high");
375
+ mlx_array value = mlx_array_new_float((float)NUM2DBL(vvalue));
376
+ mlx_array r = mlx_array_new();
377
+ int rc = mlx_pad(&r, get(va), axes, n0, low, n1, high, n2, value, "constant", g_stream);
378
+ mlx_array_free(value);
379
+ if (rc) { mlx_array_free(r); raise_mlx("pad"); }
380
+ return wrap(r);
381
+ }
382
+
383
+ /* ---------- reductions ---------- */
384
+
385
+ typedef int (*reduce_all_fn)(mlx_array *, const mlx_array, bool, const mlx_stream);
386
+ typedef int (*reduce_axes_fn)(mlx_array *, const mlx_array, const int *, size_t, bool, const mlx_stream);
387
+
388
+ static VALUE reduce(VALUE va, VALUE vaxes, VALUE vkeep, reduce_all_fn all, reduce_axes_fn some, const char *what)
389
+ {
390
+ mlx_array r = mlx_array_new();
391
+ int rc;
392
+ if (NIL_P(vaxes)) {
393
+ rc = all(&r, get(va), RTEST(vkeep), g_stream);
394
+ } else {
395
+ int axes[16];
396
+ size_t n = int_list(rb_Array(vaxes), axes, 16, "axes");
397
+ rc = some(&r, get(va), axes, n, RTEST(vkeep), g_stream);
398
+ }
399
+ if (rc) { mlx_array_free(r); raise_mlx(what); }
400
+ return wrap(r);
401
+ }
402
+
403
+ static VALUE mlx_sum_rb(VALUE self, VALUE a, VALUE axes, VALUE keep) { return reduce(a, axes, keep, mlx_sum, mlx_sum_axes, "sum"); }
404
+ static VALUE mlx_mean_rb(VALUE self, VALUE a, VALUE axes, VALUE keep) { return reduce(a, axes, keep, mlx_mean, mlx_mean_axes, "mean"); }
405
+ static VALUE mlx_max_rb(VALUE self, VALUE a, VALUE axes, VALUE keep) { return reduce(a, axes, keep, mlx_max, mlx_max_axes, "max"); }
406
+
407
+ /* ---------- elementwise / linear algebra ---------- */
408
+
409
+ static VALUE mlx_exp_rb(VALUE self, VALUE a) { return unary(a, mlx_exp, "exp"); }
410
+ static VALUE mlx_log_rb(VALUE self, VALUE a) { return unary(a, mlx_log, "log"); }
411
+ static VALUE mlx_sqrt_rb(VALUE self, VALUE a) { return unary(a, mlx_sqrt, "sqrt"); }
412
+ static VALUE mlx_maximum_rb(VALUE self, VALUE a, VALUE b) { return binary(a, b, mlx_maximum, "maximum"); }
413
+ static VALUE mlx_greater_rb(VALUE self, VALUE a, VALUE b) { return compare_as_float(a, b, mlx_greater, "greater"); }
414
+ static VALUE mlx_equal_rb(VALUE self, VALUE a, VALUE b) { return compare_as_float(a, b, mlx_equal, "equal"); }
415
+ static VALUE mlx_matmul_rb(VALUE self, VALUE a, VALUE b) { return binary(a, b, mlx_matmul, "matmul"); }
416
+
417
+ /* Index of the first maximum along `axis` (int32). */
418
+ static VALUE mlx_argmax_rb(VALUE self, VALUE va, VALUE vaxis)
419
+ {
420
+ mlx_array r = mlx_array_new();
421
+ if (mlx_argmax_axis(&r, get(va), NUM2INT(vaxis), false, g_stream)) { mlx_array_free(r); raise_mlx("argmax"); }
422
+ VALUE idx = wrap(r);
423
+ return astype(get(idx), MLX_INT32);
424
+ }
425
+
426
+ /* [0, 1, ..., n-1] as int32. */
427
+ static VALUE mlx_arange_rb(VALUE self, VALUE vn)
428
+ {
429
+ mlx_array r = mlx_array_new();
430
+ if (mlx_arange(&r, 0, NUM2INT(vn), 1, MLX_INT32, g_stream)) { mlx_array_free(r); raise_mlx("arange"); }
431
+ return wrap(r);
432
+ }
433
+
434
+ /* Float [N, C] one-hot rows: (indices[:, None] == arange(C)). */
435
+ static VALUE mlx_one_hot_rb(VALUE self, VALUE vidx, VALUE vc)
436
+ {
437
+ VALUE idx = astype(get(vidx), MLX_INT32);
438
+ mlx_array col = mlx_array_new();
439
+ if (mlx_expand_dims(&col, get(idx), 1, g_stream)) { mlx_array_free(col); raise_mlx("expand_dims"); }
440
+ VALUE vcol = wrap(col);
441
+ mlx_array range = mlx_array_new();
442
+ if (mlx_arange(&range, 0, NUM2INT(vc), 1, MLX_INT32, g_stream)) { mlx_array_free(range); raise_mlx("arange"); }
443
+ VALUE vrange = wrap(range);
444
+ VALUE out = compare_as_float(vcol, vrange, mlx_equal, "equal");
445
+ RB_GC_GUARD(idx);
446
+ return out;
447
+ }
448
+
449
+ /* Channels-last convolution: x [N,H,W,C], w [Cout,KH,KW,C] -> [N,OH,OW,Cout]. */
450
+ static VALUE mlx_conv2d_rb(VALUE self, VALUE vx, VALUE vw, VALUE vstride, VALUE vpad)
451
+ {
452
+ int s = NUM2INT(vstride), p = NUM2INT(vpad);
453
+ mlx_array r = mlx_array_new();
454
+ if (mlx_conv2d(&r, get(vx), get(vw), s, s, p, p, 1, 1, 1, g_stream)) { mlx_array_free(r); raise_mlx("conv2d"); }
455
+ return wrap(r);
456
+ }
457
+
458
+ /* ---------- evaluation ---------- */
459
+
460
+ static mlx_vector_array vector_of(VALUE list)
461
+ {
462
+ Check_Type(list, T_ARRAY);
463
+ mlx_vector_array v = mlx_vector_array_new();
464
+ for (long i = 0; i < RARRAY_LEN(list); i++) {
465
+ VALUE e = rb_ary_entry(list, i);
466
+ if (!NIL_P(e)) mlx_vector_array_append_value(v, get(e));
467
+ }
468
+ return v;
469
+ }
470
+
471
+ /* Computes every array in the list now. */
472
+ static VALUE mlx_eval_rb(VALUE self, VALUE list)
473
+ {
474
+ mlx_vector_array v = vector_of(list);
475
+ int rc = mlx_eval(v);
476
+ mlx_vector_array_free(v);
477
+ if (rc) raise_mlx("eval");
478
+ return Qnil;
479
+ }
480
+
481
+ /* Schedules the computation of every array in the list, without waiting. */
482
+ static VALUE mlx_async_eval_rb(VALUE self, VALUE list)
483
+ {
484
+ mlx_vector_array v = vector_of(list);
485
+ int rc = mlx_async_eval(v);
486
+ mlx_vector_array_free(v);
487
+ if (rc) raise_mlx("async_eval");
488
+ return Qnil;
489
+ }
490
+
491
+ /* ---------- vjp of a Ruby block ---------- */
492
+
493
+ /*
494
+ * MLX.vjp(primals, cotangents) { |*xs| outputs } -> gradients
495
+ *
496
+ * Runs MLX's reverse-mode differentiation of the function the block
497
+ * defines: the block receives one MLX::Array per primal and returns an
498
+ * Array of outputs; the result holds d(sum(outputs * cotangents))/d(primal)
499
+ * for each primal. The block runs synchronously, on this thread, while MLX
500
+ * traces it inside mlx_vjp, so calling Ruby is safe there; exceptions are
501
+ * caught with rb_protect and re-raised after MLX has returned.
502
+ */
503
+ typedef struct {
504
+ VALUE block;
505
+ int state; /* Ruby exception state from the block, if any */
506
+ int bad; /* block returned something that isn't Array of MLX::Array */
507
+ } vjp_payload;
508
+
509
+ static VALUE call_block(VALUE args)
510
+ {
511
+ return rb_proc_call(rb_ary_entry(args, 0), rb_ary_entry(args, 1));
512
+ }
513
+
514
+ static int vjp_closure(mlx_vector_array *res, const mlx_vector_array in, void *payload)
515
+ {
516
+ vjp_payload *p = (vjp_payload *)payload;
517
+ size_t n = mlx_vector_array_size(in);
518
+ VALUE inputs = rb_ary_new_capa((long)n);
519
+ for (size_t i = 0; i < n; i++) {
520
+ mlx_array a = mlx_array_new();
521
+ mlx_vector_array_get(&a, in, i);
522
+ rb_ary_push(inputs, wrap(a));
523
+ }
524
+
525
+ VALUE args = rb_assoc_new(p->block, inputs);
526
+ int state = 0;
527
+ VALUE out = rb_protect(call_block, args, &state);
528
+ if (state) { p->state = state; return 1; }
529
+
530
+ if (!RB_TYPE_P(out, T_ARRAY)) { p->bad = 1; return 1; }
531
+ mlx_vector_array v = mlx_vector_array_new();
532
+ for (long i = 0; i < RARRAY_LEN(out); i++) {
533
+ VALUE e = rb_ary_entry(out, i);
534
+ if (!is_array(e)) { mlx_vector_array_free(v); p->bad = 1; return 1; }
535
+ mlx_vector_array_append_value(v, get(e));
536
+ }
537
+ mlx_vector_array_set(res, v);
538
+ mlx_vector_array_free(v);
539
+ RB_GC_GUARD(inputs);
540
+ RB_GC_GUARD(out);
541
+ return 0;
542
+ }
543
+
544
+ static VALUE mlx_vjp_rb(VALUE self, VALUE vprimals, VALUE vcotangents)
545
+ {
546
+ if (!rb_block_given_p()) rb_raise(rb_eArgError, "vjp needs a block");
547
+ vjp_payload payload = { rb_block_proc(), 0, 0 };
548
+
549
+ mlx_closure fn = mlx_closure_new_func_payload(vjp_closure, &payload, NULL);
550
+ mlx_vector_array primals = vector_of(vprimals);
551
+ mlx_vector_array cotangents = vector_of(vcotangents);
552
+ mlx_vector_array outs = mlx_vector_array_new();
553
+ mlx_vector_array grads = mlx_vector_array_new();
554
+
555
+ int rc = mlx_vjp(&outs, &grads, fn, primals, cotangents);
556
+
557
+ mlx_closure_free(fn);
558
+ mlx_vector_array_free(primals);
559
+ mlx_vector_array_free(cotangents);
560
+ mlx_vector_array_free(outs);
561
+
562
+ if (payload.state) { mlx_vector_array_free(grads); g_err_set = 0; rb_jump_tag(payload.state); }
563
+ if (payload.bad) { mlx_vector_array_free(grads); g_err_set = 0; rb_raise(rb_eTypeError, "vjp block must return an Array of Maurograd::MLX::Array"); }
564
+ if (rc) { mlx_vector_array_free(grads); raise_mlx("vjp"); }
565
+
566
+ size_t n = mlx_vector_array_size(grads);
567
+ VALUE result = rb_ary_new_capa((long)n);
568
+ for (size_t i = 0; i < n; i++) {
569
+ mlx_array g = mlx_array_new();
570
+ mlx_vector_array_get(&g, grads, i);
571
+ rb_ary_push(result, wrap(g));
572
+ }
573
+ mlx_vector_array_free(grads);
574
+ RB_GC_GUARD(payload.block);
575
+ return result;
576
+ }
577
+
578
+ /* ---------- device ---------- */
579
+
580
+ static void set_device(int gpu)
581
+ {
582
+ mlx_device dev = mlx_device_new_type(gpu ? MLX_GPU : MLX_CPU, 0);
583
+ if (mlx_set_default_device(dev)) { mlx_device_free(dev); raise_mlx("set_default_device"); }
584
+ mlx_stream s = mlx_stream_new();
585
+ if (mlx_get_default_stream(&s, dev)) { mlx_stream_free(s); mlx_device_free(dev); raise_mlx("get_default_stream"); }
586
+ mlx_device_free(dev);
587
+ if (g_stream.ctx) mlx_stream_free(g_stream);
588
+ g_stream = s;
589
+ g_gpu = gpu;
590
+ }
591
+
592
+ /* MLX.device -> :gpu or :cpu */
593
+ static VALUE mlx_device_rb(VALUE self) { return ID2SYM(rb_intern(g_gpu ? "gpu" : "cpu")); }
594
+
595
+ /* MLX.device = :gpu / :cpu. Arrays already created keep working. */
596
+ static VALUE mlx_set_device_rb(VALUE self, VALUE vdev)
597
+ {
598
+ ID id = SYM2ID(rb_to_symbol(vdev));
599
+ if (id == rb_intern("gpu")) {
600
+ bool ok = false;
601
+ mlx_metal_is_available(&ok);
602
+ if (!ok) rb_raise(eMLXError, "no Metal GPU available");
603
+ set_device(1);
604
+ } else if (id == rb_intern("cpu")) {
605
+ set_device(0);
606
+ } else {
607
+ rb_raise(rb_eArgError, "device must be :gpu or :cpu");
608
+ }
609
+ return vdev;
610
+ }
611
+
612
+ void Init_maurograd_mlx(void)
613
+ {
614
+ VALUE cNumo = rb_const_get(rb_cObject, rb_intern("Numo"));
615
+ cSFloat = rb_const_get(cNumo, rb_intern("SFloat"));
616
+ cInt32 = rb_const_get(cNumo, rb_intern("Int32"));
617
+
618
+ mMaurograd = rb_define_module("Maurograd");
619
+ mMLX = rb_define_module_under(mMaurograd, "MLX");
620
+ eMLXError = rb_define_class_under(mMLX, "Error", rb_eStandardError);
621
+
622
+ mlx_set_error_handler(on_mlx_error, NULL, NULL);
623
+
624
+ g_stream.ctx = NULL;
625
+ bool metal = false;
626
+ mlx_metal_is_available(&metal);
627
+ set_device(metal ? 1 : 0);
628
+
629
+ cArray = rb_define_class_under(mMLX, "Array", rb_cObject);
630
+ rb_undef_alloc_func(cArray);
631
+ rb_define_method(cArray, "+", arr_add, 1);
632
+ rb_define_method(cArray, "-", arr_sub, 1);
633
+ rb_define_method(cArray, "*", arr_mul, 1);
634
+ rb_define_method(cArray, "/", arr_div, 1);
635
+ rb_define_method(cArray, "**", arr_pow, 1);
636
+ rb_define_method(cArray, "-@", arr_neg, 0);
637
+ rb_define_method(cArray, "coerce", arr_coerce, 1);
638
+ rb_define_method(cArray, "shape", arr_shape, 0);
639
+ rb_define_method(cArray, "size", arr_size, 0);
640
+ rb_define_method(cArray, "dtype", arr_dtype, 0);
641
+ rb_define_method(cArray, "to_numo", arr_to_numo, 0);
642
+
643
+ rb_define_module_function(mMLX, "from_numo", mlx_from_numo, 1);
644
+ rb_define_module_function(mMLX, "to_numo", mlx_to_numo, 1);
645
+ rb_define_module_function(mMLX, "zeros", mlx_zeros_rb, 1);
646
+ rb_define_module_function(mMLX, "ones", mlx_ones_rb, 1);
647
+ rb_define_module_function(mMLX, "bernoulli", mlx_bernoulli_rb, 2);
648
+ rb_define_module_function(mMLX, "seed", mlx_seed_rb, 1);
649
+ rb_define_module_function(mMLX, "reshape", mlx_reshape_rb, 2);
650
+ rb_define_module_function(mMLX, "transpose", mlx_transpose_rb, 2);
651
+ rb_define_module_function(mMLX, "slice", mlx_slice_rb, 4);
652
+ rb_define_module_function(mMLX, "stack", mlx_stack_rb, 1);
653
+ rb_define_module_function(mMLX, "pad", mlx_pad_rb, 5);
654
+ rb_define_module_function(mMLX, "sum", mlx_sum_rb, 3);
655
+ rb_define_module_function(mMLX, "mean", mlx_mean_rb, 3);
656
+ rb_define_module_function(mMLX, "max", mlx_max_rb, 3);
657
+ rb_define_module_function(mMLX, "exp", mlx_exp_rb, 1);
658
+ rb_define_module_function(mMLX, "log", mlx_log_rb, 1);
659
+ rb_define_module_function(mMLX, "sqrt", mlx_sqrt_rb, 1);
660
+ rb_define_module_function(mMLX, "maximum", mlx_maximum_rb, 2);
661
+ rb_define_module_function(mMLX, "greater", mlx_greater_rb, 2);
662
+ rb_define_module_function(mMLX, "equal", mlx_equal_rb, 2);
663
+ rb_define_module_function(mMLX, "argmax", mlx_argmax_rb, 2);
664
+ rb_define_module_function(mMLX, "arange", mlx_arange_rb, 1);
665
+ rb_define_module_function(mMLX, "matmul", mlx_matmul_rb, 2);
666
+ rb_define_module_function(mMLX, "one_hot", mlx_one_hot_rb, 2);
667
+ rb_define_module_function(mMLX, "conv2d", mlx_conv2d_rb, 4);
668
+ rb_define_module_function(mMLX, "eval", mlx_eval_rb, 1);
669
+ rb_define_module_function(mMLX, "async_eval", mlx_async_eval_rb, 1);
670
+ rb_define_module_function(mMLX, "vjp", mlx_vjp_rb, 2);
671
+ rb_define_module_function(mMLX, "device", mlx_device_rb, 0);
672
+ rb_define_module_function(mMLX, "device=", mlx_set_device_rb, 1);
673
+ }
@@ -0,0 +1,359 @@
1
+ require "numo/narray"
2
+ # A plain require, not require_relative: installed as a gem, this file is in
3
+ # maurograd-mlx while backends.rb is in maurograd.
4
+ require "maurograd/backends"
5
+
6
+ # MLX runs float32 matrix products in TF32 on GPUs that support it (e.g.
7
+ # Apple M5): faster, but only ~10 mantissa bits, i.e. ~1e-3 relative error,
8
+ # where the CPU backend gives ~1e-7. Like PyTorch, we default to full float32
9
+ # precision; set MLX_ENABLE_TF32=1 in the environment to trade it for speed.
10
+ # (MLX reads the variable once, on first use.)
11
+ ENV["MLX_ENABLE_TF32"] ||= "0"
12
+
13
+ # Load the optional maurograd_mlx extension (built only where mlx-c is
14
+ # available), the same way ext.rb loads maurograd_ext.
15
+ begin
16
+ require "maurograd_mlx"
17
+ rescue LoadError
18
+ pattern = File.join(File.expand_path("../../..", __dir__), "ext", "maurograd_mlx", "maurograd_mlx.{bundle,so}")
19
+ candidate = Dir.glob(pattern).first
20
+ raise LoadError, <<~MSG unless candidate
21
+ the MLX backend needs the maurograd_mlx extension, which was not found.
22
+ It needs mlx-c (`brew install mlx-c`). Installed as a gem, reinstall
23
+ maurograd-mlx after installing mlx-c; in a repo checkout, run
24
+ `./bin/build_ext` (looked for #{pattern}).
25
+ MSG
26
+
27
+ require candidate
28
+ end
29
+
30
+ module Maurograd
31
+ module Backends
32
+ # MLX backend: arrays live in MLX (Apple's array framework), and run on
33
+ # the Apple Silicon GPU through Metal (or on MLX's CPU device, see
34
+ # Maurograd::MLX.device=).
35
+ #
36
+ # Native arrays are Maurograd::MLX::Array objects. Same interface and
37
+ # semantics as Backends::CPU (the reference implementation, see there for
38
+ # what each method does), except where noted.
39
+ #
40
+ # How it differs from the CPU backend:
41
+ #
42
+ # - MLX is lazy: every operation records a graph node, and computation
43
+ # only happens when values are needed (item/to_numo) or explicitly
44
+ # evaluated (#eval, which the optimizers call after each step so the
45
+ # graph never grows past one training step).
46
+ #
47
+ # - Kernels are written here, in Ruby, on top of MLX primitives. The
48
+ # backward passes of conv2d and maxpool2d come from MLX's own
49
+ # reverse-mode differentiation (MLX.vjp) of the forward function: the
50
+ # MLX counterpart of the cuDNN backward routines a CUDA backend would
51
+ # call. Maurograd's autograd still drives the graph as a whole.
52
+ #
53
+ # - MLX convolutions are channels-last (NHWC), while Maurograd tensors
54
+ # are NCHW: conv2d transposes at its boundaries.
55
+ #
56
+ # - Random numbers come from MLX's generator, so Dropout masks differ
57
+ # from the CPU backend's even with the same seed (weight init does
58
+ # not: layers initialize weights on the host, with Numo).
59
+ module MLX
60
+ Lib = Maurograd::MLX
61
+
62
+ module_function
63
+
64
+ def name
65
+ :mlx
66
+ end
67
+
68
+ # --- Conversion ---------------------------------------------------------
69
+
70
+ def native?(x)
71
+ x.is_a?(Lib::Array)
72
+ end
73
+
74
+ def from(x)
75
+ return x if native?(x)
76
+
77
+ x = ::Numo::SFloat.cast(x) unless x.is_a?(::Numo::NArray)
78
+ x = integer_type?(x) ? ::Numo::Int32.cast(x) : ::Numo::SFloat.cast(x) unless x.is_a?(::Numo::SFloat) || x.is_a?(::Numo::Int32)
79
+ Lib.from_numo(x.contiguous? ? x : x.copy)
80
+ end
81
+
82
+ def to_numo(x)
83
+ Lib.to_numo(x)
84
+ end
85
+
86
+ def item(x)
87
+ raise ArgumentError, "item needs a one-element array, got shape #{x.shape.inspect}" unless x.size == 1
88
+
89
+ to_numo(x).to_a.flatten.first.to_f
90
+ end
91
+
92
+ # Forces the computation of the given arrays (nils are ignored).
93
+ def eval(arrays)
94
+ Lib.eval(arrays)
95
+ end
96
+
97
+ # Schedules the given arrays for computation, without waiting.
98
+ def eval_async(arrays)
99
+ Lib.async_eval(arrays)
100
+ end
101
+
102
+ # --- Creation and randomness --------------------------------------------
103
+
104
+ def zeros(shape)
105
+ Lib.zeros(shape)
106
+ end
107
+
108
+ def ones(shape)
109
+ Lib.ones(shape)
110
+ end
111
+
112
+ def bernoulli(shape, keep_prob)
113
+ Lib.bernoulli(shape, keep_prob)
114
+ end
115
+
116
+ def seed(n)
117
+ Lib.seed(n)
118
+ end
119
+
120
+ # --- Shape --------------------------------------------------------------
121
+
122
+ def reshape(x, *shape)
123
+ Lib.reshape(x, shape)
124
+ end
125
+
126
+ def transpose(x, *axes)
127
+ Lib.transpose(x, axes)
128
+ end
129
+
130
+ # --- Reductions ---------------------------------------------------------
131
+
132
+ def sum(x, axis: nil, keepdims: false)
133
+ Lib.sum(x, axis, keepdims)
134
+ end
135
+
136
+ def mean(x, axis: nil, keepdims: false)
137
+ Lib.mean(x, axis, keepdims)
138
+ end
139
+
140
+ def max(x, axis: nil, keepdims: false)
141
+ Lib.max(x, axis, keepdims)
142
+ end
143
+
144
+ # --- Elementwise math ---------------------------------------------------
145
+
146
+ def exp(x)
147
+ Lib.exp(x)
148
+ end
149
+
150
+ def log(x)
151
+ Lib.log(x)
152
+ end
153
+
154
+ def sqrt(x)
155
+ Lib.sqrt(x)
156
+ end
157
+
158
+ def all_finite?(x)
159
+ CPU.all_finite?(to_numo(x))
160
+ end
161
+
162
+ # --- Linear algebra -----------------------------------------------------
163
+
164
+ def matmul(a, b)
165
+ Lib.matmul(a, b)
166
+ end
167
+
168
+ # --- Losses support -----------------------------------------------------
169
+
170
+ def one_hot(indices, num_classes)
171
+ # Range check on the host: MLX can't raise from inside a kernel.
172
+ idx = to_numo(indices)
173
+ if idx.size.positive? && (idx.min.negative? || idx.max >= num_classes)
174
+ raise ArgumentError, "class index out of range for C=#{num_classes}"
175
+ end
176
+
177
+ Lib.one_hot(indices, num_classes)
178
+ end
179
+
180
+ # --- Fused NN kernels ---------------------------------------------------
181
+
182
+ def conv2d_forward(x, w, b, stride, padding)
183
+ y = conv2d_nchw(x, w, stride, padding)
184
+ y += reshape(b, 1, b.shape[0], 1, 1) if b
185
+ [y, {x: x, w: w, stride: stride, padding: padding}]
186
+ end
187
+
188
+ def conv2d_backward(ctx, dout, want_dx:, want_dw:, want_db:)
189
+ dx = dw = db = nil
190
+ if want_dx || want_dw
191
+ dx, dw = Lib.vjp([ctx[:x], ctx[:w]], [dout]) do |x, w|
192
+ [conv2d_nchw(x, w, ctx[:stride], ctx[:padding])]
193
+ end
194
+ end
195
+ db = sum(dout, axis: [0, 2, 3]) if want_db
196
+ [want_dx ? dx : nil, want_dw ? dw : nil, db]
197
+ end
198
+
199
+ # Same semantics as the CPU backend: zero padding, and on ties the
200
+ # gradient goes to the first maximum of the window only. (MLX's own
201
+ # vjp of max would split a tied window's gradient equally among the
202
+ # tied elements, and MNIST's flat backgrounds produce plenty of
203
+ # positive ties.) In both paths below, a first-maximum mask (see
204
+ # first_max_mask) routes dout to the winning element.
205
+ def maxpool2d_forward(x, kh, kw, stride, padding)
206
+ n, c, h, w = x.shape
207
+ if tiling_pool?(h, w, kh, kw, stride, padding)
208
+ # Non-overlapping windows that tile the input exactly (the common
209
+ # case, e.g. 2x2 with stride 2): the windows are just a reshape +
210
+ # transpose of x, [N,C,OH,KH,OW,KW] -> [N,C,OH,OW,KH*KW].
211
+ oh = h / kh
212
+ ow = w / kw
213
+ tiles = reshape(transpose(reshape(x, n, c, oh, kh, ow, kw), 0, 1, 2, 4, 3, 5), n, c, oh, ow, kh * kw)
214
+ y = Lib.max(tiles, [4], true)
215
+ return [reshape(y, n, c, oh, ow), {tiles: tiles, max: y, shape: [n, c, h, w], kh: kh, kw: kw}]
216
+ end
217
+
218
+ windows = pool_windows(x, kh, kw, stride, padding)
219
+ y = Lib.max(windows, [0], true)
220
+ [reshape(y, *y.shape[1..]), {x: x, windows: windows, max: y, kh: kh, kw: kw, stride: stride, padding: padding}]
221
+ end
222
+
223
+ def maxpool2d_backward(ctx, dout)
224
+ k = ctx[:kh] * ctx[:kw]
225
+
226
+ if ctx[:tiles]
227
+ # Mask the tiles, then undo the forward reshape + transpose: no
228
+ # scatter needed, since every input element is in exactly one tile.
229
+ n, c, h, w = ctx[:shape]
230
+ oh = h / ctx[:kh]
231
+ ow = w / ctx[:kw]
232
+ mask = first_max_mask(ctx[:tiles], ctx[:max], reshape(Lib.arange(k), k), 4)
233
+ dtiles = mask * reshape(dout, n, c, oh, ow, 1)
234
+ untiled = transpose(reshape(dtiles, n, c, oh, ow, ctx[:kh], ctx[:kw]), 0, 1, 2, 4, 3, 5)
235
+ return reshape(untiled, n, c, h, w)
236
+ end
237
+
238
+ # General case (overlapping windows, padding): windows [K,N,C,OH,OW]
239
+ # come from strided slices, so the vjp of that (linear) extraction
240
+ # scatters the masked gradient back into the input. Correct, but MLX
241
+ # builds a full-size update per window offset, so it is much slower.
242
+ mask = first_max_mask(ctx[:windows], ctx[:max], reshape(Lib.arange(k), k, 1, 1, 1, 1), 0)
243
+ dx, = Lib.vjp([ctx[:x]], [mask * dout]) do |x|
244
+ [pool_windows(x, ctx[:kh], ctx[:kw], ctx[:stride], ctx[:padding])]
245
+ end
246
+ dx
247
+ end
248
+
249
+ # Float mask with a 1 at the FIRST maximum of each window, given the
250
+ # windows, their max along `axis` (keepdims) and the window-offset
251
+ # index k along that axis (shaped to broadcast). Every maximum gets weight K - k,
252
+ # so the first one has the largest, and comparing the weights with
253
+ # their max keeps exactly that one. This avoids MLX's argmax, which
254
+ # was ~100x slower than max on these shapes (39 ms vs 0.4 ms for a
255
+ # [512, 6, 14, 14, 4] tensor on an M5).
256
+ def first_max_mask(windows, max, offsets, axis)
257
+ k = offsets.size
258
+ weights = Lib.equal(windows, max) * (k - offsets)
259
+ Lib.equal(weights, Lib.max(weights, [axis], true))
260
+ end
261
+
262
+ def tiling_pool?(h, w, kh, kw, stride, padding)
263
+ padding.zero? && stride == kh && stride == kw && (h % kh).zero? && (w % kw).zero?
264
+ end
265
+
266
+ def relu_forward(x)
267
+ y = Lib.maximum(x, 0.0)
268
+ [y, y]
269
+ end
270
+
271
+ def relu_backward(ctx, dout)
272
+ dout * Lib.greater(ctx, 0.0)
273
+ end
274
+
275
+ def batchnorm2d_forward(x, mean, var, gamma, beta, eps)
276
+ c = x.shape[1]
277
+ axes = [0, 2, 3]
278
+ if mean.nil?
279
+ mu = Lib.mean(x, axes, true)
280
+ var4 = Lib.mean((x - mu)**2, axes, true)
281
+ else
282
+ mu = reshape(mean, 1, c, 1, 1)
283
+ var4 = reshape(var, 1, c, 1, 1)
284
+ end
285
+
286
+ inv_std = 1.0 / sqrt(var4 + eps)
287
+ x_hat = (x - mu) * inv_std
288
+ g = gamma ? reshape(gamma, 1, c, 1, 1) : nil
289
+ y = g ? x_hat * g : x_hat
290
+ y += reshape(beta, 1, c, 1, 1) if beta
291
+
292
+ [y, {x_hat: x_hat, inv_std: inv_std, gamma: g}, reshape(mu, c), reshape(var4, c)]
293
+ end
294
+
295
+ # Same compact formulas as the CPU kernel (see Ops::BatchNorm2D).
296
+ def batchnorm2d_backward(ctx, dout, training:)
297
+ x_hat = ctx[:x_hat]
298
+ axes = [0, 2, 3]
299
+ dgamma = sum(dout * x_hat, axis: axes)
300
+ dbeta = sum(dout, axis: axes)
301
+
302
+ k = ctx[:gamma] ? ctx[:gamma] * ctx[:inv_std] : ctx[:inv_std]
303
+ dx = if training
304
+ n, _c, h, w = dout.shape
305
+ m = (n * h * w).to_f
306
+ (k / m) * ((m * dout) - sum(dout, axis: axes, keepdims: true) -
307
+ (x_hat * sum(dout * x_hat, axis: axes, keepdims: true)))
308
+ else
309
+ k * dout
310
+ end
311
+
312
+ [dx, dgamma, dbeta]
313
+ end
314
+
315
+ # --- Helpers ------------------------------------------------------------
316
+
317
+ # NCHW convolution on top of MLX's channels-last conv2d.
318
+ def conv2d_nchw(x, w, stride, padding)
319
+ x_nhwc = transpose(x, 0, 2, 3, 1)
320
+ w_ohwi = transpose(w, 0, 2, 3, 1)
321
+ transpose(Lib.conv2d(x_nhwc, w_ohwi, stride, padding), 0, 3, 1, 2)
322
+ end
323
+
324
+ # The kh*kw strided slices of the (zero-padded) input, one per window
325
+ # offset, stacked into [K, N, C, OH, OW]: slice k holds, for every output
326
+ # position, the element at offset k of its window. Max pooling is their
327
+ # elementwise max.
328
+ def pool_windows(x, kh, kw, stride, padding)
329
+ n, c, h, w = x.shape
330
+ if padding.positive?
331
+ x = Lib.pad(x, [2, 3], [padding, padding], [padding, padding], 0.0)
332
+ h += 2 * padding
333
+ w += 2 * padding
334
+ end
335
+ oh = (h - kh) / stride + 1
336
+ ow = (w - kw) / stride + 1
337
+
338
+ windows = []
339
+ kh.times do |ky|
340
+ kw.times do |kx|
341
+ windows << Lib.slice(
342
+ x, [0, 0, ky, kx],
343
+ [n, c, ky + stride * (oh - 1) + 1, kx + stride * (ow - 1) + 1],
344
+ [1, 1, stride, stride]
345
+ )
346
+ end
347
+ end
348
+ Lib.stack(windows)
349
+ end
350
+
351
+ def integer_type?(x)
352
+ x.is_a?(::Numo::Int8) || x.is_a?(::Numo::Int16) || x.is_a?(::Numo::Int32) || x.is_a?(::Numo::Int64) ||
353
+ x.is_a?(::Numo::UInt8) || x.is_a?(::Numo::UInt16) || x.is_a?(::Numo::UInt32) || x.is_a?(::Numo::UInt64)
354
+ end
355
+ end
356
+
357
+ register(:mlx, MLX)
358
+ end
359
+ end
@@ -0,0 +1,8 @@
1
+ # Entry point of the maurograd-mlx gem (what `require "maurograd-mlx"` and
2
+ # Bundler's automatic require load): Maurograd itself plus the MLX backend.
3
+ #
4
+ # Requiring it is optional: Maurograd loads the backend by itself the first
5
+ # time it is asked for (Maurograd.backend = :mlx, MAUROGRAD_BACKEND=mlx,
6
+ # tensor.to(:mlx)), as long as this gem is installed.
7
+ require "maurograd"
8
+ require "maurograd/backends/mlx"
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: maurograd-mlx
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mauro Tortonesi
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: maurograd
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.1.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.1.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: numo-narray-alt
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: 0.9.11
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: 0.9.11
40
+ description: |
41
+ Adds an :mlx backend to Maurograd that runs tensors and training on the
42
+ Apple Silicon GPU, through Ruby bindings for mlx-c (the C API of Apple's
43
+ MLX array framework). Requires mlx-c: `brew install mlx-c` before
44
+ installing this gem. Select it with MAUROGRAD_BACKEND=mlx,
45
+ Maurograd.backend = :mlx, or model.to(:mlx).
46
+ email:
47
+ - mauro.tortonesi@unife.it
48
+ executables: []
49
+ extensions:
50
+ - ext/maurograd_mlx/extconf.rb
51
+ extra_rdoc_files: []
52
+ files:
53
+ - LICENSE
54
+ - ext/maurograd_mlx/extconf.rb
55
+ - ext/maurograd_mlx/maurograd_mlx.c
56
+ - lib/maurograd-mlx.rb
57
+ - lib/maurograd/backends/mlx.rb
58
+ homepage: https://github.com/mtortonesi/maurograd
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ source_code_uri: https://github.com/mtortonesi/maurograd
63
+ bug_tracker_uri: https://github.com/mtortonesi/maurograd/issues
64
+ changelog_uri: https://github.com/mtortonesi/maurograd/blob/main/CHANGELOG.md
65
+ rubygems_mfa_required: 'true'
66
+ rdoc_options: []
67
+ require_paths:
68
+ - lib
69
+ required_ruby_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '3.3'
74
+ required_rubygems_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ requirements: []
80
+ rubygems_version: 4.0.20
81
+ specification_version: 4
82
+ summary: Apple Silicon GPU backend for Maurograd, through MLX.
83
+ test_files: []