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
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# Elementwise functions: y = f(x), applied to every element on its own.
|
|
6
|
+
#
|
|
7
|
+
# Backward is the chain rule, one element at a time:
|
|
8
|
+
#
|
|
9
|
+
# dL/dx = dL/dy * f'(x)
|
|
10
|
+
#
|
|
11
|
+
# so each function only has to say how to compute f and f'. Often f' is
|
|
12
|
+
# cheapest in terms of the output y, which forward already computed:
|
|
13
|
+
# exp' = exp = y, sigmoid' = y * (1 - y), tanh' = 1 - y^2.
|
|
14
|
+
#
|
|
15
|
+
# All of them are built from backend methods (exp, log, comparisons and
|
|
16
|
+
# arithmetic), so they need no kernels of their own on any backend.
|
|
17
|
+
# Subclasses with a parameter (LeakyReLU's slope, Clamp's bounds) take
|
|
18
|
+
# it as a keyword argument after the input.
|
|
19
|
+
class Elementwise
|
|
20
|
+
def self.apply(input, ...)
|
|
21
|
+
new(input, ...).forward
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
attr_reader :inputs
|
|
25
|
+
|
|
26
|
+
def initialize(input)
|
|
27
|
+
@inputs = [input]
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def forward
|
|
31
|
+
input = @inputs.first
|
|
32
|
+
@y = compute(input.backend, input.data)
|
|
33
|
+
|
|
34
|
+
requires_grad = Ops.requires_grad?(input)
|
|
35
|
+
out = Tensor.new(@y, requires_grad: requires_grad, backend: input.backend)
|
|
36
|
+
out.creator = self if requires_grad
|
|
37
|
+
out
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def backward(grad_output)
|
|
41
|
+
input = @inputs.first
|
|
42
|
+
return unless input.requires_grad
|
|
43
|
+
|
|
44
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
45
|
+
input.accumulate_grad(dy * derivative(input.backend, input.data, @y))
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
# f(x).
|
|
51
|
+
def compute(bk, x)
|
|
52
|
+
raise NotImplementedError
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# f'(x), given x and y = f(x).
|
|
56
|
+
def derivative(bk, x, y)
|
|
57
|
+
raise NotImplementedError
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# 1 / (1 + e^-x). For large negative x, e^-x overflows to infinity
|
|
61
|
+
# and the result is 0, which is the right limit (not NaN).
|
|
62
|
+
def sigmoid(bk, x)
|
|
63
|
+
1.0 / (bk.exp(-x) + 1.0)
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# log(1 + e^-|x|), which is between 0 and log 2 for every x and never
|
|
67
|
+
# overflows: the part softplus and log_sigmoid share.
|
|
68
|
+
def log1p_exp_neg_abs(bk, x)
|
|
69
|
+
bk.log1p(bk.exp(-bk.abs(x)))
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# e^x. Its own derivative.
|
|
74
|
+
class Exp < Elementwise
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def compute(bk, x) = bk.exp(x)
|
|
78
|
+
|
|
79
|
+
def derivative(_bk, _x, y) = y
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Natural logarithm, d/dx log x = 1/x. Inputs must be positive: log of
|
|
83
|
+
# 0 is -Infinity and of a negative number is NaN, as in NumPy.
|
|
84
|
+
class Log < Elementwise
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
def compute(bk, x) = bk.log(x)
|
|
88
|
+
|
|
89
|
+
def derivative(_bk, x, _y) = 1.0 / x
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Logistic sigmoid, 1 / (1 + e^-x): squashes to (0, 1).
|
|
93
|
+
# d/dx = sigmoid(x) * (1 - sigmoid(x)) = y * (1 - y).
|
|
94
|
+
class Sigmoid < Elementwise
|
|
95
|
+
private
|
|
96
|
+
|
|
97
|
+
def compute(bk, x) = sigmoid(bk, x)
|
|
98
|
+
|
|
99
|
+
def derivative(_bk, _x, y) = y * (1.0 - y)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Hyperbolic tangent: squashes to (-1, 1). Computed as
|
|
103
|
+
# 2 * sigmoid(2x) - 1, which is the same function and reuses the
|
|
104
|
+
# overflow-safe sigmoid. d/dx tanh x = 1 - tanh^2 x = 1 - y^2.
|
|
105
|
+
class Tanh < Elementwise
|
|
106
|
+
private
|
|
107
|
+
|
|
108
|
+
def compute(bk, x) = (sigmoid(bk, x * 2.0) * 2.0) - 1.0
|
|
109
|
+
|
|
110
|
+
def derivative(_bk, _x, y) = 1.0 - (y * y)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# SiLU (also called swish): x * sigmoid(x). Smooth, and close to ReLU
|
|
114
|
+
# for large |x|; the usual activation in diffusion UNets.
|
|
115
|
+
# d/dx = s + x * s * (1 - s) = s * (1 + x * (1 - s)), with s = sigmoid(x).
|
|
116
|
+
class SiLU < Elementwise
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
def compute(bk, x) = x * sigmoid(bk, x)
|
|
120
|
+
|
|
121
|
+
def derivative(bk, x, _y)
|
|
122
|
+
s = sigmoid(bk, x)
|
|
123
|
+
s * ((x * (1.0 - s)) + 1.0)
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Softplus, log(1 + e^x): a smooth ReLU, always positive. Used to
|
|
128
|
+
# make a network output positive (a standard deviation, say), and the
|
|
129
|
+
# heart of binary cross-entropy with logits.
|
|
130
|
+
#
|
|
131
|
+
# Computed as max(x, 0) + log(1 + e^-|x|), which is the same function
|
|
132
|
+
# (for x > 0, log(1 + e^x) = x + log(1 + e^-x)) but can't overflow: the
|
|
133
|
+
# direct formula gives Infinity for x above about 88 in float32.
|
|
134
|
+
# d/dx = e^x / (1 + e^x) = sigmoid(x).
|
|
135
|
+
class Softplus < Elementwise
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
def compute(bk, x) = bk.maximum(x, 0.0) + log1p_exp_neg_abs(bk, x)
|
|
139
|
+
|
|
140
|
+
def derivative(bk, x, _y) = sigmoid(bk, x)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# log(sigmoid(x)) = -softplus(-x): the log-probability of a Bernoulli
|
|
144
|
+
# outcome 1 when x is its logit (and log_sigmoid(-x) that of 0), so a
|
|
145
|
+
# Bernoulli likelihood is x*log_sigmoid(z) + (1-x)*log_sigmoid(-z).
|
|
146
|
+
# Computing log(sigmoid(x)) directly gives log(0) = -Infinity once
|
|
147
|
+
# sigmoid(x) underflows, around x = -88 in float32; this form is
|
|
148
|
+
# min(x, 0) - log(1 + e^-|x|), finite everywhere.
|
|
149
|
+
# d/dx = 1 - sigmoid(x) = sigmoid(-x).
|
|
150
|
+
class LogSigmoid < Elementwise
|
|
151
|
+
private
|
|
152
|
+
|
|
153
|
+
def compute(bk, x) = bk.minimum(x, 0.0) - log1p_exp_neg_abs(bk, x)
|
|
154
|
+
|
|
155
|
+
def derivative(bk, x, _y) = sigmoid(bk, -x)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Leaky ReLU: x for x > 0, negative_slope * x otherwise. Unlike ReLU,
|
|
159
|
+
# negative inputs keep a small gradient, so units can't "die"; the usual
|
|
160
|
+
# activation in GAN discriminators and energy-based models.
|
|
161
|
+
# d/dx = 1 for x > 0, negative_slope otherwise (at 0: negative_slope, as
|
|
162
|
+
# ReLU takes 0 there).
|
|
163
|
+
class LeakyReLU < Elementwise
|
|
164
|
+
def initialize(input, negative_slope: 0.01)
|
|
165
|
+
super(input)
|
|
166
|
+
@slope = Float(negative_slope)
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
private
|
|
170
|
+
|
|
171
|
+
def compute(bk, x) = x * slope_mask(bk, x)
|
|
172
|
+
|
|
173
|
+
def derivative(bk, x, _y) = slope_mask(bk, x)
|
|
174
|
+
|
|
175
|
+
# 1 where x > 0, the slope elsewhere.
|
|
176
|
+
def slope_mask(bk, x)
|
|
177
|
+
positive = bk.greater(x, 0.0)
|
|
178
|
+
positive + ((1.0 - positive) * @slope)
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# Clamp (clip) to [min, max]; either bound may be nil. Used to keep
|
|
183
|
+
# values in a valid range, e.g. a log-variance, or pixels in [-1, 1]
|
|
184
|
+
# after sampling.
|
|
185
|
+
# d/dx = 1 inside [min, max], bounds included (as in PyTorch), and 0
|
|
186
|
+
# outside, where the output no longer depends on x.
|
|
187
|
+
class Clamp < Elementwise
|
|
188
|
+
def initialize(input, min: nil, max: nil)
|
|
189
|
+
super(input)
|
|
190
|
+
raise ArgumentError, "clamp needs a min:, a max:, or both" if min.nil? && max.nil?
|
|
191
|
+
raise ArgumentError, "clamp needs min <= max, got #{min} and #{max}" if min && max && min > max
|
|
192
|
+
|
|
193
|
+
@min = min&.to_f
|
|
194
|
+
@max = max&.to_f
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
private
|
|
198
|
+
|
|
199
|
+
def compute(bk, x)
|
|
200
|
+
y = @min ? bk.maximum(x, @min) : x
|
|
201
|
+
@max ? bk.minimum(y, @max) : y
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def derivative(bk, x, _y)
|
|
205
|
+
inside = @min ? bk.greater_equal(x, @min) : bk.ones(x.shape)
|
|
206
|
+
@max ? inside * (1.0 - bk.greater(x, @max)) : inside
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
end
|
|
@@ -37,7 +37,7 @@ module Maurograd
|
|
|
37
37
|
flat_dim = input.size / n
|
|
38
38
|
y = input.backend.reshape(x, n, flat_dim)
|
|
39
39
|
|
|
40
|
-
requires_grad = @inputs.first
|
|
40
|
+
requires_grad = Ops.requires_grad?(@inputs.first)
|
|
41
41
|
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
42
42
|
out.creator = self if requires_grad
|
|
43
43
|
out
|
data/lib/maurograd/ops/linear.rb
CHANGED
|
@@ -72,7 +72,7 @@ module Maurograd
|
|
|
72
72
|
y += bk.reshape(bias.data, 1, w.shape[0])
|
|
73
73
|
end
|
|
74
74
|
|
|
75
|
-
requires_grad =
|
|
75
|
+
requires_grad = Ops.requires_grad?(*@inputs)
|
|
76
76
|
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
77
77
|
out.creator = self if requires_grad
|
|
78
78
|
out
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# log(sum(exp(x))) over the given axes, computed without overflow.
|
|
6
|
+
#
|
|
7
|
+
# Forward:
|
|
8
|
+
# exp overflows float32 above about 88, so the sum is taken after
|
|
9
|
+
# shifting by the maximum m, which cancels out exactly:
|
|
10
|
+
#
|
|
11
|
+
# logsumexp(x) = m + log(sum(exp(x - m)))
|
|
12
|
+
#
|
|
13
|
+
# Every exp(x - m) is then at most 1, and at least one is exactly 1,
|
|
14
|
+
# so the log is finite too.
|
|
15
|
+
#
|
|
16
|
+
# Backward:
|
|
17
|
+
# d/dx_i logsumexp(x) = exp(x_i) / sum(exp(x)) = softmax(x)_i, which is
|
|
18
|
+
# exp(x_i - y), y being the output: each element's gradient is dy
|
|
19
|
+
# weighted by its share of the sum.
|
|
20
|
+
#
|
|
21
|
+
# It turns sums of probabilities into sums in log space: the
|
|
22
|
+
# log-likelihood of a mixture of Gaussians, the VampPrior's log-density,
|
|
23
|
+
# and an importance-sampled log-likelihood estimate are all logsumexps.
|
|
24
|
+
class LogSumExp
|
|
25
|
+
def self.apply(input, axis: nil, keepdims: false)
|
|
26
|
+
new(input, axis: axis, keepdims: keepdims).forward
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
attr_reader :inputs, :axes
|
|
30
|
+
|
|
31
|
+
def initialize(input, axis: nil, keepdims: false)
|
|
32
|
+
@inputs = [input]
|
|
33
|
+
@axes = Sum.normalize_axes(axis, input.ndim) || (0...input.ndim).to_a
|
|
34
|
+
@keepdims = keepdims
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def forward
|
|
38
|
+
input = @inputs.first
|
|
39
|
+
bk = input.backend
|
|
40
|
+
x = input.data
|
|
41
|
+
|
|
42
|
+
m = bk.max(x, axis: @axes, keepdims: true)
|
|
43
|
+
@y_kept = bk.log(bk.sum(bk.exp(x - m), axis: @axes, keepdims: true)) + m
|
|
44
|
+
y = @keepdims ? @y_kept : drop_axes(bk, @y_kept)
|
|
45
|
+
|
|
46
|
+
requires_grad = Ops.requires_grad?(input)
|
|
47
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: bk)
|
|
48
|
+
out.creator = self if requires_grad
|
|
49
|
+
out
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def backward(grad_output)
|
|
53
|
+
input = @inputs.first
|
|
54
|
+
return unless input.requires_grad
|
|
55
|
+
|
|
56
|
+
bk = input.backend
|
|
57
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
58
|
+
dy = bk.reshape(dy, *@y_kept.shape) unless @keepdims
|
|
59
|
+
input.accumulate_grad(dy * bk.exp(input.data - @y_kept))
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
private
|
|
63
|
+
|
|
64
|
+
# The keepdims result without its size-1 axes: a scalar when every
|
|
65
|
+
# axis was reduced.
|
|
66
|
+
def drop_axes(bk, y)
|
|
67
|
+
shape = @inputs.first.shape.each_with_index.reject { |_, i| @axes.include?(i) }.map(&:first)
|
|
68
|
+
shape.empty? ? bk.sum(y) : bk.reshape(y, *shape)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# log(softmax(x)) along one axis: x - logsumexp(x), the log-probabilities
|
|
73
|
+
# of a categorical distribution whose logits are x.
|
|
74
|
+
#
|
|
75
|
+
# Forward:
|
|
76
|
+
# y = x - logsumexp(x, axis, keepdims: true). Taking the log of a
|
|
77
|
+
# softmax computed first would give log(0) = -Infinity for classes
|
|
78
|
+
# whose probability underflows; this form doesn't.
|
|
79
|
+
#
|
|
80
|
+
# Backward:
|
|
81
|
+
# With p = softmax(x) = exp(y), dy_j/dx_i = [i == j] - p_i, so
|
|
82
|
+
#
|
|
83
|
+
# dx = dy - p * sum(dy) (the sum along the axis)
|
|
84
|
+
class LogSoftmax
|
|
85
|
+
def self.apply(input, axis: -1)
|
|
86
|
+
new(input, axis: axis).forward
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
attr_reader :inputs, :axis
|
|
90
|
+
|
|
91
|
+
def initialize(input, axis: -1)
|
|
92
|
+
@inputs = [input]
|
|
93
|
+
@axis = Sum.normalize_axes(axis, input.ndim).first
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def forward
|
|
97
|
+
input = @inputs.first
|
|
98
|
+
bk = input.backend
|
|
99
|
+
x = input.data
|
|
100
|
+
|
|
101
|
+
m = bk.max(x, axis: @axis, keepdims: true)
|
|
102
|
+
shifted = x - m
|
|
103
|
+
@y = shifted - bk.log(bk.sum(bk.exp(shifted), axis: @axis, keepdims: true))
|
|
104
|
+
|
|
105
|
+
requires_grad = Ops.requires_grad?(input)
|
|
106
|
+
out = Tensor.new(@y, requires_grad: requires_grad, backend: bk)
|
|
107
|
+
out.creator = self if requires_grad
|
|
108
|
+
out
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def backward(grad_output)
|
|
112
|
+
input = @inputs.first
|
|
113
|
+
return unless input.requires_grad
|
|
114
|
+
|
|
115
|
+
bk = input.backend
|
|
116
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
117
|
+
input.accumulate_grad(dy - (bk.exp(@y) * bk.sum(dy, axis: @axis, keepdims: true)))
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
end
|
data/lib/maurograd/ops/matmul.rb
CHANGED
|
@@ -32,7 +32,7 @@ module Maurograd
|
|
|
32
32
|
result_data = @backend.matmul(a.data, b.data)
|
|
33
33
|
|
|
34
34
|
# The output requires the gradient if at least one of the inputs requires it.
|
|
35
|
-
requires_grad =
|
|
35
|
+
requires_grad = Ops.requires_grad?(a, b)
|
|
36
36
|
result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
37
37
|
|
|
38
38
|
# We set the creator ONLY if it is needed for backward
|
|
@@ -67,7 +67,7 @@ module Maurograd
|
|
|
67
67
|
|
|
68
68
|
y, ctx = input.backend.maxpool2d_forward(input.data, @kernel_h, @kernel_w, @stride, @padding)
|
|
69
69
|
|
|
70
|
-
requires_grad =
|
|
70
|
+
requires_grad = Ops.requires_grad?(input)
|
|
71
71
|
@ctx = ctx if requires_grad
|
|
72
72
|
|
|
73
73
|
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
data/lib/maurograd/ops/mul.rb
CHANGED
|
@@ -27,7 +27,7 @@ module Maurograd
|
|
|
27
27
|
a, b = @inputs
|
|
28
28
|
@backend = Ops.backend_of(a, b)
|
|
29
29
|
out_data = a.data * b.data
|
|
30
|
-
requires_grad =
|
|
30
|
+
requires_grad = Ops.requires_grad?(a, b)
|
|
31
31
|
out = Tensor.new(out_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
32
32
|
out.creator = self if requires_grad
|
|
33
33
|
out
|
|
@@ -54,7 +54,7 @@ module Maurograd
|
|
|
54
54
|
input = @inputs.first
|
|
55
55
|
y = input.backend.transpose(input.data, *@axes)
|
|
56
56
|
|
|
57
|
-
requires_grad =
|
|
57
|
+
requires_grad = Ops.requires_grad?(input)
|
|
58
58
|
out = Tensor.new(y, requires_grad: requires_grad, backend: input.backend)
|
|
59
59
|
out.creator = self if requires_grad
|
|
60
60
|
out
|
data/lib/maurograd/ops/power.rb
CHANGED
|
@@ -22,7 +22,7 @@ module Maurograd
|
|
|
22
22
|
tensor = @inputs.first
|
|
23
23
|
result_data = tensor.data**@exponent
|
|
24
24
|
|
|
25
|
-
requires_grad =
|
|
25
|
+
requires_grad = Ops.requires_grad?(tensor)
|
|
26
26
|
result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
27
27
|
|
|
28
28
|
result.creator = self if requires_grad
|
data/lib/maurograd/ops/relu.rb
CHANGED
|
@@ -29,7 +29,7 @@ module Maurograd
|
|
|
29
29
|
input = @inputs.first
|
|
30
30
|
y, ctx = input.backend.relu_forward(input.data)
|
|
31
31
|
|
|
32
|
-
requires_grad =
|
|
32
|
+
requires_grad = Ops.requires_grad?(input)
|
|
33
33
|
@ctx = ctx if requires_grad
|
|
34
34
|
|
|
35
35
|
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# Reshape a tensor: same elements, same order, different shape.
|
|
6
|
+
#
|
|
7
|
+
# Forward:
|
|
8
|
+
# y = x read in row-major order (last axis fastest) and laid out again
|
|
9
|
+
# in `shape`. The number of elements must not change, e.g.
|
|
10
|
+
# [2, 3, 4] -> [6, 4], [2, 12] or [24]. One dimension may be -1, which
|
|
11
|
+
# means "whatever makes the sizes match", as in NumPy and PyTorch:
|
|
12
|
+
# [2, 3, 4] -> [2, -1] gives [2, 12].
|
|
13
|
+
#
|
|
14
|
+
# Backward:
|
|
15
|
+
# Reshape doesn't change any value, it only regroups them, so element
|
|
16
|
+
# k (in row-major order) of y is element k of x. The gradient is
|
|
17
|
+
# therefore dy reshaped back to x's shape. Nothing is summed or
|
|
18
|
+
# reordered, which is what makes it different from Permute: permute
|
|
19
|
+
# moves elements to new positions in row-major order, reshape doesn't.
|
|
20
|
+
#
|
|
21
|
+
# Reshape vs Permute: [2, 3] -> [3, 2] by reshape regroups 0 1 2 | 3 4 5
|
|
22
|
+
# as 0 1 | 2 3 | 4 5, while transpose gives 0 3 | 1 4 | 2 5. Using one
|
|
23
|
+
# where the other was meant is a classic silent bug: the shapes match,
|
|
24
|
+
# the model trains, and the channels are scrambled.
|
|
25
|
+
#
|
|
26
|
+
# Flatten is the special case [N, ...] -> [N, -1].
|
|
27
|
+
class Reshape
|
|
28
|
+
def self.apply(input, shape)
|
|
29
|
+
new(input, shape).forward
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Resolves a requested `shape` for a tensor of `size` elements: checks
|
|
33
|
+
# the dimensions and replaces a -1 with the size it must have. Returns
|
|
34
|
+
# the concrete shape. The backends get only concrete shapes, since
|
|
35
|
+
# Numo doesn't accept -1 (it spells it nil or true) and MLX does.
|
|
36
|
+
def self.resolve_shape(shape, size)
|
|
37
|
+
unless shape.all? { |d| d.is_a?(Integer) && (d >= 0 || d == -1) }
|
|
38
|
+
raise ArgumentError, "reshape dimensions must be non-negative Integers or a single -1, got #{shape.inspect}"
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
inferred = shape.count(-1)
|
|
42
|
+
raise ArgumentError, "reshape can infer only one dimension, got #{shape.inspect}" if inferred > 1
|
|
43
|
+
|
|
44
|
+
known = shape.reject { |d| d == -1 }.reduce(1, :*)
|
|
45
|
+
if inferred == 1
|
|
46
|
+
if known.zero? || size % known != 0
|
|
47
|
+
raise ArgumentError, "cannot reshape #{size} elements into #{shape.inspect}"
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
return shape.map { |d| (d == -1) ? size / known : d }
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
raise ArgumentError, "cannot reshape #{size} elements into #{shape.inspect}" unless known == size
|
|
54
|
+
|
|
55
|
+
shape
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
attr_reader :inputs, :shape
|
|
59
|
+
|
|
60
|
+
def initialize(input, shape)
|
|
61
|
+
@inputs = [input]
|
|
62
|
+
@shape = self.class.resolve_shape(shape, input.size)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def forward
|
|
66
|
+
input = @inputs.first
|
|
67
|
+
# Both backends read strided views (e.g. the output of permute) in
|
|
68
|
+
# logical row-major order, so no explicit copy is needed here.
|
|
69
|
+
y = input.backend.reshape(input.data, *@shape)
|
|
70
|
+
|
|
71
|
+
requires_grad = Ops.requires_grad?(input)
|
|
72
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: input.backend)
|
|
73
|
+
out.creator = self if requires_grad
|
|
74
|
+
out
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def backward(grad_output)
|
|
78
|
+
input = @inputs.first
|
|
79
|
+
return unless input.requires_grad
|
|
80
|
+
|
|
81
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
82
|
+
input.accumulate_grad(input.backend.reshape(dy, *input.shape))
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# A contiguous range of a tensor along one axis.
|
|
6
|
+
#
|
|
7
|
+
# Forward:
|
|
8
|
+
# y = x[..., start...stop, ...] (the range on `axis`, everything on
|
|
9
|
+
# the other axes), e.g. for x of shape [N, 8]:
|
|
10
|
+
# x.slice(1, 0...4) -> [N, 4], the first four columns
|
|
11
|
+
# x.slice(1, 4..) -> [N, 4], the rest
|
|
12
|
+
# x.slice(1, -2..) -> [N, 2], the last two
|
|
13
|
+
#
|
|
14
|
+
# Backward:
|
|
15
|
+
# Each element of y is one element of x, copied, so its gradient goes
|
|
16
|
+
# back to the position it came from, and the elements of x that were
|
|
17
|
+
# left out get zero: dx is dy padded with zeros, `start` of them before
|
|
18
|
+
# and `size - stop` after, along `axis`.
|
|
19
|
+
#
|
|
20
|
+
# The usual use is splitting a network's output in parts: a VAE encoder
|
|
21
|
+
# that outputs [mean, log-variance] side by side, or a coupling layer
|
|
22
|
+
# that transforms half of its input (see Tensor#chunk).
|
|
23
|
+
class Slice
|
|
24
|
+
def self.apply(input, axis, range)
|
|
25
|
+
new(input, axis, range).forward
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Turns `range` (any Ruby Range of Integers: 1...3, 2.., ..-1, -2..)
|
|
29
|
+
# into [start, stop] with 0 <= start < stop <= size, stop excluded, as
|
|
30
|
+
# Array#[] reads ranges. Raises ArgumentError for a range that selects
|
|
31
|
+
# nothing.
|
|
32
|
+
def self.resolve_range(range, size)
|
|
33
|
+
raise ArgumentError, "slice needs a Range, got #{range.inspect}" unless range.is_a?(Range)
|
|
34
|
+
|
|
35
|
+
first = range.begin || 0
|
|
36
|
+
last = range.end
|
|
37
|
+
integers = first.is_a?(Integer) && (last.nil? || last.is_a?(Integer))
|
|
38
|
+
raise ArgumentError, "slice ranges must be of Integers, got #{range.inspect}" unless integers
|
|
39
|
+
|
|
40
|
+
start = first.negative? ? first + size : first
|
|
41
|
+
stop = if last.nil?
|
|
42
|
+
size
|
|
43
|
+
else
|
|
44
|
+
(last.negative? ? last + size : last) + (range.exclude_end? ? 0 : 1)
|
|
45
|
+
end
|
|
46
|
+
stop = stop.clamp(0, size)
|
|
47
|
+
if start.negative? || start >= stop
|
|
48
|
+
raise ArgumentError, "range #{range.inspect} selects nothing from an axis of size #{size}"
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
[start, stop]
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
attr_reader :inputs, :axis, :start, :stop
|
|
55
|
+
|
|
56
|
+
def initialize(input, axis, range)
|
|
57
|
+
@inputs = [input]
|
|
58
|
+
@axis = Sum.normalize_axes(axis, input.ndim).first
|
|
59
|
+
@start, @stop = self.class.resolve_range(range, input.shape[@axis])
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def forward
|
|
63
|
+
input = @inputs.first
|
|
64
|
+
y = input.backend.slice(input.data, @axis, @start, @stop)
|
|
65
|
+
|
|
66
|
+
requires_grad = Ops.requires_grad?(input)
|
|
67
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: input.backend)
|
|
68
|
+
out.creator = self if requires_grad
|
|
69
|
+
out
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def backward(grad_output)
|
|
73
|
+
input = @inputs.first
|
|
74
|
+
return unless input.requires_grad
|
|
75
|
+
|
|
76
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
77
|
+
after = input.shape[@axis] - @stop
|
|
78
|
+
input.accumulate_grad(input.backend.pad(dy, @axis, @start, after))
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
data/lib/maurograd/ops/sub.rb
CHANGED
|
@@ -27,7 +27,7 @@ module Maurograd
|
|
|
27
27
|
a, b = @inputs
|
|
28
28
|
@backend = Ops.backend_of(a, b)
|
|
29
29
|
out_data = a.data - b.data
|
|
30
|
-
requires_grad =
|
|
30
|
+
requires_grad = Ops.requires_grad?(a, b)
|
|
31
31
|
out = Tensor.new(out_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
32
32
|
out.creator = self if requires_grad
|
|
33
33
|
out
|