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
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 597868356a8add0f4030ce05096dea52ec51ea13359f57377e0b6cadc0c377a1
|
|
4
|
+
data.tar.gz: afeacf80d6200fd386143245e98bbd99e9855132da34b0fbab610d2afce2b1d6
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 7cdfa709dcbb9d91508a78d69086de64fe12fc4c775b39333a213eeb9c2cbafd6c8909e1a8431447207d49f7c017f9529ce08d4d82665c086f0fac54379f3649
|
|
7
|
+
data.tar.gz: b02bafb005ebbbb8978bc912d6d3e127109f49854189eb46528995ea89c9a1834777e77867a6b434fe44b4712b51b98e8265e3dad544626c41406e6068cc52d0
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to Maurograd are documented here. The project follows
|
|
4
|
+
[Semantic Versioning](https://semver.org/); before 1.0, a minor version bump
|
|
5
|
+
(0.1 → 0.2) may include breaking changes.
|
|
6
|
+
|
|
7
|
+
The `maurograd` and `maurograd-mlx` gems are released together, at the same
|
|
8
|
+
version.
|
|
9
|
+
|
|
10
|
+
## [0.1.0] - 2026-11-27
|
|
11
|
+
|
|
12
|
+
First public release.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- Tensors with reverse-mode automatic differentiation over arbitrary
|
|
17
|
+
computation graphs (gradients from multiple paths are summed).
|
|
18
|
+
- Ops: addition, subtraction and multiplication with broadcasting, power,
|
|
19
|
+
sum, 2D matrix product, linear, 2D convolution (stride, padding), 2D max
|
|
20
|
+
pooling, ReLU, 2D batch normalization, dropout, flatten, and axis
|
|
21
|
+
permutation (`Tensor#transpose`, `Tensor#permute`).
|
|
22
|
+
- Layers: `Conv2D`, `Linear`, `MaxPool2D`, `ReLU`, `BatchNorm2D`,
|
|
23
|
+
`Dropout`, `Flatten`, `Sequential`, with `train`/`eval` modes.
|
|
24
|
+
- Losses: cross-entropy with logits (class indices or soft targets), MSE,
|
|
25
|
+
binary cross-entropy.
|
|
26
|
+
- Optimizers: SGD with momentum and weight decay; Adam.
|
|
27
|
+
- MNIST download and loading, and shuffled mini-batching.
|
|
28
|
+
- `Maurograd.seed!` for reproducible runs.
|
|
29
|
+
- Compute backends behind one interface: `:cpu` (Numo plus C kernels, with
|
|
30
|
+
Apple's Accelerate on macOS and OpenBLAS elsewhere) and `:mlx` (the Apple
|
|
31
|
+
Silicon GPU through MLX, in the separate `maurograd-mlx` gem). Select
|
|
32
|
+
with `MAUROGRAD_BACKEND`, `Maurograd.backend =` or `model.to`.
|
|
33
|
+
- Examples: LeNet on MNIST, and LeNet with and without BatchNorm.
|
|
34
|
+
|
|
35
|
+
### Defaults worth knowing
|
|
36
|
+
|
|
37
|
+
- BLAS/OpenMP thread pools default to one thread unless
|
|
38
|
+
`OPENBLAS_NUM_THREADS`/`OMP_NUM_THREADS` are set.
|
|
39
|
+
- The MLX backend computes float32 matrix products at full precision
|
|
40
|
+
(`MLX_ENABLE_TF32=0`) unless the variable is set.
|
|
41
|
+
|
|
42
|
+
### Known limitations
|
|
43
|
+
|
|
44
|
+
- `MatMul` supports 2D matrices only (no batched products).
|
|
45
|
+
- No module base class, general reshape, `no_grad` mode or model
|
|
46
|
+
saving/loading yet.
|
|
47
|
+
- No pure-Ruby fallback: the C extension must build.
|
|
48
|
+
|
|
49
|
+
[0.1.0]: https://github.com/mtortonesi/maurograd/releases/tag/v0.1.0
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Mauro Tortonesi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Maurograd
|
|
2
|
+
|
|
3
|
+
Maurograd is my take on creating a framwork for Artificial Neural Networks
|
|
4
|
+
(ANNs) in the Ruby programming language.
|
|
5
|
+
|
|
6
|
+
It started as an exercise to develop a clone of Andrej Karpathy's
|
|
7
|
+
[micrograd](https://github.com/karpathy/micrograd) but it almost immediately
|
|
8
|
+
became something more ambitious. I wanted to add support for Convolutional
|
|
9
|
+
Neural Networks (CNNs) and to have a reasonably CPU-competent framework. So,
|
|
10
|
+
after many experiments (and the corresponding performance evaluations) I ended
|
|
11
|
+
up with a relatively clean mostly-Ruby codebase that leverages
|
|
12
|
+
[numo-narray-alt](https://github.com/yoshoku/numo-narray-alt) as a tensor
|
|
13
|
+
framwork and implements 2D convolution in C using the im2col + GEMM + col2im
|
|
14
|
+
approach. For simplicity, GEMM is performed with
|
|
15
|
+
[OpenBLAS](https://github.com/OpenMathLib/OpenBLAS) (or Apple's Accelerate
|
|
16
|
+
framework on macOS). (In general, I hate the
|
|
17
|
+
idea of developing C extensions for Ruby, but they are perfect for this task.)
|
|
18
|
+
|
|
19
|
+
The original scalar-valued micrograd clone this project started as now lives
|
|
20
|
+
on its own, unchanged, in
|
|
21
|
+
[maurograd_scalar](https://github.com/mtortonesi/maurograd_scalar) — worth a
|
|
22
|
+
look if you want to see backpropagation with nothing but plain Ruby arithmetic
|
|
23
|
+
in the way.
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
gem install maurograd
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Maurograd compiles a C extension on install, so it needs a C compiler and a
|
|
33
|
+
BLAS library:
|
|
34
|
+
|
|
35
|
+
- **macOS**: the Xcode command line tools (`xcode-select --install`). The
|
|
36
|
+
extension uses Apple's Accelerate framework, so nothing else is needed.
|
|
37
|
+
- **Linux**: a compiler and the OpenBLAS headers, e.g. on Debian/Ubuntu
|
|
38
|
+
`sudo apt-get install build-essential libopenblas-dev`.
|
|
39
|
+
|
|
40
|
+
There is no pure-Ruby fallback: if the extension can't be built, Maurograd
|
|
41
|
+
can't be loaded.
|
|
42
|
+
|
|
43
|
+
For the Apple Silicon GPU backend, install mlx-c first, then the separate
|
|
44
|
+
`maurograd-mlx` gem:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
brew install mlx-c
|
|
48
|
+
gem install maurograd-mlx
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
To work on Maurograd itself: `bundle install`, then `./bin/build_ext` to
|
|
52
|
+
build the extensions (the MLX one is skipped without mlx-c) and
|
|
53
|
+
`bundle exec bake ci` to build and run the tests.
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
## Examples
|
|
57
|
+
|
|
58
|
+
While a full documentation will come down the road, Maurograd comes with a
|
|
59
|
+
couple of examples under `examples/` that should explain how to use the
|
|
60
|
+
framework:
|
|
61
|
+
|
|
62
|
+
- [`mnist.rb`](examples/mnist.rb): a multi-class classifier for digit
|
|
63
|
+
recognition on the MNIST dataset, based on the LeNet CNN architecture.
|
|
64
|
+
- [`mnist_batchnorm.rb`](examples/mnist_batchnorm.rb): the same LeNet-style
|
|
65
|
+
CNN, trained twice - once as-is, once with a `BatchNorm2D` layer after
|
|
66
|
+
every `Conv2D` - so you can see what BatchNorm actually changes about
|
|
67
|
+
training, rather than just reading about it.
|
|
68
|
+
|
|
69
|
+
(An MLP classifier for the two moons dataset also exists, but it's built on
|
|
70
|
+
the scalar-valued engine, so it now lives in
|
|
71
|
+
[maurograd_scalar](https://github.com/mtortonesi/maurograd_scalar) instead.)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
## Backends
|
|
75
|
+
|
|
76
|
+
The autograd engine is the same everywhere, but tensor storage and the math
|
|
77
|
+
run on a pluggable *backend* (`lib/maurograd/backends/`):
|
|
78
|
+
|
|
79
|
+
- `:cpu` (default): Numo arrays, plus the C kernels in `ext/maurograd_ext`.
|
|
80
|
+
The C extension links Accelerate on macOS and OpenBLAS elsewhere; set
|
|
81
|
+
`MAUROGRAD_BLAS=openblas` (or `accelerate`) when building to choose.
|
|
82
|
+
- `:mlx`: [MLX](https://github.com/ml-explore/mlx) arrays, running on the
|
|
83
|
+
Apple Silicon GPU, through bindings for
|
|
84
|
+
[mlx-c](https://github.com/ml-explore/mlx-c) in `ext/maurograd_mlx`. It
|
|
85
|
+
ships as the separate `maurograd-mlx` gem (see Installation); once that
|
|
86
|
+
is installed, Maurograd loads it by itself when you ask for `:mlx`.
|
|
87
|
+
|
|
88
|
+
Pick one for a whole script with `MAUROGRAD_BACKEND=mlx`, or in code with
|
|
89
|
+
`Maurograd.backend = :mlx` (before building the model) or `model.to(:mlx)`.
|
|
90
|
+
`tensor.item` and `tensor.to_numo` read values back on any backend.
|
|
91
|
+
|
|
92
|
+
Two runtime defaults worth knowing about:
|
|
93
|
+
|
|
94
|
+
- BLAS/OpenMP thread pools default to a single thread
|
|
95
|
+
(`OPENBLAS_NUM_THREADS`/`OMP_NUM_THREADS`, unless you set them):
|
|
96
|
+
numo-linalg-alt's bundled OpenBLAS keeps busy-waiting threads that slow
|
|
97
|
+
training down, badly so on Linux, where the extension's own OpenBLAS adds
|
|
98
|
+
a second pool.
|
|
99
|
+
- The MLX backend runs float32 matrix products at full precision
|
|
100
|
+
(`MLX_ENABLE_TF32=0`, unless you set it), like the CPU backend.
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
## Disclaimers
|
|
105
|
+
|
|
106
|
+
At its heart, Maurograd is a didactic project. It is designed to be as simple
|
|
107
|
+
as possible, while reasonably CPU-competent. The project's goal is to enable
|
|
108
|
+
students to easily understand the inner working of serious ANN framework, by
|
|
109
|
+
leveraging Ruby's expressiveness and readability. So, Maurograd is not a
|
|
110
|
+
state-of-the-art ANN solution from the performance point of view - and never
|
|
111
|
+
will be. If you have a performance-oriented focus, you will be much better
|
|
112
|
+
server by [torch.rb](https://github.com/ankane/torch.rb) or (if you are on
|
|
113
|
+
Apple silicon) [mlx-ruby](https://github.com/skryl/mlx-ruby).
|
|
114
|
+
|
|
115
|
+
In addition, while developing Maurograd I heavily used AI-assisted coding
|
|
116
|
+
solutions. A secondary goal of this project for me was to familiarize with
|
|
117
|
+
state-of-the-art AI coding tools. I am completely open and unapologetic about
|
|
118
|
+
this. Of course, I ended up revising most of the code generated by AI. I would
|
|
119
|
+
guess that at the time of this writing (2026) the majority of software project
|
|
120
|
+
are being developed with a similar approach.
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
This software is available as open source under the terms of the [MIT
|
|
126
|
+
License](https://opensource.org/licenses/MIT).
|
data/examples/mnist.rb
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
|
|
3
|
+
require "maurograd"
|
|
4
|
+
require "stackprof"
|
|
5
|
+
|
|
6
|
+
root = "data"
|
|
7
|
+
epochs = 5
|
|
8
|
+
batch_size = 64
|
|
9
|
+
seed = 1
|
|
10
|
+
|
|
11
|
+
# Download (idempotent) and load.
|
|
12
|
+
Maurograd::Datasets::MNIST.download(root: root)
|
|
13
|
+
x_train, y_train = Maurograd::Datasets::MNIST.load(root: root, split: :train, normalize: true)
|
|
14
|
+
x_test, y_test = Maurograd::Datasets::MNIST.load(root: root, split: :test, normalize: true)
|
|
15
|
+
y_train = Numo::Int32.cast(y_train)
|
|
16
|
+
|
|
17
|
+
model = Maurograd::Layers::Sequential.new(
|
|
18
|
+
Maurograd::Layers::Conv2D.new(1, 6, 5, padding: 2),
|
|
19
|
+
Maurograd::Layers::ReLU.new,
|
|
20
|
+
Maurograd::Layers::MaxPool2D.new(2, stride: 2),
|
|
21
|
+
Maurograd::Layers::Conv2D.new(6, 16, 5),
|
|
22
|
+
Maurograd::Layers::ReLU.new,
|
|
23
|
+
Maurograd::Layers::MaxPool2D.new(2, stride: 2),
|
|
24
|
+
Maurograd::Layers::Flatten.new,
|
|
25
|
+
Maurograd::Layers::Linear.new(16 * 5 * 5, 120),
|
|
26
|
+
Maurograd::Layers::ReLU.new,
|
|
27
|
+
Maurograd::Layers::Linear.new(120, 84),
|
|
28
|
+
Maurograd::Layers::ReLU.new,
|
|
29
|
+
Maurograd::Layers::Linear.new(84, 10)
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
optimizer = Maurograd::Optim::SGD.new(model.parameters, lr: 0.01)
|
|
33
|
+
|
|
34
|
+
def train_epoch(model, x, y, optimizer, batch_size:, seed:, epoch:)
|
|
35
|
+
model.train
|
|
36
|
+
loader = Maurograd::Datasets::Batching.batches(
|
|
37
|
+
x, y,
|
|
38
|
+
batch_size: batch_size,
|
|
39
|
+
shuffle: true,
|
|
40
|
+
seed: seed # seed + epoch # to vary the seed on every epoch
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
i = 0
|
|
44
|
+
tb0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
45
|
+
loss = nil
|
|
46
|
+
|
|
47
|
+
if epoch == 1
|
|
48
|
+
puts "Running profiler on first epoch..."
|
|
49
|
+
StackProf.run(mode: :wall, out: "stackprof.dump") do
|
|
50
|
+
loader.each do |xb, yb|
|
|
51
|
+
optimizer.zero_grad
|
|
52
|
+
|
|
53
|
+
# Make sure tensors are contiguous for better performance, as Maurograd
|
|
54
|
+
# expects contiguous data for efficient access patterns. If not contiguous,
|
|
55
|
+
# we create a copy which will be contiguous.
|
|
56
|
+
xb_t = Maurograd::Tensor.new(
|
|
57
|
+
xb.contiguous? ? xb : xb.copy,
|
|
58
|
+
requires_grad: false
|
|
59
|
+
)
|
|
60
|
+
yb_t = Maurograd::Tensor.new(
|
|
61
|
+
yb.contiguous? ? yb : yb.copy,
|
|
62
|
+
requires_grad: false
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
logits = model.forward(xb_t)
|
|
66
|
+
loss = Maurograd::Losses::CrossEntropyWithLogits.apply(logits, yb_t)
|
|
67
|
+
loss.backward
|
|
68
|
+
|
|
69
|
+
optimizer.step
|
|
70
|
+
|
|
71
|
+
if (i % 10).zero?
|
|
72
|
+
tb1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
73
|
+
puts "Epoch #{epoch} | batch #{i} | dt=#{(tb1 - tb0).round(2)}s | loss #{loss.item}"
|
|
74
|
+
tb0 = tb1
|
|
75
|
+
end
|
|
76
|
+
i += 1
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
puts "Profiler run complete. Output written to stackprof.dump"
|
|
81
|
+
else
|
|
82
|
+
loader.each do |xb, yb|
|
|
83
|
+
optimizer.zero_grad
|
|
84
|
+
|
|
85
|
+
# Make sure tensors are contiguous for better performance, as Maurograd
|
|
86
|
+
# expects contiguous data for efficient access patterns. If not contiguous,
|
|
87
|
+
# we create a copy which will be contiguous.
|
|
88
|
+
xb_t = Maurograd::Tensor.new(
|
|
89
|
+
xb.contiguous? ? xb : xb.copy,
|
|
90
|
+
requires_grad: false
|
|
91
|
+
)
|
|
92
|
+
yb_t = Maurograd::Tensor.new(
|
|
93
|
+
yb.contiguous? ? yb : yb.copy,
|
|
94
|
+
requires_grad: false
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
logits = model.forward(xb_t)
|
|
98
|
+
loss = Maurograd::Losses::CrossEntropyWithLogits.apply(logits, yb_t)
|
|
99
|
+
loss.backward
|
|
100
|
+
|
|
101
|
+
optimizer.step
|
|
102
|
+
|
|
103
|
+
if (i % 10).zero?
|
|
104
|
+
tb1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
105
|
+
puts "Epoch #{epoch} | batch #{i} | dt=#{(tb1 - tb0).round(2)}s | loss #{loss.item}"
|
|
106
|
+
tb0 = tb1
|
|
107
|
+
end
|
|
108
|
+
i += 1
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def evaluate(model, x, y, batch_size:)
|
|
114
|
+
model.eval
|
|
115
|
+
loader = Maurograd::Datasets::Batching.batches(x, y, batch_size: batch_size, shuffle: false, seed: 0)
|
|
116
|
+
|
|
117
|
+
correct = 0
|
|
118
|
+
total = 0
|
|
119
|
+
|
|
120
|
+
loader.each do |xb, yb|
|
|
121
|
+
# Make sure tensors are contiguous for better performance, as Maurograd
|
|
122
|
+
# expects contiguous data for efficient access patterns. If not contiguous,
|
|
123
|
+
# we create a copy which will be contiguous.
|
|
124
|
+
xb_e = Maurograd::Tensor.new(
|
|
125
|
+
xb.contiguous? ? xb : xb.copy,
|
|
126
|
+
requires_grad: false
|
|
127
|
+
)
|
|
128
|
+
yb_e = Maurograd::Tensor.new(
|
|
129
|
+
yb.contiguous? ? yb : yb.copy,
|
|
130
|
+
requires_grad: false
|
|
131
|
+
)
|
|
132
|
+
logits = model.forward(xb_e)
|
|
133
|
+
pred = logits.to_numo.max_index(axis: 1) % 10
|
|
134
|
+
|
|
135
|
+
correct += pred.eq(yb_e.to_numo).count_true
|
|
136
|
+
total += yb_e.shape[0]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
puts "Accuracy: #{(100.0 * correct / total).round(2)}%"
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
1.upto(epochs) do |e|
|
|
143
|
+
train_epoch(model, x_train, y_train, optimizer, batch_size: batch_size, seed: seed + e, epoch: e)
|
|
144
|
+
evaluate(model, x_test, y_test, batch_size: 256)
|
|
145
|
+
end
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# Same LeNet-style CNN as examples/mnist.rb, trained twice - once as-is,
|
|
3
|
+
# once with a BatchNorm2D layer after every Conv2D - so you can watch what
|
|
4
|
+
# BatchNorm actually changes about training: same architecture, same data,
|
|
5
|
+
# same seed, same learning rate, only its presence differs.
|
|
6
|
+
#
|
|
7
|
+
# What to look for in the output: at the `lr` below, the two runs are hard
|
|
8
|
+
# to tell apart. At the time this comment was written, both reached about
|
|
9
|
+
# 97% test accuracy after one epoch and about 98.7-98.9% after three, on
|
|
10
|
+
# both the CPU and the MLX backend. That is a result worth knowing: LeNet
|
|
11
|
+
# is only two conv layers deep, and MNIST is easy, so plain SGD already
|
|
12
|
+
# trains it quickly and BatchNorm has little left to speed up. Its benefits
|
|
13
|
+
# (faster, more stable training) grow with depth, where activation scales
|
|
14
|
+
# drift more from layer to layer. Treat any epoch-1 gap of a point or two
|
|
15
|
+
# as noise: at this learning rate, tiny numerical differences (a different
|
|
16
|
+
# BLAS, say) are enough to change the early trajectory.
|
|
17
|
+
#
|
|
18
|
+
# Try varying `lr` yourself. It's tempting to assume BatchNorm always makes
|
|
19
|
+
# training *more* forgiving of a high learning rate - that's the textbook
|
|
20
|
+
# claim, and it usually holds at the scale a full training run operates at.
|
|
21
|
+
# But it's worth checking rather than taking on faith: with plain SGD (no
|
|
22
|
+
# momentum) and only a few thousand updates, gamma/beta get pushed by the
|
|
23
|
+
# same raw learning rate as everything else, and past a certain point that
|
|
24
|
+
# coupling can make the "with BatchNorm2D" run *less* stable than the
|
|
25
|
+
# "without" one, not more - the opposite of what the textbook framing
|
|
26
|
+
# implies. Push `lr` well past its default and watch for that reversal.
|
|
27
|
+
|
|
28
|
+
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
|
|
29
|
+
require "maurograd"
|
|
30
|
+
|
|
31
|
+
Maurograd.seed!(1)
|
|
32
|
+
|
|
33
|
+
root = "data"
|
|
34
|
+
epochs = 3
|
|
35
|
+
batch_size = 64
|
|
36
|
+
lr = 0.3
|
|
37
|
+
|
|
38
|
+
Maurograd::Datasets::MNIST.download(root: root)
|
|
39
|
+
x_train, y_train = Maurograd::Datasets::MNIST.load(root: root, split: :train, normalize: true)
|
|
40
|
+
x_test, y_test = Maurograd::Datasets::MNIST.load(root: root, split: :test, normalize: true)
|
|
41
|
+
y_train = Numo::Int32.cast(y_train)
|
|
42
|
+
|
|
43
|
+
def build_model(batchnorm:)
|
|
44
|
+
layers = [Maurograd::Layers::Conv2D.new(1, 6, 5, padding: 2)]
|
|
45
|
+
layers << Maurograd::Layers::BatchNorm2D.new(6) if batchnorm
|
|
46
|
+
layers += [
|
|
47
|
+
Maurograd::Layers::ReLU.new,
|
|
48
|
+
Maurograd::Layers::MaxPool2D.new(2, stride: 2),
|
|
49
|
+
Maurograd::Layers::Conv2D.new(6, 16, 5)
|
|
50
|
+
]
|
|
51
|
+
layers << Maurograd::Layers::BatchNorm2D.new(16) if batchnorm
|
|
52
|
+
layers += [
|
|
53
|
+
Maurograd::Layers::ReLU.new,
|
|
54
|
+
Maurograd::Layers::MaxPool2D.new(2, stride: 2),
|
|
55
|
+
Maurograd::Layers::Flatten.new,
|
|
56
|
+
Maurograd::Layers::Linear.new(16 * 5 * 5, 120),
|
|
57
|
+
Maurograd::Layers::ReLU.new,
|
|
58
|
+
Maurograd::Layers::Linear.new(120, 84),
|
|
59
|
+
Maurograd::Layers::ReLU.new,
|
|
60
|
+
Maurograd::Layers::Linear.new(84, 10)
|
|
61
|
+
]
|
|
62
|
+
Maurograd::Layers::Sequential.new(*layers)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Make sure tensors are contiguous for better performance, as Maurograd
|
|
66
|
+
# expects contiguous data for efficient access patterns. If not contiguous,
|
|
67
|
+
# we create a copy which will be contiguous.
|
|
68
|
+
def to_tensor(data)
|
|
69
|
+
Maurograd::Tensor.new(data.contiguous? ? data : data.copy, requires_grad: false)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def train_epoch(model, x, y, optimizer, batch_size:, seed:)
|
|
73
|
+
model.train
|
|
74
|
+
loader = Maurograd::Datasets::Batching.batches(x, y, batch_size: batch_size, shuffle: true, seed: seed)
|
|
75
|
+
|
|
76
|
+
total_loss = 0.0
|
|
77
|
+
batches = 0
|
|
78
|
+
|
|
79
|
+
loader.each do |xb, yb|
|
|
80
|
+
optimizer.zero_grad
|
|
81
|
+
|
|
82
|
+
logits = model.forward(to_tensor(xb))
|
|
83
|
+
loss = Maurograd::Losses::CrossEntropyWithLogits.apply(logits, to_tensor(yb))
|
|
84
|
+
loss.backward
|
|
85
|
+
|
|
86
|
+
optimizer.step
|
|
87
|
+
|
|
88
|
+
total_loss += loss.item
|
|
89
|
+
batches += 1
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
total_loss / batches
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def evaluate(model, x, y, batch_size:)
|
|
96
|
+
model.eval
|
|
97
|
+
loader = Maurograd::Datasets::Batching.batches(x, y, batch_size: batch_size, shuffle: false, seed: 0)
|
|
98
|
+
|
|
99
|
+
correct = 0
|
|
100
|
+
total = 0
|
|
101
|
+
|
|
102
|
+
loader.each do |xb, yb|
|
|
103
|
+
xb_t = to_tensor(xb)
|
|
104
|
+
yb_t = to_tensor(yb)
|
|
105
|
+
|
|
106
|
+
logits = model.forward(xb_t)
|
|
107
|
+
pred = logits.to_numo.max_index(axis: 1) % 10
|
|
108
|
+
|
|
109
|
+
correct += pred.eq(yb_t.to_numo).count_true
|
|
110
|
+
total += yb_t.shape[0]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
100.0 * correct / total
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def run(name, batchnorm:, x_train:, y_train:, x_test:, y_test:, epochs:, batch_size:, lr:)
|
|
117
|
+
puts "== #{name} =="
|
|
118
|
+
|
|
119
|
+
model = build_model(batchnorm: batchnorm)
|
|
120
|
+
optimizer = Maurograd::Optim::SGD.new(model.parameters, lr: lr)
|
|
121
|
+
|
|
122
|
+
1.upto(epochs) do |e|
|
|
123
|
+
avg_loss = train_epoch(model, x_train, y_train, optimizer, batch_size: batch_size, seed: e)
|
|
124
|
+
accuracy = evaluate(model, x_test, y_test, batch_size: 256)
|
|
125
|
+
puts " epoch #{e} | avg train loss #{avg_loss.round(4)} | test accuracy #{accuracy.round(2)}%"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
puts
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
run(
|
|
132
|
+
"without BatchNorm2D", batchnorm: false,
|
|
133
|
+
x_train: x_train, y_train: y_train, x_test: x_test, y_test: y_test,
|
|
134
|
+
epochs: epochs, batch_size: batch_size, lr: lr
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
run(
|
|
138
|
+
"with BatchNorm2D", batchnorm: true,
|
|
139
|
+
x_train: x_train, y_train: y_train, x_test: x_test, y_test: y_test,
|
|
140
|
+
epochs: epochs, batch_size: batch_size, lr: lr
|
|
141
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
require "mkmf"
|
|
2
|
+
require "rubygems"
|
|
3
|
+
|
|
4
|
+
extension_name = "maurograd_ext"
|
|
5
|
+
|
|
6
|
+
# Find Numo NArray include path via gem specification
|
|
7
|
+
|
|
8
|
+
begin
|
|
9
|
+
spec = Gem::Specification.find_by_name("numo-narray-alt")
|
|
10
|
+
rescue Gem::LoadError => e
|
|
11
|
+
abort "numo-narray-alt not found, and its headers are needed to compile (#{e.class}: #{e.message}; gem search path: #{Gem.path.join(File::PATH_SEPARATOR)})"
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
numo_narray_candidates = Dir[File.join(spec.full_gem_path, "**", "numo", "narray.h")]
|
|
15
|
+
|
|
16
|
+
hdr =
|
|
17
|
+
numo_narray_candidates.find { |p| p.include?("/ext/") } ||
|
|
18
|
+
numo_narray_candidates.first
|
|
19
|
+
|
|
20
|
+
abort "Could not locate numo/narray.h inside #{spec.full_gem_path}" unless hdr
|
|
21
|
+
|
|
22
|
+
numo_inc = File.dirname(hdr, 2)
|
|
23
|
+
$INCFLAGS << " -I#{numo_inc}"
|
|
24
|
+
|
|
25
|
+
have_header("numo/narray.h") or abort "numo/narray.h not found even after adding include path"
|
|
26
|
+
|
|
27
|
+
# Choose the BLAS implementation.
|
|
28
|
+
#
|
|
29
|
+
# MAUROGRAD_BLAS=accelerate|openblas selects it explicitly. By default we use
|
|
30
|
+
# Apple's Accelerate framework on macOS and OpenBLAS everywhere else.
|
|
31
|
+
#
|
|
32
|
+
# Why Accelerate on macOS: on Apple Silicon its sgemm runs on the CPU's
|
|
33
|
+
# matrix units, and it is dramatically faster on the GEMM shapes
|
|
34
|
+
# convolutions produce. The weight gradient of a conv layer is a
|
|
35
|
+
# "tiny output, huge reduction" product ([Cout x rows] * [rows x K], with
|
|
36
|
+
# rows = N*OH*OW in the tens of thousands): for LeNet's first layer on a
|
|
37
|
+
# batch of 64, OpenBLAS (single thread) took 1.28 ms and Accelerate 0.06 ms.
|
|
38
|
+
default_blas = RUBY_PLATFORM.include?("darwin") ? "accelerate" : "openblas"
|
|
39
|
+
blas = (ENV["MAUROGRAD_BLAS"] || default_blas).downcase
|
|
40
|
+
abort "MAUROGRAD_BLAS must be 'accelerate' or 'openblas', got '#{blas}'" unless %w[accelerate openblas].include?(blas)
|
|
41
|
+
abort "MAUROGRAD_BLAS=accelerate is only available on macOS" if blas == "accelerate" && !RUBY_PLATFORM.include?("darwin")
|
|
42
|
+
|
|
43
|
+
# Flags (keep conservative; you can add -O3 -march=native later)
|
|
44
|
+
$CFLAGS << " -O3"
|
|
45
|
+
$CFLAGS << " -std=c11"
|
|
46
|
+
|
|
47
|
+
if blas == "accelerate"
|
|
48
|
+
# ACCELERATE_NEW_LAPACK selects Accelerate's current CBLAS/LAPACK headers
|
|
49
|
+
# (the old ones are deprecated since macOS 13.3).
|
|
50
|
+
$CFLAGS << " -DMAUROGRAD_USE_ACCELERATE -DACCELERATE_NEW_LAPACK"
|
|
51
|
+
$LDFLAGS << " -framework Accelerate"
|
|
52
|
+
have_header("Accelerate/Accelerate.h") or abort "Accelerate framework headers not found (are the Xcode command line tools installed?)"
|
|
53
|
+
else
|
|
54
|
+
# Find OpenBLAS include and lib paths
|
|
55
|
+
|
|
56
|
+
# Try pkg-config first (portable across distros; how apt's libopenblas-dev
|
|
57
|
+
# and most Linux package managers register themselves).
|
|
58
|
+
pkg_config("openblas")
|
|
59
|
+
|
|
60
|
+
# Prefer Homebrew OpenBLAS if present; otherwise fall back to common
|
|
61
|
+
# Linux system prefixes (apt's libopenblas-dev installs under plain /usr).
|
|
62
|
+
openblas_candidates = [
|
|
63
|
+
ENV["OPENBLAS_DIR"],
|
|
64
|
+
"/opt/homebrew/opt/openblas", # Apple Silicon
|
|
65
|
+
"/usr/local/opt/openblas", # Intel Homebrew
|
|
66
|
+
"/usr" # common Linux system install
|
|
67
|
+
].compact.uniq
|
|
68
|
+
|
|
69
|
+
openblas_inc = nil
|
|
70
|
+
openblas_lib = nil
|
|
71
|
+
|
|
72
|
+
openblas_candidates.each do |prefix|
|
|
73
|
+
inc = File.join(prefix, "include")
|
|
74
|
+
lib = File.join(prefix, "lib")
|
|
75
|
+
next unless File.directory?(inc) && File.directory?(lib)
|
|
76
|
+
openblas_inc = inc
|
|
77
|
+
openblas_lib = lib
|
|
78
|
+
break
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Adds -I and -L only if found
|
|
82
|
+
if openblas_inc && openblas_lib
|
|
83
|
+
dir_config("openblas", openblas_inc, openblas_lib)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Check headers + library
|
|
87
|
+
have_header("cblas.h") or abort "cblas.h not found (install openblas and/or set OPENBLAS_DIR)"
|
|
88
|
+
have_library("openblas") or abort "libopenblas not found"
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
warn "[extconf] BLAS backend: #{blas}"
|
|
92
|
+
|
|
93
|
+
create_makefile(extension_name)
|