maurograd 0.1.0 → 0.2.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 +4 -4
- data/CHANGELOG.md +66 -0
- data/README.md +44 -0
- data/lib/maurograd/backends/cpu.rb +64 -0
- data/lib/maurograd/backends.rb +9 -0
- data/lib/maurograd/grad_mode.rb +44 -0
- data/lib/maurograd/layers/activations.rb +39 -0
- data/lib/maurograd/layers/batchnorm2d.rb +10 -29
- data/lib/maurograd/layers/conv2d.rb +2 -11
- data/lib/maurograd/layers/dropout.rb +4 -18
- data/lib/maurograd/layers/flatten.rb +2 -1
- data/lib/maurograd/layers/linear.rb +2 -13
- data/lib/maurograd/layers/maxpool2d.rb +2 -1
- data/lib/maurograd/layers/module.rb +280 -0
- data/lib/maurograd/layers/relu.rb +2 -1
- data/lib/maurograd/layers/sequential.rb +18 -30
- data/lib/maurograd/losses/bce.rb +1 -1
- data/lib/maurograd/losses/bce_with_logits.rb +78 -0
- data/lib/maurograd/losses/cross_entropy_with_logits.rb +1 -1
- data/lib/maurograd/losses/mse.rb +1 -1
- data/lib/maurograd/ops/add.rb +1 -1
- data/lib/maurograd/ops/batchnorm2d.rb +1 -1
- data/lib/maurograd/ops/concat.rb +69 -0
- data/lib/maurograd/ops/conv2d.rb +1 -1
- data/lib/maurograd/ops/dropout.rb +1 -1
- data/lib/maurograd/ops/elementwise.rb +210 -0
- data/lib/maurograd/ops/flatten.rb +1 -1
- data/lib/maurograd/ops/linear.rb +1 -1
- data/lib/maurograd/ops/log_softmax.rb +121 -0
- data/lib/maurograd/ops/matmul.rb +1 -1
- data/lib/maurograd/ops/maxpool2d.rb +1 -1
- data/lib/maurograd/ops/mul.rb +1 -1
- data/lib/maurograd/ops/permute.rb +1 -1
- data/lib/maurograd/ops/power.rb +1 -1
- data/lib/maurograd/ops/relu.rb +1 -1
- data/lib/maurograd/ops/reshape.rb +86 -0
- data/lib/maurograd/ops/slice.rb +82 -0
- data/lib/maurograd/ops/sub.rb +1 -1
- data/lib/maurograd/ops/sum.rb +65 -18
- data/lib/maurograd/random.rb +50 -0
- data/lib/maurograd/safetensors.rb +115 -0
- data/lib/maurograd/tensor.rb +112 -2
- data/lib/maurograd/version.rb +1 -1
- data/lib/maurograd.rb +17 -0
- metadata +12 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 7e549dfc12295d9f6b94d2c9153cd013ce8b4df8ae53ffd0d14ff5e55613f7f2
|
|
4
|
+
data.tar.gz: dbcb73f924cccdab4bc45505277a51221422540b9f438eb2f61a3d56b190a30c
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: aa3cf80a7e5135959ca14d4232f8fbf184ea16a9e6481826b16c64e5aa1fd2b315a4e05faf0dd88fb14732ce4bd42d551d5a7c94a1f74fad2ac3d93f6d481c67
|
|
7
|
+
data.tar.gz: 612758587f2dcd7f1eefdb61fa68e8a45d90f59771cece8b633e10ef06d32ea27015287b1475f77037b4229d09ccfe95c35b89885317a855ecb14201c9731382
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,70 @@ All notable changes to Maurograd are documented here. The project follows
|
|
|
7
7
|
The `maurograd` and `maurograd-mlx` gems are released together, at the same
|
|
8
8
|
version.
|
|
9
9
|
|
|
10
|
+
## [Unreleased]
|
|
11
|
+
|
|
12
|
+
## [0.2.0] - 2026-11-28
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- `Tensor#reshape` (`Ops::Reshape`), differentiable, with one dimension
|
|
17
|
+
inferable as `-1`, e.g. `x.reshape(n, -1)`.
|
|
18
|
+
- `Layers::Module`, a base class for layers and models: it finds
|
|
19
|
+
parameters and sublayers in instance variables (also inside Arrays and
|
|
20
|
+
Hashes), and provides `parameters`, `named_parameters`, `children`,
|
|
21
|
+
`modules`, `train`/`eval`/`training?`, `to`, `call` (so `model.call(x)`
|
|
22
|
+
works like `forward`) and a short `inspect`. Shared parameters are listed once.
|
|
23
|
+
- Differentiable elementwise functions `Tensor#exp`, `#log`, `#sigmoid`,
|
|
24
|
+
`#tanh` and `#silu`, and the activation layers `Layers::Sigmoid`,
|
|
25
|
+
`Layers::Tanh` and `Layers::SiLU`.
|
|
26
|
+
- `Tensor#sum` and the new `Tensor#mean` take `axis:` (an axis or a list of
|
|
27
|
+
them, negative counting from the end) and `keepdims:`; e.g.
|
|
28
|
+
`x.mean(axis: [2, 3])` is global average pooling.
|
|
29
|
+
- `Tensor#/` (by a number or a tensor) and unary minus.
|
|
30
|
+
- `Maurograd.no_grad { ... }`: ops inside the block build no graph (for
|
|
31
|
+
evaluation and sampling); `Maurograd.grad_enabled?`. Per thread,
|
|
32
|
+
nestable, and separate from `model.eval`.
|
|
33
|
+
- `Module#state_dict` and `#load_state_dict` (strict by default; keys and
|
|
34
|
+
shapes are checked before anything changes), and buffers: non-trainable
|
|
35
|
+
state declared with `buffers :name`, which `to` moves and `state_dict`
|
|
36
|
+
saves, as BatchNorm2D's running statistics now are.
|
|
37
|
+
- `Maurograd::SafeTensors.save` and `.load`, for the safetensors file
|
|
38
|
+
format: weights saved by Maurograd load in Python's safetensors package,
|
|
39
|
+
and the other way round, and loading a file can't run code.
|
|
40
|
+
- `Tensor#slice(axis, range)` (`Ops::Slice`), with any Ruby Range
|
|
41
|
+
(`0...4`, `4..`, `-2..`), and `Tensor#chunk(n, axis:)` to split a tensor
|
|
42
|
+
into equal parts, e.g. a VAE encoder's output into mean and log-variance.
|
|
43
|
+
- `Maurograd.concat(tensors, axis:)` (`Ops::Concat`), e.g. for the skip
|
|
44
|
+
connections of a UNet.
|
|
45
|
+
- `Tensor#softplus` and `#log_sigmoid`, computed so they never overflow or
|
|
46
|
+
underflow (`log(1 + e^x)` and `log(sigmoid(x))` directly give Infinity
|
|
47
|
+
and -Infinity for large inputs); `Tensor#leaky_relu(negative_slope:)`;
|
|
48
|
+
`Tensor#clamp(min:, max:)`; and the layers `Layers::LeakyReLU` and
|
|
49
|
+
`Layers::Softplus`.
|
|
50
|
+
- `Tensor#detach`: the same data as a new leaf that stops gradients.
|
|
51
|
+
- `Tensor#logsumexp(axis:, keepdims:)` (`Ops::LogSumExp`),
|
|
52
|
+
`Tensor#log_softmax(axis:)` (`Ops::LogSoftmax`) and `Tensor#softmax`,
|
|
53
|
+
computed with the maximum subtracted first, so they stay finite for
|
|
54
|
+
logits in the thousands.
|
|
55
|
+
- `Losses::BCEWithLogits` (`reduction: :mean` or `:sum`): binary
|
|
56
|
+
cross-entropy on logits, finite and with a full gradient even for
|
|
57
|
+
confident wrong predictions.
|
|
58
|
+
- `Maurograd.randn`, `.rand`, `.randn_like` and `.rand_like`: random
|
|
59
|
+
tensors drawn by their backend (on the GPU for MLX), seeded by
|
|
60
|
+
`Maurograd.seed!`.
|
|
61
|
+
- Backend methods `slice`, `pad`, `concat`, `normal`, `uniform`, `log1p`,
|
|
62
|
+
`abs`, `maximum`, `minimum`, `greater` and `greater_equal`, on the CPU
|
|
63
|
+
and MLX backends.
|
|
64
|
+
|
|
65
|
+
### Changed
|
|
66
|
+
|
|
67
|
+
- Every built-in layer, and `Sequential`, is now a `Layers::Module`.
|
|
68
|
+
Parameter order is unchanged.
|
|
69
|
+
- `BatchNorm2D` no longer overrides `to`; its running statistics are
|
|
70
|
+
buffers.
|
|
71
|
+
- `Sequential.new` raises `TypeError` for a layer that isn't a
|
|
72
|
+
`Layers::Module`, instead of silently skipping its parameters.
|
|
73
|
+
|
|
10
74
|
## [0.1.0] - 2026-11-27
|
|
11
75
|
|
|
12
76
|
First public release.
|
|
@@ -46,4 +110,6 @@ First public release.
|
|
|
46
110
|
saving/loading yet.
|
|
47
111
|
- No pure-Ruby fallback: the C extension must build.
|
|
48
112
|
|
|
113
|
+
[Unreleased]: https://github.com/mtortonesi/maurograd/compare/v0.2.0...HEAD
|
|
114
|
+
[0.2.0]: https://github.com/mtortonesi/maurograd/compare/v0.1.0...v0.2.0
|
|
49
115
|
[0.1.0]: https://github.com/mtortonesi/maurograd/releases/tag/v0.1.0
|
data/README.md
CHANGED
|
@@ -66,6 +66,50 @@ framework:
|
|
|
66
66
|
every `Conv2D` - so you can see what BatchNorm actually changes about
|
|
67
67
|
training, rather than just reading about it.
|
|
68
68
|
|
|
69
|
+
Models with more than a chain of layers subclass `Layers::Module`: keep
|
|
70
|
+
layers and parameters in instance variables and write `forward`, and
|
|
71
|
+
`parameters`, `train`/`eval` and `to` work with no further code. A
|
|
72
|
+
residual block, for instance:
|
|
73
|
+
|
|
74
|
+
```ruby
|
|
75
|
+
class ResidualBlock < Maurograd::Layers::Module
|
|
76
|
+
def initialize(channels)
|
|
77
|
+
@conv1 = Maurograd::Layers::Conv2D.new(channels, channels, 3, padding: 1)
|
|
78
|
+
@conv2 = Maurograd::Layers::Conv2D.new(channels, channels, 3, padding: 1)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def forward(x)
|
|
82
|
+
x + @conv2.call(@conv1.call(x).relu)
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
To save a trained model and load it back later, use its `state_dict`,
|
|
88
|
+
written in the [safetensors](https://github.com/huggingface/safetensors)
|
|
89
|
+
format (readable from Python too):
|
|
90
|
+
|
|
91
|
+
```ruby
|
|
92
|
+
Maurograd::SafeTensors.save(model.state_dict, "model.safetensors")
|
|
93
|
+
model.load_state_dict(Maurograd::SafeTensors.load("model.safetensors"))
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Wrap evaluation and sampling in `Maurograd.no_grad { ... }`, so that no
|
|
97
|
+
graph is recorded, and call `model.eval` first, so that Dropout and
|
|
98
|
+
BatchNorm behave as at inference time.
|
|
99
|
+
|
|
100
|
+
Besides arithmetic and the layers, tensors have differentiable elementwise
|
|
101
|
+
functions (`exp`, `log`, `sigmoid`, `tanh`, `silu`, `softplus`,
|
|
102
|
+
`log_sigmoid`, `leaky_relu`, `clamp`), reductions (`sum` and `mean` over
|
|
103
|
+
any axes, `logsumexp`, `log_softmax`, `softmax`), and ways to cut and join
|
|
104
|
+
them (`slice`, `chunk`, `Maurograd.concat`). `Maurograd.randn` and
|
|
105
|
+
`Maurograd.rand` draw random tensors on their backend, and `detach` cuts a
|
|
106
|
+
tensor off the graph. For instance, a VAE's reparameterization trick:
|
|
107
|
+
|
|
108
|
+
```ruby
|
|
109
|
+
mean, log_var = encoder.call(x).chunk(2, axis: 1)
|
|
110
|
+
z = mean + (log_var * 0.5).exp * Maurograd.randn_like(mean)
|
|
111
|
+
```
|
|
112
|
+
|
|
69
113
|
(An MLP classifier for the two moons dataset also exists, but it's built on
|
|
70
114
|
the scalar-valued engine, so it now lives in
|
|
71
115
|
[maurograd_scalar](https://github.com/mtortonesi/maurograd_scalar) instead.)
|
|
@@ -81,6 +81,16 @@ module Maurograd
|
|
|
81
81
|
::Numo::NArray.srand(n)
|
|
82
82
|
end
|
|
83
83
|
|
|
84
|
+
# Samples of the standard normal distribution N(0, 1).
|
|
85
|
+
def normal(shape)
|
|
86
|
+
::Numo::SFloat.new(*shape).rand_norm
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Samples of the uniform distribution on [0, 1).
|
|
90
|
+
def uniform(shape)
|
|
91
|
+
::Numo::SFloat.new(*shape).rand
|
|
92
|
+
end
|
|
93
|
+
|
|
84
94
|
# --- Shape --------------------------------------------------------------
|
|
85
95
|
|
|
86
96
|
def reshape(x, *shape)
|
|
@@ -92,6 +102,31 @@ module Maurograd
|
|
|
92
102
|
x.transpose(*axes)
|
|
93
103
|
end
|
|
94
104
|
|
|
105
|
+
# Elements start...stop (stop excluded) along `axis`, everything along
|
|
106
|
+
# the other axes. On this backend, a view of x.
|
|
107
|
+
def slice(x, axis, start, stop)
|
|
108
|
+
index = Array.new(x.ndim, true)
|
|
109
|
+
index[axis] = start...stop
|
|
110
|
+
x[*index]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# x with `before` zeros in front and `after` zeros at the end of
|
|
114
|
+
# `axis`: the inverse of slice, for its backward pass.
|
|
115
|
+
def pad(x, axis, before, after)
|
|
116
|
+
shape = x.shape.dup
|
|
117
|
+
shape[axis] += before + after
|
|
118
|
+
out = x.class.zeros(*shape)
|
|
119
|
+
index = Array.new(x.ndim, true)
|
|
120
|
+
index[axis] = before...(before + x.shape[axis])
|
|
121
|
+
out[*index] = x
|
|
122
|
+
out
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Joins arrays of the same shape except along `axis`.
|
|
126
|
+
def concat(arrays, axis)
|
|
127
|
+
arrays.first.concatenate(*arrays.drop(1), axis: axis)
|
|
128
|
+
end
|
|
129
|
+
|
|
95
130
|
# --- Reductions ---------------------------------------------------------
|
|
96
131
|
#
|
|
97
132
|
# axis: nil reduces over everything and returns a 0-dim array.
|
|
@@ -128,6 +163,35 @@ module Maurograd
|
|
|
128
163
|
::Numo::NMath.sqrt(x)
|
|
129
164
|
end
|
|
130
165
|
|
|
166
|
+
# log(1 + x), accurate for x near 0 (where log(1 + x) would round 1 + x).
|
|
167
|
+
def log1p(x)
|
|
168
|
+
::Numo::NMath.log1p(x)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def abs(x)
|
|
172
|
+
x.abs
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# Elementwise maximum and minimum of two arrays, or of an array and a
|
|
176
|
+
# number.
|
|
177
|
+
def maximum(a, b)
|
|
178
|
+
::Numo::SFloat.maximum(a, b)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def minimum(a, b)
|
|
182
|
+
::Numo::SFloat.minimum(a, b)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# 1.0 where a > b (or a >= b), 0.0 elsewhere: masks for gradients.
|
|
186
|
+
# `a` is an array, `b` an array or a number.
|
|
187
|
+
def greater(a, b)
|
|
188
|
+
::Numo::SFloat.cast(a.gt(b))
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def greater_equal(a, b)
|
|
192
|
+
::Numo::SFloat.cast(a.ge(b))
|
|
193
|
+
end
|
|
194
|
+
|
|
131
195
|
# True iff every element is finite (used by Maurograd.debug checks).
|
|
132
196
|
def all_finite?(x)
|
|
133
197
|
flat = ::Numo::SFloat.cast(x).flatten
|
data/lib/maurograd/backends.rb
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
require_relative "grad_mode"
|
|
2
|
+
|
|
1
3
|
module Maurograd
|
|
2
4
|
# Compute backends: where tensor data lives and which code runs the math.
|
|
3
5
|
#
|
|
@@ -97,6 +99,13 @@ module Maurograd
|
|
|
97
99
|
end
|
|
98
100
|
backend
|
|
99
101
|
end
|
|
102
|
+
|
|
103
|
+
# Whether an op's output must be recorded for backward: some input
|
|
104
|
+
# requires grad (nils ignored), and recording isn't switched off by
|
|
105
|
+
# Maurograd.no_grad. Every op decides through this one method.
|
|
106
|
+
def self.requires_grad?(*tensors)
|
|
107
|
+
Maurograd.grad_enabled? && tensors.any? { |t| t&.requires_grad }
|
|
108
|
+
end
|
|
100
109
|
end
|
|
101
110
|
|
|
102
111
|
class << self
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
# Gradient recording, on by default.
|
|
3
|
+
#
|
|
4
|
+
# Every op normally records how it computed its output (the output's
|
|
5
|
+
# creator), so that backward can walk the graph later. That costs memory
|
|
6
|
+
# (each op keeps its inputs and whatever it saved for backward) and some
|
|
7
|
+
# time, and is wasted when no backward will follow: evaluating a model,
|
|
8
|
+
# sampling from a generative model, updating weights by hand.
|
|
9
|
+
#
|
|
10
|
+
# Maurograd.no_grad do
|
|
11
|
+
# logits = model.call(x_test) # no graph is built
|
|
12
|
+
# end
|
|
13
|
+
#
|
|
14
|
+
# Inside the block, op outputs don't require grad and have no creator,
|
|
15
|
+
# whatever their inputs. Tensors created directly keep the requires_grad
|
|
16
|
+
# they were given, and parameters stay trainable: only recording stops.
|
|
17
|
+
#
|
|
18
|
+
# no_grad does NOT switch layers to evaluation mode (Dropout, BatchNorm2D
|
|
19
|
+
# running statistics): that is model.eval, a separate setting, as in
|
|
20
|
+
# PyTorch. Evaluation usually wants both.
|
|
21
|
+
#
|
|
22
|
+
# The setting is per thread, and blocks can be nested.
|
|
23
|
+
GRAD_ENABLED_KEY = :maurograd_grad_enabled
|
|
24
|
+
|
|
25
|
+
class << self
|
|
26
|
+
# Runs the block with gradient recording off, and returns its value.
|
|
27
|
+
def no_grad
|
|
28
|
+
raise ArgumentError, "Maurograd.no_grad needs a block" unless block_given?
|
|
29
|
+
|
|
30
|
+
previous = grad_enabled?
|
|
31
|
+
Thread.current.thread_variable_set(GRAD_ENABLED_KEY, false)
|
|
32
|
+
begin
|
|
33
|
+
yield
|
|
34
|
+
ensure
|
|
35
|
+
Thread.current.thread_variable_set(GRAD_ENABLED_KEY, previous)
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# True unless inside a no_grad block (on this thread).
|
|
40
|
+
def grad_enabled?
|
|
41
|
+
Thread.current.thread_variable_get(GRAD_ENABLED_KEY) != false
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
require_relative "../ops/elementwise"
|
|
2
|
+
require_relative "module"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Layers
|
|
6
|
+
# Activation layers without parameters, for use in Sequential; in a
|
|
7
|
+
# custom Module's forward, calling x.sigmoid, x.tanh or x.silu directly
|
|
8
|
+
# is the same thing. (ReLU has its own file, and a C kernel.)
|
|
9
|
+
|
|
10
|
+
class Sigmoid < Module
|
|
11
|
+
def forward(input) = input.sigmoid
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
class Tanh < Module
|
|
15
|
+
def forward(input) = input.tanh
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# SiLU / swish: x * sigmoid(x).
|
|
19
|
+
class SiLU < Module
|
|
20
|
+
def forward(input) = input.silu
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Leaky ReLU, with a fixed negative slope (default 0.01).
|
|
24
|
+
class LeakyReLU < Module
|
|
25
|
+
attr_reader :negative_slope
|
|
26
|
+
|
|
27
|
+
def initialize(negative_slope: 0.01)
|
|
28
|
+
@negative_slope = negative_slope
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def forward(input) = input.leaky_relu(negative_slope: @negative_slope)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Softplus, log(1 + e^x): a smooth, positive ReLU.
|
|
35
|
+
class Softplus < Module
|
|
36
|
+
def forward(input) = input.softplus
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require_relative "../tensor"
|
|
2
2
|
require_relative "../ops/batchnorm2d"
|
|
3
|
+
require_relative "module"
|
|
3
4
|
|
|
4
5
|
module Maurograd
|
|
5
6
|
module Layers
|
|
@@ -13,16 +14,20 @@ module Maurograd
|
|
|
13
14
|
# backend (Numo::SFloat on the CPU backend), not Tensors: they are
|
|
14
15
|
# statistics, not parameters trained by gradient descent, so they must
|
|
15
16
|
# NOT appear in #parameters (Optim::SGD#step would otherwise try to
|
|
16
|
-
# update them with a gradient they don't have)
|
|
17
|
-
#
|
|
17
|
+
# update them with a gradient they don't have); Module only collects
|
|
18
|
+
# Tensors, so they don't. They are declared as buffers instead, which
|
|
19
|
+
# #to and #state_dict handle. In training mode, forward replaces them with
|
|
20
|
+
# their updated values.
|
|
18
21
|
#
|
|
19
|
-
class BatchNorm2D
|
|
22
|
+
class BatchNorm2D < Module
|
|
23
|
+
# Moved by #to and saved by #state_dict with the parameters.
|
|
24
|
+
buffers :running_mean, :running_var
|
|
25
|
+
|
|
20
26
|
attr_accessor :gamma, :beta, :running_mean, :running_var, :momentum, :eps
|
|
21
27
|
|
|
22
28
|
def initialize(num_features, momentum: 0.1, eps: 1e-5)
|
|
23
29
|
@momentum = momentum
|
|
24
30
|
@eps = eps
|
|
25
|
-
@training = true
|
|
26
31
|
|
|
27
32
|
@gamma = Maurograd::Tensor.new(Numo::SFloat.ones(num_features), requires_grad: true)
|
|
28
33
|
@beta = Maurograd::Tensor.new(Numo::SFloat.zeros(num_features), requires_grad: true)
|
|
@@ -35,35 +40,11 @@ module Maurograd
|
|
|
35
40
|
Maurograd::Ops::BatchNorm2D.apply(
|
|
36
41
|
input, @gamma, @beta,
|
|
37
42
|
stats: self,
|
|
38
|
-
training:
|
|
43
|
+
training: training?,
|
|
39
44
|
momentum: @momentum,
|
|
40
45
|
eps: @eps
|
|
41
46
|
)
|
|
42
47
|
end
|
|
43
|
-
|
|
44
|
-
def parameters
|
|
45
|
-
[@gamma, @beta]
|
|
46
|
-
end
|
|
47
|
-
|
|
48
|
-
# Moves parameters and running statistics to another backend.
|
|
49
|
-
def to(backend)
|
|
50
|
-
source = @gamma.backend
|
|
51
|
-
parameters.each { |p| p.to(backend) }
|
|
52
|
-
target = @gamma.backend
|
|
53
|
-
@running_mean = target.from(source.to_numo(@running_mean))
|
|
54
|
-
@running_var = target.from(source.to_numo(@running_var))
|
|
55
|
-
self
|
|
56
|
-
end
|
|
57
|
-
|
|
58
|
-
def train
|
|
59
|
-
@training = true
|
|
60
|
-
self
|
|
61
|
-
end
|
|
62
|
-
|
|
63
|
-
def eval
|
|
64
|
-
@training = false
|
|
65
|
-
self
|
|
66
|
-
end
|
|
67
48
|
end
|
|
68
49
|
end
|
|
69
50
|
end
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
require_relative "../tensor"
|
|
2
2
|
require_relative "../ops/conv2d"
|
|
3
3
|
require_relative "../utils/utils"
|
|
4
|
+
require_relative "module"
|
|
4
5
|
|
|
5
6
|
module Maurograd
|
|
6
7
|
module Layers
|
|
@@ -26,7 +27,7 @@ module Maurograd
|
|
|
26
27
|
# - nn.Conv2d -> Layer (parameters + forward interface)
|
|
27
28
|
# - aten/ops -> low-level operations used by autograd
|
|
28
29
|
#
|
|
29
|
-
class Conv2D
|
|
30
|
+
class Conv2D < Module
|
|
30
31
|
attr_accessor :weights, :bias, :stride, :padding
|
|
31
32
|
|
|
32
33
|
# Create a 2D convolutional layer.
|
|
@@ -120,16 +121,6 @@ module Maurograd
|
|
|
120
121
|
def forward(input)
|
|
121
122
|
Maurograd::Ops::Conv2D.apply(input, @weights, @bias, @stride, @padding)
|
|
122
123
|
end
|
|
123
|
-
|
|
124
|
-
# Moves the parameters to another backend (see Tensor#to).
|
|
125
|
-
def to(backend)
|
|
126
|
-
parameters.each { |p| p.to(backend) }
|
|
127
|
-
self
|
|
128
|
-
end
|
|
129
|
-
|
|
130
|
-
def parameters
|
|
131
|
-
[@weights, @bias]
|
|
132
|
-
end
|
|
133
124
|
end
|
|
134
125
|
end
|
|
135
126
|
end
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
require_relative "../ops/dropout"
|
|
2
|
+
require_relative "module"
|
|
2
3
|
|
|
3
4
|
module Maurograd
|
|
4
5
|
module Layers
|
|
@@ -9,32 +10,17 @@ module Maurograd
|
|
|
9
10
|
# Delegates the actual work to Ops::Dropout.
|
|
10
11
|
#
|
|
11
12
|
# Like PyTorch, a freshly constructed layer is in training mode: call
|
|
12
|
-
# #eval (usually
|
|
13
|
-
class Dropout
|
|
13
|
+
# #eval (usually on the whole model) before evaluating it.
|
|
14
|
+
class Dropout < Module
|
|
14
15
|
attr_reader :p
|
|
15
16
|
|
|
16
17
|
def initialize(p = 0.5)
|
|
17
18
|
Maurograd::Ops::Dropout.validate_p!(p)
|
|
18
19
|
@p = p
|
|
19
|
-
@training = true
|
|
20
20
|
end
|
|
21
21
|
|
|
22
22
|
def forward(input)
|
|
23
|
-
Maurograd::Ops::Dropout.apply(input, p: @p, training:
|
|
24
|
-
end
|
|
25
|
-
|
|
26
|
-
def train
|
|
27
|
-
@training = true
|
|
28
|
-
self
|
|
29
|
-
end
|
|
30
|
-
|
|
31
|
-
def eval
|
|
32
|
-
@training = false
|
|
33
|
-
self
|
|
34
|
-
end
|
|
35
|
-
|
|
36
|
-
def training?
|
|
37
|
-
@training
|
|
23
|
+
Maurograd::Ops::Dropout.apply(input, p: @p, training: training?)
|
|
38
24
|
end
|
|
39
25
|
end
|
|
40
26
|
end
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
require_relative "../tensor"
|
|
2
2
|
require_relative "../ops/linear"
|
|
3
3
|
require_relative "../utils/utils"
|
|
4
|
+
require_relative "module"
|
|
4
5
|
|
|
5
6
|
module Maurograd
|
|
6
7
|
module Layers
|
|
@@ -11,7 +12,7 @@ module Maurograd
|
|
|
11
12
|
# - bias: [Out]
|
|
12
13
|
#
|
|
13
14
|
# Delegates actual computation + autograd logic to Ops::Linear.
|
|
14
|
-
class Linear
|
|
15
|
+
class Linear < Module
|
|
15
16
|
attr_accessor :weights, :bias
|
|
16
17
|
|
|
17
18
|
# - seed: optional seed for reproducible weight initialization.
|
|
@@ -37,18 +38,6 @@ module Maurograd
|
|
|
37
38
|
def forward(input)
|
|
38
39
|
Maurograd::Ops::Linear.apply(input, @weights, @bias)
|
|
39
40
|
end
|
|
40
|
-
|
|
41
|
-
# Moves the parameters to another backend (see Tensor#to).
|
|
42
|
-
def to(backend)
|
|
43
|
-
parameters.each { |p| p.to(backend) }
|
|
44
|
-
self
|
|
45
|
-
end
|
|
46
|
-
|
|
47
|
-
def parameters
|
|
48
|
-
ps = [@weights]
|
|
49
|
-
ps << @bias if @bias
|
|
50
|
-
ps
|
|
51
|
-
end
|
|
52
41
|
end
|
|
53
42
|
end
|
|
54
43
|
end
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
require_relative "../ops/maxpool2d"
|
|
2
|
+
require_relative "module"
|
|
2
3
|
|
|
3
4
|
module Maurograd
|
|
4
5
|
module Layers
|
|
5
|
-
class MaxPool2D
|
|
6
|
+
class MaxPool2D < Module
|
|
6
7
|
def initialize(kernel_size, stride: nil, padding: 0)
|
|
7
8
|
@kh, @kw = kernel_size.is_a?(Integer) ? [kernel_size, kernel_size] : kernel_size
|
|
8
9
|
@stride = stride || @kh
|