-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
defaultengine_mapreduce.go
308 lines (276 loc) · 8.35 KB
/
defaultengine_mapreduce.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package tensor
import (
"reflect"
"sort"
"github.com/pkg/errors"
"gorgonia.org/tensor/internal/execution"
"gorgonia.org/tensor/internal/storage"
)
func (e StdEng) Map(fn interface{}, a Tensor, opts ...FuncOpt) (retVal Tensor, err error) {
if err = unaryCheck(a, nil); err != nil {
err = errors.Wrap(err, "Failed Map()")
return
}
var reuse DenseTensor
var safe, _, incr bool
if reuse, safe, _, incr, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {
return
}
switch {
case safe && reuse == nil:
// create reuse
if v, ok := a.(View); ok {
if v.IsMaterializable() {
reuse = v.Materialize().(DenseTensor)
} else {
reuse = v.Clone().(DenseTensor)
}
} else {
reuse = New(Of(a.Dtype()), WithShape(a.Shape().Clone()...))
}
case reuse != nil:
if !reuse.IsNativelyAccessible() {
return nil, errors.Errorf(inaccessibleData, reuse)
}
if a.Size() != reuse.Size() {
return nil, errors.Errorf(shapeMismatch, a.Shape(), reuse.Shape())
}
}
// PREP DATA
typ := a.Dtype().Type
var dataA, dataReuse, used *storage.Header
var ait, rit, uit Iterator
var useIter bool
if dataA, dataReuse, ait, rit, useIter, err = prepDataUnary(a, reuse); err != nil {
return nil, errors.Wrapf(err, "StdEng.Map")
}
// HANDLE USE CASES
switch {
case !safe:
used = dataA
uit = ait
default:
used = dataReuse
uit = rit
}
// DO
if useIter {
err = e.E.MapIter(typ, fn, used, incr, uit)
} else {
err = e.E.Map(typ, fn, used, incr)
}
if err != nil {
err = errors.Wrapf(err, "Unable to apply function %v to tensor of %v", fn, typ)
return
}
// SET RETVAL
switch {
case reuse != nil:
if err = reuseCheckShape(reuse, a.Shape()); err != nil {
err = errors.Wrapf(err, "Reuse shape check failed")
return
}
retVal = reuse
case !safe:
retVal = a
default:
retVal = reuse
}
return
}
func (e StdEng) Reduce(fn interface{}, a Tensor, axis int, defaultValue interface{}, opts ...FuncOpt) (retVal Tensor, err error) {
if !a.IsNativelyAccessible() {
return nil, errors.Errorf(inaccessibleData, a)
}
var at, reuse DenseTensor
var dataA, dataReuse *storage.Header
if at, reuse, dataA, dataReuse, err = e.prepReduce(a, axis, opts...); err != nil {
err = errors.Wrap(err, "Prep Reduce failed")
return
}
lastAxis := a.Dims() - 1
typ := a.Dtype().Type
// actual call out to the internal engine
switch {
case (axis == 0 && at.DataOrder().IsRowMajor()) || ((axis == lastAxis || axis == len(a.Shape())-1) && at.DataOrder().IsColMajor()):
var size, split int
if at.DataOrder().IsColMajor() {
return nil, errors.Errorf("NYI: colmajor")
}
size = a.Shape()[0]
split = a.DataSize() / size
storage.CopySliced(typ, dataReuse, 0, split, dataA, 0, split)
err = e.E.ReduceFirst(typ, dataA, dataReuse, split, size, fn)
case (axis == lastAxis && at.DataOrder().IsRowMajor()) || (axis == 0 && at.DataOrder().IsColMajor()):
var dimSize int
if at.DataOrder().IsColMajor() {
return nil, errors.Errorf("NYI: colmajor")
}
dimSize = a.Shape()[axis]
err = e.E.ReduceLast(typ, dataA, dataReuse, dimSize, defaultValue, fn)
default:
dim0 := a.Shape()[0]
dimSize := a.Shape()[axis]
outerStride := a.Strides()[0]
stride := a.Strides()[axis]
expected := reuse.Strides()[0]
err = e.E.ReduceDefault(typ, dataA, dataReuse, dim0, dimSize, outerStride, stride, expected, fn)
}
retVal = reuse
return
}
func (e StdEng) OptimizedReduce(a Tensor, axis int, firstFn, lastFn, defaultFn, defaultValue interface{}, opts ...FuncOpt) (retVal Tensor, err error) {
if !a.IsNativelyAccessible() {
return nil, errors.Errorf(inaccessibleData, a)
}
var at, reuse DenseTensor
var dataA, dataReuse *storage.Header
if at, reuse, dataA, dataReuse, err = e.prepReduce(a, axis, opts...); err != nil {
err = errors.Wrap(err, "Prep Reduce failed")
return
}
lastAxis := a.Dims() - 1
typ := a.Dtype().Type
// actual call out to the internal engine
switch {
case (axis == 0 && at.DataOrder().IsRowMajor()) || ((axis == lastAxis || axis == len(a.Shape())-1) && at.DataOrder().IsColMajor()):
var size, split int
if at.DataOrder().IsColMajor() {
return nil, errors.Errorf("NYI: colmajor")
}
size = a.Shape()[0]
split = a.DataSize() / size
storage.CopySliced(typ, dataReuse, 0, split, dataA, 0, split)
err = e.E.ReduceFirst(typ, dataA, dataReuse, split, size, firstFn)
case (axis == lastAxis && at.DataOrder().IsRowMajor()) || (axis == 0 && at.DataOrder().IsColMajor()):
var dimSize int
if at.DataOrder().IsColMajor() {
return nil, errors.Errorf("NYI: colmajor")
}
dimSize = a.Shape()[axis]
err = e.E.ReduceLast(typ, dataA, dataReuse, dimSize, defaultValue, lastFn)
default:
dim0 := a.Shape()[0]
dimSize := a.Shape()[axis]
outerStride := a.Strides()[0]
stride := a.Strides()[axis]
expected := reuse.Strides()[0]
err = e.E.ReduceDefault(typ, dataA, dataReuse, dim0, dimSize, outerStride, stride, expected, defaultFn)
}
retVal = reuse
return
}
func (e StdEng) Sum(a Tensor, along ...int) (retVal Tensor, err error) {
a2 := a
if v, ok := a.(View); ok && v.IsMaterializable() {
a2 = v.Materialize()
}
return e.reduce("Sum", execution.MonotonicSum, execution.SumMethods, a2, along...)
}
func (e StdEng) Min(a Tensor, along ...int) (retVal Tensor, err error) {
a2 := a
if v, ok := a.(View); ok && v.IsMaterializable() {
a2 = v.Materialize()
}
return e.reduce("Min", execution.MonotonicMin, execution.MinMethods, a2, along...)
}
func (e StdEng) Max(a Tensor, along ...int) (retVal Tensor, err error) {
a2 := a
if v, ok := a.(View); ok && v.IsMaterializable() {
a2 = v.Materialize()
}
return e.reduce("Max", execution.MonotonicMax, execution.MaxMethods, a2, along...)
}
func (e StdEng) reduce(
op string,
monotonicMethod func(t reflect.Type, a *storage.Header) (interface{}, error),
methods func(t reflect.Type) (interface{}, interface{}, interface{}, error),
a Tensor,
along ...int) (retVal Tensor, err error) {
switch at := a.(type) {
case *Dense:
hdr := at.hdr()
typ := at.t.Type
monotonic, incr1 := IsMonotonicInts(along) // if both are true, then it means all axes are accounted for, then it'll return a scalar value
if (monotonic && incr1 && len(along) == a.Dims()) || len(along) == 0 {
var ret interface{}
if ret, err = monotonicMethod(typ, hdr); err != nil {
return
}
return New(FromScalar(ret)), nil
}
var firstFn, lastFn, defaultFn interface{}
if firstFn, lastFn, defaultFn, err = methods(typ); err != nil {
return
}
defaultVal := reflect.Zero(typ).Interface()
retVal = a
dimsReduced := 0
sort.Slice(along, func(i, j int) bool { return along[i] < along[j] })
for _, axis := range along {
axis -= dimsReduced
dimsReduced++
if axis >= retVal.Dims() {
err = errors.Errorf(dimMismatch, retVal.Dims(), axis)
return
}
if retVal, err = e.OptimizedReduce(retVal, axis, firstFn, lastFn, defaultFn, defaultVal); err != nil {
return
}
}
return
default:
return nil, errors.Errorf("Cannot perform %s on %T", op, a)
}
}
func (StdEng) prepReduce(a Tensor, axis int, opts ...FuncOpt) (at, reuse DenseTensor, dataA, dataReuse *storage.Header, err error) {
if axis >= a.Dims() {
err = errors.Errorf(dimMismatch, axis, a.Dims())
return
}
if err = unaryCheck(a, nil); err != nil {
err = errors.Wrap(err, "prepReduce failed")
return
}
// FUNC PREP
var safe bool
if reuse, safe, _, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), false, opts...); err != nil {
err = errors.Wrap(err, "Unable to prep unary tensor")
return
}
var newShape Shape
for i, s := range a.Shape() {
if i == axis {
continue
}
newShape = append(newShape, s)
}
switch {
case !safe:
err = errors.New("Reduce only supports safe operations.")
return
case reuse != nil && !reuse.IsNativelyAccessible():
err = errors.Errorf(inaccessibleData, reuse)
return
case reuse != nil:
if reuse.Shape().TotalSize() != newShape.TotalSize() {
err = errors.Errorf(shapeMismatch, reuse.Shape(), newShape)
return
}
reuse.Reshape(newShape...)
case safe && reuse == nil:
reuse = New(Of(a.Dtype()), WithShape(newShape...))
}
// DATA PREP
var useIter bool
if dataA, dataReuse, _, _, useIter, err = prepDataUnary(a, reuse); err != nil {
err = errors.Wrapf(err, "StdEng.Reduce data prep")
return
}
var ok bool
if at, ok = a.(DenseTensor); !ok || useIter {
err = errors.Errorf("Reduce does not (yet) support iterable tensors")
return
}
return
}