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,55 @@
|
|
|
1
|
+
require_relative "../utils/utils"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
class Add
|
|
6
|
+
def self.apply(a, b)
|
|
7
|
+
new(a, b).forward
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
attr_reader :inputs
|
|
11
|
+
|
|
12
|
+
def initialize(a, b)
|
|
13
|
+
@inputs = [a, b]
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def forward
|
|
17
|
+
a, b = @inputs
|
|
18
|
+
@backend = Ops.backend_of(a, b)
|
|
19
|
+
result_data = a.data + b.data
|
|
20
|
+
|
|
21
|
+
requires_grad = a.requires_grad || b.requires_grad
|
|
22
|
+
|
|
23
|
+
result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
24
|
+
result.creator = self if requires_grad
|
|
25
|
+
result
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def backward(grad_output)
|
|
29
|
+
a, b = @inputs
|
|
30
|
+
|
|
31
|
+
# Note: We explicitly address the broadcasting issue because in the Add
|
|
32
|
+
# operation case broadcasting is "wild" and very common. You can add a
|
|
33
|
+
# scalar to a matrix, or a row vector to a matrix. This is the typical
|
|
34
|
+
# case of bias in CNNs: you have an image [64,32,32] (64 channels) and
|
|
35
|
+
# you add a bias of [64,1,1]. Numo expands the bias across all pixels.
|
|
36
|
+
# Backward has to add the gradients of all those pixels to get back to
|
|
37
|
+
# the single bias value. Without unbroadcast, the bias would learn
|
|
38
|
+
# nothing.
|
|
39
|
+
|
|
40
|
+
if a.requires_grad
|
|
41
|
+
# The derivative of a + b w.r.t. a is 1.
|
|
42
|
+
# The gradient is simply grad_output, but we must handle broadcasting.
|
|
43
|
+
grad_a = Utils.unbroadcast(grad_output, a.shape, @backend)
|
|
44
|
+
a.accumulate_grad(grad_a)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
if b.requires_grad
|
|
48
|
+
# The derivative of a + b w.r.t. b is 1.
|
|
49
|
+
grad_b = Utils.unbroadcast(grad_output, b.shape, @backend)
|
|
50
|
+
b.accumulate_grad(grad_b)
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../utils/utils"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Ops
|
|
6
|
+
# 2D Batch Normalization (per-channel), for NCHW tensors.
|
|
7
|
+
#
|
|
8
|
+
# Forward (training):
|
|
9
|
+
# mu = mean(x, over N,H,W) [C]
|
|
10
|
+
# var = mean((x - mu)^2, over N,H,W) [C] (biased)
|
|
11
|
+
# x_hat = (x - mu) / sqrt(var + eps)
|
|
12
|
+
# y = gamma * x_hat + beta
|
|
13
|
+
#
|
|
14
|
+
# running_mean/running_var are updated in place (exponential moving
|
|
15
|
+
# average). Matches the common convention: the *unbiased* variance
|
|
16
|
+
# estimate (Bessel's correction, factor m/(m-1)) is used for the
|
|
17
|
+
# running estimate, while the *biased* variance is used to actually
|
|
18
|
+
# normalize the batch.
|
|
19
|
+
#
|
|
20
|
+
# Forward (eval):
|
|
21
|
+
# x_hat = (x - running_mean) / sqrt(running_var + eps)
|
|
22
|
+
# y = gamma * x_hat + beta
|
|
23
|
+
# (no running-stat update; batch statistics are never computed)
|
|
24
|
+
#
|
|
25
|
+
# Backward (training) follows the standard derivation (Ioffe & Szegedy,
|
|
26
|
+
# 2015), broken into the same steps as the forward pass rather than the
|
|
27
|
+
# single compressed closed-form expression, so each intermediate value
|
|
28
|
+
# is independently checkable:
|
|
29
|
+
#
|
|
30
|
+
# dgamma = sum(dout * x_hat, over N,H,W)
|
|
31
|
+
# dbeta = sum(dout, over N,H,W)
|
|
32
|
+
# dxhat = dout * gamma
|
|
33
|
+
# dvar = sum(dxhat * (x - mu), over N,H,W) * -0.5 * (var+eps)^-1.5
|
|
34
|
+
# dmu = sum(dxhat, over N,H,W) * -1/sqrt(var+eps)
|
|
35
|
+
# + dvar * mean(-2*(x - mu), over N,H,W)
|
|
36
|
+
# dx = dxhat / sqrt(var+eps) + dvar * 2*(x-mu)/m + dmu/m
|
|
37
|
+
#
|
|
38
|
+
# Backward (eval) is simpler: running_mean/running_var are fixed
|
|
39
|
+
# constants there, not functions of x, so there's no dvar/dmu term:
|
|
40
|
+
#
|
|
41
|
+
# dx = dxhat / sqrt(running_var + eps)
|
|
42
|
+
#
|
|
43
|
+
# Implementation: the per-element math is a backend kernel (on the CPU
|
|
44
|
+
# backend, Ext.batchnorm2d_forward/backward in C, one channel at a time,
|
|
45
|
+
# with the sums accumulated in double precision). Substituting dvar and dmu into dx
|
|
46
|
+
# above and simplifying gives the compact per-channel form it uses:
|
|
47
|
+
#
|
|
48
|
+
# dx = gamma * inv_std / m * (m * dout - sum(dout) - x_hat * sum(dout * x_hat))
|
|
49
|
+
#
|
|
50
|
+
# (using sum(x - mu) = 0, which makes dmu's second term vanish). Only
|
|
51
|
+
# the running-statistics update, which works on [C]-sized arrays, stays
|
|
52
|
+
# in Ruby.
|
|
53
|
+
#
|
|
54
|
+
class BatchNorm2D
|
|
55
|
+
# `stats` holds the running statistics: any object with
|
|
56
|
+
# running_mean/running_var readers and writers (Layers::BatchNorm2D
|
|
57
|
+
# passes itself). In training mode they are replaced with their
|
|
58
|
+
# updated values; arrays are never modified in place, since not every
|
|
59
|
+
# backend's arrays are mutable.
|
|
60
|
+
def self.apply(input, gamma, beta, stats:, training: true, momentum: 0.1, eps: 1e-5)
|
|
61
|
+
new(input, gamma, beta, stats, training, momentum, eps).forward
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
attr_reader :inputs
|
|
65
|
+
|
|
66
|
+
def initialize(input, gamma, beta, stats, training, momentum, eps)
|
|
67
|
+
@inputs = [input, gamma, beta].compact
|
|
68
|
+
@input = input
|
|
69
|
+
@gamma = gamma
|
|
70
|
+
@beta = beta
|
|
71
|
+
@stats = stats
|
|
72
|
+
@training = training
|
|
73
|
+
@momentum = momentum
|
|
74
|
+
@eps = eps
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def forward
|
|
78
|
+
@backend = bk = Ops.backend_of(*@inputs)
|
|
79
|
+
n, _c, h, w = @input.shape
|
|
80
|
+
m = n * h * w
|
|
81
|
+
|
|
82
|
+
mean, var = @training ? [nil, nil] : [@stats.running_mean, @stats.running_var]
|
|
83
|
+
y, @ctx, batch_mean, batch_var =
|
|
84
|
+
bk.batchnorm2d_forward(@input.data, mean, var, @gamma&.data, @beta&.data, @eps)
|
|
85
|
+
|
|
86
|
+
if @training
|
|
87
|
+
# Exponential moving average of the batch statistics. Unbiased
|
|
88
|
+
# variance estimate (Bessel's correction) for the running value,
|
|
89
|
+
# matching the common convention; batch_var itself is biased.
|
|
90
|
+
shape = @stats.running_mean.shape
|
|
91
|
+
unbiased_var = batch_var * (m.to_f / (m - 1))
|
|
92
|
+
@stats.running_mean = (@stats.running_mean * (1.0 - @momentum)) + (bk.reshape(batch_mean, *shape) * @momentum)
|
|
93
|
+
@stats.running_var = (@stats.running_var * (1.0 - @momentum)) + (bk.reshape(unbiased_var, *shape) * @momentum)
|
|
94
|
+
# Nothing reads the running statistics during training, so on a
|
|
95
|
+
# lazy backend each update would chain onto the previous one for a
|
|
96
|
+
# whole epoch: start computing them now instead.
|
|
97
|
+
bk.eval_async([@stats.running_mean, @stats.running_var])
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# ctx (cached for backward) holds x_hat and inv_std. In training
|
|
101
|
+
# mode inv_std comes from the *batch* statistics; in eval mode from
|
|
102
|
+
# the running ones (fixed constants, hence no dvar/dmu term there).
|
|
103
|
+
requires_grad = @inputs.any?(&:requires_grad)
|
|
104
|
+
@ctx = nil unless requires_grad
|
|
105
|
+
|
|
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
|
+
dout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
113
|
+
|
|
114
|
+
dx, dgamma, dbeta = @backend.batchnorm2d_backward(@ctx, dout, training: @training)
|
|
115
|
+
|
|
116
|
+
@gamma.accumulate_grad(dgamma) if @gamma&.requires_grad
|
|
117
|
+
@beta.accumulate_grad(dbeta) if @beta&.requires_grad
|
|
118
|
+
@input.accumulate_grad(dx) if @input.requires_grad
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../utils/utils"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Ops
|
|
6
|
+
# Conv2D operation (NCHW) implemented via im2col + GEMM.
|
|
7
|
+
#
|
|
8
|
+
# This class is an autograd "Op":
|
|
9
|
+
# - forward() builds the output Tensor and stores any context needed for backward()
|
|
10
|
+
# - backward(dout) propagates gradients to inputs (input, weight, bias)
|
|
11
|
+
#
|
|
12
|
+
# Shapes (PyTorch-style, channels-first):
|
|
13
|
+
# - input X: [N, C_in, H, W]
|
|
14
|
+
# - weight W: [C_out, C_in, KH, KW]
|
|
15
|
+
# - bias b: [C_out] (optional)
|
|
16
|
+
# - output Y: [N, C_out, OH, OW]
|
|
17
|
+
#
|
|
18
|
+
# Hyperparameters:
|
|
19
|
+
# - stride: integer step of the sliding kernel
|
|
20
|
+
# - padding: integer zero-padding applied to H and W
|
|
21
|
+
#
|
|
22
|
+
# Output spatial sizes:
|
|
23
|
+
# OH = (H + 2*padding - KH) / stride + 1
|
|
24
|
+
# OW = (W + 2*padding - KW) / stride + 1
|
|
25
|
+
#
|
|
26
|
+
# Implementation overview (forward):
|
|
27
|
+
# ---------------------------------
|
|
28
|
+
# 1) im2col(X) produces a 2D matrix X_col of shape:
|
|
29
|
+
# X_col: [N*OH*OW, C_in*KH*KW]
|
|
30
|
+
#
|
|
31
|
+
# Each row corresponds to one receptive field (one output spatial location).
|
|
32
|
+
#
|
|
33
|
+
# 2) Flatten weights into W_col with shape:
|
|
34
|
+
# W_col: [C_in*KH*KW, C_out]
|
|
35
|
+
#
|
|
36
|
+
# 3) Compute:
|
|
37
|
+
# Y_col = X_col dot W_col -> [N*OH*OW, C_out]
|
|
38
|
+
# Then add bias (broadcasted over rows) if present.
|
|
39
|
+
#
|
|
40
|
+
# 4) Reshape Y_col back into NCHW:
|
|
41
|
+
# [N, OH, OW, C_out] -> transpose -> [N, C_out, OH, OW]
|
|
42
|
+
#
|
|
43
|
+
# Backward overview:
|
|
44
|
+
# ------------------
|
|
45
|
+
# Let dout be dL/dY with shape [N, C_out, OH, OW].
|
|
46
|
+
#
|
|
47
|
+
# We reshape it to:
|
|
48
|
+
# dout_col: [N*OH*OW, C_out]
|
|
49
|
+
#
|
|
50
|
+
# Then:
|
|
51
|
+
# - db = sum(dout over N,OH,OW) -> [C_out]
|
|
52
|
+
# - dW_col = X_col^T dot dout_col -> [C_in*KH*KW, C_out]
|
|
53
|
+
# - dX_col = dout_col dot W_flat -> [N*OH*OW, C_in*KH*KW]
|
|
54
|
+
# and finally col2im(dX_col) -> dX: [N, C_in, H, W]
|
|
55
|
+
#
|
|
56
|
+
class Conv2D
|
|
57
|
+
def self.apply(input, weight, bias = nil, stride = 1, padding = 0)
|
|
58
|
+
new(input, weight, bias, stride, padding).forward
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
attr_reader :inputs, :stride, :padding
|
|
62
|
+
|
|
63
|
+
def initialize(input, weight, bias = nil, stride = 1, padding = 0)
|
|
64
|
+
# Store only non-nil inputs so that graph traversal is easy.
|
|
65
|
+
# Backward must mirror the same order.
|
|
66
|
+
@inputs = [input, weight, bias].compact
|
|
67
|
+
@stride = stride
|
|
68
|
+
@padding = padding
|
|
69
|
+
|
|
70
|
+
@ctx = nil # backend-specific state saved by forward for backward
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def forward
|
|
74
|
+
input, weight, bias = @inputs
|
|
75
|
+
@backend = Ops.backend_of(*@inputs)
|
|
76
|
+
|
|
77
|
+
out_data, @ctx = @backend.conv2d_forward(input.data, weight.data, bias&.data, @stride, @padding)
|
|
78
|
+
|
|
79
|
+
requires_grad = @inputs.any?(&:requires_grad)
|
|
80
|
+
@ctx = nil unless requires_grad
|
|
81
|
+
|
|
82
|
+
out = Tensor.new(out_data, requires_grad: requires_grad, backend: @backend)
|
|
83
|
+
out.creator = self if requires_grad
|
|
84
|
+
out
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def backward(grad_output)
|
|
88
|
+
input, weight, bias = @inputs
|
|
89
|
+
|
|
90
|
+
go = grad_output.is_a?(Maurograd::Tensor) ? grad_output.data : grad_output
|
|
91
|
+
|
|
92
|
+
want_dx = input.requires_grad
|
|
93
|
+
want_dw = weight.requires_grad
|
|
94
|
+
want_db = bias&.requires_grad || false
|
|
95
|
+
|
|
96
|
+
dx, dw, db = @backend.conv2d_backward(@ctx, go, want_dx: want_dx, want_dw: want_dw, want_db: want_db)
|
|
97
|
+
|
|
98
|
+
if db && bias.grad && bias.grad.shape != db.shape
|
|
99
|
+
raise "db shape mismatch: grad=#{bias.grad.shape} db=#{db.shape}"
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
if dw && weight.grad && weight.grad.shape != dw.shape
|
|
103
|
+
raise "dw shape mismatch: grad=#{weight.grad.shape} dw=#{dw.shape}"
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
if dx && input.grad && input.grad.shape != dx.shape
|
|
107
|
+
raise "dx shape mismatch: grad=#{input.grad.shape} dx=#{dx.shape}"
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
if want_db
|
|
111
|
+
bias.accumulate_grad(db)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
if want_dw
|
|
115
|
+
weight.accumulate_grad(dw)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
if want_dx
|
|
119
|
+
input.accumulate_grad(dx)
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# Dropout (Srivastava et al., 2014), "inverted" variant.
|
|
6
|
+
#
|
|
7
|
+
# Forward (training):
|
|
8
|
+
# mask = 1 / (1 - p) with probability 1 - p (element kept)
|
|
9
|
+
# 0 with probability p (element dropped)
|
|
10
|
+
# y = x * mask
|
|
11
|
+
#
|
|
12
|
+
# Forward (eval):
|
|
13
|
+
# y = x
|
|
14
|
+
#
|
|
15
|
+
# Why "inverted": the original formulation dropped units at training time
|
|
16
|
+
# and then multiplied by (1 - p) at test time, so that the expected input
|
|
17
|
+
# of the next layer was the same in both phases. Scaling the survivors by
|
|
18
|
+
# 1 / (1 - p) during training instead gives the same expectation
|
|
19
|
+
# (E[y] = (1 - p) * x / (1 - p) = x) and leaves eval mode a plain
|
|
20
|
+
# identity - nothing to remember at inference time. This is what PyTorch
|
|
21
|
+
# does too.
|
|
22
|
+
#
|
|
23
|
+
# Backward (training): y is x times a constant mask, so
|
|
24
|
+
# dx = dout * mask
|
|
25
|
+
# (dropped elements get no gradient, kept ones get it scaled by 1/(1-p)).
|
|
26
|
+
#
|
|
27
|
+
# The mask is drawn from the backend's random number generator, so
|
|
28
|
+
# Maurograd.seed! makes it reproducible.
|
|
29
|
+
class Dropout
|
|
30
|
+
def self.apply(input, p: 0.5, training: true)
|
|
31
|
+
new(input, p, training).forward
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def self.validate_p!(p)
|
|
35
|
+
return if p.is_a?(Numeric) && p >= 0.0 && p <= 1.0
|
|
36
|
+
|
|
37
|
+
raise ArgumentError, "dropout probability must be in [0, 1], got #{p.inspect}"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
attr_reader :inputs
|
|
41
|
+
|
|
42
|
+
def initialize(input, p, training)
|
|
43
|
+
self.class.validate_p!(p)
|
|
44
|
+
@inputs = [input]
|
|
45
|
+
@p = p
|
|
46
|
+
@training = training
|
|
47
|
+
@mask = nil
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def forward
|
|
51
|
+
input = @inputs.first
|
|
52
|
+
|
|
53
|
+
# Identity: in eval mode, or when nothing would be dropped. Returning
|
|
54
|
+
# the input itself keeps the graph unchanged (no extra node at all).
|
|
55
|
+
return input if !@training || @p == 0.0
|
|
56
|
+
|
|
57
|
+
bk = input.backend
|
|
58
|
+
@mask = if @p >= 1.0 # i.e. p == 1, since validate_p! caps it at 1
|
|
59
|
+
# Everything dropped; avoid the 1 / (1 - p) division by zero.
|
|
60
|
+
bk.zeros(input.shape)
|
|
61
|
+
else
|
|
62
|
+
bk.bernoulli(input.shape, 1.0 - @p) * (1.0 / (1.0 - @p))
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
y = input.data * @mask
|
|
66
|
+
|
|
67
|
+
requires_grad = input.requires_grad
|
|
68
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
69
|
+
out.creator = self if requires_grad
|
|
70
|
+
out
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def backward(grad_output)
|
|
74
|
+
input = @inputs.first
|
|
75
|
+
return unless input.requires_grad
|
|
76
|
+
|
|
77
|
+
dout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
78
|
+
input.accumulate_grad(dout * @mask)
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Ops
|
|
5
|
+
# Flatten operation.
|
|
6
|
+
#
|
|
7
|
+
# Converts a tensor of shape:
|
|
8
|
+
# [N, d1, d2, ..., dk]
|
|
9
|
+
# into:
|
|
10
|
+
# [N, d1*d2*...*dk]
|
|
11
|
+
#
|
|
12
|
+
# This is typically used to connect convolutional stacks (4D NCHW)
|
|
13
|
+
# to fully connected layers (2D).
|
|
14
|
+
#
|
|
15
|
+
# Forward caches the original shape so backward can reshape gradients back.
|
|
16
|
+
class Flatten
|
|
17
|
+
def self.apply(input)
|
|
18
|
+
new(input).forward
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
attr_reader :inputs
|
|
22
|
+
|
|
23
|
+
def initialize(input)
|
|
24
|
+
@inputs = [input]
|
|
25
|
+
@orig_shape = nil
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def forward
|
|
29
|
+
input = @inputs.first
|
|
30
|
+
x = input.data
|
|
31
|
+
@orig_shape = input.shape
|
|
32
|
+
|
|
33
|
+
# Keep batch dimension N intact.
|
|
34
|
+
n = @orig_shape[0]
|
|
35
|
+
raise "Flatten expects at least 1 dimension" if n.nil?
|
|
36
|
+
|
|
37
|
+
flat_dim = input.size / n
|
|
38
|
+
y = input.backend.reshape(x, n, flat_dim)
|
|
39
|
+
|
|
40
|
+
requires_grad = @inputs.first.requires_grad
|
|
41
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
42
|
+
out.creator = self if requires_grad
|
|
43
|
+
out
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def backward(grad_output)
|
|
47
|
+
input = @inputs.first
|
|
48
|
+
return unless input.requires_grad
|
|
49
|
+
|
|
50
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
51
|
+
dx = input.backend.reshape(dy, *@orig_shape)
|
|
52
|
+
input.accumulate_grad(dx)
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../utils/utils"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Ops
|
|
6
|
+
# Linear (fully connected) operation.
|
|
7
|
+
#
|
|
8
|
+
# This is the tensor analogue of a "dense layer":
|
|
9
|
+
# Y = X @ W^T + b
|
|
10
|
+
#
|
|
11
|
+
# Shapes (we keep it minimal and explicit):
|
|
12
|
+
# - X: [N, In] (batch of vectors)
|
|
13
|
+
# - W: [Out, In] (one row per output unit)
|
|
14
|
+
# - b: [Out] or [1, Out] (optional)
|
|
15
|
+
# - Y: [N, Out]
|
|
16
|
+
#
|
|
17
|
+
# Why W is [Out, In] (and not [In, Out])?
|
|
18
|
+
# ---------------------------------------
|
|
19
|
+
# It's consistent with Conv2D weights being "out-first".
|
|
20
|
+
# Each output unit has its own weight vector of length In.
|
|
21
|
+
#
|
|
22
|
+
# Forward:
|
|
23
|
+
# - Compute X @ W^T using Numo dot:
|
|
24
|
+
# X: [N, In]
|
|
25
|
+
# W^T: [In, Out]
|
|
26
|
+
# -> [N, Out]
|
|
27
|
+
# - Add bias (broadcast over N) if present.
|
|
28
|
+
#
|
|
29
|
+
# Backward:
|
|
30
|
+
# - dX = dY @ W where W is [Out, In]
|
|
31
|
+
# - dW = dY^T @ X -> [Out, In]
|
|
32
|
+
# - db = sum(dY over batch axis) -> [Out] (then reshape to bias.shape)
|
|
33
|
+
#
|
|
34
|
+
class Linear
|
|
35
|
+
def self.apply(input, weight, bias = nil)
|
|
36
|
+
new(input, weight, bias).forward
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
attr_reader :inputs
|
|
40
|
+
|
|
41
|
+
def initialize(input, weight, bias = nil)
|
|
42
|
+
@inputs = [input, weight, bias].compact
|
|
43
|
+
|
|
44
|
+
# Cached for backward (Numo arrays)
|
|
45
|
+
@x = nil
|
|
46
|
+
@w = nil
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def forward
|
|
50
|
+
input, weight, bias = @inputs
|
|
51
|
+
@backend = bk = Ops.backend_of(*@inputs)
|
|
52
|
+
|
|
53
|
+
x = input.data
|
|
54
|
+
w = weight.data
|
|
55
|
+
|
|
56
|
+
# Cache raw arrays for backward.
|
|
57
|
+
@x = x
|
|
58
|
+
@w = w
|
|
59
|
+
|
|
60
|
+
# Shapes sanity (didactic; can be removed later if you want).
|
|
61
|
+
# X: [N, In]
|
|
62
|
+
# W: [Out, In]
|
|
63
|
+
in_dim = x.shape[-1]
|
|
64
|
+
raise "Linear: input last dim #{in_dim} must match weight In #{w.shape[1]}" if in_dim != w.shape[1]
|
|
65
|
+
|
|
66
|
+
# Y = X @ W^T
|
|
67
|
+
y = bk.matmul(x, bk.transpose(w, 1, 0)) # [N, Out]
|
|
68
|
+
|
|
69
|
+
# Add bias (broadcast over batch).
|
|
70
|
+
if bias
|
|
71
|
+
# bias can be [Out] or [1, Out]; reshape to [1, Out] then broadcast over N.
|
|
72
|
+
y += bk.reshape(bias.data, 1, w.shape[0])
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
requires_grad = @inputs.any?(&:requires_grad)
|
|
76
|
+
out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
77
|
+
out.creator = self if requires_grad
|
|
78
|
+
out
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def backward(grad_output)
|
|
82
|
+
Maurograd::Utils.assert_finite!(grad_output, where: "Linear backward: grad_output")
|
|
83
|
+
|
|
84
|
+
input, weight, bias = @inputs
|
|
85
|
+
dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
86
|
+
bk = @backend
|
|
87
|
+
# dy: [N, Out]
|
|
88
|
+
|
|
89
|
+
# A) Bias gradient: db = sum over batch axis -> [Out]
|
|
90
|
+
if bias&.requires_grad
|
|
91
|
+
db = bk.sum(dy, axis: 0) # [Out]
|
|
92
|
+
bias.accumulate_grad(bk.reshape(db, *bias.shape))
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# B) Weight gradient: dw = dy^T @ X -> [Out, In]
|
|
96
|
+
if weight.requires_grad
|
|
97
|
+
dw = bk.matmul(bk.transpose(dy, 1, 0), @x) # [Out, In]
|
|
98
|
+
weight.accumulate_grad(dw)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# C) Input gradient: dx = dy @ W -> [N, In]
|
|
102
|
+
if input.requires_grad
|
|
103
|
+
dx = bk.matmul(dy, @w) # [N, In]
|
|
104
|
+
input.accumulate_grad(dx)
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Note: In PyTorch, to optimize memory, the forward method doesn't save the entire input
|
|
2
|
+
# Tensor object unless needed, but only the strictly required data. Later we might want to
|
|
3
|
+
# implement a small Context object (as you mentioned in your conv2d_context.rb
|
|
4
|
+
# file structure) to "save for backward."
|
|
5
|
+
#
|
|
6
|
+
# # Example of "cache" to save memory
|
|
7
|
+
# def forward
|
|
8
|
+
# # ... computation ...
|
|
9
|
+
# @ctx_save_for_backward = [a.data, b.data]
|
|
10
|
+
# # ...
|
|
11
|
+
# end
|
|
12
|
+
|
|
13
|
+
module Maurograd
|
|
14
|
+
module Ops
|
|
15
|
+
class MatMul
|
|
16
|
+
def self.apply(a, b)
|
|
17
|
+
new(a, b).forward
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
attr_reader :inputs
|
|
21
|
+
|
|
22
|
+
def initialize(a, b)
|
|
23
|
+
@inputs = [a, b]
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def forward
|
|
27
|
+
a, b = @inputs
|
|
28
|
+
@backend = Ops.backend_of(a, b)
|
|
29
|
+
|
|
30
|
+
# We multiply the underlying contents of the a and b tensors with
|
|
31
|
+
# the backend's 2D matrix product.
|
|
32
|
+
result_data = @backend.matmul(a.data, b.data)
|
|
33
|
+
|
|
34
|
+
# The output requires the gradient if at least one of the inputs requires it.
|
|
35
|
+
requires_grad = a.requires_grad || b.requires_grad
|
|
36
|
+
result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
37
|
+
|
|
38
|
+
# We set the creator ONLY if it is needed for backward
|
|
39
|
+
result.creator = self if requires_grad
|
|
40
|
+
|
|
41
|
+
result
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def backward(grad_output)
|
|
45
|
+
a, b = @inputs
|
|
46
|
+
|
|
47
|
+
# TODO: Handle broadcasting in gradient computation.
|
|
48
|
+
# Currently, we assume grad_output shape matches the expected output shape
|
|
49
|
+
# of the matmul operation without broadcasting across batch dimensions.
|
|
50
|
+
# If broadcasting was applied during the forward pass, we must aggregate
|
|
51
|
+
# (sum) the gradients across the broadcasted dimensions to match
|
|
52
|
+
# the original input shapes.
|
|
53
|
+
#
|
|
54
|
+
# The broadcasting issue emerges in Batch Matrix Multiplication. If you
|
|
55
|
+
# have a batch of matrices [B,N,M] and multiply them by a matrix [M,P],
|
|
56
|
+
# you expect the operation to be "repeated" for each element of the
|
|
57
|
+
# batch. In PyTorch, this is handled by torch.matmul. This is a more
|
|
58
|
+
# complex operation because it's not a simple element-by-element
|
|
59
|
+
# addition, but involves index contraction. For now, we've decided to
|
|
60
|
+
# limit MatMul to the standard 2D case (or fixed batches) to stabilize
|
|
61
|
+
# the Maurograd core before tackling multidimensional tensor calculus.
|
|
62
|
+
|
|
63
|
+
# Explicit check for shape mismatch to avoid silent errors
|
|
64
|
+
expected_shape = [a.shape[0], b.shape[1]]
|
|
65
|
+
if grad_output.shape != expected_shape
|
|
66
|
+
raise ArgumentError, "Broadcasting detected: grad_output shape #{grad_output.shape} " \
|
|
67
|
+
"does not match expected shape #{expected_shape}. " \
|
|
68
|
+
"Broadcasting support in backward pass is not yet implemented."
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
if a.requires_grad
|
|
72
|
+
# grad_a = grad_output @ B.T (transposing the last 2 dimensions of B)
|
|
73
|
+
# Note: transpose(-1, -2) and transpose(-2, -1) are, of course, equivalent
|
|
74
|
+
grad_a = @backend.matmul(grad_output, @backend.transpose(b.data, 1, 0))
|
|
75
|
+
a.accumulate_grad(grad_a)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
if b.requires_grad
|
|
79
|
+
# grad_b = A.T (transposing the last 2 dimensions of A) @ grad_output
|
|
80
|
+
grad_b = @backend.matmul(@backend.transpose(a.data, 1, 0), grad_output)
|
|
81
|
+
b.accumulate_grad(grad_b)
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|