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
data/lib/maurograd/ops/sum.rb
CHANGED
|
@@ -1,26 +1,71 @@
|
|
|
1
1
|
module Maurograd
|
|
2
2
|
module Ops
|
|
3
|
+
# Sum of a tensor's elements: over all of them, or over chosen axes.
|
|
4
|
+
#
|
|
5
|
+
# Forward:
|
|
6
|
+
# axis: nil -> a scalar, the sum of every element
|
|
7
|
+
# axis: 1 -> sum over axis 1: [N, C, H, W] -> [N, H, W]
|
|
8
|
+
# axis: [2, 3] -> sum over several axes: [N, C, H, W] -> [N, C]
|
|
9
|
+
# keepdims: true -> the summed axes stay, with size 1: [N, C, 1, 1],
|
|
10
|
+
# which broadcasts against the input
|
|
11
|
+
# Negative axes count from the end.
|
|
12
|
+
#
|
|
13
|
+
# Backward:
|
|
14
|
+
# Each input element contributes to exactly one output element, with
|
|
15
|
+
# derivative 1. So the gradient of an input element is the upstream
|
|
16
|
+
# gradient of the output element it was summed into: dy, copied
|
|
17
|
+
# ("broadcast back") along the summed axes. To do that, dy is first
|
|
18
|
+
# given the keepdims shape (size-1 axes where the sums were), then
|
|
19
|
+
# broadcast to the input's shape.
|
|
20
|
+
#
|
|
21
|
+
# Mean is this sum times 1/count (Tensor#mean).
|
|
3
22
|
class Sum
|
|
4
|
-
def self.apply(tensor)
|
|
5
|
-
new(tensor).forward
|
|
23
|
+
def self.apply(tensor, axis: nil, keepdims: false)
|
|
24
|
+
new(tensor, axis: axis, keepdims: keepdims).forward
|
|
6
25
|
end
|
|
7
26
|
|
|
8
|
-
|
|
27
|
+
# Turns `axis` (nil, an Integer or an Array of them) into a sorted
|
|
28
|
+
# Array of non-negative axes for a tensor with `ndim` dimensions, or
|
|
29
|
+
# nil for "all axes". Raises ArgumentError for an axis out of range or
|
|
30
|
+
# given twice.
|
|
31
|
+
def self.normalize_axes(axis, ndim)
|
|
32
|
+
return nil if axis.nil?
|
|
9
33
|
|
|
10
|
-
|
|
34
|
+
axes = Array(axis).map do |a|
|
|
35
|
+
raise ArgumentError, "axes must be Integers, got #{axis.inspect}" unless a.is_a?(Integer)
|
|
36
|
+
|
|
37
|
+
n = a.negative? ? a + ndim : a
|
|
38
|
+
raise ArgumentError, "axis #{a} is out of range for a #{ndim}-dimensional tensor" unless n.between?(0, ndim - 1)
|
|
39
|
+
|
|
40
|
+
n
|
|
41
|
+
end
|
|
42
|
+
raise ArgumentError, "axis #{axis.inspect} repeats an axis" unless axes.uniq.length == axes.length
|
|
43
|
+
|
|
44
|
+
axes.sort
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
attr_reader :inputs, :axes
|
|
48
|
+
|
|
49
|
+
def initialize(tensor, axis: nil, keepdims: false)
|
|
11
50
|
# Store the tensor in inputs for backtracking.
|
|
12
51
|
@inputs = [tensor]
|
|
52
|
+
@axes = self.class.normalize_axes(axis, tensor.ndim)
|
|
53
|
+
@keepdims = keepdims
|
|
13
54
|
end
|
|
14
55
|
|
|
15
56
|
def forward
|
|
16
57
|
tensor = @inputs.first
|
|
58
|
+
bk = tensor.backend
|
|
17
59
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
60
|
+
result_data = if @axes.nil?
|
|
61
|
+
s = bk.sum(tensor.data)
|
|
62
|
+
@keepdims ? bk.reshape(s, *Array.new(tensor.ndim, 1)) : s
|
|
63
|
+
else
|
|
64
|
+
bk.sum(tensor.data, axis: @axes, keepdims: @keepdims)
|
|
65
|
+
end
|
|
21
66
|
|
|
22
|
-
requires_grad =
|
|
23
|
-
result = Tensor.new(result_data, requires_grad: requires_grad, backend:
|
|
67
|
+
requires_grad = Ops.requires_grad?(tensor)
|
|
68
|
+
result = Tensor.new(result_data, requires_grad: requires_grad, backend: bk)
|
|
24
69
|
|
|
25
70
|
result.creator = self if requires_grad
|
|
26
71
|
result
|
|
@@ -30,16 +75,18 @@ module Maurograd
|
|
|
30
75
|
tensor = @inputs.first
|
|
31
76
|
return unless tensor.requires_grad
|
|
32
77
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
|
|
40
|
-
|
|
78
|
+
bk = tensor.backend
|
|
79
|
+
g = grad_output.is_a?(Tensor) ? grad_output.data : grad_output
|
|
80
|
+
|
|
81
|
+
# Give the gradient the keepdims shape, so that it broadcasts along
|
|
82
|
+
# the summed axes. (With axis: nil and no keepdims, it's a scalar,
|
|
83
|
+
# which broadcasts as it is.)
|
|
84
|
+
if @axes && !@keepdims
|
|
85
|
+
kept = tensor.shape.each_with_index.map { |d, i| @axes.include?(i) ? 1 : d }
|
|
86
|
+
g = bk.reshape(g, *kept)
|
|
87
|
+
end
|
|
41
88
|
|
|
42
|
-
tensor.accumulate_grad(
|
|
89
|
+
tensor.accumulate_grad(g * bk.ones(tensor.shape))
|
|
43
90
|
end
|
|
44
91
|
end
|
|
45
92
|
end
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
module Maurograd
|
|
2
|
+
# Random tensors, drawn by the backend that will hold them.
|
|
3
|
+
#
|
|
4
|
+
# eps = Maurograd.randn_like(mean) # reparameterization: mean + std * eps
|
|
5
|
+
# noise = Maurograd.randn(64, 1, 28, 28) # a batch of diffusion noise
|
|
6
|
+
# t = Maurograd.rand(64) # uniform times in [0, 1)
|
|
7
|
+
#
|
|
8
|
+
# Drawing on the backend matters on the GPU: generative models draw new
|
|
9
|
+
# noise at every training and sampling step, and noise drawn on the host
|
|
10
|
+
# would have to be copied to the GPU each time.
|
|
11
|
+
#
|
|
12
|
+
# Maurograd.seed! seeds every loaded backend, so runs are reproducible on
|
|
13
|
+
# each of them, but the numbers differ between backends (each has its own
|
|
14
|
+
# generator). Weight initialization doesn't use these: layers draw their
|
|
15
|
+
# initial weights on the host, so a seed gives the same model everywhere.
|
|
16
|
+
class << self
|
|
17
|
+
# Samples of the standard normal distribution N(0, 1), as a float32
|
|
18
|
+
# tensor of the given shape: randn(2, 3) or randn([2, 3]).
|
|
19
|
+
def randn(*shape, backend: nil, requires_grad: false)
|
|
20
|
+
random_tensor(:normal, shape, backend, requires_grad)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Samples of the uniform distribution on [0, 1).
|
|
24
|
+
def rand(*shape, backend: nil, requires_grad: false)
|
|
25
|
+
random_tensor(:uniform, shape, backend, requires_grad)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# randn with the shape and backend of `tensor`.
|
|
29
|
+
def randn_like(tensor)
|
|
30
|
+
randn(tensor.shape, backend: tensor.backend)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# rand with the shape and backend of `tensor`.
|
|
34
|
+
def rand_like(tensor)
|
|
35
|
+
rand(tensor.shape, backend: tensor.backend)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
def random_tensor(kind, shape, backend, requires_grad)
|
|
41
|
+
shape = shape.first if shape.length == 1 && shape.first.is_a?(Array)
|
|
42
|
+
unless shape.all? { |d| d.is_a?(Integer) && d >= 0 }
|
|
43
|
+
raise ArgumentError, "dimensions must be non-negative Integers, got #{shape.inspect}"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
backend = backend ? Backends.fetch(backend) : self.backend
|
|
47
|
+
Tensor.new(backend.public_send(kind, shape), requires_grad: requires_grad, backend: backend)
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "numo/narray"
|
|
3
|
+
|
|
4
|
+
module Maurograd
|
|
5
|
+
# Reads and writes the safetensors format, the common file format for
|
|
6
|
+
# model weights (https://github.com/huggingface/safetensors): files saved
|
|
7
|
+
# here can be loaded by Python's safetensors package, and the other way
|
|
8
|
+
# round.
|
|
9
|
+
#
|
|
10
|
+
# Maurograd::SafeTensors.save(model.state_dict, "lenet.safetensors")
|
|
11
|
+
# model.load_state_dict(Maurograd::SafeTensors.load("lenet.safetensors"))
|
|
12
|
+
#
|
|
13
|
+
# The format is deliberately simple, and can't run code when loaded
|
|
14
|
+
# (unlike Ruby's Marshal or Python's pickle), so loading a file from
|
|
15
|
+
# someone else is safe:
|
|
16
|
+
#
|
|
17
|
+
# 8 bytes N, the header size (unsigned 64-bit, little-endian)
|
|
18
|
+
# N bytes a JSON header: for each tensor, its dtype, shape and the
|
|
19
|
+
# byte range of its data, e.g.
|
|
20
|
+
# {"weights": {"dtype": "F32", "shape": [2, 3],
|
|
21
|
+
# "data_offsets": [0, 24]}, ...}
|
|
22
|
+
# the rest the tensors' raw bytes, row-major, little-endian
|
|
23
|
+
module SafeTensors
|
|
24
|
+
DTYPES = {
|
|
25
|
+
::Numo::SFloat => "F32", ::Numo::DFloat => "F64",
|
|
26
|
+
::Numo::Int8 => "I8", ::Numo::Int16 => "I16", ::Numo::Int32 => "I32", ::Numo::Int64 => "I64",
|
|
27
|
+
::Numo::UInt8 => "U8", ::Numo::UInt16 => "U16", ::Numo::UInt32 => "U32", ::Numo::UInt64 => "U64"
|
|
28
|
+
}.freeze
|
|
29
|
+
|
|
30
|
+
# Larger headers are refused when loading, so that a corrupt or hostile
|
|
31
|
+
# file can't make us allocate gigabytes for one.
|
|
32
|
+
MAX_HEADER_BYTES = 100 * 1024 * 1024
|
|
33
|
+
|
|
34
|
+
class << self
|
|
35
|
+
# Writes `tensors`, a Hash from names to Numo arrays (or Tensors, or
|
|
36
|
+
# anything Numo can cast), to `path`. `metadata` is an optional Hash
|
|
37
|
+
# of strings, stored in the header.
|
|
38
|
+
def save(tensors, path, metadata: nil)
|
|
39
|
+
check_little_endian!
|
|
40
|
+
header = {}
|
|
41
|
+
blobs = []
|
|
42
|
+
offset = 0
|
|
43
|
+
tensors.each do |name, value|
|
|
44
|
+
array = host_array(value)
|
|
45
|
+
dtype = DTYPES[array.class] or raise ArgumentError, "#{name}: #{array.class} has no safetensors dtype"
|
|
46
|
+
bytes = array.to_binary
|
|
47
|
+
header[name.to_s] = {"dtype" => dtype, "shape" => array.shape, "data_offsets" => [offset, offset + bytes.bytesize]}
|
|
48
|
+
blobs << bytes
|
|
49
|
+
offset += bytes.bytesize
|
|
50
|
+
end
|
|
51
|
+
header["__metadata__"] = metadata.to_h { |k, v| [k.to_s, v.to_s] } if metadata
|
|
52
|
+
|
|
53
|
+
json = JSON.generate(header)
|
|
54
|
+
json += " " * (-json.bytesize % 8) # pad so the data starts 8-byte aligned
|
|
55
|
+
File.open(path, "wb") do |f|
|
|
56
|
+
f.write([json.bytesize].pack("Q<"), json)
|
|
57
|
+
blobs.each { |b| f.write(b) }
|
|
58
|
+
end
|
|
59
|
+
path
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Reads a safetensors file into a Hash from names to Numo arrays.
|
|
63
|
+
# Raises ArgumentError if the file is malformed.
|
|
64
|
+
def load(path)
|
|
65
|
+
check_little_endian!
|
|
66
|
+
File.open(path, "rb") do |f|
|
|
67
|
+
size_bytes = f.read(8)
|
|
68
|
+
raise ArgumentError, "#{path}: too short to be a safetensors file" unless size_bytes&.bytesize == 8
|
|
69
|
+
|
|
70
|
+
n = size_bytes.unpack1("Q<")
|
|
71
|
+
raise ArgumentError, "#{path}: header size #{n} is not plausible" if n > MAX_HEADER_BYTES || n > f.size - 8
|
|
72
|
+
|
|
73
|
+
header = JSON.parse(f.read(n))
|
|
74
|
+
raise ArgumentError, "#{path}: the header is not a JSON object" unless header.is_a?(Hash)
|
|
75
|
+
|
|
76
|
+
header.delete("__metadata__")
|
|
77
|
+
data = f.read || ""
|
|
78
|
+
header.to_h { |name, info| [name, decode(path, name, info, data)] }
|
|
79
|
+
end
|
|
80
|
+
rescue JSON::ParserError => e
|
|
81
|
+
raise ArgumentError, "#{path}: the header is not valid JSON (#{e.message})"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
private
|
|
85
|
+
|
|
86
|
+
def decode(path, name, info, data)
|
|
87
|
+
klass = DTYPES.key(info["dtype"]) or
|
|
88
|
+
raise ArgumentError, "#{path}: #{name} has dtype #{info["dtype"].inspect}, which Numo can't represent"
|
|
89
|
+
shape = info["shape"]
|
|
90
|
+
unless shape.is_a?(Array) && shape.all? { |d| d.is_a?(Integer) && d >= 0 }
|
|
91
|
+
raise ArgumentError, "#{path}: #{name} has an invalid shape #{shape.inspect}"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
from, to = info["data_offsets"]
|
|
95
|
+
expected = shape.reduce(1, :*) * klass::ELEMENT_BYTE_SIZE
|
|
96
|
+
unless from.is_a?(Integer) && to.is_a?(Integer) && from >= 0 && to <= data.bytesize && to - from == expected
|
|
97
|
+
raise ArgumentError, "#{path}: #{name}'s data offsets #{info["data_offsets"].inspect} don't fit its shape or the file"
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
klass.from_binary(data.byteslice(from, expected), shape)
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def host_array(value)
|
|
104
|
+
value = value.to_numo if value.is_a?(Tensor)
|
|
105
|
+
value.is_a?(::Numo::NArray) ? value : ::Numo::SFloat.cast(value)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Numo reads and writes memory in the machine's byte order, and the
|
|
109
|
+
# format is little-endian, as are x86 and ARM machines.
|
|
110
|
+
def check_little_endian!
|
|
111
|
+
raise NotImplementedError, "safetensors I/O needs a little-endian machine" unless [1].pack("L") == [1].pack("L<")
|
|
112
|
+
end
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
data/lib/maurograd/tensor.rb
CHANGED
|
@@ -15,6 +15,11 @@ require_relative "ops/flatten"
|
|
|
15
15
|
require_relative "ops/relu"
|
|
16
16
|
require_relative "ops/maxpool2d"
|
|
17
17
|
require_relative "ops/permute"
|
|
18
|
+
require_relative "ops/reshape"
|
|
19
|
+
require_relative "ops/elementwise"
|
|
20
|
+
require_relative "ops/slice"
|
|
21
|
+
require_relative "ops/concat"
|
|
22
|
+
require_relative "ops/log_softmax"
|
|
18
23
|
|
|
19
24
|
module Maurograd
|
|
20
25
|
# Tensor is the core data structure of Maurograd.
|
|
@@ -240,8 +245,19 @@ module Maurograd
|
|
|
240
245
|
Ops::Power.apply(self, other)
|
|
241
246
|
end
|
|
242
247
|
|
|
243
|
-
|
|
244
|
-
|
|
248
|
+
# Sum of all elements (a scalar), or over the given axes:
|
|
249
|
+
# x.sum(axis: 1), x.sum(axis: [2, 3], keepdims: true). See Ops::Sum.
|
|
250
|
+
def sum(axis: nil, keepdims: false)
|
|
251
|
+
Ops::Sum.apply(self, axis: axis, keepdims: keepdims)
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# Mean of all elements, or over the given axes (same arguments as
|
|
255
|
+
# #sum): the sum times 1/count, so its gradient is the upstream
|
|
256
|
+
# gradient spread evenly over the elements that were averaged.
|
|
257
|
+
def mean(axis: nil, keepdims: false)
|
|
258
|
+
axes = Ops::Sum.normalize_axes(axis, ndim)
|
|
259
|
+
count = axes ? axes.map { |a| shape[a] }.reduce(1, :*) : size
|
|
260
|
+
sum(axis: axis, keepdims: keepdims) * (1.0 / count)
|
|
245
261
|
end
|
|
246
262
|
|
|
247
263
|
def -(other)
|
|
@@ -254,6 +270,68 @@ module Maurograd
|
|
|
254
270
|
Ops::Mul.apply(self, other)
|
|
255
271
|
end
|
|
256
272
|
|
|
273
|
+
# x / y: by a number it's x * (1/y); by a Tensor, x * y**-1, so the
|
|
274
|
+
# gradient comes from Mul and Power with no op of its own.
|
|
275
|
+
def /(other)
|
|
276
|
+
return self * (1.0 / other) if other.is_a?(Numeric)
|
|
277
|
+
|
|
278
|
+
other = Tensor.new(other, backend: @backend) unless other.is_a?(Tensor)
|
|
279
|
+
self * (other**-1)
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
# -x, as x * -1.
|
|
283
|
+
def -@
|
|
284
|
+
self * -1.0
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
# Elementwise functions (Ops::Elementwise and its subclasses).
|
|
288
|
+
def exp = Ops::Exp.apply(self)
|
|
289
|
+
|
|
290
|
+
def log = Ops::Log.apply(self)
|
|
291
|
+
|
|
292
|
+
def sigmoid = Ops::Sigmoid.apply(self)
|
|
293
|
+
|
|
294
|
+
def tanh = Ops::Tanh.apply(self)
|
|
295
|
+
|
|
296
|
+
def silu = Ops::SiLU.apply(self)
|
|
297
|
+
|
|
298
|
+
# log(1 + e^x), computed without overflow.
|
|
299
|
+
def softplus = Ops::Softplus.apply(self)
|
|
300
|
+
|
|
301
|
+
# log(sigmoid(x)), computed without underflow.
|
|
302
|
+
def log_sigmoid = Ops::LogSigmoid.apply(self)
|
|
303
|
+
|
|
304
|
+
def leaky_relu(negative_slope: 0.01) = Ops::LeakyReLU.apply(self, negative_slope: negative_slope)
|
|
305
|
+
|
|
306
|
+
# log(sum(exp(x))) over all elements or the given axes (same arguments
|
|
307
|
+
# as #sum), computed without overflow; see Ops::LogSumExp.
|
|
308
|
+
def logsumexp(axis: nil, keepdims: false)
|
|
309
|
+
Ops::LogSumExp.apply(self, axis: axis, keepdims: keepdims)
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
# Log-probabilities from logits along `axis`: x - logsumexp(x).
|
|
313
|
+
def log_softmax(axis: -1)
|
|
314
|
+
Ops::LogSoftmax.apply(self, axis: axis)
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
# Probabilities from logits along `axis`, summing to 1 there:
|
|
318
|
+
# exp(log_softmax(x)), so its gradient comes from those two ops.
|
|
319
|
+
def softmax(axis: -1)
|
|
320
|
+
log_softmax(axis: axis).exp
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
# Clips to [min, max] (either may be nil).
|
|
324
|
+
def clamp(min: nil, max: nil) = Ops::Clamp.apply(self, min: min, max: max)
|
|
325
|
+
|
|
326
|
+
# The same data, cut off from the graph: a new leaf tensor that doesn't
|
|
327
|
+
# require grad, so nothing is backpropagated through it. Use it to treat
|
|
328
|
+
# a value as a constant, e.g. a GAN generator's samples when training
|
|
329
|
+
# the discriminator. The data is shared, not copied (ops never modify
|
|
330
|
+
# their inputs, so that's safe).
|
|
331
|
+
def detach
|
|
332
|
+
Tensor.new(@data, backend: @backend)
|
|
333
|
+
end
|
|
334
|
+
|
|
257
335
|
def linear(weight, bias = nil)
|
|
258
336
|
weight = Tensor.new(weight, backend: @backend) unless weight.is_a?(Tensor)
|
|
259
337
|
bias = Tensor.new(bias, backend: @backend) if bias && !bias.is_a?(Tensor)
|
|
@@ -264,6 +342,38 @@ module Maurograd
|
|
|
264
342
|
Ops::Flatten.apply(self)
|
|
265
343
|
end
|
|
266
344
|
|
|
345
|
+
# Same elements in the same (row-major) order, in a new shape:
|
|
346
|
+
# reshape(6, 4), reshape([6, 4]), or reshape(2, -1) to infer one
|
|
347
|
+
# dimension. The element count must not change.
|
|
348
|
+
#
|
|
349
|
+
# An autograd op (Ops::Reshape). It regroups elements and never moves
|
|
350
|
+
# them, so it is not a substitute for permute/transpose: [2, 3] ->
|
|
351
|
+
# [3, 2] by reshape is not the transposed matrix.
|
|
352
|
+
def reshape(*shape)
|
|
353
|
+
shape = shape.first if shape.length == 1 && shape.first.is_a?(Array)
|
|
354
|
+
Ops::Reshape.apply(self, shape)
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
# The elements in `range` along `axis` (Ops::Slice): x.slice(1, 0...4)
|
|
358
|
+
# is x[:, 0:4] in NumPy. Any Ruby Range works, including negative and
|
|
359
|
+
# endless ones: x.slice(-1, -2..) is the last two along the last axis.
|
|
360
|
+
def slice(axis, range)
|
|
361
|
+
Ops::Slice.apply(self, axis, range)
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
# Splits the tensor into `n` parts along `axis`, as consecutive slices
|
|
365
|
+
# of equal size (the last one smaller if the size isn't a multiple of
|
|
366
|
+
# n, so there may be fewer than n parts, as in PyTorch):
|
|
367
|
+
#
|
|
368
|
+
# mean, log_var = encoder.call(x).chunk(2, axis: 1)
|
|
369
|
+
def chunk(n, axis: 0)
|
|
370
|
+
raise ArgumentError, "chunk needs a positive number of parts, got #{n.inspect}" unless n.is_a?(Integer) && n.positive?
|
|
371
|
+
|
|
372
|
+
axis = Ops::Sum.normalize_axes(axis, ndim).first
|
|
373
|
+
step = (shape[axis] + n - 1) / n
|
|
374
|
+
(0...shape[axis]).step(step).map { |start| slice(axis, start...(start + step)) }
|
|
375
|
+
end
|
|
376
|
+
|
|
267
377
|
def relu
|
|
268
378
|
Ops::ReLU.apply(self)
|
|
269
379
|
end
|
data/lib/maurograd/version.rb
CHANGED
data/lib/maurograd.rb
CHANGED
|
@@ -21,6 +21,9 @@ module Maurograd
|
|
|
21
21
|
# Maurograd.debug flag, off by default (used by Utils.assert_finite!).
|
|
22
22
|
require_relative "maurograd/debug"
|
|
23
23
|
|
|
24
|
+
# Maurograd.no_grad { ... }: switches gradient recording off.
|
|
25
|
+
require_relative "maurograd/grad_mode"
|
|
26
|
+
|
|
24
27
|
# Maurograd.seed! for reproducible runs (also re-randomizes Numo's global
|
|
25
28
|
# RNG at load time, so unseeded weight init is genuinely random).
|
|
26
29
|
require_relative "maurograd/seed"
|
|
@@ -33,6 +36,9 @@ module Maurograd
|
|
|
33
36
|
# Core tensor type (autograd graph node).
|
|
34
37
|
require_relative "maurograd/tensor"
|
|
35
38
|
|
|
39
|
+
# Maurograd.randn / .rand: random tensors drawn on their backend.
|
|
40
|
+
require_relative "maurograd/random"
|
|
41
|
+
|
|
36
42
|
# Utilities used by multiple ops (broadcast reduction, im2col/col2im, etc.).
|
|
37
43
|
require_relative "maurograd/utils/utils"
|
|
38
44
|
|
|
@@ -49,21 +55,29 @@ module Maurograd
|
|
|
49
55
|
require_relative "maurograd/ops/relu"
|
|
50
56
|
require_relative "maurograd/ops/maxpool2d"
|
|
51
57
|
require_relative "maurograd/ops/permute"
|
|
58
|
+
require_relative "maurograd/ops/reshape"
|
|
59
|
+
require_relative "maurograd/ops/elementwise"
|
|
60
|
+
require_relative "maurograd/ops/slice"
|
|
61
|
+
require_relative "maurograd/ops/concat"
|
|
62
|
+
require_relative "maurograd/ops/log_softmax"
|
|
52
63
|
require_relative "maurograd/ops/batchnorm2d"
|
|
53
64
|
require_relative "maurograd/ops/dropout"
|
|
54
65
|
|
|
55
66
|
# Layers (high-level modules that own parameters).
|
|
67
|
+
require_relative "maurograd/layers/module"
|
|
56
68
|
require_relative "maurograd/layers/conv2d"
|
|
57
69
|
require_relative "maurograd/layers/linear"
|
|
58
70
|
require_relative "maurograd/layers/flatten"
|
|
59
71
|
require_relative "maurograd/layers/maxpool2d"
|
|
60
72
|
require_relative "maurograd/layers/relu"
|
|
73
|
+
require_relative "maurograd/layers/activations"
|
|
61
74
|
require_relative "maurograd/layers/batchnorm2d"
|
|
62
75
|
require_relative "maurograd/layers/dropout"
|
|
63
76
|
require_relative "maurograd/layers/sequential"
|
|
64
77
|
|
|
65
78
|
# Loss functions
|
|
66
79
|
require_relative "maurograd/losses/bce"
|
|
80
|
+
require_relative "maurograd/losses/bce_with_logits"
|
|
67
81
|
require_relative "maurograd/losses/mse"
|
|
68
82
|
require_relative "maurograd/losses/cross_entropy_with_logits"
|
|
69
83
|
|
|
@@ -73,6 +87,9 @@ module Maurograd
|
|
|
73
87
|
require_relative "maurograd/optim/adam"
|
|
74
88
|
|
|
75
89
|
# Datasets
|
|
90
|
+
# Saving and loading weights (safetensors format).
|
|
91
|
+
require_relative "maurograd/safetensors"
|
|
92
|
+
|
|
76
93
|
require_relative "maurograd/datasets/mnist"
|
|
77
94
|
require_relative "maurograd/datasets/batching"
|
|
78
95
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: maurograd
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.2.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Mauro Tortonesi
|
|
@@ -82,34 +82,45 @@ files:
|
|
|
82
82
|
- lib/maurograd/datasets/mnist.rb
|
|
83
83
|
- lib/maurograd/debug.rb
|
|
84
84
|
- lib/maurograd/ext.rb
|
|
85
|
+
- lib/maurograd/grad_mode.rb
|
|
86
|
+
- lib/maurograd/layers/activations.rb
|
|
85
87
|
- lib/maurograd/layers/batchnorm2d.rb
|
|
86
88
|
- lib/maurograd/layers/conv2d.rb
|
|
87
89
|
- lib/maurograd/layers/dropout.rb
|
|
88
90
|
- lib/maurograd/layers/flatten.rb
|
|
89
91
|
- lib/maurograd/layers/linear.rb
|
|
90
92
|
- lib/maurograd/layers/maxpool2d.rb
|
|
93
|
+
- lib/maurograd/layers/module.rb
|
|
91
94
|
- lib/maurograd/layers/relu.rb
|
|
92
95
|
- lib/maurograd/layers/sequential.rb
|
|
93
96
|
- lib/maurograd/losses/bce.rb
|
|
97
|
+
- lib/maurograd/losses/bce_with_logits.rb
|
|
94
98
|
- lib/maurograd/losses/cross_entropy_with_logits.rb
|
|
95
99
|
- lib/maurograd/losses/mse.rb
|
|
96
100
|
- lib/maurograd/ops/add.rb
|
|
97
101
|
- lib/maurograd/ops/batchnorm2d.rb
|
|
102
|
+
- lib/maurograd/ops/concat.rb
|
|
98
103
|
- lib/maurograd/ops/conv2d.rb
|
|
99
104
|
- lib/maurograd/ops/dropout.rb
|
|
105
|
+
- lib/maurograd/ops/elementwise.rb
|
|
100
106
|
- lib/maurograd/ops/flatten.rb
|
|
101
107
|
- lib/maurograd/ops/linear.rb
|
|
108
|
+
- lib/maurograd/ops/log_softmax.rb
|
|
102
109
|
- lib/maurograd/ops/matmul.rb
|
|
103
110
|
- lib/maurograd/ops/maxpool2d.rb
|
|
104
111
|
- lib/maurograd/ops/mul.rb
|
|
105
112
|
- lib/maurograd/ops/permute.rb
|
|
106
113
|
- lib/maurograd/ops/power.rb
|
|
107
114
|
- lib/maurograd/ops/relu.rb
|
|
115
|
+
- lib/maurograd/ops/reshape.rb
|
|
116
|
+
- lib/maurograd/ops/slice.rb
|
|
108
117
|
- lib/maurograd/ops/sub.rb
|
|
109
118
|
- lib/maurograd/ops/sum.rb
|
|
110
119
|
- lib/maurograd/optim/adam.rb
|
|
111
120
|
- lib/maurograd/optim/optimizer.rb
|
|
112
121
|
- lib/maurograd/optim/sgd.rb
|
|
122
|
+
- lib/maurograd/random.rb
|
|
123
|
+
- lib/maurograd/safetensors.rb
|
|
113
124
|
- lib/maurograd/seed.rb
|
|
114
125
|
- lib/maurograd/tensor.rb
|
|
115
126
|
- lib/maurograd/utils/utils.rb
|