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,241 @@
1
+ require "numo/narray"
2
+ require "numo/linalg"
3
+ require_relative "../backends"
4
+ require_relative "../ext"
5
+
6
+ module Maurograd
7
+ module Backends
8
+ # CPU backend: Numo::NArray storage, BLAS through Numo::Linalg and the
9
+ # maurograd_ext C extension (convolution, pooling, ReLU, BatchNorm).
10
+ #
11
+ # This is the reference implementation of the backend interface: every
12
+ # backend implements the same methods, with the same semantics, and the
13
+ # cross-backend tests compare the others against this one.
14
+ #
15
+ # Native arrays are Numo arrays, normally Numo::SFloat (float32). Integer
16
+ # arrays (e.g. class labels) are kept as they are.
17
+ #
18
+ # Note: inside Maurograd::Backends, `Numo` must be written `::Numo`, or
19
+ # Ruby would look for Maurograd::Backends::Numo first.
20
+ module CPU
21
+ module_function
22
+
23
+ def name
24
+ :cpu
25
+ end
26
+
27
+ # --- Conversion ---------------------------------------------------------
28
+
29
+ def native?(x)
30
+ x.is_a?(::Numo::NArray)
31
+ end
32
+
33
+ # Converts host data (Numeric, Array, any Numo array) into a native
34
+ # array. Numo arrays are kept as they are; everything else becomes
35
+ # SFloat.
36
+ def from(x)
37
+ native?(x) ? x : ::Numo::SFloat.cast(x)
38
+ end
39
+
40
+ # Forces the computation of the given arrays. A no-op here: Numo
41
+ # computes eagerly. (Lazy backends such as MLX need it.)
42
+ def eval(_arrays)
43
+ nil
44
+ end
45
+
46
+ # Starts computing the given arrays without waiting for the result.
47
+ # Also a no-op here.
48
+ def eval_async(_arrays)
49
+ nil
50
+ end
51
+
52
+ # Copies a native array to host memory, as a Numo array.
53
+ def to_numo(x)
54
+ x
55
+ end
56
+
57
+ # The single value of a one-element array, as a Ruby Float.
58
+ def item(x)
59
+ raise ArgumentError, "item needs a one-element array, got shape #{x.shape.inspect}" unless x.size == 1
60
+
61
+ x.to_a.flatten.first.to_f
62
+ end
63
+
64
+ # --- Creation and randomness --------------------------------------------
65
+
66
+ def zeros(shape)
67
+ ::Numo::SFloat.zeros(*shape)
68
+ end
69
+
70
+ def ones(shape)
71
+ ::Numo::SFloat.ones(*shape)
72
+ end
73
+
74
+ # Float 0/1 array where each element is 1 with probability keep_prob.
75
+ def bernoulli(shape, keep_prob)
76
+ ::Numo::SFloat.cast(::Numo::SFloat.new(*shape).rand >= (1.0 - keep_prob))
77
+ end
78
+
79
+ # Seeds this backend's random number generator.
80
+ def seed(n)
81
+ ::Numo::NArray.srand(n)
82
+ end
83
+
84
+ # --- Shape --------------------------------------------------------------
85
+
86
+ def reshape(x, *shape)
87
+ x.reshape(*shape)
88
+ end
89
+
90
+ # Permutes axes (all of them must be given, like NumPy's transpose).
91
+ def transpose(x, *axes)
92
+ x.transpose(*axes)
93
+ end
94
+
95
+ # --- Reductions ---------------------------------------------------------
96
+ #
97
+ # axis: nil reduces over everything and returns a 0-dim array.
98
+
99
+ def sum(x, axis: nil, keepdims: false)
100
+ return ::Numo::SFloat.cast(x.sum) if axis.nil?
101
+
102
+ x.sum(axis: axis, keepdims: keepdims)
103
+ end
104
+
105
+ def mean(x, axis: nil, keepdims: false)
106
+ return ::Numo::SFloat.cast(x.mean) if axis.nil?
107
+
108
+ x.mean(axis: axis, keepdims: keepdims)
109
+ end
110
+
111
+ def max(x, axis: nil, keepdims: false)
112
+ return ::Numo::SFloat.cast(x.max) if axis.nil?
113
+
114
+ x.max(axis: axis, keepdims: keepdims)
115
+ end
116
+
117
+ # --- Elementwise math ---------------------------------------------------
118
+
119
+ def exp(x)
120
+ ::Numo::NMath.exp(x)
121
+ end
122
+
123
+ def log(x)
124
+ ::Numo::NMath.log(x)
125
+ end
126
+
127
+ def sqrt(x)
128
+ ::Numo::NMath.sqrt(x)
129
+ end
130
+
131
+ # True iff every element is finite (used by Maurograd.debug checks).
132
+ def all_finite?(x)
133
+ flat = ::Numo::SFloat.cast(x).flatten
134
+ !(flat.ne(flat).any? || flat.abs.gt(1e30).any?)
135
+ end
136
+
137
+ # --- Linear algebra -----------------------------------------------------
138
+
139
+ # 2D matrix product [M, K] x [K, N] -> [M, N].
140
+ def matmul(a, b)
141
+ a.dot(b)
142
+ end
143
+
144
+ # --- Losses support -----------------------------------------------------
145
+
146
+ # Float [N, C] one-hot encoding of integer class indices [N].
147
+ def one_hot(indices, num_classes)
148
+ idx = ::Numo::Int32.cast(indices)
149
+ n = idx.size
150
+ if n.positive? && (idx.min.negative? || idx.max >= num_classes)
151
+ raise ArgumentError, "class index out of range for C=#{num_classes}"
152
+ end
153
+
154
+ out = ::Numo::SFloat.zeros(n, num_classes)
155
+ out[(::Numo::Int32.new(n).seq * num_classes) + idx] = 1.0 unless n.zero?
156
+ out
157
+ end
158
+
159
+ # --- Fused NN kernels ---------------------------------------------------
160
+ #
161
+ # Each *_forward returns the result plus a backend-specific `ctx` with
162
+ # whatever its *_backward needs; Ops treat ctx as opaque. All image
163
+ # tensors are NCHW.
164
+
165
+ # x [N,C,H,W], w [Cout,C,KH,KW], b [Cout] or nil -> [y [N,Cout,OH,OW], ctx]
166
+ def conv2d_forward(x, w, b, stride, padding)
167
+ x = contiguous_sfloat(x)
168
+ w = contiguous_sfloat(w)
169
+ b &&= contiguous_sfloat(b)
170
+ workspace = {}
171
+ y = Maurograd::Ext.conv2d_forward(x, w, b, stride, padding, workspace)
172
+ [y, {x: x, w: w, stride: stride, padding: padding, workspace: workspace}]
173
+ end
174
+
175
+ # -> [dx, dw, db] (nil for each gradient not requested)
176
+ #
177
+ # The want_* flags must be real booleans: the C side tests them with
178
+ # Ruby truthiness (RTEST), where 0 counts as true.
179
+ def conv2d_backward(ctx, dout, want_dx:, want_dw:, want_db:)
180
+ Maurograd::Ext.conv2d_backward(
181
+ ctx[:x], ctx[:w], contiguous_sfloat(dout),
182
+ ctx[:stride], ctx[:padding],
183
+ want_dx ? true : false, want_dw ? true : false, want_db ? true : false,
184
+ ctx[:workspace]
185
+ )
186
+ end
187
+
188
+ # Padding cells count as 0; ties go to the first maximum.
189
+ # -> [y [N,C,OH,OW], ctx]
190
+ def maxpool2d_forward(x, kh, kw, stride, padding)
191
+ x = contiguous_sfloat(x)
192
+ y, argmax = Maurograd::Ext.maxpool2d_forward(x, kh, kw, stride, padding)
193
+ [y, {argmax: argmax, input_shape: x.shape}]
194
+ end
195
+
196
+ def maxpool2d_backward(ctx, dout)
197
+ Maurograd::Ext.maxpool2d_backward(contiguous_sfloat(dout), ctx[:argmax], ctx[:input_shape])
198
+ end
199
+
200
+ # -> [y, ctx]
201
+ def relu_forward(x)
202
+ y = Maurograd::Ext.relu_forward(contiguous_sfloat(x))
203
+ [y, y]
204
+ end
205
+
206
+ def relu_backward(ctx, dout)
207
+ Maurograd::Ext.relu_backward(contiguous_sfloat(dout), ctx)
208
+ end
209
+
210
+ # Per-channel batch normalization. With mean/var nil (training) uses
211
+ # the batch statistics, otherwise the given running ones.
212
+ # -> [y, ctx, batch_mean [C], batch_var [C] (biased)]
213
+ def batchnorm2d_forward(x, mean, var, gamma, beta, eps)
214
+ x = contiguous_sfloat(x)
215
+ mean &&= contiguous_sfloat(mean)
216
+ var &&= contiguous_sfloat(var)
217
+ gamma &&= contiguous_sfloat(gamma)
218
+ beta &&= contiguous_sfloat(beta)
219
+ y, x_hat, bmean, bvar, inv_std = Maurograd::Ext.batchnorm2d_forward(x, mean, var, gamma, beta, eps)
220
+ [y, {x_hat: x_hat, inv_std: inv_std, gamma: gamma}, bmean, bvar]
221
+ end
222
+
223
+ # training: whether forward used batch statistics. -> [dx, dgamma, dbeta]
224
+ def batchnorm2d_backward(ctx, dout, training:)
225
+ Maurograd::Ext.batchnorm2d_backward(
226
+ contiguous_sfloat(dout), ctx[:x_hat], ctx[:inv_std], ctx[:gamma], training
227
+ )
228
+ end
229
+
230
+ # The C kernels read raw float32 memory, so they need contiguous
231
+ # SFloat arrays; arrays reaching an op may be strided views (e.g. after
232
+ # a transpose) or another dtype (e.g. a DFloat upstream gradient).
233
+ def contiguous_sfloat(a)
234
+ a = ::Numo::SFloat.cast(a) unless a.is_a?(::Numo::SFloat)
235
+ a.contiguous? ? a : a.copy
236
+ end
237
+ end
238
+
239
+ register(:cpu, CPU)
240
+ end
241
+ end
@@ -0,0 +1,114 @@
1
+ module Maurograd
2
+ # Compute backends: where tensor data lives and which code runs the math.
3
+ #
4
+ # Maurograd's autograd (Tensor, Ops, the backward graph walk) is the same
5
+ # for every backend. What a backend provides is the array type stored in
6
+ # Tensor#data / Tensor#grad (its "native" arrays) and the operations the
7
+ # Ops need on them. Backends::CPU is the reference implementation (Numo +
8
+ # the C extension); see it for the full interface, documented method by
9
+ # method.
10
+ #
11
+ # The contract has two parts:
12
+ #
13
+ # 1. Native arrays support Ruby arithmetic directly: + - * / ** and unary
14
+ # minus, between two arrays (with NumPy-style broadcasting) and between
15
+ # an array and a Numeric on either side. Op formulas use these
16
+ # operators as-is, so they read like the math.
17
+ #
18
+ # 2. Everything else (creation, reductions, reshaping, math functions,
19
+ # the fused NN kernels, conversion to/from host memory) is a method on
20
+ # the backend object: `tensor.backend.sum(x, axis: 1)`.
21
+ #
22
+ # Usage:
23
+ #
24
+ # Maurograd.backend = :mlx # default for tensors created from now on
25
+ # model.to(:mlx) # move an existing model's parameters
26
+ # t = Maurograd::Tensor.new(data, backend: :cpu)
27
+ #
28
+ module Backends
29
+ @registry = {}
30
+ @loaders = {}
31
+
32
+ class << self
33
+ # Registers a backend object under `name`.
34
+ def register(name, backend)
35
+ @registry[name.to_sym] = backend
36
+ end
37
+
38
+ # Registers a lazy loader for an optional backend: `block` runs the
39
+ # first time the backend is requested, and must register it.
40
+ def register_loader(name, &block)
41
+ @loaders[name.to_sym] = block
42
+ end
43
+
44
+ # Looks a backend up by name (Symbol/String), or returns it unchanged
45
+ # if it already is a backend object.
46
+ def fetch(name_or_backend)
47
+ return name_or_backend unless name_or_backend.is_a?(Symbol) || name_or_backend.is_a?(String)
48
+
49
+ name = name_or_backend.to_sym
50
+ unless @registry.key?(name)
51
+ loader = @loaders[name]
52
+ raise ArgumentError, "unknown backend #{name.inspect} (available: #{available.inspect})" unless loader
53
+
54
+ loader.call
55
+ raise LoadError, "loading backend #{name.inspect} did not register it" unless @registry.key?(name)
56
+ end
57
+ @registry[name]
58
+ end
59
+
60
+ # Backend objects loaded so far.
61
+ def loaded
62
+ @registry.values
63
+ end
64
+
65
+ # Names of the backends that are registered or can be loaded.
66
+ def available
67
+ (@registry.keys + @loaders.keys).uniq
68
+ end
69
+ end
70
+ end
71
+
72
+ # The MLX backend ships separately, in the maurograd-mlx gem (it needs
73
+ # mlx-c and its own extension), so it is only loaded the first time
74
+ # someone asks for it. A plain `require` (not require_relative) finds it in
75
+ # whichever installed gem provides it, or under lib/ in a repo checkout.
76
+ Backends.register_loader(:mlx) do
77
+ require "maurograd/backends/mlx"
78
+ rescue LoadError => e
79
+ raise unless e.path == "maurograd/backends/mlx"
80
+
81
+ raise LoadError, "the MLX backend is in the maurograd-mlx gem, which is not installed " \
82
+ "(it needs mlx-c: `brew install mlx-c`, then `gem install maurograd-mlx`)"
83
+ end
84
+
85
+ module Ops
86
+ # The backend shared by all the given tensors (nils ignored). Ops run on
87
+ # their inputs' backend, so mixing backends in one op is an error rather
88
+ # than a silent copy: move tensors explicitly with Tensor#to.
89
+ def self.backend_of(*tensors)
90
+ tensors = tensors.compact
91
+ backend = tensors.first.backend
92
+ tensors.each do |t|
93
+ next if t.backend.equal?(backend)
94
+
95
+ raise ArgumentError, "tensors on different backends (#{backend.name} and #{t.backend.name}) " \
96
+ "in one operation; move them with Tensor#to first"
97
+ end
98
+ backend
99
+ end
100
+ end
101
+
102
+ class << self
103
+ # The backend used for tensors created without an explicit backend:.
104
+ # Starts as the MAUROGRAD_BACKEND environment variable (e.g. "mlx"), or
105
+ # :cpu, so existing scripts can switch backend without code changes.
106
+ def backend
107
+ @backend ||= Backends.fetch(ENV.fetch("MAUROGRAD_BACKEND", "cpu"))
108
+ end
109
+
110
+ def backend=(name_or_backend)
111
+ @backend = Backends.fetch(name_or_backend)
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,28 @@
1
+ module Maurograd
2
+ # Process-level setup that has to happen before the native libraries load.
3
+ module Bootstrap
4
+ # Environment variables that cap the thread pools of the BLAS/OpenMP
5
+ # libraries we load.
6
+ BLAS_THREAD_VARS = %w[OPENBLAS_NUM_THREADS OMP_NUM_THREADS].freeze
7
+
8
+ # Defaults BLAS/OpenMP thread pools to a single thread, unless the user
9
+ # has already chosen a value.
10
+ #
11
+ # Why: numo-linalg-alt (used by Linear/MatMul via Numo's #dot) bundles
12
+ # its own OpenBLAS, whose worker threads busy-wait between calls and
13
+ # compete with everything else for the cores. Where maurograd_ext also
14
+ # links OpenBLAS (Linux), that is two such pools starving each other: on
15
+ # a 10-core Apple M5 built against OpenBLAS, one LeNet training step went
16
+ # from 13 ms (single-threaded) to 278 ms (default threading). With the
17
+ # extension on Accelerate (macOS) it is milder but still a loss: 4.9 ms
18
+ # vs 9.3 ms. At the matrix sizes Maurograd works with, multithreaded
19
+ # BLAS has little to gain anyway.
20
+ #
21
+ # This must run before those libraries are loaded: both read the
22
+ # variables once, when they initialize. To experiment with threading,
23
+ # set the variables explicitly in the environment of the process.
24
+ def self.limit_blas_threads!
25
+ BLAS_THREAD_VARS.each { |var| ENV[var] ||= "1" }
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,25 @@
1
+ module Maurograd
2
+ module Datasets
3
+ module Batching
4
+ def self.batches(x, y, batch_size: 64, shuffle: true, seed: 0, drop_last: false)
5
+ n = x.shape[0]
6
+ idx = (0...n).to_a
7
+
8
+ if shuffle
9
+ rng = Random.new(seed)
10
+ idx = idx.shuffle(random: rng)
11
+ end
12
+
13
+ Enumerator.new do |enum|
14
+ idx.each_slice(batch_size) do |ii|
15
+ next if drop_last && ii.length < batch_size
16
+
17
+ xb = x[ii, true, true, true]
18
+ yb = y[ii]
19
+ enum << [xb, yb]
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,191 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "fileutils"
4
+ require "zlib"
5
+ require "digest"
6
+ require "numo/narray"
7
+
8
+ module Maurograd
9
+ module Datasets
10
+ module MNIST
11
+ MIRRORS = [
12
+ "https://ossci-datasets.s3.amazonaws.com/mnist/",
13
+ "https://yann.lecun.com/exdb/mnist/", # Try HTTPS first
14
+ "http://yann.lecun.com/exdb/mnist/"
15
+ ].freeze
16
+
17
+ FILES = [
18
+ "train-images-idx3-ubyte.gz",
19
+ "train-labels-idx1-ubyte.gz",
20
+ "t10k-images-idx3-ubyte.gz",
21
+ "t10k-labels-idx1-ubyte.gz"
22
+ ].freeze
23
+
24
+ MD5 = {
25
+ "train-images-idx3-ubyte.gz" => "f68b3c2dcbeaaa9fbdd348bbdeb94873",
26
+ "train-labels-idx1-ubyte.gz" => "d53e105ee54ea40749a09fcbcd1e9432",
27
+ "t10k-images-idx3-ubyte.gz" => "9fb629c4189551a2d022fa330f9573f3",
28
+ "t10k-labels-idx1-ubyte.gz" => "ec29112dd5afa0611ce80d1b7f02629c"
29
+ }.freeze
30
+
31
+ def self.fetch(dest_path:, urls:, expected_md5: nil,
32
+ force: false, timeout: 30)
33
+ # If it already exists and (if requested) the MD5 checks out, return right away.
34
+ if !force && File.exist?(dest_path)
35
+ if expected_md5
36
+ got = Digest::MD5.file(dest_path).hexdigest
37
+ return dest_path if got == expected_md5
38
+ # MD5 mismatch: re-download below.
39
+ else
40
+ return dest_path
41
+ end
42
+ end
43
+
44
+ FileUtils.mkdir_p(File.dirname(dest_path))
45
+ tmp = dest_path + ".tmp"
46
+ errors = []
47
+
48
+ # Try each mirror/URL.
49
+ Array(urls).each do |u|
50
+ uri = u.is_a?(URI) ? u : URI.parse(u.to_s)
51
+ begin
52
+ File.open(tmp, "wb") do |f|
53
+ Net::HTTP.start(
54
+ uri.host,
55
+ uri.port,
56
+ use_ssl: uri.scheme == "https",
57
+ open_timeout: timeout,
58
+ read_timeout: timeout
59
+ ) do |http|
60
+ req = Net::HTTP::Get.new(uri)
61
+ http.request(req) do |res|
62
+ unless res.is_a?(Net::HTTPSuccess)
63
+ raise "HTTP #{res.code} #{res.message} for #{uri}"
64
+ end
65
+ res.read_body { |chunk| f.write(chunk) }
66
+ end
67
+ end
68
+ end
69
+
70
+ if expected_md5
71
+ got = Digest::MD5.file(tmp).hexdigest
72
+ if got != expected_md5
73
+ raise "MD5 mismatch for #{File.basename(dest_path)}: got #{got}, expected #{expected_md5}"
74
+ end
75
+ end
76
+
77
+ FileUtils.mv(tmp, dest_path)
78
+ return dest_path
79
+ rescue => e
80
+ errors << "#{uri} -> #{e.class}: #{e.message}"
81
+ FileUtils.rm_f(tmp)
82
+ next
83
+ end
84
+ end
85
+
86
+ raise "All mirrors failed for #{dest_path}:\n" + errors.map { |x| " - #{x}" }.join("\n")
87
+ end
88
+ private_class_method :fetch
89
+
90
+ def self.download(root: "data", force: false, verify_md5: true)
91
+ raw_dir = File.join(root, "mnist", "raw")
92
+ FileUtils.mkdir_p(raw_dir)
93
+
94
+ FILES.each do |gz_name|
95
+ gz_path = File.join(raw_dir, gz_name)
96
+ out_path = gz_path.sub(/\.gz\z/, "")
97
+
98
+ next if !force && File.exist?(out_path)
99
+
100
+ urls = MIRRORS.map { |base| URI.join(base, gz_name).to_s }
101
+ expected = verify_md5 ? MD5[gz_name] : nil
102
+
103
+ fetch(
104
+ dest_path: gz_path,
105
+ urls: urls,
106
+ expected_md5: expected,
107
+ force: force
108
+ )
109
+
110
+ gunzip(gz_path, out_path)
111
+ end
112
+
113
+ raw_dir
114
+ end
115
+
116
+ def self.load(root: "data", split: :train, normalize: true)
117
+ raw_dir = File.join(root, "mnist", "raw")
118
+
119
+ img_file, lbl_file =
120
+ case split
121
+ when :train
122
+ ["train-images-idx3-ubyte", "train-labels-idx1-ubyte"]
123
+ when :test
124
+ ["t10k-images-idx3-ubyte", "t10k-labels-idx1-ubyte"]
125
+ else
126
+ raise ArgumentError, "split must be :train or :test"
127
+ end
128
+
129
+ x = read_idx_images(File.join(raw_dir, img_file)) # uint8 -> Numo::UInt8 [N,28,28]
130
+ y = read_idx_labels(File.join(raw_dir, lbl_file)) # uint8 -> Numo::UInt8 [N]
131
+
132
+ x = if normalize
133
+ Numo::SFloat.cast(x) / 255.0 # [0,1]
134
+ else
135
+ Numo::SFloat.cast(x)
136
+ end
137
+
138
+ # Often useful: add a channel dimension for CNNs: [N, 1, 28, 28]
139
+ x = x.reshape(x.shape[0], 1, 28, 28)
140
+
141
+ [x, y] # y can be left as UInt8 (class indices)
142
+ end
143
+
144
+ # ------------------------------------------------------------
145
+
146
+ def self.download_file(uri, dest_path)
147
+ tmp = dest_path + ".tmp"
148
+ File.open(tmp, "wb") do |f|
149
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
150
+ req = Net::HTTP::Get.new(uri)
151
+ http.request(req) do |res|
152
+ raise "HTTP #{res.code} for #{uri}" unless res.is_a?(Net::HTTPSuccess)
153
+ res.read_body { |chunk| f.write(chunk) }
154
+ end
155
+ end
156
+ end
157
+ FileUtils.mv(tmp, dest_path)
158
+ end
159
+ private_class_method :download_file
160
+
161
+ def self.gunzip(gz_path, out_path)
162
+ Zlib::GzipReader.open(gz_path) do |gz|
163
+ File.open(out_path, "wb") { |f| IO.copy_stream(gz, f) }
164
+ end
165
+ out_path
166
+ end
167
+ private_class_method :gunzip
168
+
169
+ # IDX format: big-endian integers in header.
170
+ # Images: magic=2051, then n, rows, cols, then uint8 pixels.
171
+ def self.read_idx_images(path)
172
+ buf = File.binread(path)
173
+ magic, n, rows, cols = buf[0, 16].unpack("N4")
174
+ raise "Bad magic #{magic} in #{path}" unless magic == 2051
175
+ data = buf[16, n * rows * cols].bytes
176
+ Numo::UInt8.asarray(data).reshape(n, rows, cols)
177
+ end
178
+ private_class_method :read_idx_images
179
+
180
+ # Labels: magic=2049, then n, then uint8 labels.
181
+ def self.read_idx_labels(path)
182
+ buf = File.binread(path)
183
+ magic, n = buf[0, 8].unpack("N2")
184
+ raise "Bad magic #{magic} in #{path}" unless magic == 2049
185
+ data = buf[8, n].bytes
186
+ Numo::UInt8.asarray(data)
187
+ end
188
+ private_class_method :read_idx_labels
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,13 @@
1
+ module Maurograd
2
+ # Off by default: expensive checks like Utils.assert_finite! are pure
3
+ # overhead once a model is known to be numerically stable, since they
4
+ # walk the entire array on every forward/backward call.
5
+ #
6
+ # Enable with `Maurograd.debug = true`, or by setting MAUROGRAD_DEBUG=1
7
+ # in the environment before requiring maurograd.
8
+ @debug = ENV["MAUROGRAD_DEBUG"] == "1"
9
+
10
+ class << self
11
+ attr_accessor :debug
12
+ end
13
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads the native extension if present.
4
+ # In dev mode (repo checkout), the compiled artifact typically lives under ext/**/.
5
+ # In installed gem mode, it may be directly require-able as "maurograd_ext".
6
+
7
+ begin
8
+ require "maurograd_ext"
9
+ rescue LoadError
10
+ project_root = File.expand_path("../..", __dir__) # .../maurograd
11
+ pattern = File.join(project_root, "ext", "**", "maurograd_ext.{bundle,so}")
12
+
13
+ candidates = Dir.glob(pattern).sort
14
+ if candidates.empty?
15
+ raise LoadError, <<~MSG
16
+ cannot load native extension 'maurograd_ext'
17
+ Looked for: #{pattern}
18
+
19
+ Build it with:
20
+ ./bin/build_ext
21
+
22
+ (If you're on macOS: expect a .bundle; on Linux: a .so)
23
+ MSG
24
+ end
25
+
26
+ # Requiring the absolute path is fine (Ruby will load the .bundle/.so).
27
+ require candidates.first
28
+ end
29
+
30
+ # Sanity check (optional but helps catch partial loads early)
31
+ unless defined?(Maurograd::Ext) &&
32
+ Maurograd::Ext.respond_to?(:conv2d_forward) &&
33
+ Maurograd::Ext.respond_to?(:im2col) &&
34
+ Maurograd::Ext.respond_to?(:col2im) &&
35
+ Maurograd::Ext.respond_to?(:maxpool2d_forward) &&
36
+ Maurograd::Ext.respond_to?(:maxpool2d_backward) &&
37
+ Maurograd::Ext.respond_to?(:relu_forward) &&
38
+ Maurograd::Ext.respond_to?(:batchnorm2d_forward)
39
+ raise LoadError, "maurograd_ext loaded but key methods not defined"
40
+ end