-
Notifications
You must be signed in to change notification settings - Fork 0
/
new.go
113 lines (95 loc) · 2.34 KB
/
new.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package gosor
import (
"fmt"
)
type newOptions struct {
size []int
storage []float64
isNotLeaf bool
storageCreator func() ([]float64, error)
gradientTracker *GradientTracker
}
type newOption func(*newOptions)
func WithSize(size ...int) newOption {
return func(no *newOptions) {
no.size = size
}
}
func WithValues(s ...float64) newOption {
return func(no *newOptions) {
no.storage = s
}
}
func WithRange(start, end, step float64) newOption {
return func(no *newOptions) {
no.storageCreator = func() ([]float64, error) {
i := start
res := make([]float64, 0, int((end-start)/step))
for i < end {
res = append(res, i)
i += step
}
return res, nil
}
}
}
func WithRecordGradients() newOption {
return func(no *newOptions) {
no.gradientTracker = &GradientTracker{}
}
}
func withIsNotLeaf() newOption {
return func(no *newOptions) {
no.isNotLeaf = true
}
}
func New(opts ...newOption) (t *Tensor, err error) {
var options newOptions
for _, opt := range opts {
opt(&options)
}
if options.storageCreator != nil {
options.storage, err = options.storageCreator()
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrInvalidTensorCreation, err)
}
}
if options.size == nil && options.storage == nil {
return nil, fmt.Errorf("%w: must specify at least one of size or storage values", ErrInvalidTensorCreation)
}
if options.size == nil {
options.size = []int{len(options.storage)}
}
storageLen, strides := getStorageLenAndStridesFromSize(options.size)
if options.storage == nil {
options.storage = make([]float64, storageLen)
}
if storageLen != len(options.storage) {
return nil, fmt.Errorf("wrong length of storage for sizes. Got: %d. Want: %d", len(options.storage), storageLen)
}
if options.isNotLeaf {
options.gradientTracker = &GradientTracker{
isNotLeaf: true,
}
}
return &Tensor{
GradientTracker: options.gradientTracker,
strides: strides,
sizes: options.size,
offset: 0,
storage: options.storage,
}, nil
}
func getStorageLenAndStridesFromSize(sizes []int) (int, []int) {
storageLen := 1
strides := make([]int, len(sizes))
for i := len(sizes) - 1; i >= 0; i-- {
storageLen *= sizes[i]
if i == len(sizes)-1 {
strides[i] = 1
continue
}
strides[i] = sizes[i+1] * strides[i+1]
}
return storageLen, strides
}