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.
Files changed (49) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +49 -0
  3. data/LICENSE +21 -0
  4. data/README.md +126 -0
  5. data/examples/mnist.rb +145 -0
  6. data/examples/mnist_batchnorm.rb +141 -0
  7. data/ext/maurograd_ext/extconf.rb +93 -0
  8. data/ext/maurograd_ext/maurograd_ext.c +1251 -0
  9. data/lib/maurograd/backends/cpu.rb +241 -0
  10. data/lib/maurograd/backends.rb +114 -0
  11. data/lib/maurograd/bootstrap.rb +28 -0
  12. data/lib/maurograd/datasets/batching.rb +25 -0
  13. data/lib/maurograd/datasets/mnist.rb +191 -0
  14. data/lib/maurograd/debug.rb +13 -0
  15. data/lib/maurograd/ext.rb +40 -0
  16. data/lib/maurograd/layers/batchnorm2d.rb +69 -0
  17. data/lib/maurograd/layers/conv2d.rb +135 -0
  18. data/lib/maurograd/layers/dropout.rb +41 -0
  19. data/lib/maurograd/layers/flatten.rb +11 -0
  20. data/lib/maurograd/layers/linear.rb +54 -0
  21. data/lib/maurograd/layers/maxpool2d.rb +17 -0
  22. data/lib/maurograd/layers/relu.rb +11 -0
  23. data/lib/maurograd/layers/sequential.rb +45 -0
  24. data/lib/maurograd/losses/bce.rb +90 -0
  25. data/lib/maurograd/losses/cross_entropy_with_logits.rb +129 -0
  26. data/lib/maurograd/losses/mse.rb +73 -0
  27. data/lib/maurograd/ops/add.rb +55 -0
  28. data/lib/maurograd/ops/batchnorm2d.rb +122 -0
  29. data/lib/maurograd/ops/conv2d.rb +124 -0
  30. data/lib/maurograd/ops/dropout.rb +82 -0
  31. data/lib/maurograd/ops/flatten.rb +56 -0
  32. data/lib/maurograd/ops/linear.rb +109 -0
  33. data/lib/maurograd/ops/matmul.rb +86 -0
  34. data/lib/maurograd/ops/maxpool2d.rb +91 -0
  35. data/lib/maurograd/ops/mul.rb +52 -0
  36. data/lib/maurograd/ops/permute.rb +75 -0
  37. data/lib/maurograd/ops/power.rb +46 -0
  38. data/lib/maurograd/ops/relu.rb +50 -0
  39. data/lib/maurograd/ops/sub.rb +52 -0
  40. data/lib/maurograd/ops/sum.rb +46 -0
  41. data/lib/maurograd/optim/adam.rb +91 -0
  42. data/lib/maurograd/optim/optimizer.rb +52 -0
  43. data/lib/maurograd/optim/sgd.rb +73 -0
  44. data/lib/maurograd/seed.rb +34 -0
  45. data/lib/maurograd/tensor.rb +326 -0
  46. data/lib/maurograd/utils/utils.rb +186 -0
  47. data/lib/maurograd/version.rb +3 -0
  48. data/lib/maurograd.rb +78 -0
  49. metadata +142 -0
@@ -0,0 +1,91 @@
1
+ require_relative "../tensor"
2
+ require_relative "../utils/utils"
3
+
4
+ module Maurograd
5
+ module Ops
6
+ # MaxPool2D (NCHW).
7
+ #
8
+ # Input: X [N, C, H, W]
9
+ # Output: Y [N, C, OH, OW]
10
+ #
11
+ # Pooling is per-channel (no mixing across channels).
12
+ #
13
+ # Both passes are backend kernels; on the CPU backend, C functions in
14
+ # maurograd_ext (Ext.maxpool2d_forward/backward):
15
+ #
16
+ # Forward: for every output position, scan its KH x KW window and record
17
+ # both the maximum (-> Y) and WHERE it was (-> @argmax, the flat index
18
+ # into X of the winning element, or -1 if it was a padding cell).
19
+ #
20
+ # Backward: max(...) passes its gradient only to the element that won,
21
+ # so dX is all zeros except dX[argmax] += dY for each output (+= because
22
+ # overlapping windows, i.e. stride < kernel, can pick the same element).
23
+ #
24
+ # Ties go to the first maximum in the window (row-major order), so each
25
+ # output's gradient lands on exactly one input - as in PyTorch.
26
+ #
27
+ # An earlier version built the full im2col window matrix [R, C*KH*KW]
28
+ # plus a float mask of the same size with Numo, and scattered back with
29
+ # col2im. Same result (bar ties, which it split across ALL tied
30
+ # elements), but several times slower and far more memory-hungry.
31
+ class MaxPool2D
32
+ def self.apply(input, kernel_h, kernel_w, stride = nil, padding = 0)
33
+ stride ||= kernel_h
34
+ new(input, kernel_h, kernel_w, stride, padding).forward
35
+ end
36
+
37
+ attr_reader :inputs, :kernel_h, :kernel_w, :stride, :padding
38
+
39
+ def initialize(input, kernel_h, kernel_w, stride, padding)
40
+ @inputs = [input]
41
+ @kernel_h = kernel_h
42
+ @kernel_w = kernel_w
43
+ @stride = stride
44
+ @padding = padding
45
+
46
+ # Cached for backward: backend-specific (on the CPU backend, an
47
+ # Int32 [N, C, OH, OW] array of flat input indices, -1 = padding).
48
+ @ctx = nil
49
+ end
50
+
51
+ def forward
52
+ # NOTE ON PADDING FOR MAXPOOL:
53
+ # ----------------------------
54
+ # Using padding in pooling is conceptually the same as convolution padding:
55
+ # we pad the spatial dimensions with zeros BEFORE extracting windows.
56
+ # Therefore windows near the borders may include padded zeros.
57
+ #
58
+ # This affects:
59
+ # - output size OH/OW
60
+ # - which elements can become the max in a window (a padded zero
61
+ # beats an all-negative window; its gradient then goes nowhere)
62
+ #
63
+ # Note that PyTorch pads with -inf instead, so padding never wins
64
+ # there. With non-negative inputs (e.g. after ReLU, the usual case)
65
+ # the two conventions agree.
66
+ input = @inputs.first
67
+
68
+ y, ctx = input.backend.maxpool2d_forward(input.data, @kernel_h, @kernel_w, @stride, @padding)
69
+
70
+ requires_grad = input.requires_grad
71
+ @ctx = ctx if requires_grad
72
+
73
+ out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.backend)
74
+ out.creator = self if requires_grad
75
+ out
76
+ end
77
+
78
+ def backward(grad_output)
79
+ Maurograd::Utils.assert_finite!(grad_output, where: "MaxPool2D backward: grad_output")
80
+
81
+ input = @inputs.first
82
+ return unless input.requires_grad
83
+
84
+ dout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
85
+
86
+ dx = input.backend.maxpool2d_backward(@ctx, dout)
87
+ input.accumulate_grad(dx)
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,52 @@
1
+ require_relative "../utils/utils"
2
+
3
+ module Maurograd
4
+ module Ops
5
+ # Elementwise multiplication: a * b
6
+ #
7
+ # Forward: out = a * b (Numo broadcasting allowed)
8
+ # Backward:
9
+ # dL/da = grad_output * b
10
+ # dL/db = grad_output * a
11
+ #
12
+ # Broadcasting notes:
13
+ # If broadcasting happened in forward, we must "undo" it in backward by summing
14
+ # gradients across broadcasted dimensions (Utils.unbroadcast).
15
+ class Mul
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
+ out_data = a.data * b.data
30
+ requires_grad = a.requires_grad || b.requires_grad
31
+ out = Tensor.new(out_data, requires_grad: requires_grad, backend: @inputs.first.backend)
32
+ out.creator = self if requires_grad
33
+ out
34
+ end
35
+
36
+ def backward(grad_output)
37
+ a, b = @inputs
38
+ gout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
39
+
40
+ if a.requires_grad
41
+ ga = gout * b.data
42
+ a.accumulate_grad(Utils.unbroadcast(ga, a.shape, @backend))
43
+ end
44
+
45
+ if b.requires_grad
46
+ gb = gout * a.data
47
+ b.accumulate_grad(Utils.unbroadcast(gb, b.shape, @backend))
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,75 @@
1
+ require_relative "../tensor"
2
+
3
+ module Maurograd
4
+ module Ops
5
+ # Permute (reorder) the axes of a tensor.
6
+ #
7
+ # Forward:
8
+ # y = x with its axes reordered: y.shape[i] == x.shape[axes[i]]
9
+ # (e.g. axes = [0, 2, 3, 1] turns NCHW into NHWC)
10
+ #
11
+ # Backward:
12
+ # A permutation only moves values around, so the gradient is dy with
13
+ # its axes moved back: apply the inverse permutation, the one that
14
+ # sends axis axes[i] back to position i.
15
+ #
16
+ # Example: axes = [0, 2, 3, 1] (NCHW -> NHWC) has inverse
17
+ # [0, 3, 1, 2] (NHWC -> NCHW).
18
+ #
19
+ # Tensor#transpose (swap two axes) and Tensor#permute both go through
20
+ # this op, so gradients flow through them like through any other op.
21
+ class Permute
22
+ def self.apply(input, axes)
23
+ new(input, axes).forward
24
+ end
25
+
26
+ # Normalizes `axes` for a tensor with `ndim` dimensions (negative axes
27
+ # count from the end) and checks that it is a permutation of
28
+ # 0...ndim. Returns the normalized axes.
29
+ def self.normalize_axes(axes, ndim)
30
+ unless axes.length == ndim
31
+ raise ArgumentError, "permute needs #{ndim} axes for a #{ndim}-dimensional tensor, got #{axes.inspect}"
32
+ end
33
+
34
+ normalized = axes.map do |a|
35
+ raise ArgumentError, "axes must be Integers, got #{axes.inspect}" unless a.is_a?(Integer)
36
+
37
+ a.negative? ? a + ndim : a
38
+ end
39
+ unless normalized.sort == (0...ndim).to_a
40
+ raise ArgumentError, "axes #{axes.inspect} are not a permutation of 0...#{ndim}"
41
+ end
42
+
43
+ normalized
44
+ end
45
+
46
+ attr_reader :inputs, :axes
47
+
48
+ def initialize(input, axes)
49
+ @inputs = [input]
50
+ @axes = self.class.normalize_axes(axes, input.ndim)
51
+ end
52
+
53
+ def forward
54
+ input = @inputs.first
55
+ y = input.backend.transpose(input.data, *@axes)
56
+
57
+ requires_grad = input.requires_grad
58
+ out = Tensor.new(y, requires_grad: requires_grad, backend: input.backend)
59
+ out.creator = self if requires_grad
60
+ out
61
+ end
62
+
63
+ def backward(grad_output)
64
+ input = @inputs.first
65
+ return unless input.requires_grad
66
+
67
+ inverse = Array.new(@axes.length)
68
+ @axes.each_with_index { |a, i| inverse[a] = i }
69
+
70
+ dy = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
71
+ input.accumulate_grad(input.backend.transpose(dy, *inverse))
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,46 @@
1
+ module Maurograd
2
+ module Ops
3
+ class Power
4
+ def self.apply(tensor, exponent)
5
+ new(tensor, exponent).forward
6
+ end
7
+
8
+ attr_reader :inputs
9
+
10
+ def initialize(tensor, exponent)
11
+ # Check that the exponent is a number (Integer, Float, etc.)
12
+ unless exponent.is_a?(Numeric)
13
+ raise ArgumentError, "The exponent must be a scalar numeric value, not a #{exponent.class}"
14
+ end
15
+ # Store the tensor in inputs for backtracking.
16
+ @inputs = [tensor]
17
+ # Store the exponent as a static parameter.
18
+ @exponent = exponent
19
+ end
20
+
21
+ def forward
22
+ tensor = @inputs.first
23
+ result_data = tensor.data**@exponent
24
+
25
+ requires_grad = tensor.requires_grad
26
+ result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
27
+
28
+ result.creator = self if requires_grad
29
+ result
30
+ end
31
+
32
+ def backward(grad_output)
33
+ tensor = @inputs.first
34
+ return unless tensor.requires_grad
35
+
36
+ # Local derivative: n * x^(n-1)
37
+ local_derivative = @exponent * (tensor.data**(@exponent - 1))
38
+
39
+ # Accumulate the gradient (chain rule)
40
+ grad_input = grad_output * local_derivative
41
+
42
+ tensor.accumulate_grad(grad_input)
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,50 @@
1
+ require_relative "../tensor"
2
+ require_relative "../utils/utils"
3
+
4
+ module Maurograd
5
+ module Ops
6
+ # ReLU activation:
7
+ # y = max(0, x)
8
+ #
9
+ # Backward:
10
+ # dy/dx = 1 if x > 0 else 0
11
+ #
12
+ # Both passes are backend kernels (on the CPU backend, C functions in
13
+ # maurograd_ext). Backward only needs to know where x was positive,
14
+ # which is exactly where y is positive, so the CPU kernel caches the
15
+ # output y instead of a separate mask.
16
+ class ReLU
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
+ @ctx = nil
26
+ end
27
+
28
+ def forward
29
+ input = @inputs.first
30
+ y, ctx = input.backend.relu_forward(input.data)
31
+
32
+ requires_grad = input.requires_grad
33
+ @ctx = ctx if requires_grad
34
+
35
+ out = Tensor.new(y, requires_grad: requires_grad, backend: @inputs.first.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
+ dout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
45
+ dx = input.backend.relu_backward(@ctx, dout)
46
+ input.accumulate_grad(dx)
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,52 @@
1
+ require_relative "../utils/utils"
2
+
3
+ module Maurograd
4
+ module Ops
5
+ # Elementwise subtraction: a - b
6
+ #
7
+ # Forward: out = a - b (Numo broadcasting allowed)
8
+ # Backward:
9
+ # dL/da = +grad_output
10
+ # dL/db = -grad_output
11
+ #
12
+ # Broadcasting notes:
13
+ # If broadcasting happened in forward, we must "undo" it in backward by summing
14
+ # gradients across broadcasted dimensions (Utils.unbroadcast).
15
+ class Sub
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
+ out_data = a.data - b.data
30
+ requires_grad = a.requires_grad || b.requires_grad
31
+ out = Tensor.new(out_data, requires_grad: requires_grad, backend: @inputs.first.backend)
32
+ out.creator = self if requires_grad
33
+ out
34
+ end
35
+
36
+ def backward(grad_output)
37
+ a, b = @inputs
38
+ gout = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
39
+
40
+ if a.requires_grad
41
+ ga = Utils.unbroadcast(gout, a.shape, @backend)
42
+ a.accumulate_grad(ga)
43
+ end
44
+
45
+ if b.requires_grad
46
+ gb = Utils.unbroadcast(-gout, b.shape, @backend)
47
+ b.accumulate_grad(gb)
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,46 @@
1
+ module Maurograd
2
+ module Ops
3
+ class Sum
4
+ def self.apply(tensor)
5
+ new(tensor).forward
6
+ end
7
+
8
+ attr_reader :inputs
9
+
10
+ def initialize(tensor)
11
+ # Store the tensor in inputs for backtracking.
12
+ @inputs = [tensor]
13
+ end
14
+
15
+ def forward
16
+ tensor = @inputs.first
17
+
18
+ # The result of the sum is a single scalar value containing
19
+ # the sum of all elements.
20
+ result_data = tensor.backend.sum(tensor.data)
21
+
22
+ requires_grad = tensor.requires_grad
23
+ result = Tensor.new(result_data, requires_grad: requires_grad, backend: @inputs.first.backend)
24
+
25
+ result.creator = self if requires_grad
26
+ result
27
+ end
28
+
29
+ def backward(grad_output)
30
+ tensor = @inputs.first
31
+ return unless tensor.requires_grad
32
+
33
+ # If y = sum(x), then dy/dx_i = 1 for every i.
34
+ # The total gradient is grad_output * 1, broadcast to tensor's shape.
35
+ #
36
+ # grad_output is a scalar. We use Numo::SFloat.cast to make sure
37
+ # grad_output is handled correctly, then multiply it by an array
38
+ # of ones with the same shape as the input.
39
+ ones = tensor.backend.ones(tensor.shape)
40
+ grad_input = grad_output * ones
41
+
42
+ tensor.accumulate_grad(grad_input)
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,91 @@
1
+ require_relative "optimizer"
2
+
3
+ module Maurograd
4
+ module Optim
5
+ # Adam (Kingma & Ba, 2014): "adaptive moment estimation".
6
+ #
7
+ # Adam keeps two running averages per parameter:
8
+ #
9
+ # m = beta1 * m + (1 - beta1) * g # 1st moment: mean of gradients
10
+ # v = beta2 * v + (1 - beta2) * g^2 # 2nd moment: mean of squared gradients
11
+ #
12
+ # m plays the role of momentum. v tracks how large the gradients of each
13
+ # individual weight usually are, so dividing by sqrt(v) gives every
14
+ # weight its own effective step size: weights with consistently large
15
+ # gradients take smaller steps, weights with tiny gradients take larger
16
+ # ones.
17
+ #
18
+ # Both averages start at zero, so in the first steps they are biased
19
+ # towards zero (after one step, m is only (1 - beta1) * g, i.e. 10% of
20
+ # g with the default beta1). Bias correction undoes that:
21
+ #
22
+ # m_hat = m / (1 - beta1^t)
23
+ # v_hat = v / (1 - beta2^t)
24
+ #
25
+ # where t is the step count (starting at 1). Then:
26
+ #
27
+ # param = param - lr * m_hat / (sqrt(v_hat) + eps)
28
+ #
29
+ # A useful consequence: on the very first step m_hat = g and
30
+ # v_hat = g^2, so every weight moves by almost exactly lr (in the
31
+ # direction opposite to its gradient), regardless of the gradient's
32
+ # magnitude. lr in Adam is therefore roughly "how far each weight moves
33
+ # per step", which is why its default (1e-3) is much smaller than
34
+ # typical SGD learning rates.
35
+ #
36
+ # weight_decay here is the classic L2 penalty folded into the gradient
37
+ # (g = grad + weight_decay * param), exactly as PyTorch's Adam does. Note
38
+ # that this interacts with the adaptive scaling (the penalty gets divided
39
+ # by sqrt(v_hat) too), which is what AdamW's "decoupled" weight decay
40
+ # was later designed to avoid.
41
+ #
42
+ # Defaults match PyTorch's torch.optim.Adam.
43
+ class Adam < Optimizer
44
+ attr_reader :lr, :beta1, :beta2, :eps, :weight_decay, :t
45
+
46
+ def initialize(params, lr: 1e-3, betas: [0.9, 0.999], eps: 1e-8, weight_decay: 0.0)
47
+ super(params)
48
+ @beta1, @beta2 = betas
49
+ [@beta1, @beta2].each do |b|
50
+ raise ArgumentError, "betas must be in [0, 1), got #{betas.inspect}" unless b >= 0.0 && b < 1.0
51
+ end
52
+ raise ArgumentError, "weight_decay must be >= 0, got #{weight_decay}" if weight_decay.negative?
53
+
54
+ @lr = lr
55
+ @eps = eps
56
+ @weight_decay = weight_decay
57
+
58
+ # Step counter, shared by all parameters (used for bias correction).
59
+ @t = 0
60
+
61
+ # Moment estimates, aligned with @params (allocated lazily).
62
+ @m = Array.new(params.size)
63
+ @v = Array.new(params.size)
64
+ end
65
+
66
+ def step
67
+ @t += 1
68
+ bias_correction1 = 1.0 - (@beta1**@t)
69
+ bias_correction2 = 1.0 - (@beta2**@t)
70
+
71
+ each_updatable_param do |p, grad, i|
72
+ g = grad
73
+ g += @weight_decay * p.data if @weight_decay > 0
74
+
75
+ @m[i] ||= p.backend.zeros(p.shape)
76
+ @v[i] ||= p.backend.zeros(p.shape)
77
+
78
+ @m[i] = (@beta1 * @m[i]) + ((1.0 - @beta1) * g)
79
+ @v[i] = (@beta2 * @v[i]) + ((1.0 - @beta2) * (g**2))
80
+
81
+ m_hat = @m[i] / bias_correction1
82
+ v_hat = @v[i] / bias_correction2
83
+
84
+ p.data -= @lr * m_hat / (p.backend.sqrt(v_hat) + @eps)
85
+ end
86
+
87
+ eval_params!
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,52 @@
1
+ module Maurograd
2
+ module Optim
3
+ # Base class for optimizers.
4
+ #
5
+ # Holds the list of parameters to optimize and implements what every
6
+ # optimizer shares (zero_grad). Subclasses implement #step.
7
+ #
8
+ # Optimizers that need per-parameter state (momentum buffers, Adam's moment
9
+ # estimates, ...) keep it in plain arrays aligned with @params: state for
10
+ # @params[i] lives at index i. That keeps Tensor itself free of any
11
+ # optimizer-specific fields.
12
+ class Optimizer
13
+ attr_reader :params
14
+
15
+ def initialize(params)
16
+ @params = params
17
+ end
18
+
19
+ # Reset gradients of all parameters to zero.
20
+ #
21
+ # This mirrors PyTorch's optimizer.zero_grad().
22
+ def zero_grad
23
+ @params.each(&:zero_grad)
24
+ end
25
+
26
+ def step
27
+ raise NotImplementedError, "#{self.class} must implement #step"
28
+ end
29
+
30
+ private
31
+
32
+ # Lazy backends (MLX) only record the update; computing the new
33
+ # parameter values right away keeps each step's graph from being
34
+ # chained onto the next one. A no-op on the CPU backend.
35
+ def eval_params!
36
+ @params.group_by(&:backend).each { |backend, ps| backend.eval(ps.map(&:data)) }
37
+ end
38
+
39
+ # Yields [param, grad, index] for each parameter that should be updated:
40
+ # it requires grad and already has one (grad=nil means it never took
41
+ # part in a backward pass yet, so there's nothing to apply).
42
+ def each_updatable_param
43
+ @params.each_with_index do |p, i|
44
+ next unless p.requires_grad
45
+ next if p.grad.nil?
46
+
47
+ yield p, p.grad, i
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,73 @@
1
+ require_relative "optimizer"
2
+
3
+ module Maurograd
4
+ module Optim
5
+ # Stochastic Gradient Descent (SGD), with optional momentum and weight decay.
6
+ #
7
+ # Plain SGD (the default, momentum: 0, weight_decay: 0) is the simplest
8
+ # optimizer:
9
+ #
10
+ # param = param - lr * grad
11
+ #
12
+ # Weight decay adds an L2 penalty (weight_decay/2 * ||param||^2) to the
13
+ # loss. Its gradient is weight_decay * param, so we simply fold it into
14
+ # the gradient before doing anything else:
15
+ #
16
+ # g = grad + weight_decay * param
17
+ #
18
+ # Momentum keeps a "velocity" v per parameter: an exponentially decaying
19
+ # sum of past gradients. Consistent gradient directions build up speed,
20
+ # while directions that keep flipping sign (noise, or oscillation across a
21
+ # narrow valley) largely cancel out:
22
+ #
23
+ # v = momentum * v + g
24
+ # param = param - lr * v
25
+ #
26
+ # This is the formulation PyTorch uses (velocity accumulates raw
27
+ # gradients, lr is applied at update time), so results are directly
28
+ # comparable. On the first step v is initialized to g itself, so the
29
+ # first update is identical to plain SGD.
30
+ #
31
+ # We keep it intentionally small and readable (didactic goal).
32
+ class SGD < Optimizer
33
+ attr_reader :lr, :momentum, :weight_decay
34
+
35
+ def initialize(params, lr: 1e-2, momentum: 0.0, weight_decay: 0.0)
36
+ super(params)
37
+ raise ArgumentError, "momentum must be >= 0, got #{momentum}" if momentum.negative?
38
+ raise ArgumentError, "weight_decay must be >= 0, got #{weight_decay}" if weight_decay.negative?
39
+
40
+ @lr = lr
41
+ @momentum = momentum
42
+ @weight_decay = weight_decay
43
+
44
+ # Velocity buffers, aligned with @params (set on the first step that
45
+ # touches each parameter). Arrays are never modified in place, so
46
+ # the first velocity can simply be the gradient array itself.
47
+ @velocities = Array.new(params.size)
48
+ end
49
+
50
+ # Apply one optimization step.
51
+ #
52
+ # Notes:
53
+ # - If a parameter has no gradient yet (grad=nil), we skip it.
54
+ # - We replace `.data` with the updated array (like typical optimizers,
55
+ # the parameter Tensor object itself stays the same).
56
+ def step
57
+ each_updatable_param do |p, grad, i|
58
+ g = grad
59
+ g += @weight_decay * p.data if @weight_decay > 0
60
+
61
+ if @momentum > 0
62
+ @velocities[i] = @velocities[i] ? (@momentum * @velocities[i]) + g : g
63
+ g = @velocities[i]
64
+ end
65
+
66
+ p.data -= @lr * g
67
+ end
68
+
69
+ eval_params!
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,34 @@
1
+ module Maurograd
2
+ # Numo::NArray seeds its own global RNG to the fixed constant 0 at load
3
+ # time (see numo-narray's ext/numo/narray/rand.c, Init_nary_rand), not
4
+ # from OS entropy. Left alone, that makes any unseeded Numo.rand/rand_norm
5
+ # call - including Layers::Conv2D/Linear's weight init when no seed: is
6
+ # given - silently identical across every process run. Re-randomize it
7
+ # here at load time so "no seed given" genuinely means random; the
8
+ # inverse case (asking for a reproducible run) is exactly what
9
+ # Maurograd.seed! is for.
10
+ Numo::NArray.srand
11
+
12
+ # Seeds every source of randomness Maurograd's layers rely on by default,
13
+ # so a full run becomes reproducible from one call - instead of having to
14
+ # pass seed: to every single layer by hand.
15
+ #
16
+ # Affects:
17
+ # - Weight initialization in any layer constructed without its own
18
+ # explicit seed: (Layers::Conv2D, Layers::Linear) - they fall back to
19
+ # Numo::NArray's global RNG, which this reseeds.
20
+ # - Dropout masks (Ops::Dropout / Layers::Dropout), drawn from each
21
+ # backend's RNG (the same global Numo RNG on the CPU backend).
22
+ # - Ruby's own Kernel#rand, in case other code relies on it.
23
+ #
24
+ # Does NOT affect Datasets::Batching.batches, which already has its own
25
+ # independent seed: (default 0, so it's already deterministic on its own)
26
+ # - pass seed: there directly if you also want to control data order.
27
+ def self.seed!(n)
28
+ Numo::NArray.srand(n)
29
+ srand(n)
30
+ # Every loaded backend's own RNG too (e.g. MLX's, for its Dropout masks).
31
+ Backends.loaded.each { |b| b.seed(n) } if defined?(Backends)
32
+ n
33
+ end
34
+ end