maurograd 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.
Files changed (49) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +49 -0
  3. data/LICENSE +21 -0
  4. data/README.md +126 -0
  5. data/examples/mnist.rb +145 -0
  6. data/examples/mnist_batchnorm.rb +141 -0
  7. data/ext/maurograd_ext/extconf.rb +93 -0
  8. data/ext/maurograd_ext/maurograd_ext.c +1251 -0
  9. data/lib/maurograd/backends/cpu.rb +241 -0
  10. data/lib/maurograd/backends.rb +114 -0
  11. data/lib/maurograd/bootstrap.rb +28 -0
  12. data/lib/maurograd/datasets/batching.rb +25 -0
  13. data/lib/maurograd/datasets/mnist.rb +191 -0
  14. data/lib/maurograd/debug.rb +13 -0
  15. data/lib/maurograd/ext.rb +40 -0
  16. data/lib/maurograd/layers/batchnorm2d.rb +69 -0
  17. data/lib/maurograd/layers/conv2d.rb +135 -0
  18. data/lib/maurograd/layers/dropout.rb +41 -0
  19. data/lib/maurograd/layers/flatten.rb +11 -0
  20. data/lib/maurograd/layers/linear.rb +54 -0
  21. data/lib/maurograd/layers/maxpool2d.rb +17 -0
  22. data/lib/maurograd/layers/relu.rb +11 -0
  23. data/lib/maurograd/layers/sequential.rb +45 -0
  24. data/lib/maurograd/losses/bce.rb +90 -0
  25. data/lib/maurograd/losses/cross_entropy_with_logits.rb +129 -0
  26. data/lib/maurograd/losses/mse.rb +73 -0
  27. data/lib/maurograd/ops/add.rb +55 -0
  28. data/lib/maurograd/ops/batchnorm2d.rb +122 -0
  29. data/lib/maurograd/ops/conv2d.rb +124 -0
  30. data/lib/maurograd/ops/dropout.rb +82 -0
  31. data/lib/maurograd/ops/flatten.rb +56 -0
  32. data/lib/maurograd/ops/linear.rb +109 -0
  33. data/lib/maurograd/ops/matmul.rb +86 -0
  34. data/lib/maurograd/ops/maxpool2d.rb +91 -0
  35. data/lib/maurograd/ops/mul.rb +52 -0
  36. data/lib/maurograd/ops/permute.rb +75 -0
  37. data/lib/maurograd/ops/power.rb +46 -0
  38. data/lib/maurograd/ops/relu.rb +50 -0
  39. data/lib/maurograd/ops/sub.rb +52 -0
  40. data/lib/maurograd/ops/sum.rb +46 -0
  41. data/lib/maurograd/optim/adam.rb +91 -0
  42. data/lib/maurograd/optim/optimizer.rb +52 -0
  43. data/lib/maurograd/optim/sgd.rb +73 -0
  44. data/lib/maurograd/seed.rb +34 -0
  45. data/lib/maurograd/tensor.rb +326 -0
  46. data/lib/maurograd/utils/utils.rb +186 -0
  47. data/lib/maurograd/version.rb +3 -0
  48. data/lib/maurograd.rb +78 -0
  49. metadata +142 -0
@@ -0,0 +1,1251 @@
1
+ #include "ruby.h"
2
+ #include "ruby/thread.h"
3
+ #include "numo/narray.h"
4
+
5
+ #include <stdbool.h>
6
+ #include <stddef.h>
7
+ #include <stdint.h>
8
+ #include <string.h>
9
+ #include <limits.h>
10
+
11
+ #ifdef MAUROGRAD_USE_ACCELERATE
12
+ #include <Accelerate/Accelerate.h> // Apple Accelerate (cblas_*)
13
+ #define MAUROGRAD_BLAS_NAME "accelerate"
14
+ #else
15
+ #include <cblas.h> // OpenBLAS (cblas_*)
16
+ #define MAUROGRAD_BLAS_NAME "openblas"
17
+ #endif
18
+
19
+ /*
20
+ * Minimal helpers: type checks and pointer access.
21
+ * NB: use the Numo API to get pointers BEFORE releasing the GVL.
22
+ */
23
+
24
+ static VALUE mMaurograd;
25
+ static VALUE mExt;
26
+ static VALUE cNumo;
27
+ static VALUE cNArray_;
28
+ static VALUE cSFloat_;
29
+ static VALUE cInt32_;
30
+ static ID id_zeros;
31
+ static ID id_col;
32
+ static VALUE sym_col;
33
+
34
+
35
+ /* ---------- Helper functions ---------- */
36
+ #include <math.h>
37
+
38
+ static inline int any_nonfinite(const float *p, size_t n) {
39
+ for (size_t i = 0; i < n; i++) {
40
+ if (!isfinite(p[i])) return 1;
41
+ }
42
+ return 0;
43
+ }
44
+
45
+ static inline VALUE sfloat_new_2d(size_t row, size_t col)
46
+ {
47
+ size_t shape[2] = { row, col };
48
+ return nary_new(cSFloat_, 2, shape);
49
+ }
50
+
51
+ static inline VALUE sfloat_new_4d(size_t a, size_t b, size_t c, size_t d) {
52
+ size_t shape[4] = { a, b, c, d };
53
+ return nary_new(cSFloat_, 4, shape);
54
+ }
55
+
56
+ static inline int sz_to_int(size_t v, const char *name)
57
+ {
58
+ if (v > (size_t)INT_MAX) {
59
+ rb_raise(rb_eArgError, "%s too large: %zu > INT_MAX", name, v);
60
+ }
61
+ return (int)v;
62
+ }
63
+
64
+ /* The kernels read raw float32 memory in row-major order, so every array
65
+ * they read must be a contiguous Numo::SFloat: a strided view (a slice, a
66
+ * transpose) would be read as if it were contiguous, giving wrong values or
67
+ * reading past the end of its buffer. */
68
+ static void check_sfloat_contiguous(VALUE v, const char *name)
69
+ {
70
+ if (!rb_obj_is_kind_of(v, cSFloat_)) rb_raise(rb_eTypeError, "%s must be Numo::SFloat", name);
71
+ if (!RTEST(na_check_contiguous(v))) rb_raise(rb_eArgError, "%s must be contiguous", name);
72
+ }
73
+
74
+ /* Sliding-window parameters shared by conv and im2col/col2im. stride 0 would
75
+ * divide by zero when computing the output size: a crash on x86, and silently
76
+ * wrong shapes on ARM, where integer division by zero returns 0. */
77
+ static void check_window_params(int kh, int kw, int stride, int pad)
78
+ {
79
+ if (kh <= 0 || kw <= 0) rb_raise(rb_eArgError, "kernel size must be positive, got %dx%d", kh, kw);
80
+ if (stride <= 0) rb_raise(rb_eArgError, "stride must be positive, got %d", stride);
81
+ if (pad < 0) rb_raise(rb_eArgError, "padding must be >= 0, got %d", pad);
82
+ }
83
+
84
+ /* ---------- reusable GEMM (row-major) ---------- */
85
+
86
+ static inline void sgemm_rowmajor_nt(int M, int N, int K,
87
+ const float *A, const float *B, float *C,
88
+ int B_rows, int B_cols)
89
+ {
90
+ // C = A * B^T, where:
91
+ // A: (M,K) row-major
92
+ // B: (N,K) row-major (so B^T is (K,N))
93
+ // C: (M,N) row-major
94
+ //
95
+ // Here B is stored as (N,K) row-major contiguous (B_rows=N, B_cols=K).
96
+ const float alpha = 1.0f;
97
+ const float beta = 0.0f;
98
+
99
+ cblas_sgemm(CblasRowMajor,
100
+ CblasNoTrans, CblasTrans,
101
+ M, N, K,
102
+ alpha,
103
+ A, K, // lda = K
104
+ B, B_cols, // ldb = K (num columns of B as stored)
105
+ beta,
106
+ C, N); // ldc = N
107
+ }
108
+
109
+
110
+ /* ---------- reusable GEMM (row-major) ---------- */
111
+
112
+ static inline void im2col_f32(const float *x, float *col, int N, int C, int H,
113
+ int W, int Kh, int Kw, int stride, int pad,
114
+ int OH, int OW)
115
+ {
116
+ // 1) im2col: col[row, k] with row = ((n*OH + oy)*OW + ox)
117
+ // k enumerates (c, ky, kx) in channel-major order:
118
+ // k = c*(Kh*Kw) + ky*Kw + kx
119
+ const int K = C*Kh*Kw;
120
+
121
+ // Not needed as we overwrite all values
122
+ // const int rows = N*OH*OW;
123
+ // memset(col, 0, (size_t)rows * (size_t)K * sizeof(float));
124
+
125
+ int row = 0;
126
+ for (int n = 0; n < N; n++) {
127
+ for (int oy = 0; oy < OH; oy++) {
128
+ const int base_y = oy * stride - pad;
129
+ for (int ox = 0; ox < OW; ox++, row++) {
130
+ const int base_x = ox * stride - pad;
131
+
132
+ int k = 0;
133
+ for (int c = 0; c < C; c++) {
134
+ const int xc_base = (n * C + c) * H * W;
135
+ for (int ky = 0; ky < Kh; ky++) {
136
+ const int iy = base_y + ky;
137
+ for (int kx = 0; kx < Kw; kx++, k++) {
138
+ const int ix = base_x + kx;
139
+ float v = 0.0f;
140
+ if ((unsigned)iy < (unsigned)H && (unsigned)ix < (unsigned)W) {
141
+ v = x[xc_base + iy * W + ix];
142
+ }
143
+ col[row * K + k] = v;
144
+ }
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ static inline void col2im_f32(const float *dcol, float *dx, int N, int C, int H,
153
+ int W, int Kh, int Kw, int stride, int pad,
154
+ int OH, int OW)
155
+ {
156
+ memset(dx, 0, sizeof(float) * (size_t)N * (size_t)C * (size_t)H * (size_t)W);
157
+
158
+ int cols = C * Kh * Kw;
159
+
160
+ int row = 0;
161
+ for (int n = 0; n < N; n++) {
162
+ for (int oy = 0; oy < OH; oy++) {
163
+ for (int ox = 0; ox < OW; ox++, row++) {
164
+ int col = 0;
165
+ for (int c = 0; c < C; c++) {
166
+ for (int ky = 0; ky < Kh; ky++) {
167
+ int iy = oy * stride + ky - pad;
168
+ for (int kx = 0; kx < Kw; kx++, col++) {
169
+ int ix = ox * stride + kx - pad;
170
+ if (iy >= 0 && iy < H && ix >= 0 && ix < W) {
171
+ size_t idx = ((size_t)((n*C + c)*H + iy))*W + (size_t)ix;
172
+ dx[idx] += dcol[(size_t)row * (size_t)cols + (size_t)col];
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+
182
+ /* ---------- conv2d_forward worker (runs w/o GVL) ---------- */
183
+
184
+ typedef struct {
185
+ const float *x; // [N,C,H,W]
186
+ const float *w; // [Cout,Cin,Kh,Kw]
187
+ const float *bias; // [Cout] or NULL
188
+
189
+ float *col; // [rows,K]
190
+ float *out2d; // [rows,Cout]
191
+ float *out; // [N,Cout,OH,OW]
192
+
193
+ int N, C, H, W;
194
+ int Cout, Cin, Kh, Kw;
195
+ int stride, pad;
196
+ int OH, OW;
197
+ int rows, K;
198
+ } conv2d_fwd_args;
199
+
200
+ static void* conv2d_forward_nogvl(void *ptr)
201
+ {
202
+ conv2d_fwd_args *a = (conv2d_fwd_args*)ptr;
203
+
204
+ const int N = a->N;
205
+ const int C = a->C;
206
+ const int H = a->H;
207
+ const int W = a->W;
208
+ const int Cout = a->Cout;
209
+ const int Kh = a->Kh;
210
+ const int Kw = a->Kw;
211
+ const int stride = a->stride;
212
+ const int pad = a->pad;
213
+ const int OH = a->OH;
214
+ const int OW = a->OW;
215
+ const int rows = a->rows;
216
+ const int K = a->K;
217
+
218
+ const float *x = a->x;
219
+ const float *w = a->w;
220
+
221
+ float *col = a->col;
222
+ float *out2d = a->out2d;
223
+ float *out = a->out;
224
+
225
+ /* 1) im2col: col[rows, K] */
226
+ im2col_f32(x, col, N, C, H, W, Kh, Kw, stride, pad, OH, OW);
227
+
228
+ // 2) GEMM: out2d = col (rows,K) * w_flat^T
229
+ // w is [Cout,Cin,Kh,Kw] contiguous => treat as w_flat [Cout,K] row-major
230
+ sgemm_rowmajor_nt(rows, Cout, K, col, w, out2d, Cout, K);
231
+
232
+ // 3) Scatter + bias into out[N,Cout,OH,OW] (NCHW contiguous)
233
+ // out index: (((n*Cout + co)*OH + oy)*OW + ox)
234
+ if (a->bias) {
235
+ const float *b = a->bias;
236
+ int r = 0;
237
+ for (int n = 0; n < N; n++) {
238
+ for (int oy = 0; oy < OH; oy++) {
239
+ for (int ox = 0; ox < OW; ox++, r++) {
240
+ const int out_base = ((n * Cout) * OH + oy) * OW + ox;
241
+ for (int co = 0; co < Cout; co++) {
242
+ out[out_base + co * OH * OW] = out2d[r * Cout + co] + b[co];
243
+ }
244
+ }
245
+ }
246
+ }
247
+ } else {
248
+ int r = 0;
249
+ for (int n = 0; n < N; n++) {
250
+ for (int oy = 0; oy < OH; oy++) {
251
+ for (int ox = 0; ox < OW; ox++, r++) {
252
+ const int out_base = ((n * Cout) * OH + oy) * OW + ox;
253
+ for (int co = 0; co < Cout; co++) {
254
+ out[out_base + co * OH * OW] = out2d[r * Cout + co];
255
+ }
256
+ }
257
+ }
258
+ }
259
+ }
260
+
261
+ return NULL;
262
+ }
263
+
264
+ /* ---------- Maurograd::Ext.conv2d_forward ---------- */
265
+
266
+ static VALUE mg_conv2d_forward(VALUE self,
267
+ VALUE vx,
268
+ VALUE vw,
269
+ VALUE vbias, // nil ok
270
+ VALUE vstride,
271
+ VALUE vpad,
272
+ VALUE workspace)
273
+ {
274
+ // Basic type checks
275
+ if (!rb_obj_is_kind_of(vx, cNArray_)) rb_raise(rb_eTypeError, "x must be Numo::NArray");
276
+ if (!rb_obj_is_kind_of(vw, cNArray_)) rb_raise(rb_eTypeError, "w must be Numo::NArray");
277
+ if (!rb_obj_is_kind_of(vx, cSFloat_)) rb_raise(rb_eArgError, "x must be Numo::SFloat");
278
+ if (!rb_obj_is_kind_of(vw, cSFloat_)) rb_raise(rb_eArgError, "w must be Numo::SFloat");
279
+ if (vbias != Qnil && !rb_obj_is_kind_of(vbias, cSFloat_)) rb_raise(rb_eArgError, "bias must be Numo::SFloat or nil");
280
+ check_sfloat_contiguous(vx, "x");
281
+ check_sfloat_contiguous(vw, "w");
282
+ if (vbias != Qnil) check_sfloat_contiguous(vbias, "bias");
283
+
284
+ narray_t *nx, *nw;
285
+ GetNArray(vx, nx);
286
+ GetNArray(vw, nw);
287
+
288
+ // Dim checks
289
+ if (nx->ndim != 4) rb_raise(rb_eArgError, "x must be 4D (NCHW)");
290
+ if (nw->ndim != 4) rb_raise(rb_eArgError, "w must be 4D (Cout,Cin,Kh,Kw)");
291
+
292
+ const int stride = NUM2INT(vstride);
293
+ const int pad = NUM2INT(vpad);
294
+
295
+ // Shapes (size_t -> int with bounds assumption)
296
+ const int N = sz_to_int(nx->shape[0], "N");
297
+ const int C = sz_to_int(nx->shape[1], "C");
298
+ const int H = sz_to_int(nx->shape[2], "H");
299
+ const int W = sz_to_int(nx->shape[3], "W");
300
+
301
+ const int Cout = sz_to_int(nw->shape[0], "Cout");
302
+ const int Cin = sz_to_int(nw->shape[1], "Cin");
303
+ const int Kh = sz_to_int(nw->shape[2], "Kh");
304
+ const int Kw = sz_to_int(nw->shape[3], "Kw");
305
+
306
+ if (Cin != C) rb_raise(rb_eArgError, "channel mismatch: x.C=%d, w.Cin=%d", C, Cin);
307
+ check_window_params(Kh, Kw, stride, pad);
308
+
309
+ if (vbias != Qnil) {
310
+ narray_t *nb;
311
+ GetNArray(vbias, nb);
312
+ if (nb->ndim != 1 || (int)nb->shape[0] != Cout) {
313
+ rb_raise(rb_eArgError, "bias must have shape [Cout]");
314
+ }
315
+ }
316
+
317
+ const int OH = (H + 2*pad - Kh) / stride + 1;
318
+ const int OW = (W + 2*pad - Kw) / stride + 1;
319
+ if (N <= 0 || C <= 0 || H <= 0 || W <= 0) rb_raise(rb_eArgError, "invalid input shape");
320
+ if (OH <= 0 || OW <= 0) rb_raise(rb_eArgError, "invalid output shape (OH/OW <= 0)");
321
+
322
+ if ((size_t)N * (size_t)OH * (size_t)OW > (size_t)INT_MAX)
323
+ rb_raise(rb_eArgError, "rows too large");
324
+ if ((size_t)C * (size_t)Kh * (size_t)Kw > (size_t)INT_MAX)
325
+ rb_raise(rb_eArgError, "K too large");
326
+
327
+ const int rows = N * OH * OW;
328
+ const int K = C * Kh * Kw;
329
+
330
+ // Allocate the output [N,Cout,OH,OW] and the temporary buffers
331
+ // col [rows, K] and out2d [rows, Cout] as NArrays, so Ruby's GC manages them.
332
+ VALUE vcol = sfloat_new_2d(rows, K);
333
+ VALUE vout2 = sfloat_new_2d(rows, Cout);
334
+ VALUE vout = sfloat_new_4d(N, Cout, OH, OW);
335
+
336
+ // Pointers (get them BEFORE releasing GVL)
337
+ const float *x = (const float*)na_get_pointer_for_read(vx);
338
+ const float *w = (const float*)na_get_pointer_for_read(vw);
339
+
340
+ const float *b = NULL;
341
+ if (vbias != Qnil) {
342
+ // Shape already checked above: bias is [Cout].
343
+ b = (const float*)na_get_pointer_for_read(vbias);
344
+ }
345
+
346
+ float *col = (float*)na_get_pointer_for_write(vcol);
347
+ float *out2d = (float*)na_get_pointer_for_write(vout2);
348
+ float *out = (float*)na_get_pointer_for_write(vout);
349
+
350
+ conv2d_fwd_args args;
351
+ args.x = x; args.w = w; args.bias = b;
352
+ args.col = col; args.out2d = out2d; args.out = out;
353
+ args.N=N; args.C=C; args.H=H; args.W=W;
354
+ args.Cout=Cout; args.Cin=Cin; args.Kh=Kh; args.Kw=Kw;
355
+ args.stride=stride; args.pad=pad;
356
+ args.OH=OH; args.OW=OW;
357
+ args.rows=rows; args.K=K;
358
+
359
+ /* We tell the GC not to touch vcol and vout2. Theoretically not needed, but
360
+ * an extra check is never wrong. */
361
+ RB_GC_GUARD(vcol);
362
+ RB_GC_GUARD(vout2);
363
+ RB_GC_GUARD(vout);
364
+
365
+ /* Run without GVL */
366
+ rb_thread_call_without_gvl(conv2d_forward_nogvl, &args, RUBY_UBF_IO, NULL);
367
+
368
+ /* Save col in workspace */
369
+ rb_hash_aset(workspace, ID2SYM(rb_intern("col")), vcol);
370
+
371
+ return vout;
372
+ }
373
+
374
+
375
+ /* ---------- support functions for backward ---------- */
376
+
377
+ static inline void pack_dout2d_nchw(const float* dout, float* dout2d,
378
+ int N, int Cout, int OH, int OW)
379
+ {
380
+ int r = 0;
381
+ for (int n = 0; n < N; n++) {
382
+ for (int oy = 0; oy < OH; oy++) {
383
+ for (int ox = 0; ox < OW; ox++, r++) {
384
+ // dout layout: (((n*Cout + co)*OH + oy)*OW + ox)
385
+ const int base = ((n * Cout) * OH + oy) * OW + ox;
386
+ for (int co = 0; co < Cout; co++) {
387
+ dout2d[r * Cout + co] = dout[base + co * OH * OW];
388
+ }
389
+ }
390
+ }
391
+ }
392
+ }
393
+
394
+ static inline void reduce_dbias(const float* dout2d, float* db, int rows, int Cout)
395
+ {
396
+ memset(db, 0, sizeof(float) * (size_t)Cout);
397
+ for (int r = 0; r < rows; r++) {
398
+ const float *p = dout2d + r * Cout;
399
+ for (int co = 0; co < Cout; co++) db[co] += p[co];
400
+ }
401
+ }
402
+
403
+ typedef struct {
404
+ // inputs
405
+ const float *x; // [N,C,H,W]
406
+ const float *w; // [Cout,C,Kh,Kw] contiguous => treat as [Cout,K]
407
+ const float *dout; // [N,Cout,OH,OW]
408
+
409
+ // temps
410
+ float *dout2d; // [rows,Cout] (may be NULL if not needed)
411
+ float *col; // [rows,K] (may be NULL if not needed)
412
+ float *dcol; // [rows,K] (may be NULL if not needed)
413
+
414
+ // outputs
415
+ float *dx; // [N,C,H,W] (may be NULL)
416
+ float *dw; // [Cout,K] (may be NULL) but stored into [Cout,C,Kh,Kw] memory
417
+ float *db; // [Cout] (may be NULL)
418
+
419
+ // dims
420
+ int N, C, H, W;
421
+ int Cout, Kh, Kw;
422
+ int OH, OW;
423
+ int rows, K;
424
+ int stride, pad;
425
+
426
+ int want_dx, want_dw, want_db;
427
+
428
+ bool have_col;
429
+
430
+ // Non-finite guard: checked after each step, surfaced as a Ruby exception.
431
+ int bad; // 0 ok, 1 found non-finite
432
+ int bad_where; // 1=dout2d, 2=dw, 3=dcol, 4=dx, 5=db
433
+ } conv2d_bwd_args;
434
+
435
+
436
+ static void* conv2d_backward_nogvl(void *ptr)
437
+ {
438
+ conv2d_bwd_args *a = (conv2d_bwd_args*)ptr;
439
+
440
+ // Precondition: if anything is needed, dout2d must exist.
441
+ if ((a->want_dx || a->want_dw || a->want_db) && !a->dout2d) {
442
+ return NULL; // should never actually get here
443
+ }
444
+
445
+
446
+ // 1) pack dout -> dout2d
447
+ pack_dout2d_nchw(a->dout, a->dout2d, a->N, a->Cout, a->OH, a->OW);
448
+
449
+ if (a->dout2d) {
450
+ // Full-array check; could be restricted to a subset for speed.
451
+ if (any_nonfinite(a->dout2d, (size_t)a->rows * (size_t)a->Cout)) {
452
+ a->bad = 1; a->bad_where = 1; return NULL;
453
+ }
454
+ }
455
+
456
+
457
+ // 2) db
458
+ if (a->want_db && a->db) {
459
+ reduce_dbias(a->dout2d, a->db, a->rows, a->Cout);
460
+ }
461
+
462
+ if (a->want_db && a->db) {
463
+ if (any_nonfinite(a->db, (size_t)a->Cout)) {
464
+ a->bad = 1; a->bad_where = 5; return NULL;
465
+ }
466
+ }
467
+
468
+ // 3) dw
469
+ if (a->want_dw && a->dw) {
470
+ // dw needs col.
471
+ if (a->col) {
472
+ if (!a->have_col) {
473
+ im2col_f32(a->x, a->col,
474
+ a->N, a->C, a->H, a->W,
475
+ a->Kh, a->Kw,
476
+ a->stride, a->pad,
477
+ a->OH, a->OW);
478
+ }
479
+
480
+ cblas_sgemm(CblasRowMajor,
481
+ CblasTrans, CblasNoTrans,
482
+ a->Cout, a->K, a->rows,
483
+ 1.0f,
484
+ a->dout2d, a->Cout,
485
+ a->col, a->K,
486
+ 0.0f,
487
+ a->dw, a->K);
488
+ }
489
+ // No early return here: if col were NULL, it's better to leave dw
490
+ // uncomputed than to crash, but this should never actually happen
491
+ // (the caller guarantees col is allocated whenever want_dw is set).
492
+ }
493
+
494
+ if (a->want_dw && a->dw) {
495
+ if (any_nonfinite(a->dw, (size_t)a->Cout * (size_t)a->K)) {
496
+ a->bad = 1; a->bad_where = 2; return NULL;
497
+ }
498
+ }
499
+
500
+ // 4) dx
501
+ if (a->want_dx && a->dx) {
502
+ // dx does NOT need col; it needs dcol.
503
+ if (a->dcol) {
504
+ cblas_sgemm(CblasRowMajor,
505
+ CblasNoTrans, CblasNoTrans,
506
+ a->rows, a->K, a->Cout,
507
+ 1.0f,
508
+ a->dout2d, a->Cout,
509
+ a->w, a->K,
510
+ 0.0f,
511
+ a->dcol, a->K);
512
+
513
+ if (a->want_dx && a->dcol) {
514
+ if (any_nonfinite(a->dcol, (size_t)a->rows * (size_t)a->K)) {
515
+ a->bad = 1; a->bad_where = 3; return NULL;
516
+ }
517
+ }
518
+
519
+ col2im_f32(a->dcol, a->dx,
520
+ a->N, a->C, a->H, a->W,
521
+ a->Kh, a->Kw,
522
+ a->stride, a->pad,
523
+ a->OH, a->OW);
524
+
525
+ if (a->want_dx && a->dx) {
526
+ if (any_nonfinite(a->dx, (size_t)a->N * (size_t)a->C * (size_t)a->H * (size_t)a->W)) {
527
+ a->bad = 1; a->bad_where = 4; return NULL;
528
+ }
529
+ }
530
+ }
531
+ // no early return
532
+ }
533
+
534
+
535
+
536
+ return NULL;
537
+ }
538
+
539
+
540
+ /* ---------- Maurograd::Ext.conv2d_backward ---------- */
541
+
542
+ static VALUE mg_conv2d_backward(VALUE self, VALUE vx, VALUE vw, VALUE vdout,
543
+ VALUE vstride, VALUE vpad,
544
+ VALUE vwant_dx, VALUE vwant_dw, VALUE vwant_db,
545
+ VALUE workspace)
546
+ {
547
+ // type checks
548
+ if (!rb_obj_is_kind_of(vx, cNArray_) || !rb_obj_is_kind_of(vx, cSFloat_))
549
+ rb_raise(rb_eTypeError, "x must be Numo::SFloat");
550
+ if (!rb_obj_is_kind_of(vw, cNArray_) || !rb_obj_is_kind_of(vw, cSFloat_))
551
+ rb_raise(rb_eTypeError, "w must be Numo::SFloat");
552
+ if (!rb_obj_is_kind_of(vdout, cNArray_) || !rb_obj_is_kind_of(vdout, cSFloat_))
553
+ rb_raise(rb_eTypeError, "dout must be Numo::SFloat");
554
+ check_sfloat_contiguous(vx, "x");
555
+ check_sfloat_contiguous(vw, "w");
556
+ check_sfloat_contiguous(vdout, "dout");
557
+
558
+ narray_t *nx, *nw, *ndout;
559
+ GetNArray(vx, nx);
560
+ GetNArray(vw, nw);
561
+ GetNArray(vdout, ndout);
562
+
563
+ if (nx->ndim != 4) rb_raise(rb_eArgError, "x must be 4D [N,C,H,W]");
564
+ if (nw->ndim != 4) rb_raise(rb_eArgError, "w must be 4D [Cout,C,Kh,Kw]");
565
+ if (ndout->ndim != 4)rb_raise(rb_eArgError, "dout must be 4D [N,Cout,OH,OW]");
566
+
567
+ const int stride = NUM2INT(vstride);
568
+ const int pad = NUM2INT(vpad);
569
+
570
+ const int want_dx = RTEST(vwant_dx) ? 1 : 0;
571
+ const int want_dw = RTEST(vwant_dw) ? 1 : 0;
572
+ const int want_db = RTEST(vwant_db) ? 1 : 0;
573
+
574
+ // shapes
575
+ const int N = sz_to_int(nx->shape[0], "N");
576
+ const int C = sz_to_int(nx->shape[1], "C");
577
+ const int H = sz_to_int(nx->shape[2], "H");
578
+ const int W = sz_to_int(nx->shape[3], "W");
579
+
580
+ const int Cout = sz_to_int(nw->shape[0], "Cout");
581
+ const int Cin = sz_to_int(nw->shape[1], "Cin");
582
+ const int Kh = sz_to_int(nw->shape[2], "Kh");
583
+ const int Kw = sz_to_int(nw->shape[3], "Kw");
584
+
585
+ if (Cin != C) rb_raise(rb_eArgError, "channel mismatch: x.C=%d, w.Cin=%d", C, Cin);
586
+
587
+ const int dN = sz_to_int(ndout->shape[0], "dout.N");
588
+ const int dCout = sz_to_int(ndout->shape[1], "dout.Cout");
589
+ const int OH = sz_to_int(ndout->shape[2], "OH");
590
+ const int OW = sz_to_int(ndout->shape[3], "OW");
591
+
592
+ if (dN != N) rb_raise(rb_eArgError, "dout N mismatch: %d vs %d", dN, N);
593
+ if (dCout != Cout) rb_raise(rb_eArgError, "dout Cout mismatch: %d vs %d", dCout, Cout);
594
+ check_window_params(Kh, Kw, stride, pad);
595
+
596
+ // expected OH/OW sanity
597
+ const int exp_OH = (H + 2*pad - Kh) / stride + 1;
598
+ const int exp_OW = (W + 2*pad - Kw) / stride + 1;
599
+ if (OH != exp_OH || OW != exp_OW) {
600
+ rb_raise(rb_eArgError, "dout OH/OW mismatch: got (%d,%d), expected (%d,%d)",
601
+ OH, OW, exp_OH, exp_OW);
602
+ }
603
+
604
+ const int rows = N * OH * OW;
605
+ const int K = C * Kh * Kw;
606
+
607
+ // Allocate outputs (or nil)
608
+ VALUE vdx = Qnil, vdw = Qnil, vdb = Qnil;
609
+
610
+ if (want_dx) {
611
+ vdx = sfloat_new_4d(N, C, H, W);
612
+ float *dx = (float*)na_get_pointer_for_write(vdx);
613
+ memset(dx, 0, sizeof(float) * (size_t)N * C * H * W);
614
+ }
615
+ if (want_dw) {
616
+ vdw = sfloat_new_4d(Cout, C, Kh, Kw);
617
+ float *dwp = (float*)na_get_pointer_for_write(vdw);
618
+ memset(dwp, 0, sizeof(float) * (size_t)Cout * (size_t)C * (size_t)Kh * (size_t)Kw);
619
+ }
620
+ if (want_db) {
621
+ size_t args[1] = { (size_t)(Cout) };
622
+ vdb = nary_new(cSFloat_, 1, args);
623
+ float *dbp = (float*)na_get_pointer_for_write(vdb);
624
+ memset(dbp, 0, sizeof(float) * (size_t)Cout);
625
+ }
626
+
627
+ // Allocate temporaries as needed
628
+ VALUE vdout2d = Qnil;
629
+ VALUE vdcol = Qnil;
630
+
631
+ if (want_dx || want_dw || want_db) {
632
+ vdout2d = sfloat_new_2d(rows, Cout);
633
+ float *dout2d = (float*)na_get_pointer_for_write(vdout2d);
634
+ memset(dout2d, 0, sizeof(float) * (size_t)(rows * Cout));
635
+ }
636
+ if (want_dx) {
637
+ vdcol = sfloat_new_2d(rows, K);
638
+ float *dcol = (float*)na_get_pointer_for_write(vdcol);
639
+ memset(dcol, 0, sizeof(float) * (size_t)(rows * K));
640
+ }
641
+
642
+ // Get pointers BEFORE releasing GVL
643
+ const float *x = (const float*)na_get_pointer_for_read(vx);
644
+ const float *w = (const float*)na_get_pointer_for_read(vw);
645
+ const float *dout = (const float*)na_get_pointer_for_read(vdout);
646
+
647
+ float *dout2d = (vdout2d == Qnil) ? NULL : (float*)na_get_pointer_for_write(vdout2d);
648
+ float *dcol = (vdcol == Qnil) ? NULL : (float*)na_get_pointer_for_write(vdcol);
649
+
650
+ float *dx = (vdx == Qnil) ? NULL : (float*)na_get_pointer_for_write(vdx);
651
+ float *dw = (vdw == Qnil) ? NULL : (float*)na_get_pointer_for_write(vdw);
652
+ float *db = (vdb == Qnil) ? NULL : (float*)na_get_pointer_for_write(vdb);
653
+
654
+ VALUE ws_col = rb_hash_aref(workspace, sym_col);
655
+
656
+ int have_col = 0;
657
+ if (ws_col != Qnil) {
658
+ // Deve essere SFloat 2D [rows, K]
659
+ if (rb_obj_is_kind_of(ws_col, cNArray_) &&
660
+ rb_obj_is_kind_of(ws_col, cSFloat_)) {
661
+ narray_t *nws;
662
+ GetNArray(ws_col, nws);
663
+ if (nws->ndim == 2) {
664
+ int r0 = sz_to_int(nws->shape[0], "ws_col.rows");
665
+ int k0 = sz_to_int(nws->shape[1], "ws_col.K");
666
+ if (r0 == rows && k0 == K) {
667
+ have_col = 1;
668
+ }
669
+ }
670
+ }
671
+ }
672
+
673
+ VALUE vcol = Qnil;
674
+ if (want_dw && !have_col) {
675
+ /* Need to allocate col */
676
+ vcol = sfloat_new_2d(rows, K);
677
+ } else if (want_dw && have_col) {
678
+ /* Use col from workspace */
679
+ vcol = ws_col;
680
+ }
681
+
682
+ float *col = NULL;
683
+ if (vcol != Qnil) {
684
+ if (have_col) {
685
+ /* We take col from workspace, so we need the read pointer */
686
+ col = (float*)na_get_pointer_for_read(vcol);
687
+ } else {
688
+ /* We have to calculate col with im2col */
689
+ col = (float*)na_get_pointer_for_write(vcol);
690
+ }
691
+ }
692
+
693
+ conv2d_bwd_args args;
694
+ args.x = x; args.w = w; args.dout = dout;
695
+ args.dout2d = dout2d;
696
+ args.dcol = dcol;
697
+ args.dx = dx;
698
+ args.dw = dw;
699
+ args.db = db;
700
+ args.N=N; args.C=C; args.H=H; args.W=W;
701
+ args.Cout=Cout; args.Kh=Kh; args.Kw=Kw;
702
+ args.OH=OH; args.OW=OW;
703
+ args.rows=rows; args.K=K;
704
+ args.stride=stride; args.pad=pad;
705
+ args.want_dx=want_dx; args.want_dw=want_dw; args.want_db=want_db;
706
+ args.col = col;
707
+ args.have_col = have_col;
708
+
709
+ args.bad = 0;
710
+ args.bad_where = 0;
711
+
712
+ /* Guard temporary and output variables */
713
+ RB_GC_GUARD(vdx);
714
+ RB_GC_GUARD(vdw);
715
+ RB_GC_GUARD(vdb);
716
+ RB_GC_GUARD(vdout2d);
717
+ RB_GC_GUARD(vcol);
718
+ RB_GC_GUARD(vdcol);
719
+
720
+ if ((want_dx || want_dw || want_db) && !dout2d) {
721
+ rb_raise(rb_eRuntimeError, "internal: dout2d is NULL but required");
722
+ }
723
+ if (want_dx && (!dx || !dcol)) {
724
+ rb_raise(rb_eRuntimeError, "internal: dx/dcol is NULL but want_dx=1");
725
+ }
726
+ if (want_dw && (!dw || !col)) {
727
+ rb_raise(rb_eRuntimeError, "internal: dw/col is NULL but want_dw=1");
728
+ }
729
+ if (want_db && (!db)) {
730
+ rb_raise(rb_eRuntimeError, "internal: db is NULL but want_db=1");
731
+ }
732
+
733
+ /* Run without GVL */
734
+ rb_thread_call_without_gvl(conv2d_backward_nogvl, &args, RUBY_UBF_IO, NULL);
735
+
736
+ if (args.bad) {
737
+ const char *where =
738
+ (args.bad_where==1) ? "dout2d" :
739
+ (args.bad_where==2) ? "dw" :
740
+ (args.bad_where==3) ? "dcol" :
741
+ (args.bad_where==4) ? "dx" :
742
+ (args.bad_where==5) ? "db" : "unknown";
743
+ rb_raise(rb_eRuntimeError, "conv2d_backward produced NaN/Inf in %s", where);
744
+ }
745
+
746
+
747
+ return rb_ary_new_from_args(3, vdx, vdw, vdb);
748
+ }
749
+
750
+
751
+ /* ---------- Maurograd::Ext.im2col ---------- */
752
+
753
+ static VALUE mg_im2col(VALUE self, VALUE vx, VALUE vkh, VALUE vkw, VALUE vstride, VALUE vpad)
754
+ {
755
+ check_sfloat_contiguous(vx, "x");
756
+ narray_t *nx;
757
+ GetNArray(vx, nx);
758
+
759
+ int kh = NUM2INT(vkh), kw = NUM2INT(vkw);
760
+ int stride = NUM2INT(vstride), pad = NUM2INT(vpad);
761
+ check_window_params(kh, kw, stride, pad);
762
+
763
+ if (nx->ndim != 4) rb_raise(rb_eArgError, "x must be 4D (NCHW)");
764
+
765
+ int N = sz_to_int(nx->shape[0], "N");
766
+ int C = sz_to_int(nx->shape[1], "C");
767
+ int H = sz_to_int(nx->shape[2], "H");
768
+ int W = sz_to_int(nx->shape[3], "W");
769
+
770
+ int OH = (H + 2*pad - kh) / stride + 1;
771
+ int OW = (W + 2*pad - kw) / stride + 1;
772
+ if (OH <= 0 || OW <= 0) rb_raise(rb_eArgError, "invalid output shape");
773
+
774
+ int rows = sz_to_int((size_t)N * (size_t)OH * (size_t)OW, "rows");
775
+ int cols = sz_to_int((size_t)C * (size_t)kh * (size_t)kw, "cols");
776
+
777
+ size_t out_shape[2] = { (size_t)rows, (size_t)cols };
778
+ VALUE vout = nary_new(cSFloat_, 2, out_shape);
779
+
780
+ float *x = (float*)na_get_pointer_for_read(vx);
781
+ float *out = (float*)na_get_pointer_for_write(vout);
782
+
783
+ im2col_f32(x, out, N, C, H, W, kh, kw, stride, pad, OH, OW);
784
+
785
+ return vout;
786
+ }
787
+
788
+
789
+
790
+ /* ---------- col2im ---------- */
791
+
792
+ static VALUE mg_col2im(VALUE self,
793
+ VALUE vdcol,
794
+ VALUE vxshape,
795
+ VALUE vkh,
796
+ VALUE vkw,
797
+ VALUE vstride,
798
+ VALUE vpad)
799
+ {
800
+ check_sfloat_contiguous(vdcol, "dcol");
801
+
802
+ int Kh = NUM2INT(vkh);
803
+ int Kw = NUM2INT(vkw);
804
+ int stride = NUM2INT(vstride);
805
+ int pad = NUM2INT(vpad);
806
+ check_window_params(Kh, Kw, stride, pad);
807
+
808
+ Check_Type(vxshape, T_ARRAY);
809
+ if (RARRAY_LEN(vxshape) != 4) rb_raise(rb_eArgError, "x_shape must be [N, C, H, W]");
810
+ int dims[4];
811
+ for (int i = 0; i < 4; i++) {
812
+ long d = NUM2LONG(rb_ary_entry(vxshape, i));
813
+ if (d <= 0) rb_raise(rb_eArgError, "x_shape entries must be positive");
814
+ dims[i] = sz_to_int((size_t)d, "x_shape entry");
815
+ }
816
+ int N = dims[0], C = dims[1], H = dims[2], W = dims[3];
817
+
818
+ int OH = (H + 2*pad - Kh) / stride + 1;
819
+ int OW = (W + 2*pad - Kw) / stride + 1;
820
+ if (OH <= 0 || OW <= 0) rb_raise(rb_eArgError, "invalid output shape");
821
+
822
+ /* dcol must be exactly the [N*OH*OW, C*Kh*Kw] matrix im2col would
823
+ * produce for this shape: col2im_f32 reads that many floats from it. */
824
+ size_t rows = (size_t)N * (size_t)OH * (size_t)OW;
825
+ size_t cols = (size_t)C * (size_t)Kh * (size_t)Kw;
826
+ sz_to_int(rows, "rows");
827
+ sz_to_int(cols, "cols");
828
+ narray_t *ndc;
829
+ GetNArray(vdcol, ndc);
830
+ if (ndc->ndim != 2 || ndc->shape[0] != rows || ndc->shape[1] != cols) {
831
+ rb_raise(rb_eArgError, "dcol must have shape [%zu, %zu] for x_shape [%d, %d, %d, %d]",
832
+ rows, cols, N, C, H, W);
833
+ }
834
+
835
+ size_t out_shape[4] = { (size_t)N, (size_t)C, (size_t)H, (size_t)W };
836
+ VALUE vdx = nary_new(cSFloat_, 4, out_shape);
837
+
838
+ float *dx = (float*)na_get_pointer_for_write(vdx);
839
+ float *dcol = (float*)na_get_pointer_for_read(vdcol);
840
+
841
+ col2im_f32(dcol, dx, N, C, H, W, Kh, Kw, stride, pad, OH, OW);
842
+
843
+ return vdx;
844
+ }
845
+
846
+
847
+
848
+ /* ---------- Init ---------- */
849
+
850
+ /* ---------- Maurograd::Ext.maxpool2d_forward / maxpool2d_backward ---------- */
851
+
852
+ /*
853
+ * Direct MaxPool2D kernels (NCHW), replacing the im2col + Numo reduction
854
+ * path: no [rows, C*Kh*Kw] window matrix and no float mask are ever built.
855
+ *
856
+ * Forward returns [y, argmax]:
857
+ * y SFloat [N,C,OH,OW] window maxima
858
+ * argmax Int32 [N,C,OH,OW] flat index into x of each window's maximum,
859
+ * or -1 when the maximum is a padding cell
860
+ *
861
+ * Semantics:
862
+ * - Padding cells count as 0.0 (Maurograd's documented convention; PyTorch
863
+ * pads with -inf instead).
864
+ * - Ties go to the FIRST maximum in row-major window order, so each output
865
+ * sends its gradient to exactly one input (as PyTorch does).
866
+ *
867
+ * Backward scatters dout into dx at the recorded argmax positions (windows
868
+ * can overlap when stride < kernel, hence +=).
869
+ */
870
+ static VALUE mg_maxpool2d_forward(VALUE self, VALUE vx, VALUE vkh, VALUE vkw, VALUE vstride, VALUE vpad)
871
+ {
872
+ if (!rb_obj_is_kind_of(vx, cSFloat_)) rb_raise(rb_eTypeError, "x must be Numo::SFloat");
873
+
874
+ narray_t *nx;
875
+ GetNArray(vx, nx);
876
+ if (nx->ndim != 4) rb_raise(rb_eArgError, "x must be 4D (NCHW)");
877
+ if (!RTEST(na_check_contiguous(vx))) rb_raise(rb_eArgError, "x must be contiguous");
878
+
879
+ const int kh = NUM2INT(vkh), kw = NUM2INT(vkw);
880
+ const int stride = NUM2INT(vstride), pad = NUM2INT(vpad);
881
+ if (kh <= 0 || kw <= 0 || stride <= 0 || pad < 0) rb_raise(rb_eArgError, "invalid kernel/stride/padding");
882
+
883
+ const int N = sz_to_int(nx->shape[0], "N");
884
+ const int C = sz_to_int(nx->shape[1], "C");
885
+ const int H = sz_to_int(nx->shape[2], "H");
886
+ const int W = sz_to_int(nx->shape[3], "W");
887
+
888
+ const int OH = (H + 2*pad - kh) / stride + 1;
889
+ const int OW = (W + 2*pad - kw) / stride + 1;
890
+ if (OH <= 0 || OW <= 0) rb_raise(rb_eArgError, "invalid output shape");
891
+ if ((size_t)N * C * H * W > (size_t)INT32_MAX) rb_raise(rb_eArgError, "input too large for int32 argmax");
892
+
893
+ size_t oshape[4] = { (size_t)N, (size_t)C, (size_t)OH, (size_t)OW };
894
+ VALUE vy = nary_new(cSFloat_, 4, oshape);
895
+ VALUE vidx = nary_new(cInt32_, 4, oshape);
896
+
897
+ const float *x = (const float*)na_get_pointer_for_read(vx);
898
+ float *y = (float*)na_get_pointer_for_write(vy);
899
+ int32_t *idx = (int32_t*)na_get_pointer_for_write(vidx);
900
+
901
+ size_t o = 0;
902
+ for (int nc = 0; nc < N * C; nc++) {
903
+ const float *xp = x + (size_t)nc * H * W;
904
+ const int32_t plane = nc * H * W;
905
+ for (int oy = 0; oy < OH; oy++) {
906
+ const int y0 = oy * stride - pad;
907
+ for (int ox = 0; ox < OW; ox++, o++) {
908
+ const int x0 = ox * stride - pad;
909
+ float best = 0.0f;
910
+ int32_t best_i = -1;
911
+ int first = 1;
912
+ for (int ky = 0; ky < kh; ky++) {
913
+ const int iy = y0 + ky;
914
+ const int row_in = (unsigned)iy < (unsigned)H;
915
+ for (int kx = 0; kx < kw; kx++) {
916
+ const int ix = x0 + kx;
917
+ const int in = row_in && (unsigned)ix < (unsigned)W;
918
+ const float v = in ? xp[iy * W + ix] : 0.0f;
919
+ if (first || v > best) {
920
+ best = v;
921
+ best_i = in ? plane + iy * W + ix : -1;
922
+ first = 0;
923
+ }
924
+ }
925
+ }
926
+ y[o] = best;
927
+ idx[o] = best_i;
928
+ }
929
+ }
930
+ }
931
+
932
+ RB_GC_GUARD(vx);
933
+ return rb_assoc_new(vy, vidx);
934
+ }
935
+
936
+ static VALUE mg_maxpool2d_backward(VALUE self, VALUE vdout, VALUE vidx, VALUE vinput_shape)
937
+ {
938
+ if (!rb_obj_is_kind_of(vdout, cSFloat_)) rb_raise(rb_eTypeError, "dout must be Numo::SFloat");
939
+ if (!rb_obj_is_kind_of(vidx, cInt32_)) rb_raise(rb_eTypeError, "argmax must be Numo::Int32");
940
+ if (!RTEST(na_check_contiguous(vdout))) rb_raise(rb_eArgError, "dout must be contiguous");
941
+ Check_Type(vinput_shape, T_ARRAY);
942
+ if (RARRAY_LEN(vinput_shape) != 4) rb_raise(rb_eArgError, "input_shape must have 4 dims");
943
+
944
+ narray_t *nd, *ni;
945
+ GetNArray(vdout, nd);
946
+ GetNArray(vidx, ni);
947
+ if (nd->size != ni->size) rb_raise(rb_eArgError, "dout/argmax size mismatch");
948
+
949
+ size_t xshape[4];
950
+ size_t xsize = 1;
951
+ for (int i = 0; i < 4; i++) {
952
+ long d = NUM2LONG(rb_ary_entry(vinput_shape, i));
953
+ if (d <= 0) rb_raise(rb_eArgError, "invalid input_shape");
954
+ xshape[i] = (size_t)d;
955
+ xsize *= (size_t)d;
956
+ }
957
+
958
+ VALUE vdx = nary_new(cSFloat_, 4, xshape);
959
+ float *dx = (float*)na_get_pointer_for_write(vdx);
960
+ memset(dx, 0, sizeof(float) * xsize);
961
+
962
+ const float *dout = (const float*)na_get_pointer_for_read(vdout);
963
+ const int32_t *idx = (const int32_t*)na_get_pointer_for_read(vidx);
964
+
965
+ for (size_t o = 0; o < nd->size; o++) {
966
+ const int32_t i = idx[o];
967
+ if (i >= 0) {
968
+ if ((size_t)i >= xsize) rb_raise(rb_eArgError, "argmax index out of range");
969
+ dx[i] += dout[o];
970
+ }
971
+ }
972
+
973
+ RB_GC_GUARD(vdout);
974
+ RB_GC_GUARD(vidx);
975
+ return vdx;
976
+ }
977
+
978
+ /* ---------- Maurograd::Ext.relu_forward / relu_backward ---------- */
979
+
980
+ static VALUE sfloat_new_like(VALUE v)
981
+ {
982
+ narray_t *na;
983
+ GetNArray(v, na);
984
+ return nary_new(cSFloat_, na->ndim, na->shape);
985
+ }
986
+
987
+ /* y = max(x, 0), any shape. */
988
+ static VALUE mg_relu_forward(VALUE self, VALUE vx)
989
+ {
990
+ check_sfloat_contiguous(vx, "x");
991
+ narray_t *nx;
992
+ GetNArray(vx, nx);
993
+
994
+ VALUE vy = sfloat_new_like(vx);
995
+ const float *restrict x = (const float*)na_get_pointer_for_read(vx);
996
+ float *restrict y = (float*)na_get_pointer_for_write(vy);
997
+ for (size_t i = 0; i < nx->size; i++) y[i] = x[i] > 0.0f ? x[i] : 0.0f;
998
+
999
+ RB_GC_GUARD(vx);
1000
+ return vy;
1001
+ }
1002
+
1003
+ /* dx = dy where y > 0, else 0 (y > 0 exactly where x > 0). */
1004
+ static VALUE mg_relu_backward(VALUE self, VALUE vdy, VALUE vy)
1005
+ {
1006
+ check_sfloat_contiguous(vdy, "dy");
1007
+ check_sfloat_contiguous(vy, "y");
1008
+ narray_t *nd, *ny;
1009
+ GetNArray(vdy, nd);
1010
+ GetNArray(vy, ny);
1011
+ if (nd->size != ny->size) rb_raise(rb_eArgError, "dy/y size mismatch");
1012
+
1013
+ VALUE vdx = sfloat_new_like(vdy);
1014
+ const float *restrict dy = (const float*)na_get_pointer_for_read(vdy);
1015
+ const float *restrict y = (const float*)na_get_pointer_for_read(vy);
1016
+ float *restrict dx = (float*)na_get_pointer_for_write(vdx);
1017
+ /* Load both operands unconditionally: written as `y > 0 ? dy[i] : 0`,
1018
+ * the compiler may not read dy[i] speculatively, so it emits a real
1019
+ * branch, which the CPU mispredicts ~50% of the time on activations
1020
+ * (~9x slower than this vectorizable select, measured). */
1021
+ for (size_t i = 0; i < nd->size; i++) {
1022
+ const float g = dy[i];
1023
+ dx[i] = y[i] > 0.0f ? g : 0.0f;
1024
+ }
1025
+
1026
+ RB_GC_GUARD(vdy);
1027
+ RB_GC_GUARD(vy);
1028
+ return vdx;
1029
+ }
1030
+
1031
+ /* ---------- Maurograd::Ext.batchnorm2d_forward / batchnorm2d_backward ---------- */
1032
+
1033
+ /* Optional per-channel [C] SFloat (nil allowed); returns NULL for nil. */
1034
+ static const float* channel_vec_or_null(VALUE v, int C, const char *name)
1035
+ {
1036
+ if (NIL_P(v)) return NULL;
1037
+ check_sfloat_contiguous(v, name);
1038
+ narray_t *na;
1039
+ GetNArray(v, na);
1040
+ if ((int)na->size != C) rb_raise(rb_eArgError, "%s must have %d elements", name, C);
1041
+ return (const float*)na_get_pointer_for_read(v);
1042
+ }
1043
+
1044
+ /*
1045
+ * Per-channel batch normalization of x [N,C,H,W].
1046
+ *
1047
+ * If mean/var are nil (training), the batch statistics are computed here
1048
+ * (biased variance, accumulated in double). Otherwise (eval) the given
1049
+ * running statistics are used.
1050
+ *
1051
+ * Returns [y, x_hat, mean, var, inv_std]; the last three are [C] arrays.
1052
+ */
1053
+ static VALUE mg_batchnorm2d_forward(VALUE self, VALUE vx, VALUE vmean, VALUE vvar,
1054
+ VALUE vgamma, VALUE vbeta, VALUE veps)
1055
+ {
1056
+ check_sfloat_contiguous(vx, "x");
1057
+ narray_t *nx;
1058
+ GetNArray(vx, nx);
1059
+ if (nx->ndim != 4) rb_raise(rb_eArgError, "x must be 4D (NCHW)");
1060
+
1061
+ const int N = sz_to_int(nx->shape[0], "N");
1062
+ const int C = sz_to_int(nx->shape[1], "C");
1063
+ const size_t HW = nx->shape[2] * nx->shape[3];
1064
+ const double m = (double)N * (double)HW;
1065
+ const double eps = NUM2DBL(veps);
1066
+
1067
+ if (NIL_P(vmean) != NIL_P(vvar)) rb_raise(rb_eArgError, "mean and var must both be given or both be nil");
1068
+ const float *rmean = channel_vec_or_null(vmean, C, "mean");
1069
+ const float *rvar = channel_vec_or_null(vvar, C, "var");
1070
+ const float *gamma = channel_vec_or_null(vgamma, C, "gamma");
1071
+ const float *beta = channel_vec_or_null(vbeta, C, "beta");
1072
+
1073
+ size_t cshape[1] = { (size_t)C };
1074
+ VALUE vy = sfloat_new_like(vx);
1075
+ VALUE vxhat = sfloat_new_like(vx);
1076
+ VALUE vmean_out = nary_new(cSFloat_, 1, cshape);
1077
+ VALUE vvar_out = nary_new(cSFloat_, 1, cshape);
1078
+ VALUE vinv_out = nary_new(cSFloat_, 1, cshape);
1079
+
1080
+ const float *x = (const float*)na_get_pointer_for_read(vx);
1081
+ float *y = (float*)na_get_pointer_for_write(vy);
1082
+ float *xhat = (float*)na_get_pointer_for_write(vxhat);
1083
+ float *mean_out = (float*)na_get_pointer_for_write(vmean_out);
1084
+ float *var_out = (float*)na_get_pointer_for_write(vvar_out);
1085
+ float *inv_out = (float*)na_get_pointer_for_write(vinv_out);
1086
+
1087
+ for (int c = 0; c < C; c++) {
1088
+ double mu, var;
1089
+ if (rmean) {
1090
+ mu = rmean[c];
1091
+ var = rvar[c];
1092
+ } else {
1093
+ double s = 0.0;
1094
+ for (int n = 0; n < N; n++) {
1095
+ const float *p = x + ((size_t)n * C + c) * HW;
1096
+ for (size_t i = 0; i < HW; i++) s += p[i];
1097
+ }
1098
+ mu = s / m;
1099
+ double ss = 0.0;
1100
+ for (int n = 0; n < N; n++) {
1101
+ const float *p = x + ((size_t)n * C + c) * HW;
1102
+ for (size_t i = 0; i < HW; i++) { const double d = p[i] - mu; ss += d * d; }
1103
+ }
1104
+ var = ss / m;
1105
+ }
1106
+
1107
+ const float inv_std = (float)(1.0 / sqrt(var + eps));
1108
+ const float g = gamma ? gamma[c] : 1.0f;
1109
+ const float b = beta ? beta[c] : 0.0f;
1110
+ const float fmu = (float)mu;
1111
+
1112
+ for (int n = 0; n < N; n++) {
1113
+ const size_t off = ((size_t)n * C + c) * HW;
1114
+ for (size_t i = 0; i < HW; i++) {
1115
+ const float xh = (x[off + i] - fmu) * inv_std;
1116
+ xhat[off + i] = xh;
1117
+ y[off + i] = g * xh + b;
1118
+ }
1119
+ }
1120
+
1121
+ mean_out[c] = fmu;
1122
+ var_out[c] = (float)var;
1123
+ inv_out[c] = inv_std;
1124
+ }
1125
+
1126
+ RB_GC_GUARD(vx);
1127
+ VALUE res = rb_ary_new_capa(5);
1128
+ rb_ary_push(res, vy);
1129
+ rb_ary_push(res, vxhat);
1130
+ rb_ary_push(res, vmean_out);
1131
+ rb_ary_push(res, vvar_out);
1132
+ rb_ary_push(res, vinv_out);
1133
+ return res;
1134
+ }
1135
+
1136
+ /*
1137
+ * Backward of the above, given dout [N,C,H,W] and the cached x_hat/inv_std.
1138
+ *
1139
+ * dgamma[c] = sum(dout * x_hat) dbeta[c] = sum(dout)
1140
+ *
1141
+ * training (batch statistics depend on x), per channel:
1142
+ * dx = gamma * inv_std / m * (m * dout - sum(dout) - x_hat * sum(dout * x_hat))
1143
+ * eval (fixed running statistics):
1144
+ * dx = gamma * inv_std * dout
1145
+ *
1146
+ * Returns [dx, dgamma, dbeta].
1147
+ */
1148
+ static VALUE mg_batchnorm2d_backward(VALUE self, VALUE vdout, VALUE vxhat, VALUE vinv,
1149
+ VALUE vgamma, VALUE vtraining)
1150
+ {
1151
+ check_sfloat_contiguous(vdout, "dout");
1152
+ check_sfloat_contiguous(vxhat, "x_hat");
1153
+ narray_t *nd, *nh;
1154
+ GetNArray(vdout, nd);
1155
+ GetNArray(vxhat, nh);
1156
+ if (nd->ndim != 4) rb_raise(rb_eArgError, "dout must be 4D (NCHW)");
1157
+ if (nd->size != nh->size) rb_raise(rb_eArgError, "dout/x_hat size mismatch");
1158
+
1159
+ const int N = sz_to_int(nd->shape[0], "N");
1160
+ const int C = sz_to_int(nd->shape[1], "C");
1161
+ const size_t HW = nd->shape[2] * nd->shape[3];
1162
+ const double m = (double)N * (double)HW;
1163
+ const int training = RTEST(vtraining);
1164
+
1165
+ const float *inv = channel_vec_or_null(vinv, C, "inv_std");
1166
+ if (!inv) rb_raise(rb_eArgError, "inv_std is required");
1167
+ const float *gamma = channel_vec_or_null(vgamma, C, "gamma");
1168
+
1169
+ size_t cshape[1] = { (size_t)C };
1170
+ VALUE vdx = sfloat_new_like(vdout);
1171
+ VALUE vdgamma = nary_new(cSFloat_, 1, cshape);
1172
+ VALUE vdbeta = nary_new(cSFloat_, 1, cshape);
1173
+
1174
+ const float *dout = (const float*)na_get_pointer_for_read(vdout);
1175
+ const float *xhat = (const float*)na_get_pointer_for_read(vxhat);
1176
+ float *dx = (float*)na_get_pointer_for_write(vdx);
1177
+ float *dgamma = (float*)na_get_pointer_for_write(vdgamma);
1178
+ float *dbeta = (float*)na_get_pointer_for_write(vdbeta);
1179
+
1180
+ for (int c = 0; c < C; c++) {
1181
+ double sum_d = 0.0, sum_dx = 0.0;
1182
+ for (int n = 0; n < N; n++) {
1183
+ const size_t off = ((size_t)n * C + c) * HW;
1184
+ for (size_t i = 0; i < HW; i++) {
1185
+ sum_d += dout[off + i];
1186
+ sum_dx += (double)dout[off + i] * xhat[off + i];
1187
+ }
1188
+ }
1189
+ dgamma[c] = (float)sum_dx;
1190
+ dbeta[c] = (float)sum_d;
1191
+
1192
+ const float g = gamma ? gamma[c] : 1.0f;
1193
+ if (training) {
1194
+ const float k = (float)(g * inv[c] / m);
1195
+ const float fm = (float)m, fsd = (float)sum_d, fsdx = (float)sum_dx;
1196
+ for (int n = 0; n < N; n++) {
1197
+ const size_t off = ((size_t)n * C + c) * HW;
1198
+ for (size_t i = 0; i < HW; i++)
1199
+ dx[off + i] = k * (fm * dout[off + i] - fsd - xhat[off + i] * fsdx);
1200
+ }
1201
+ } else {
1202
+ const float k = g * inv[c];
1203
+ for (int n = 0; n < N; n++) {
1204
+ const size_t off = ((size_t)n * C + c) * HW;
1205
+ for (size_t i = 0; i < HW; i++) dx[off + i] = k * dout[off + i];
1206
+ }
1207
+ }
1208
+ }
1209
+
1210
+ RB_GC_GUARD(vdout);
1211
+ RB_GC_GUARD(vxhat);
1212
+ return rb_ary_new_from_args(3, vdx, vdgamma, vdbeta);
1213
+ }
1214
+
1215
+ void Init_maurograd_ext(void)
1216
+ {
1217
+ cNumo = rb_const_get(rb_cObject, rb_intern("Numo"));
1218
+ cNArray_ = rb_const_get(cNumo, rb_intern("NArray"));
1219
+ cSFloat_ = rb_const_get(cNumo, rb_intern("SFloat"));
1220
+ cInt32_ = rb_const_get(cNumo, rb_intern("Int32"));
1221
+ id_zeros = rb_intern("zeros");
1222
+
1223
+ mMaurograd = rb_define_module("Maurograd");
1224
+ mExt = rb_define_module_under(mMaurograd, "Ext");
1225
+
1226
+ /* Which BLAS this build links against ("accelerate" or "openblas"). */
1227
+ rb_define_const(mExt, "BLAS", rb_str_freeze(rb_str_new_cstr(MAUROGRAD_BLAS_NAME)));
1228
+
1229
+ rb_define_singleton_method(mExt, "conv2d_forward", mg_conv2d_forward, 6);
1230
+ rb_define_singleton_method(mExt, "conv2d_backward", mg_conv2d_backward, 9);
1231
+
1232
+ rb_define_singleton_method(mExt, "im2col", mg_im2col, 5);
1233
+ rb_define_singleton_method(mExt, "col2im", mg_col2im, 6);
1234
+
1235
+ rb_define_singleton_method(mExt, "maxpool2d_forward", mg_maxpool2d_forward, 5);
1236
+ rb_define_singleton_method(mExt, "maxpool2d_backward", mg_maxpool2d_backward, 3);
1237
+
1238
+ rb_define_singleton_method(mExt, "relu_forward", mg_relu_forward, 1);
1239
+ rb_define_singleton_method(mExt, "relu_backward", mg_relu_backward, 2);
1240
+
1241
+ rb_define_singleton_method(mExt, "batchnorm2d_forward", mg_batchnorm2d_forward, 6);
1242
+ rb_define_singleton_method(mExt, "batchnorm2d_backward", mg_batchnorm2d_backward, 5);
1243
+
1244
+ id_col = rb_intern("col");
1245
+ sym_col = ID2SYM(id_col);
1246
+ rb_global_variable(&sym_col); // optional, but good for safety
1247
+ }
1248
+
1249
+ /*
1250
+ * vim: set ts=4 sw=4 et ai
1251
+ */