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,69 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../ops/batchnorm2d"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Layers
|
|
6
|
+
# BatchNorm2D Layer (high-level API), for NCHW tensors.
|
|
7
|
+
#
|
|
8
|
+
# Owns the trainable per-channel scale/shift (gamma/beta) and the
|
|
9
|
+
# non-trainable running mean/variance used at eval time. Delegates the
|
|
10
|
+
# actual normalization math to Ops::BatchNorm2D.
|
|
11
|
+
#
|
|
12
|
+
# running_mean/running_var are plain native arrays of the layer's
|
|
13
|
+
# backend (Numo::SFloat on the CPU backend), not Tensors: they are
|
|
14
|
+
# statistics, not parameters trained by gradient descent, so they must
|
|
15
|
+
# NOT appear in #parameters (Optim::SGD#step would otherwise try to
|
|
16
|
+
# update them with a gradient they don't have). In training mode,
|
|
17
|
+
# forward replaces them with their updated values.
|
|
18
|
+
#
|
|
19
|
+
class BatchNorm2D
|
|
20
|
+
attr_accessor :gamma, :beta, :running_mean, :running_var, :momentum, :eps
|
|
21
|
+
|
|
22
|
+
def initialize(num_features, momentum: 0.1, eps: 1e-5)
|
|
23
|
+
@momentum = momentum
|
|
24
|
+
@eps = eps
|
|
25
|
+
@training = true
|
|
26
|
+
|
|
27
|
+
@gamma = Maurograd::Tensor.new(Numo::SFloat.ones(num_features), requires_grad: true)
|
|
28
|
+
@beta = Maurograd::Tensor.new(Numo::SFloat.zeros(num_features), requires_grad: true)
|
|
29
|
+
|
|
30
|
+
@running_mean = @gamma.backend.zeros([num_features])
|
|
31
|
+
@running_var = @gamma.backend.ones([num_features])
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def forward(input)
|
|
35
|
+
Maurograd::Ops::BatchNorm2D.apply(
|
|
36
|
+
input, @gamma, @beta,
|
|
37
|
+
stats: self,
|
|
38
|
+
training: @training,
|
|
39
|
+
momentum: @momentum,
|
|
40
|
+
eps: @eps
|
|
41
|
+
)
|
|
42
|
+
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
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../ops/conv2d"
|
|
3
|
+
require_relative "../utils/utils"
|
|
4
|
+
|
|
5
|
+
module Maurograd
|
|
6
|
+
module Layers
|
|
7
|
+
# Conv2D Layer (high-level API).
|
|
8
|
+
#
|
|
9
|
+
# This class represents a *neural network layer*, not a low-level operation.
|
|
10
|
+
#
|
|
11
|
+
# Responsibilities of a Layer:
|
|
12
|
+
# -----------------------------
|
|
13
|
+
# - Own trainable parameters (weights and bias)
|
|
14
|
+
# - Initialize parameters with a suitable strategy
|
|
15
|
+
# - Expose a forward(input) method that applies the corresponding Op
|
|
16
|
+
#
|
|
17
|
+
# What a Layer does NOT do:
|
|
18
|
+
# -------------------------
|
|
19
|
+
# - It does NOT implement the actual convolution math
|
|
20
|
+
# - It does NOT implement backward logic
|
|
21
|
+
#
|
|
22
|
+
# Those responsibilities belong to Ops::Conv2D, which builds the computation
|
|
23
|
+
# graph and handles autograd.
|
|
24
|
+
#
|
|
25
|
+
# This separation mirrors PyTorch's design:
|
|
26
|
+
# - nn.Conv2d -> Layer (parameters + forward interface)
|
|
27
|
+
# - aten/ops -> low-level operations used by autograd
|
|
28
|
+
#
|
|
29
|
+
class Conv2D
|
|
30
|
+
attr_accessor :weights, :bias, :stride, :padding
|
|
31
|
+
|
|
32
|
+
# Create a 2D convolutional layer.
|
|
33
|
+
#
|
|
34
|
+
# Parameters:
|
|
35
|
+
# - in_channels: number of input channels (C_in)
|
|
36
|
+
# - out_channels: number of output channels / filters (C_out)
|
|
37
|
+
# - kernel_size: integer (e.g. 3) or [kh, kw]
|
|
38
|
+
# - stride: convolution stride (default: 1)
|
|
39
|
+
# - padding: zero-padding applied to H and W (default: 0)
|
|
40
|
+
# - seed: optional seed for reproducible weight initialization.
|
|
41
|
+
# Without it, weight init draws from Numo's global RNG,
|
|
42
|
+
# which Maurograd.seed!(n) can seed for a whole run at
|
|
43
|
+
# once instead of passing seed: to every layer.
|
|
44
|
+
#
|
|
45
|
+
# Weight tensor shape:
|
|
46
|
+
# [C_out, C_in, KH, KW]
|
|
47
|
+
#
|
|
48
|
+
# Bias shape:
|
|
49
|
+
# [C_out]
|
|
50
|
+
#
|
|
51
|
+
# Initialization strategy:
|
|
52
|
+
# ------------------------
|
|
53
|
+
# We use He (Kaiming) initialization, which is standard for layers
|
|
54
|
+
# followed by ReLU-like activations.
|
|
55
|
+
#
|
|
56
|
+
# The idea is to keep the variance of activations roughly constant
|
|
57
|
+
# across layers, preventing vanishing or exploding gradients.
|
|
58
|
+
#
|
|
59
|
+
# The standard deviation is:
|
|
60
|
+
#
|
|
61
|
+
# std = sqrt(2 / fan_in)
|
|
62
|
+
#
|
|
63
|
+
# where:
|
|
64
|
+
# fan_in = C_in * KH * KW
|
|
65
|
+
#
|
|
66
|
+
# Note:
|
|
67
|
+
# -----
|
|
68
|
+
# fan_in depends only on the number of *inputs* to each neuron,
|
|
69
|
+
# not on out_channels.
|
|
70
|
+
#
|
|
71
|
+
def initialize(in_channels, out_channels, kernel_size, stride: 1, padding: 0, seed: nil)
|
|
72
|
+
@stride = stride
|
|
73
|
+
@padding = padding
|
|
74
|
+
|
|
75
|
+
# Normalize kernel_size to (KH, KW).
|
|
76
|
+
#
|
|
77
|
+
# If kernel_size is an integer (e.g. 3), we assume a square kernel (3x3).
|
|
78
|
+
# Otherwise, we expect [kh, kw].
|
|
79
|
+
kh, kw = kernel_size.is_a?(Integer) ? [kernel_size, kernel_size] : kernel_size
|
|
80
|
+
|
|
81
|
+
# Compute fan_in for He initialization.
|
|
82
|
+
#
|
|
83
|
+
# Each output unit receives inputs from:
|
|
84
|
+
# C_in channels * KH * KW spatial positions
|
|
85
|
+
fan_in = in_channels * kh * kw
|
|
86
|
+
std = Math.sqrt(2.0 / fan_in)
|
|
87
|
+
|
|
88
|
+
# Initialize weights with a normal distribution N(0, std).
|
|
89
|
+
#
|
|
90
|
+
# Shape: [C_out, C_in, KH, KW]
|
|
91
|
+
weight_data = Maurograd::Utils.rand_norm(out_channels, in_channels, kh, kw, std: std, seed: seed)
|
|
92
|
+
|
|
93
|
+
@weights = Maurograd::Tensor.new(weight_data, requires_grad: true)
|
|
94
|
+
|
|
95
|
+
# Initialize bias to zero.
|
|
96
|
+
#
|
|
97
|
+
# One bias value per output channel.
|
|
98
|
+
# Shape: [C_out]
|
|
99
|
+
@bias = Maurograd::Tensor.new(
|
|
100
|
+
Numo::SFloat.zeros(out_channels),
|
|
101
|
+
requires_grad: true
|
|
102
|
+
)
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# Forward pass of the Conv2D layer.
|
|
106
|
+
#
|
|
107
|
+
# This method does NOT implement convolution itself.
|
|
108
|
+
# Instead, it delegates the computation to Ops::Conv2D,
|
|
109
|
+
# which:
|
|
110
|
+
# - builds the computation graph
|
|
111
|
+
# - caches intermediate values for backward
|
|
112
|
+
# - handles gradient propagation
|
|
113
|
+
#
|
|
114
|
+
# Parameters:
|
|
115
|
+
# - input: Tensor with shape [N, C_in, H, W]
|
|
116
|
+
#
|
|
117
|
+
# Returns:
|
|
118
|
+
# - output Tensor with shape [N, C_out, OH, OW]
|
|
119
|
+
#
|
|
120
|
+
def forward(input)
|
|
121
|
+
Maurograd::Ops::Conv2D.apply(input, @weights, @bias, @stride, @padding)
|
|
122
|
+
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
|
+
end
|
|
134
|
+
end
|
|
135
|
+
end
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
require_relative "../ops/dropout"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Layers
|
|
5
|
+
# Dropout Layer (high-level API).
|
|
6
|
+
#
|
|
7
|
+
# Has no parameters; it only remembers the drop probability and whether
|
|
8
|
+
# it is in training mode (dropout active) or eval mode (identity).
|
|
9
|
+
# Delegates the actual work to Ops::Dropout.
|
|
10
|
+
#
|
|
11
|
+
# Like PyTorch, a freshly constructed layer is in training mode: call
|
|
12
|
+
# #eval (usually via Sequential#eval) before evaluating a model.
|
|
13
|
+
class Dropout
|
|
14
|
+
attr_reader :p
|
|
15
|
+
|
|
16
|
+
def initialize(p = 0.5)
|
|
17
|
+
Maurograd::Ops::Dropout.validate_p!(p)
|
|
18
|
+
@p = p
|
|
19
|
+
@training = true
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def forward(input)
|
|
23
|
+
Maurograd::Ops::Dropout.apply(input, p: @p, training: @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
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../ops/linear"
|
|
3
|
+
require_relative "../utils/utils"
|
|
4
|
+
|
|
5
|
+
module Maurograd
|
|
6
|
+
module Layers
|
|
7
|
+
# Linear layer (high-level API).
|
|
8
|
+
#
|
|
9
|
+
# Owns parameters:
|
|
10
|
+
# - weights: [Out, In]
|
|
11
|
+
# - bias: [Out]
|
|
12
|
+
#
|
|
13
|
+
# Delegates actual computation + autograd logic to Ops::Linear.
|
|
14
|
+
class Linear
|
|
15
|
+
attr_accessor :weights, :bias
|
|
16
|
+
|
|
17
|
+
# - seed: optional seed for reproducible weight initialization.
|
|
18
|
+
# Without it, weight init draws from Numo's global RNG, which
|
|
19
|
+
# Maurograd.seed!(n) can seed for a whole run at once instead
|
|
20
|
+
# of passing seed: to every layer.
|
|
21
|
+
def initialize(in_features, out_features, bias: true, seed: nil)
|
|
22
|
+
# He initialization is usually associated with ReLU.
|
|
23
|
+
# For a generic Linear layer, Xavier (Glorot) is also common.
|
|
24
|
+
# We'll keep He for consistency with your Conv2D layer style,
|
|
25
|
+
# and because many MLPs will use ReLU.
|
|
26
|
+
fan_in = in_features
|
|
27
|
+
std = Math.sqrt(2.0 / fan_in)
|
|
28
|
+
|
|
29
|
+
w = Maurograd::Utils.rand_norm(out_features, in_features, std: std, seed: seed)
|
|
30
|
+
@weights = Maurograd::Tensor.new(w, requires_grad: true)
|
|
31
|
+
|
|
32
|
+
@bias = if bias
|
|
33
|
+
Maurograd::Tensor.new(Numo::SFloat.zeros(out_features), requires_grad: true)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def forward(input)
|
|
38
|
+
Maurograd::Ops::Linear.apply(input, @weights, @bias)
|
|
39
|
+
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
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
require_relative "../ops/maxpool2d"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Layers
|
|
5
|
+
class MaxPool2D
|
|
6
|
+
def initialize(kernel_size, stride: nil, padding: 0)
|
|
7
|
+
@kh, @kw = kernel_size.is_a?(Integer) ? [kernel_size, kernel_size] : kernel_size
|
|
8
|
+
@stride = stride || @kh
|
|
9
|
+
@padding = padding
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def forward(input)
|
|
13
|
+
Maurograd::Ops::MaxPool2D.apply(input, @kh, @kw, @stride, @padding)
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
module Layers
|
|
3
|
+
class Sequential
|
|
4
|
+
attr_reader :layers
|
|
5
|
+
|
|
6
|
+
def initialize(*layers)
|
|
7
|
+
@layers = layers.flatten
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
def forward(x)
|
|
11
|
+
layer_num = 1
|
|
12
|
+
@layers.reduce(x) do |acc, layer|
|
|
13
|
+
a = layer.forward(acc)
|
|
14
|
+
Maurograd::Utils.assert_finite!(a.data, where: "after layer #{layer_num}")
|
|
15
|
+
layer_num += 1
|
|
16
|
+
a
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Collect parameters (tensors with grad) from all layers that expose them.
|
|
21
|
+
def parameters
|
|
22
|
+
@layers.flat_map do |layer|
|
|
23
|
+
layer.respond_to?(:parameters) ? layer.parameters : []
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Moves every layer's state (parameters, running statistics) to
|
|
28
|
+
# another backend, e.g. model.to(:mlx).
|
|
29
|
+
def to(backend)
|
|
30
|
+
@layers.each { |l| l.to(backend) if l.respond_to?(:to) }
|
|
31
|
+
self
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def train
|
|
35
|
+
@layers.each { |l| l.train if l.respond_to?(:train) }
|
|
36
|
+
self
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def eval
|
|
40
|
+
@layers.each { |l| l.eval if l.respond_to?(:eval) }
|
|
41
|
+
self
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Losses
|
|
5
|
+
# Binary Cross-Entropy (BCE) loss for probabilities.
|
|
6
|
+
#
|
|
7
|
+
# We implement BCE as a dedicated Op for two reasons:
|
|
8
|
+
# 1) Didactic clarity: BCE has a "canonical" formula and a simple closed-form gradient.
|
|
9
|
+
# 2) We avoid requiring Log/Exp Ops in the core right now, keeping the early framework small.
|
|
10
|
+
#
|
|
11
|
+
# Formula (mean over all elements):
|
|
12
|
+
# L = - mean( y * log(p + eps) + (1 - y) * log(1 - p + eps) )
|
|
13
|
+
#
|
|
14
|
+
# Gradient w.r.t. p:
|
|
15
|
+
# dL/dp = (1/N) * ( (1 - y)/(1 - p + eps) - y/(p + eps) )
|
|
16
|
+
# and then multiply by upstream grad_output (scalar).
|
|
17
|
+
#
|
|
18
|
+
# Parameters:
|
|
19
|
+
# - pred: Tensor of probabilities (0..1), any shape
|
|
20
|
+
# - target: Tensor with the exact same shape as pred
|
|
21
|
+
# - eps: small constant for numerical stability
|
|
22
|
+
class BCE
|
|
23
|
+
def self.apply(pred, target, eps: 1e-8)
|
|
24
|
+
new(pred, target, eps: eps).forward
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
attr_reader :inputs
|
|
28
|
+
|
|
29
|
+
def initialize(pred, target, eps: 1e-8)
|
|
30
|
+
@inputs = [pred, target]
|
|
31
|
+
@eps = eps
|
|
32
|
+
@p = nil
|
|
33
|
+
@y = nil
|
|
34
|
+
@n_elems = nil
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def forward
|
|
38
|
+
pred, target = @inputs
|
|
39
|
+
|
|
40
|
+
unless pred.shape == target.shape
|
|
41
|
+
raise "BCE expects pred and target to have the same shape, got #{pred.shape.inspect} and #{target.shape.inspect}"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Cache raw arrays for backward.
|
|
45
|
+
@p = pred.data
|
|
46
|
+
@y = target.data
|
|
47
|
+
|
|
48
|
+
# Compute BCE in raw Numo space.
|
|
49
|
+
bk = @backend = pred.backend
|
|
50
|
+
term1 = @y * bk.log(@p + @eps)
|
|
51
|
+
term2 = (1.0 - @y) * bk.log(1.0 - @p + @eps)
|
|
52
|
+
|
|
53
|
+
@n_elems = term1.size
|
|
54
|
+
loss_data = -bk.sum(term1 + term2) / @n_elems.to_f
|
|
55
|
+
|
|
56
|
+
requires_grad = pred.requires_grad || target.requires_grad
|
|
57
|
+
out = Tensor.new(loss_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
58
|
+
out.creator = self if requires_grad
|
|
59
|
+
out
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def backward(grad_output)
|
|
63
|
+
pred, target = @inputs
|
|
64
|
+
|
|
65
|
+
gout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
66
|
+
|
|
67
|
+
# dL/dp (mean reduction) times upstream gradient.
|
|
68
|
+
#
|
|
69
|
+
# dL/dp = (1/N) * [ (1-y)/(1-p+eps) - y/(p+eps) ]
|
|
70
|
+
inv_n = 1.0 / @n_elems.to_f
|
|
71
|
+
dldp = inv_n * ((1.0 - @y) / (1.0 - @p + @eps) - (@y / (@p + @eps)))
|
|
72
|
+
gpred = gout * dldp
|
|
73
|
+
|
|
74
|
+
if pred.requires_grad
|
|
75
|
+
pred.accumulate_grad(gpred)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Optional: gradient w.r.t. target (rarely used in practice),
|
|
79
|
+
# but we implement it for completeness.
|
|
80
|
+
#
|
|
81
|
+
# dL/dy = -(1/N) * [ log(p+eps) - log(1-p+eps) ]
|
|
82
|
+
if target.requires_grad
|
|
83
|
+
dldy = -inv_n * (@backend.log(@p + @eps) - @backend.log(1.0 - @p + @eps))
|
|
84
|
+
gtgt = gout * dldy
|
|
85
|
+
target.accumulate_grad(gtgt)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
require_relative "../utils/utils"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
module Losses
|
|
6
|
+
# CrossEntropyWithLogits loss (multi-class), numerically stable.
|
|
7
|
+
#
|
|
8
|
+
# We implement CE-with-logits as a dedicated loss to:
|
|
9
|
+
# 1) keep the early core small (no need for Ops::Log/Ops::Exp yet),
|
|
10
|
+
# 2) provide a stable implementation via the log-sum-exp trick.
|
|
11
|
+
#
|
|
12
|
+
# Inputs:
|
|
13
|
+
# - logits: Tensor [N, C]
|
|
14
|
+
# - target: Tensor [N] with class indices, or Tensor [N, C] one-hot / class distribution
|
|
15
|
+
#
|
|
16
|
+
# Forward (indices):
|
|
17
|
+
# log_probs = logits - logsumexp(logits) (per-row)
|
|
18
|
+
# L = -mean( log_probs[n, y_n] )
|
|
19
|
+
#
|
|
20
|
+
# Backward (indices):
|
|
21
|
+
# dL/dlogits = (softmax - one_hot(y)) / N
|
|
22
|
+
#
|
|
23
|
+
# Upstream grad_output is a scalar and is multiplied in.
|
|
24
|
+
class CrossEntropyWithLogits
|
|
25
|
+
def self.apply(logits, target)
|
|
26
|
+
new(logits, target).forward
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
attr_reader :inputs
|
|
30
|
+
|
|
31
|
+
def initialize(logits, target)
|
|
32
|
+
@inputs = [logits, target]
|
|
33
|
+
|
|
34
|
+
# cached for backward
|
|
35
|
+
@softmax = nil # [N, C]
|
|
36
|
+
@target = nil # raw target.data
|
|
37
|
+
@is_indices = nil
|
|
38
|
+
@n = nil
|
|
39
|
+
@c = nil
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def forward
|
|
43
|
+
logits, target = @inputs
|
|
44
|
+
x = logits.data
|
|
45
|
+
t = target.data
|
|
46
|
+
|
|
47
|
+
Maurograd::Utils.assert_finite!(x, where: "CEWithLogits forward: logits")
|
|
48
|
+
|
|
49
|
+
raise "CrossEntropyWithLogits expects logits [N,C], got #{x.shape.inspect}" unless x.shape.length == 2
|
|
50
|
+
@n, @c = x.shape
|
|
51
|
+
bk = @backend = Ops.backend_of(logits, target)
|
|
52
|
+
|
|
53
|
+
# Determine target format
|
|
54
|
+
if t.shape.length == 1
|
|
55
|
+
raise "Target [N] must match logits N=#{@n}, got #{t.shape.inspect}" unless t.shape[0] == @n
|
|
56
|
+
@is_indices = true
|
|
57
|
+
elsif t.shape.length == 2
|
|
58
|
+
raise "Target [N,C] must match logits [#{@n},#{@c}], got #{t.shape.inspect}" unless t.shape == [@n, @c]
|
|
59
|
+
@is_indices = false
|
|
60
|
+
else
|
|
61
|
+
raise "Target must be [N] indices or [N,C] one-hot/probs, got #{t.shape.inspect}"
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# log-sum-exp trick (row-wise)
|
|
65
|
+
# shift = max per row (keepdims)
|
|
66
|
+
shift = bk.max(x, axis: 1, keepdims: true) # [N,1]
|
|
67
|
+
Maurograd::Utils.assert_finite!(shift, where: "CEWithLogits forward: shift")
|
|
68
|
+
|
|
69
|
+
exps = bk.exp(x - shift) # [N,C]
|
|
70
|
+
Maurograd::Utils.assert_finite!(exps, where: "CEWithLogits forward: exps")
|
|
71
|
+
|
|
72
|
+
sumexp = bk.sum(exps, axis: 1, keepdims: true) # [N,1]
|
|
73
|
+
Maurograd::Utils.assert_finite!(sumexp, where: "CEWithLogits forward: sumexp")
|
|
74
|
+
|
|
75
|
+
# softmax cached for backward
|
|
76
|
+
@softmax = exps / sumexp # [N,C]
|
|
77
|
+
Maurograd::Utils.assert_finite!(@softmax, where: "CEWithLogits forward: softmax")
|
|
78
|
+
|
|
79
|
+
# log_probs = x - shift - log(sumexp)
|
|
80
|
+
logsumexp = shift + bk.log(sumexp) # [N,1]
|
|
81
|
+
log_probs = x - logsumexp # [N,C]
|
|
82
|
+
|
|
83
|
+
# Class indices are turned into one-hot rows, so both target formats
|
|
84
|
+
# share the same vectorized formula: -mean(sum(target * log_probs, axis=1)).
|
|
85
|
+
# (Selecting -log_probs[n, y_n] with a one-hot mask is the same
|
|
86
|
+
# "gather", without a per-sample Ruby loop.) Soft targets can be any
|
|
87
|
+
# probability distribution.
|
|
88
|
+
@target = @is_indices ? bk.one_hot(t, @c) : t # [N,C]
|
|
89
|
+
loss_data = -bk.sum(@target * log_probs) / @n.to_f
|
|
90
|
+
|
|
91
|
+
requires_grad = logits.requires_grad || target.requires_grad
|
|
92
|
+
out = Tensor.new(loss_data, requires_grad: requires_grad, backend: bk)
|
|
93
|
+
out.creator = self if requires_grad
|
|
94
|
+
out
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def backward(grad_output)
|
|
98
|
+
Maurograd::Utils.assert_finite!(grad_output, where: "CEWithLogits backward: grad_output")
|
|
99
|
+
|
|
100
|
+
logits, target = @inputs
|
|
101
|
+
|
|
102
|
+
gout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
103
|
+
|
|
104
|
+
# dL/dlogits = (softmax - target_one_hot) / N
|
|
105
|
+
if logits.requires_grad
|
|
106
|
+
dx = (@softmax - @target) * (gout / @n.to_f)
|
|
107
|
+
|
|
108
|
+
Maurograd::Utils.assert_finite!(dx, where: "CEWithLogits backward: dx")
|
|
109
|
+
|
|
110
|
+
logits.accumulate_grad(dx)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Optional target gradient (rarely needed). Implemented for completeness.
|
|
114
|
+
#
|
|
115
|
+
# If target is one-hot/probabilities, gradient is:
|
|
116
|
+
# dL/dtarget = -(log_probs)/N
|
|
117
|
+
# If target is indices, gradient w.r.t. indices is not meaningful (skip).
|
|
118
|
+
if target.requires_grad && !@is_indices
|
|
119
|
+
# Recompute log_probs cheaply from softmax:
|
|
120
|
+
# log_probs = log(softmax) (still stable enough since softmax in (0,1))
|
|
121
|
+
# but we used stable logsumexp forward; keeping it simple here:
|
|
122
|
+
log_probs = @backend.log(@softmax)
|
|
123
|
+
dt = -(log_probs * (gout / @n.to_f))
|
|
124
|
+
target.accumulate_grad(dt)
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
require_relative "../tensor"
|
|
2
|
+
|
|
3
|
+
module Maurograd
|
|
4
|
+
module Losses
|
|
5
|
+
# Mean Squared Error (MSE) loss.
|
|
6
|
+
#
|
|
7
|
+
# Given:
|
|
8
|
+
# pred (Tensor)
|
|
9
|
+
# target (Tensor), with the exact same shape as pred
|
|
10
|
+
#
|
|
11
|
+
# Returns a scalar loss:
|
|
12
|
+
# mean((pred - target)^2)
|
|
13
|
+
#
|
|
14
|
+
# Backward:
|
|
15
|
+
# dL/dpred = (2 / N) * (pred - target) * dL/dL
|
|
16
|
+
# dL/dtarget = -(2 / N) * (pred - target) * dL/dL (only if target.requires_grad)
|
|
17
|
+
#
|
|
18
|
+
# where N is the number of elements.
|
|
19
|
+
class MSE
|
|
20
|
+
def self.apply(pred, target)
|
|
21
|
+
new(pred, target).forward
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
attr_reader :inputs
|
|
25
|
+
|
|
26
|
+
def initialize(pred, target)
|
|
27
|
+
@inputs = [pred, target]
|
|
28
|
+
@diff = nil
|
|
29
|
+
@n_elems = nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def forward
|
|
33
|
+
pred, target = @inputs
|
|
34
|
+
|
|
35
|
+
unless pred.shape == target.shape
|
|
36
|
+
raise "MSE expects pred and target to have the same shape, got #{pred.shape.inspect} and #{target.shape.inspect}"
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Compute diff in raw Numo space (simple, reliable).
|
|
40
|
+
@diff = pred.data - target.data
|
|
41
|
+
|
|
42
|
+
# Mean squared error (scalar).
|
|
43
|
+
@n_elems = @diff.size
|
|
44
|
+
loss_data = pred.backend.sum(@diff**2) / @n_elems.to_f
|
|
45
|
+
|
|
46
|
+
requires_grad = pred.requires_grad || target.requires_grad
|
|
47
|
+
out = Tensor.new(loss_data, requires_grad: requires_grad, backend: @inputs.first.backend)
|
|
48
|
+
out.creator = self if requires_grad
|
|
49
|
+
out
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def backward(grad_output)
|
|
53
|
+
pred, target = @inputs
|
|
54
|
+
|
|
55
|
+
# grad_output is dL/d(out). For a scalar loss it is usually 1.0.
|
|
56
|
+
gout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
57
|
+
|
|
58
|
+
# Scale factor: (2/N) * grad_output
|
|
59
|
+
scale = (2.0 / @n_elems.to_f) * gout
|
|
60
|
+
|
|
61
|
+
if pred.requires_grad
|
|
62
|
+
gpred = scale * @diff
|
|
63
|
+
pred.accumulate_grad(gpred)
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
if target.requires_grad
|
|
67
|
+
gtgt = -scale * @diff
|
|
68
|
+
target.accumulate_grad(gtgt)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|