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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +49 -0
- data/LICENSE +21 -0
- data/README.md +126 -0
- data/examples/mnist.rb +145 -0
- data/examples/mnist_batchnorm.rb +141 -0
- data/ext/maurograd_ext/extconf.rb +93 -0
- data/ext/maurograd_ext/maurograd_ext.c +1251 -0
- data/lib/maurograd/backends/cpu.rb +241 -0
- data/lib/maurograd/backends.rb +114 -0
- data/lib/maurograd/bootstrap.rb +28 -0
- data/lib/maurograd/datasets/batching.rb +25 -0
- data/lib/maurograd/datasets/mnist.rb +191 -0
- data/lib/maurograd/debug.rb +13 -0
- data/lib/maurograd/ext.rb +40 -0
- data/lib/maurograd/layers/batchnorm2d.rb +69 -0
- data/lib/maurograd/layers/conv2d.rb +135 -0
- data/lib/maurograd/layers/dropout.rb +41 -0
- data/lib/maurograd/layers/flatten.rb +11 -0
- data/lib/maurograd/layers/linear.rb +54 -0
- data/lib/maurograd/layers/maxpool2d.rb +17 -0
- data/lib/maurograd/layers/relu.rb +11 -0
- data/lib/maurograd/layers/sequential.rb +45 -0
- data/lib/maurograd/losses/bce.rb +90 -0
- data/lib/maurograd/losses/cross_entropy_with_logits.rb +129 -0
- data/lib/maurograd/losses/mse.rb +73 -0
- data/lib/maurograd/ops/add.rb +55 -0
- data/lib/maurograd/ops/batchnorm2d.rb +122 -0
- data/lib/maurograd/ops/conv2d.rb +124 -0
- data/lib/maurograd/ops/dropout.rb +82 -0
- data/lib/maurograd/ops/flatten.rb +56 -0
- data/lib/maurograd/ops/linear.rb +109 -0
- data/lib/maurograd/ops/matmul.rb +86 -0
- data/lib/maurograd/ops/maxpool2d.rb +91 -0
- data/lib/maurograd/ops/mul.rb +52 -0
- data/lib/maurograd/ops/permute.rb +75 -0
- data/lib/maurograd/ops/power.rb +46 -0
- data/lib/maurograd/ops/relu.rb +50 -0
- data/lib/maurograd/ops/sub.rb +52 -0
- data/lib/maurograd/ops/sum.rb +46 -0
- data/lib/maurograd/optim/adam.rb +91 -0
- data/lib/maurograd/optim/optimizer.rb +52 -0
- data/lib/maurograd/optim/sgd.rb +73 -0
- data/lib/maurograd/seed.rb +34 -0
- data/lib/maurograd/tensor.rb +326 -0
- data/lib/maurograd/utils/utils.rb +186 -0
- data/lib/maurograd/version.rb +3 -0
- data/lib/maurograd.rb +78 -0
- metadata +142 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
require "numo/narray"
|
|
2
|
+
|
|
3
|
+
require_relative "backends"
|
|
4
|
+
require_relative "backends/cpu"
|
|
5
|
+
|
|
6
|
+
require_relative "ops/add"
|
|
7
|
+
require_relative "ops/sub"
|
|
8
|
+
require_relative "ops/mul"
|
|
9
|
+
require_relative "ops/matmul"
|
|
10
|
+
require_relative "ops/power"
|
|
11
|
+
require_relative "ops/sum"
|
|
12
|
+
require_relative "ops/conv2d"
|
|
13
|
+
require_relative "ops/linear"
|
|
14
|
+
require_relative "ops/flatten"
|
|
15
|
+
require_relative "ops/relu"
|
|
16
|
+
require_relative "ops/maxpool2d"
|
|
17
|
+
require_relative "ops/permute"
|
|
18
|
+
|
|
19
|
+
module Maurograd
|
|
20
|
+
# Tensor is the core data structure of Maurograd.
|
|
21
|
+
#
|
|
22
|
+
# A Tensor wraps:
|
|
23
|
+
# - `data`: the actual numeric values, as a native array of its backend
|
|
24
|
+
# (a Numo::NArray on the default CPU backend)
|
|
25
|
+
# - `grad`: the accumulated gradient dL/d(data) (same array type, lazily allocated)
|
|
26
|
+
# - `creator`: the Op (operation) that created this tensor in the computation graph
|
|
27
|
+
# - `backend`: where `data` lives and which code runs the math (see
|
|
28
|
+
# Maurograd::Backends)
|
|
29
|
+
#
|
|
30
|
+
# This mirrors the design of modern autograd frameworks:
|
|
31
|
+
# - Operations (Ops) build a directed acyclic graph (DAG) of tensors.
|
|
32
|
+
# - Calling backward() on a final tensor (usually the loss) propagates gradients
|
|
33
|
+
# through the graph in reverse topological order.
|
|
34
|
+
#
|
|
35
|
+
class Tensor
|
|
36
|
+
attr_accessor :data, :grad, :creator
|
|
37
|
+
attr_reader :requires_grad, :backend
|
|
38
|
+
|
|
39
|
+
# Create a new Tensor.
|
|
40
|
+
#
|
|
41
|
+
# Params:
|
|
42
|
+
# - data: numeric data (Ruby array, scalar, Numo::NArray, or a native
|
|
43
|
+
# array of any backend). Converted to a native array of `backend`.
|
|
44
|
+
# - requires_grad: if true, this tensor participates in autograd (gradients are tracked)
|
|
45
|
+
# - backend: backend name (e.g. :cpu, :mlx) or object; defaults to
|
|
46
|
+
# Maurograd.backend
|
|
47
|
+
#
|
|
48
|
+
# Notes on dtype:
|
|
49
|
+
# - We default to Numo::SFloat (float32). This is the common choice in neural networks:
|
|
50
|
+
# it is faster and uses less memory than float64, with sufficient precision in practice.
|
|
51
|
+
#
|
|
52
|
+
def initialize(data, requires_grad: false, backend: nil)
|
|
53
|
+
@backend = backend ? Backends.fetch(backend) : Maurograd.backend
|
|
54
|
+
|
|
55
|
+
# Ensure @data is a native array of our backend (float32 by default).
|
|
56
|
+
@data = Tensor.to_native(data, @backend)
|
|
57
|
+
|
|
58
|
+
# If false, backward() becomes a no-op and gradients are not stored.
|
|
59
|
+
@requires_grad = requires_grad
|
|
60
|
+
|
|
61
|
+
# Pointer to the Op that produced this tensor.
|
|
62
|
+
# This is how we traverse the computation graph during backprop.
|
|
63
|
+
# Note: leaf tensors (parameters) have creator=nil
|
|
64
|
+
@creator = nil
|
|
65
|
+
|
|
66
|
+
# Gradient buffer (native array), allocated lazily.
|
|
67
|
+
# Many tensors in a network never need to store gradients (e.g., inference),
|
|
68
|
+
# so allocating eagerly would waste memory.
|
|
69
|
+
@grad = nil
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Converts `x` (host data, a Tensor, or a native array of any backend)
|
|
73
|
+
# into a native array of `backend`, copying only when needed.
|
|
74
|
+
def self.to_native(x, backend)
|
|
75
|
+
x = x.data if x.is_a?(Tensor)
|
|
76
|
+
return x if backend.native?(x)
|
|
77
|
+
|
|
78
|
+
# A native array of another backend: go through host memory.
|
|
79
|
+
x = x.to_numo if x.respond_to?(:to_numo) && !x.is_a?(Numo::NArray)
|
|
80
|
+
backend.from(x)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Name of the backend (kept for compatibility with the old `device`
|
|
84
|
+
# placeholder).
|
|
85
|
+
def device
|
|
86
|
+
@backend.name
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Copy of the data in host memory, as a Numo array.
|
|
90
|
+
def to_numo
|
|
91
|
+
@backend.to_numo(@data)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# The value of a one-element tensor (e.g. a loss), as a Ruby Float.
|
|
95
|
+
def item
|
|
96
|
+
@backend.item(@data)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Convenience accessors.
|
|
100
|
+
def shape
|
|
101
|
+
@data.shape
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def ndim
|
|
105
|
+
shape.length
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def size
|
|
109
|
+
shape.reduce(1, :*)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Start backpropagation from this tensor.
|
|
113
|
+
#
|
|
114
|
+
# Autograd contract:
|
|
115
|
+
# ------------------
|
|
116
|
+
# backward() accumulates gradients into `.grad` and then propagates them to
|
|
117
|
+
# upstream tensors using the `.creator` links (the computation graph).
|
|
118
|
+
#
|
|
119
|
+
# Why we need a topological traversal (not simple recursion):
|
|
120
|
+
# ----------------------------------------------------------
|
|
121
|
+
# Modern neural networks often have DAG-shaped graphs, not chains:
|
|
122
|
+
# - skip connections (ResNet)
|
|
123
|
+
# - multi-branch modules (Inception)
|
|
124
|
+
# - U-Nets with concatenations
|
|
125
|
+
#
|
|
126
|
+
# In a DAG, a tensor may contribute to the output through multiple paths.
|
|
127
|
+
# Its gradient must be the SUM of contributions from all downstream branches.
|
|
128
|
+
#
|
|
129
|
+
# If we do naive recursion, we risk:
|
|
130
|
+
# - calling backward on a shared parent multiple times before all child gradients
|
|
131
|
+
# have been accumulated
|
|
132
|
+
# - redundant work / exponential blow-ups
|
|
133
|
+
# - deep recursion / stack overflows
|
|
134
|
+
#
|
|
135
|
+
# The robust solution is:
|
|
136
|
+
# 1) Build a topological ordering of tensors reachable from `self`.
|
|
137
|
+
# 2) Traverse that ordering in reverse to propagate gradients exactly once per node.
|
|
138
|
+
#
|
|
139
|
+
# Params:
|
|
140
|
+
# - gradient: optional initial gradient dL/d(self).
|
|
141
|
+
# If omitted, this tensor must be a scalar (loss), and gradient defaults to 1.
|
|
142
|
+
#
|
|
143
|
+
def backward(gradient = nil)
|
|
144
|
+
# If this tensor does not require gradients, we stop immediately.
|
|
145
|
+
return unless @requires_grad
|
|
146
|
+
|
|
147
|
+
# 1) Initialize the starting gradient.
|
|
148
|
+
#
|
|
149
|
+
# For a scalar loss L, dL/dL = 1, so backward() can be called without arguments.
|
|
150
|
+
# For non-scalars, the caller must explicitly provide a gradient of matching shape.
|
|
151
|
+
if gradient.nil?
|
|
152
|
+
raise "Gradient can be omitted only for scalar tensors" if size > 1
|
|
153
|
+
gradient = @backend.ones(shape)
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# 2) Accumulate gradient into this tensor.
|
|
157
|
+
accumulate_grad(gradient)
|
|
158
|
+
|
|
159
|
+
# 3) Build a topological ordering of the computation graph.
|
|
160
|
+
#
|
|
161
|
+
# We collect tensors that:
|
|
162
|
+
# - are Tensors
|
|
163
|
+
# - have a creator Op (i.e., are not leaf tensors)
|
|
164
|
+
#
|
|
165
|
+
# `visited` prevents revisiting shared nodes in DAGs.
|
|
166
|
+
topo = []
|
|
167
|
+
visited = Set.new
|
|
168
|
+
|
|
169
|
+
build_topo = lambda do |t|
|
|
170
|
+
# Only traverse tensors that were created by an Op.
|
|
171
|
+
return unless t.is_a?(Tensor) && t.creator
|
|
172
|
+
return if visited.include?(t)
|
|
173
|
+
|
|
174
|
+
visited.add(t)
|
|
175
|
+
|
|
176
|
+
# Recursively visit the inputs of the creator Op.
|
|
177
|
+
# This walks the graph upstream.
|
|
178
|
+
t.creator.inputs.each { |inp| build_topo.call(inp) }
|
|
179
|
+
|
|
180
|
+
# Post-order push: parents first, then the node.
|
|
181
|
+
topo << t
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
build_topo.call(self)
|
|
185
|
+
|
|
186
|
+
# 4) Traverse in reverse topological order to run backward passes.
|
|
187
|
+
#
|
|
188
|
+
# Each tensor calls backward on its creator Op exactly once,
|
|
189
|
+
# using the gradient accumulated in tensor.grad.
|
|
190
|
+
topo.reverse_each do |t|
|
|
191
|
+
t.creator&.backward(t.grad)
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Accumulates gradient into this tensor.
|
|
196
|
+
# This is called by Ops during the backward pass.
|
|
197
|
+
def accumulate_grad(gradient)
|
|
198
|
+
return unless @requires_grad
|
|
199
|
+
|
|
200
|
+
# Ensure gradients are native arrays of our backend (not Tensors, not
|
|
201
|
+
# host arrays passed in by a caller).
|
|
202
|
+
gradient = Tensor.to_native(gradient, @backend)
|
|
203
|
+
|
|
204
|
+
@grad = @grad ? (@grad + gradient) : gradient
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# Reset gradient buffer to zeros (common at the start of each training step).
|
|
208
|
+
#
|
|
209
|
+
# Note:
|
|
210
|
+
# - We allocate a new zero array of the same shape as data.
|
|
211
|
+
# - For memory/performance, some frameworks reuse buffers; here we keep it simple.
|
|
212
|
+
def zero_grad
|
|
213
|
+
@grad = @backend.zeros(shape) if @requires_grad
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# --- Basic Ops (syntactic sugar) -----------------------------------------
|
|
217
|
+
#
|
|
218
|
+
# These methods create new tensors by calling Ops, which:
|
|
219
|
+
# - compute the forward result
|
|
220
|
+
# - record graph links (creator + inputs) if gradients are required
|
|
221
|
+
#
|
|
222
|
+
# In Ruby we must explicitly wrap scalars/arrays into Tensor objects.
|
|
223
|
+
|
|
224
|
+
def +(other)
|
|
225
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
226
|
+
Ops::Add.apply(self, other)
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def matmul(other)
|
|
230
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
231
|
+
Ops::MatMul.apply(self, other)
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def conv2d(other)
|
|
235
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
236
|
+
Ops::Conv2D.apply(self, other)
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
def **(other)
|
|
240
|
+
Ops::Power.apply(self, other)
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def sum
|
|
244
|
+
Ops::Sum.apply(self)
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
def -(other)
|
|
248
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
249
|
+
Ops::Sub.apply(self, other)
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def *(other)
|
|
253
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
254
|
+
Ops::Mul.apply(self, other)
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def linear(weight, bias = nil)
|
|
258
|
+
weight = Tensor.new(weight, backend: @backend) unless weight.is_a?(Tensor)
|
|
259
|
+
bias = Tensor.new(bias, backend: @backend) if bias && !bias.is_a?(Tensor)
|
|
260
|
+
Ops::Linear.apply(self, weight, bias)
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def flatten
|
|
264
|
+
Ops::Flatten.apply(self)
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def relu
|
|
268
|
+
Ops::ReLU.apply(self)
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
def maxpool2d(kernel_size, stride: nil, padding: 0)
|
|
272
|
+
kh, kw = kernel_size.is_a?(Integer) ? [kernel_size, kernel_size] : kernel_size
|
|
273
|
+
Ops::MaxPool2D.apply(self, kh, kw, stride, padding)
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# Moves this tensor (data and gradient) to another backend, in place,
|
|
277
|
+
# and returns self. In place, so that everything holding this Tensor
|
|
278
|
+
# (layers, optimizers) keeps working with it. Meant for leaf tensors
|
|
279
|
+
# such as parameters, not for tensors in the middle of a graph.
|
|
280
|
+
def to(backend)
|
|
281
|
+
target = Backends.fetch(backend)
|
|
282
|
+
return self if target.equal?(@backend)
|
|
283
|
+
|
|
284
|
+
@data = target.from(@backend.to_numo(@data))
|
|
285
|
+
@grad = target.from(@backend.to_numo(@grad)) if @grad
|
|
286
|
+
@backend = target
|
|
287
|
+
self
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# Swap two axes of a tensor.
|
|
291
|
+
#
|
|
292
|
+
# This is the typical "transpose" used in neural nets:
|
|
293
|
+
# - For matrices (2D): swap rows and columns.
|
|
294
|
+
# - For NCHW images (4D): swap H and W (or other chosen axes) without permuting everything.
|
|
295
|
+
#
|
|
296
|
+
# Why not call Numo's transpose() directly with no args?
|
|
297
|
+
# -----------------------------------------------------
|
|
298
|
+
# Numo::NArray#transpose with no arguments reverses ALL axes.
|
|
299
|
+
# For a 4D tensor [N, C, H, W], that would become [W, H, C, N],
|
|
300
|
+
# which is almost never what we want in CNNs.
|
|
301
|
+
#
|
|
302
|
+
# Therefore this method swaps only two axes (default: the last two).
|
|
303
|
+
# It is an autograd op (Ops::Permute): gradients flow back through it.
|
|
304
|
+
def transpose(ax0 = -2, ax1 = -1)
|
|
305
|
+
axes = (0...ndim).to_a
|
|
306
|
+
axes[ax0], axes[ax1] = axes[ax1], axes[ax0]
|
|
307
|
+
Ops::Permute.apply(self, axes)
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
# Permute tensor axes arbitrarily.
|
|
311
|
+
#
|
|
312
|
+
# This is useful to change data layout conventions, e.g.:
|
|
313
|
+
# - NCHW -> NHWC: permute(0, 2, 3, 1)
|
|
314
|
+
# - NHWC -> NCHW: permute(0, 3, 1, 2)
|
|
315
|
+
#
|
|
316
|
+
# Notes:
|
|
317
|
+
# - It is an autograd op (Ops::Permute): gradients flow back through it.
|
|
318
|
+
# - Negative axes count from the end; the axes must be a permutation of
|
|
319
|
+
# 0...ndim, or it raises ArgumentError.
|
|
320
|
+
# - On the CPU backend the result may be a strided Numo view; the kernels
|
|
321
|
+
# that need contiguous memory copy it themselves.
|
|
322
|
+
def permute(*axes)
|
|
323
|
+
Ops::Permute.apply(self, axes)
|
|
324
|
+
end
|
|
325
|
+
end
|
|
326
|
+
end
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
require_relative "../ext"
|
|
2
|
+
require_relative "../debug"
|
|
3
|
+
require_relative "../seed"
|
|
4
|
+
|
|
5
|
+
module Maurograd
|
|
6
|
+
module Utils
|
|
7
|
+
# Reduce ("undo") broadcasting for gradients.
|
|
8
|
+
#
|
|
9
|
+
# In the forward pass, Numo (like NumPy/PyTorch) may broadcast tensors automatically.
|
|
10
|
+
# Example (typical in CNNs):
|
|
11
|
+
#
|
|
12
|
+
# A: [N, C, H, W]
|
|
13
|
+
# B: [1, C, 1, 1] # per-channel bias
|
|
14
|
+
# Y = A + B # B is broadcast over N, H, W
|
|
15
|
+
#
|
|
16
|
+
# In the backward pass, the gradient coming from Y has shape [N, C, H, W],
|
|
17
|
+
# but the gradient w.r.t. B must have B's *original* shape: [1, C, 1, 1].
|
|
18
|
+
#
|
|
19
|
+
# To get that, we must SUM the incoming gradient along every axis that was
|
|
20
|
+
# broadcast (i.e., every axis where the original shape had size 1, and any
|
|
21
|
+
# extra leading axes that were added).
|
|
22
|
+
#
|
|
23
|
+
# Params:
|
|
24
|
+
# - grad: native array gradient (shape = broadcasted shape)
|
|
25
|
+
# - shape: target/original shape we want to reduce back to
|
|
26
|
+
# - backend: the backend `grad` belongs to
|
|
27
|
+
#
|
|
28
|
+
# Returns:
|
|
29
|
+
# - A native array with shape == `shape`
|
|
30
|
+
def self.unbroadcast(grad, shape, backend = Maurograd.backend)
|
|
31
|
+
# If shapes already match, nothing to do.
|
|
32
|
+
return grad if grad.shape == shape
|
|
33
|
+
|
|
34
|
+
res = grad
|
|
35
|
+
|
|
36
|
+
# 1) Remove extra leading dimensions.
|
|
37
|
+
#
|
|
38
|
+
# Example:
|
|
39
|
+
# grad = [N, C, H, W]
|
|
40
|
+
# shape = [C, H, W]
|
|
41
|
+
#
|
|
42
|
+
# This happens when an operand had fewer dimensions and was implicitly
|
|
43
|
+
# left-padded with ones. We reduce along axis 0 until ranks match.
|
|
44
|
+
while res.shape.length > shape.length
|
|
45
|
+
res = backend.sum(res, axis: 0, keepdims: false)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# 2) For remaining axes, if the target shape has a 1, that axis was broadcast.
|
|
49
|
+
# We must sum along that axis and keep the dimension (keepdims: true)
|
|
50
|
+
# so the final shape matches exactly.
|
|
51
|
+
res.shape.each_with_index do |dim, i|
|
|
52
|
+
next if dim == shape[i]
|
|
53
|
+
|
|
54
|
+
if shape[i] == 1
|
|
55
|
+
res = backend.sum(res, axis: i, keepdims: true)
|
|
56
|
+
else
|
|
57
|
+
# If shapes differ and target axis is not 1, it's a shape mismatch.
|
|
58
|
+
raise ArgumentError, "Incompatible shapes for unbroadcast: grad #{res.shape} vs target #{shape}"
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
res
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Zero-pad an NCHW tensor: [N, C, H, W] -> [N, C, H+2P, W+2P]
|
|
66
|
+
#
|
|
67
|
+
# Why do we need this helper?
|
|
68
|
+
# ---------------------------
|
|
69
|
+
# Some Numo versions do not provide `Numo::NArray#pad`, while padding is essential
|
|
70
|
+
# for convolution. Implementing it explicitly keeps Maurograd compatible and
|
|
71
|
+
# avoids relying on optional extensions.
|
|
72
|
+
#
|
|
73
|
+
# Padding is applied only on the spatial dimensions (H and W), leaving batch (N)
|
|
74
|
+
# and channels (C) unchanged.
|
|
75
|
+
#
|
|
76
|
+
# Params:
|
|
77
|
+
# - x: Numo::NArray (expected float type), shape [N, C, H, W]
|
|
78
|
+
# - padding: integer P
|
|
79
|
+
#
|
|
80
|
+
# Returns:
|
|
81
|
+
# - If padding == 0: returns x (no copy)
|
|
82
|
+
# - Else: a new tensor with x copied into the centered region
|
|
83
|
+
def self.pad_nchw(x, padding)
|
|
84
|
+
return x if padding == 0
|
|
85
|
+
|
|
86
|
+
n, c, h, w = x.shape
|
|
87
|
+
|
|
88
|
+
# Allocate padded output filled with zeros.
|
|
89
|
+
out = Numo::SFloat.zeros(n, c, h + 2 * padding, w + 2 * padding)
|
|
90
|
+
|
|
91
|
+
# Copy x into the centered region.
|
|
92
|
+
out[true, true, padding...(padding + h), padding...(padding + w)] = x
|
|
93
|
+
out
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def self.im2col(*args)
|
|
97
|
+
Maurograd::Ext.im2col(*args)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def self.col2im(*args)
|
|
101
|
+
Maurograd::Ext.col2im(*args)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# 2D transpose helper.
|
|
105
|
+
# In Numo, transpose(*axes) is a general axis permutation.
|
|
106
|
+
# For a true 2D matrix transpose you want transpose(1, 0), not transpose(0, 1).
|
|
107
|
+
def self.t2d(x)
|
|
108
|
+
x.transpose(1, 0)
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def self.assert_finite!(na, where:)
|
|
112
|
+
# Off by default (see Maurograd.debug): this walks the entire array,
|
|
113
|
+
# which is pure overhead on every forward/backward call once a model
|
|
114
|
+
# is known to be numerically stable.
|
|
115
|
+
return unless Maurograd.debug
|
|
116
|
+
|
|
117
|
+
# Debug-only, so a host copy for non-CPU backends is acceptable.
|
|
118
|
+
na = na.data if na.is_a?(Maurograd::Tensor)
|
|
119
|
+
na = na.to_numo if na.respond_to?(:to_numo) && !na.is_a?(Numo::NArray)
|
|
120
|
+
|
|
121
|
+
# Numo does not provide isfinite? universally, so we use two checks:
|
|
122
|
+
flat = Numo::NArray.cast(na).flatten
|
|
123
|
+
# NaN check: NaN != NaN is true in IEEE 754.
|
|
124
|
+
if flat.ne(flat).any?
|
|
125
|
+
raise "Non-finite detected (NaN) at #{where}"
|
|
126
|
+
end
|
|
127
|
+
# Inf check: treat values with abs > 1e30 as effectively infinite.
|
|
128
|
+
if flat.abs.gt(1e30).any?
|
|
129
|
+
raise "Non-finite detected (Inf/huge) at #{where}"
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Draws a Numo::SFloat array of `shape` from a Gaussian(mean, std).
|
|
134
|
+
#
|
|
135
|
+
# Without a seed, this is exactly Numo::SFloat#rand_norm.
|
|
136
|
+
#
|
|
137
|
+
# With a seed, it deliberately avoids Numo::NArray.rand_norm: that method
|
|
138
|
+
# draws from a single RNG that is global and process-wide (seeded to a
|
|
139
|
+
# fixed constant at load time, unless Numo::NArray.srand is called), so
|
|
140
|
+
# seeding it for one layer would silently perturb every other unrelated
|
|
141
|
+
# Numo random call for the rest of the process. Instead we use a private
|
|
142
|
+
# Random.new(seed) instance plus a Box-Muller transform, matching the
|
|
143
|
+
# same seeding pattern Datasets::Batching already uses, so a seed here
|
|
144
|
+
# affects only this call.
|
|
145
|
+
def self.rand_norm(*shape, mean: 0.0, std: 1.0, seed: nil)
|
|
146
|
+
return Numo::SFloat.new(*shape).rand_norm(mean, std) if seed.nil?
|
|
147
|
+
|
|
148
|
+
rng = Random.new(seed)
|
|
149
|
+
n = shape.reduce(1, :*)
|
|
150
|
+
|
|
151
|
+
data = Array.new(n) do
|
|
152
|
+
u1 = rng.rand
|
|
153
|
+
u1 = Float::EPSILON if u1 <= 0.0 # avoid log(0)
|
|
154
|
+
u2 = rng.rand
|
|
155
|
+
r = Math.sqrt(-2.0 * Math.log(u1))
|
|
156
|
+
mean + std * r * Math.cos(2.0 * Math::PI * u2)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
Numo::SFloat.asarray(data).reshape(*shape)
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def self.clip_grad_norm_(params, max_norm, eps: 1e-6)
|
|
163
|
+
# params: array of Tensor (model parameters).
|
|
164
|
+
# Assumes p.grad is a Numo::NArray float.
|
|
165
|
+
total_sq = 0.0
|
|
166
|
+
|
|
167
|
+
params.each do |p|
|
|
168
|
+
next unless p.grad
|
|
169
|
+
g = p.grad
|
|
170
|
+
# Sum of squared gradient elements.
|
|
171
|
+
total_sq += p.backend.item(p.backend.sum(g * g))
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
total_norm = Math.sqrt(total_sq)
|
|
175
|
+
if total_norm > max_norm
|
|
176
|
+
scale = max_norm / (total_norm + eps)
|
|
177
|
+
params.each do |p|
|
|
178
|
+
next unless p.grad
|
|
179
|
+
p.grad *= scale
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
total_norm
|
|
184
|
+
end
|
|
185
|
+
end
|
|
186
|
+
end
|
data/lib/maurograd.rb
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Maurograd (Tensor/Numo autograd) - default entrypoint.
|
|
2
|
+
#
|
|
3
|
+
# This file intentionally requires an explicit, minimal set of files
|
|
4
|
+
# (rather than a directory-wide Dir[...] require) to keep the public API
|
|
5
|
+
# predictable.
|
|
6
|
+
#
|
|
7
|
+
# The original micrograd-style scalar engine this project started as now
|
|
8
|
+
# lives in its own repo: https://github.com/mtortonesi/maurograd_scalar
|
|
9
|
+
|
|
10
|
+
require_relative "maurograd/bootstrap"
|
|
11
|
+
|
|
12
|
+
Maurograd::Bootstrap.limit_blas_threads!
|
|
13
|
+
|
|
14
|
+
require "numo/narray"
|
|
15
|
+
require "numo/linalg"
|
|
16
|
+
|
|
17
|
+
module Maurograd
|
|
18
|
+
# Version first (so clients can check Maurograd::VERSION early).
|
|
19
|
+
require_relative "maurograd/version"
|
|
20
|
+
|
|
21
|
+
# Maurograd.debug flag, off by default (used by Utils.assert_finite!).
|
|
22
|
+
require_relative "maurograd/debug"
|
|
23
|
+
|
|
24
|
+
# Maurograd.seed! for reproducible runs (also re-randomizes Numo's global
|
|
25
|
+
# RNG at load time, so unseeded weight init is genuinely random).
|
|
26
|
+
require_relative "maurograd/seed"
|
|
27
|
+
|
|
28
|
+
# Compute backends (where tensor data lives): the CPU one is always
|
|
29
|
+
# loaded; optional ones (MLX) load on first use.
|
|
30
|
+
require_relative "maurograd/backends"
|
|
31
|
+
require_relative "maurograd/backends/cpu"
|
|
32
|
+
|
|
33
|
+
# Core tensor type (autograd graph node).
|
|
34
|
+
require_relative "maurograd/tensor"
|
|
35
|
+
|
|
36
|
+
# Utilities used by multiple ops (broadcast reduction, im2col/col2im, etc.).
|
|
37
|
+
require_relative "maurograd/utils/utils"
|
|
38
|
+
|
|
39
|
+
# Ops (autograd operations).
|
|
40
|
+
require_relative "maurograd/ops/add"
|
|
41
|
+
require_relative "maurograd/ops/sub"
|
|
42
|
+
require_relative "maurograd/ops/mul"
|
|
43
|
+
require_relative "maurograd/ops/matmul"
|
|
44
|
+
require_relative "maurograd/ops/power"
|
|
45
|
+
require_relative "maurograd/ops/sum"
|
|
46
|
+
require_relative "maurograd/ops/conv2d"
|
|
47
|
+
require_relative "maurograd/ops/linear"
|
|
48
|
+
require_relative "maurograd/ops/flatten"
|
|
49
|
+
require_relative "maurograd/ops/relu"
|
|
50
|
+
require_relative "maurograd/ops/maxpool2d"
|
|
51
|
+
require_relative "maurograd/ops/permute"
|
|
52
|
+
require_relative "maurograd/ops/batchnorm2d"
|
|
53
|
+
require_relative "maurograd/ops/dropout"
|
|
54
|
+
|
|
55
|
+
# Layers (high-level modules that own parameters).
|
|
56
|
+
require_relative "maurograd/layers/conv2d"
|
|
57
|
+
require_relative "maurograd/layers/linear"
|
|
58
|
+
require_relative "maurograd/layers/flatten"
|
|
59
|
+
require_relative "maurograd/layers/maxpool2d"
|
|
60
|
+
require_relative "maurograd/layers/relu"
|
|
61
|
+
require_relative "maurograd/layers/batchnorm2d"
|
|
62
|
+
require_relative "maurograd/layers/dropout"
|
|
63
|
+
require_relative "maurograd/layers/sequential"
|
|
64
|
+
|
|
65
|
+
# Loss functions
|
|
66
|
+
require_relative "maurograd/losses/bce"
|
|
67
|
+
require_relative "maurograd/losses/mse"
|
|
68
|
+
require_relative "maurograd/losses/cross_entropy_with_logits"
|
|
69
|
+
|
|
70
|
+
# Optimizers
|
|
71
|
+
require_relative "maurograd/optim/optimizer"
|
|
72
|
+
require_relative "maurograd/optim/sgd"
|
|
73
|
+
require_relative "maurograd/optim/adam"
|
|
74
|
+
|
|
75
|
+
# Datasets
|
|
76
|
+
require_relative "maurograd/datasets/mnist"
|
|
77
|
+
require_relative "maurograd/datasets/batching"
|
|
78
|
+
end
|