-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVulnAuroraOpExecutioner.java
2075 lines (1709 loc) · 88.2 KB
/
VulnAuroraOpExecutioner.java
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.linalg.aurora.ops;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.bytedeco.javacpp.*;
import org.nd4j.autodiff.functions.DifferentialFunction;
import org.nd4j.autodiff.samediff.serde.FlatBuffersMapper;
import org.nd4j.common.base.Preconditions;
import org.nd4j.linalg.api.buffer.*;
import org.nd4j.linalg.api.environment.Nd4jEnvironment;
import org.nd4j.linalg.api.memory.pointers.PagedPointer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ndarray.INDArrayStatistics;
import org.nd4j.linalg.api.ops.*;
import org.nd4j.linalg.api.ops.aggregates.Aggregate;
import org.nd4j.linalg.api.ops.aggregates.Batch;
import org.nd4j.linalg.api.ops.executioner.DefaultOpExecutioner;
import org.nd4j.linalg.api.ops.executioner.OpStatus;
import org.nd4j.linalg.api.ops.impl.scatter.ScatterUpdate;
import org.nd4j.linalg.api.ops.impl.summarystats.Variance;
import org.nd4j.linalg.api.ops.impl.transforms.any.IsMax;
import org.nd4j.linalg.api.ops.performance.PerformanceTracker;
import org.nd4j.linalg.api.ops.random.BaseRandomOp;
import org.nd4j.linalg.api.rng.Random;
import org.nd4j.linalg.api.shape.LongShapeDescriptor;
import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.api.shape.TadPack;
import org.nd4j.linalg.api.shape.options.ArrayOptionsHelper;
import org.nd4j.linalg.api.shape.options.ArrayType;
import org.nd4j.linalg.aurora.AuroraTADManager;
import org.nd4j.linalg.aurora.rng.AuroraNativeRandom;
import org.nd4j.linalg.cache.ConstantHandler;
import org.nd4j.linalg.cache.TADManager;
import org.nd4j.linalg.aurora.buffer.BaseAuroraDataBuffer;
import org.nd4j.linalg.aurora.buffer.LongBuffer;
import org.nd4j.linalg.exception.ND4JIllegalArgumentException;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.linalg.exception.ND4JOpProfilerException;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.api.memory.MemcpyDirection;
import org.nd4j.common.primitives.AtomicBoolean;
import org.nd4j.common.primitives.Optional;
import org.nd4j.common.primitives.Pair;
import org.nd4j.common.util.ArrayUtil;
import org.nd4j.nativeblas.*;
import java.util.*;
/**
*
* Native operation
* executioner in c++
*
* @author Adam Gibson
*/
@Slf4j
public class AuroraOpExecutioner extends DefaultOpExecutioner {
private NativeOps loop = NativeOpsHolder.getInstance().getDeviceNativeOps();
private ConstantHandler constantHandler = Nd4j.getConstantHandler();
@Getter
private AuroraTADManager tadManager = new AuroraTADManager();
//thread locals for custom op inputs and outputs to prevent allocations
//every time exec(CustomOp) is called
private ThreadLocal<Map<Integer,PointerPointer>> inputShapes = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> inputBuffers = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> outputShapes = new ThreadLocal<>();
private ThreadLocal<Map<Integer,PointerPointer>> outputBuffers = new ThreadLocal<>();
private ThreadLocal<Map<Integer,LongPointer>> iArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,DoublePointer>> tArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,BooleanPointer>> bArgsPointer = new ThreadLocal<>();
private ThreadLocal<Map<Integer,ShortPointer>> halfArgsPointer = new ThreadLocal<>();
protected Map<String, CustomOpDescriptor> customOps = null;
protected ThreadLocal<PointerPointer> extraz = new ThreadLocal<>();
protected AtomicBoolean experimentalMode = new AtomicBoolean(false);
protected Map<String, Boolean> mklOverrides = new HashMap<>();
/**
* Instead of allocating new memory chunks for each batch invocation, we reuse them on thread/opNum basis
* Since for NativeOpExecutioner all executions are synchronous
*/
private ThreadLocal<Map<Integer, Pointer>> batchPointers = new ThreadLocal<>();
private ThreadLocal<Map<Integer, AggregateMemoryBlock>> memoryBlocks = new ThreadLocal<>();
public AuroraOpExecutioner() {
tadManager.init(loop, constantHandler);
experimentalMode.set(loop.isExperimentalEnabled());
/*
// filling vars for possible overrides
val env = System.getenv(ND4JEnvironmentVars.ND4J_MKL_FALLBACK);
if (env != null) {
// in this case we just disable mkl-dnn globally
if (env.equalsIgnoreCase("true")) {
Nd4jCpu.Environment.getInstance().setUseMKLDNN(false);
} else {
val split = env.toLowerCase().split(",");
for (val name:split) {
mklOverrides.put(name, new Boolean(true));
}
}
}
*/
}
@Override
public INDArray exec(Op op) {
return exec(op, null);
}
@Override
public INDArray exec(Op op, OpContext opContext) {
checkForCompression(op);
if (op instanceof ScalarOp) {
ScalarOp s = (ScalarOp) op;
exec(s, opContext);
} else if (op instanceof TransformOp) {
TransformOp t = (TransformOp) op;
exec(t, opContext);
} else if (op instanceof ReduceOp) {
ReduceOp ac = (ReduceOp) op;
exec(ac, opContext);
} else if (op instanceof IndexAccumulation) {
IndexAccumulation iac = (IndexAccumulation) op;
exec(iac, opContext); //Currently using DefaultOpExecutioner
} else if (op instanceof BroadcastOp) {
BroadcastOp broadcastOp = (BroadcastOp) op;
exec(broadcastOp, opContext);
} else if (op instanceof RandomOp) {
RandomOp rngOp = (RandomOp) op;
exec(rngOp, opContext, Nd4j.getRandom());
}
return op.z();
}
@Override
public INDArray exec(IndexAccumulation op) {
return exec(op, null);
}
public INDArray exec(IndexAccumulation op, OpContext oc) {
checkForCompression(op);
INDArray x = getX(op, oc);
INDArray z = getZ(op, oc);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
val dimension = Shape.normalizeAxis(x.rank(), op.dimensions().toIntVector());
if (x.isEmpty()) {
for (val d:dimension) {
Preconditions.checkArgument(x.shape()[d] != 0, "IndexReduce can't be issued along axis with 0 in shape");
}
}
boolean keepDims = op.isKeepDims();
long[] retShape = Shape.reductionShape(x, dimension, true, keepDims);
if(z == null || x == z) {
val ret = Nd4j.createUninitialized(DataType.LONG, retShape);
setZ(ret, op, oc);
z = ret;
} else if(!Arrays.equals(retShape, z.shape())){
throw new IllegalStateException("Z array shape does not match expected return type for op " + op
+ ": expected shape " + Arrays.toString(retShape) + ", z.shape()=" + Arrays.toString(z.shape()));
}
op.validateDataTypes();
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(x, dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
DataBuffer offsets = tadBuffers.getSecond();
Pointer hostTadOffsets = offsets == null ? null : offsets.addressPointer();
PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets);
long st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
if (z.isScalar()) {
loop.execIndexReduceScalar(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null);
} else {
loop.execIndexReduce(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
return getZ(op, oc);
}
@Override
public INDArray exec(Variance op) {
return exec((ReduceOp) op);
}
@Override
public INDArray exec(ReduceOp op) {
return exec(op, null);
}
public INDArray exec(ReduceOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
Preconditions.checkNotNull(x, "Op.x() cannot be null: Was null for op %s", op);
op.validateDataTypes(oc);
if(op instanceof BaseReduceOp && ((BaseReduceOp)op).isEmptyReduce()){
//Edge case for TF import compatibility: [x,y].reduce(empty) = [x,y]
//Note that "empty" axis is NOT the same as length 0, as in INDArray.sum(new int[0]), which means "all dimensions"
if(z != null){
Preconditions.checkState(x.equalShapes(z), "For empty reductions, result (z) array must have same shape as x shape." +
" Got: x=%ndShape, z=%ndShape", x, z);
z.assign(x);
return z;
} else {
setZ(x.dup(), op, oc);
return z;
}
}
// FIXME: this should be moved down to C++ on per-op basis
val dimension = Shape.normalizeAxis(x.rank(), op.dimensions().toIntVector());
// reduce to scalar case, ReduceBool ops require special treatment
if (op instanceof BaseReduceBoolOp && x.isEmpty() && (dimension == null || (dimension.length == 1 && dimension[0] == Integer.MAX_VALUE))) {
if (z == null) {
setZ(Nd4j.scalar(((BaseReduceBoolOp) op).emptyValue()), op, oc);
} else {
z.assign(((BaseReduceBoolOp) op).emptyValue());
}
return z;
}
//validateDataType(Nd4j.dataType(), op);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
boolean keepDims = op.isKeepDims();
long[] retShape = Shape.reductionShape(x, dimension, true, keepDims);
if (x.isVector() && x.length() == ArrayUtil.prod(retShape) && ArrayUtil.prodLong(retShape) > 1 && y == null)
return op.noOp();
/**
* This is the result array.
* We create it only if we hadn't provided it before
*/
INDArray ret;
if (z == null || z == x) {
if (op.isComplexAccumulation()) {
long xT = x.tensorsAlongDimension(dimension);
long yT = y.tensorsAlongDimension(dimension);
ret = Nd4j.create(op.resultType(), new long[]{xT, yT});
} else {
if (y != null) {
//2 options here: either pairwise, equal sizes - OR every X TAD vs. entirety of Y
if(x.length() == y.length()) {
//Pairwise
if (x.tensorsAlongDimension(dimension) != y.tensorsAlongDimension(dimension)) {
throw new ND4JIllegalStateException("Number of TADs along dimension don't match: (x shape = " +
Arrays.toString(x.shape()) + ", y shape = " + Arrays.toString(y.shape()) +
", dimension = " + Arrays.toString(dimension) + ")");
}
} else {
//Every X TAD vs. entirety of Y
val xTADSize = x.length() / x.tensorsAlongDimension(dimension);
if (xTADSize != y.length()) {
throw new ND4JIllegalStateException("Size of TADs along dimension don't match for pairwise execution:" +
" (x TAD size = " + xTADSize + ", y size = " + y.length());
}
}
}
DataType dt = oc != null ? op.resultType(oc) : op.resultType();
ret = Nd4j.create(dt, retShape);
}
setZ(ret, op, oc);
z = ret;
} else {
// compare length
long shapeProduct = (retShape.length == 0 ? 1 : ArrayUtil.prodLong(retShape));
if (!op.isComplexAccumulation() && z.length() != shapeProduct) {
if(!(x.isEmpty() && op.isKeepDims())){
//Empty reductions are special case: [1,0].sum(0,1,keep=true) -> shape [1,1]
throw new ND4JIllegalStateException("Shape of target array for reduction [" + Arrays.toString(z.shape()) + "] doesn't match expected [" + Arrays.toString(retShape) + "]");
}
}
else if (op.isComplexAccumulation()) {
long xT = x.tensorsAlongDimension(dimension);
long yT = y.tensorsAlongDimension(dimension);
if (z.length() != xT * yT)
throw new ND4JIllegalStateException("Shape of target array for reduction [" + Arrays.toString(z.shape()) + "] doesn't match expected [" + (xT * yT) + "]");
}
ret = z;
}
//log.info("X dtype: {}; Z dtype: {}", x.dataType(), z.dataType());
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = x.isEmpty() ? Pair.<DataBuffer, DataBuffer>makePair(x.data(), null): tadManager.getTADOnlyShapeInfo(x, dimension);
Pair<DataBuffer, DataBuffer> yTadBuffers = null;
/**
* Note that we use addresses in libnd4j.
* We use reinterpret cast in c to take the long
* we pass to JNI. This manages overhead.
*/
Pointer hostTadShapeInfo = x.isEmpty() ? x.shapeInfoDataBuffer().addressPointer() : tadBuffers.getFirst().addressPointer();
DataBuffer offsets = x.isEmpty() ? null : tadBuffers.getSecond();
Pointer hostTadOffsets = offsets == null ? null : offsets.addressPointer();
// we're going to check, if that's TAD vs TAD comparison or TAD vs full array. if later - we're going slightly different route
boolean tvf = false;
if (y != null) {
if (x.tensorAlongDimension(0, dimension).length() == y.length()) {
tvf = true;
}
}
if (op.isComplexAccumulation()) {
yTadBuffers = tadManager.getTADOnlyShapeInfo(y, dimension);
if (x.tensorAlongDimension(0, dimension).length() != y.tensorAlongDimension(0, dimension).length())
throw new ND4JIllegalStateException("Impossible to issue AllDistances operation: TAD lengths mismatch along given dimension: " +
"x TAD length = " + x.tensorAlongDimension(0, dimension).length() + ", y TAD length " +
y.tensorAlongDimension(0, dimension).length());
}
/**
* This is a pointer to a pointer in c.
*/
// FIXME: we need something better then 3rd element being non-null here...
//PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets, tvf ? hostTadOffsets : null);
long st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
/**
* Note because dimension arrays don't change,
* we use an {@link ConstantHandler} which knows how to reserve memory
* for immutable buffers for the dimensions.
* This gives us a pointer which is passed around in libnd4j.
*/
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
if (op instanceof Variance) {
if (ret.isScalar()) {
loop.execSummaryStatsScalar(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((Variance) op).isBiasCorrected());
} else {
Variance var = (Variance) op;
try {
loop.execSummaryStatsTad(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
var.isBiasCorrected(), null, null);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
}
}
//pairwise reduction like similarity of two arrays
else if (y != null && op.getOpType() == Op.Type.REDUCE3) {
val yb = ((BaseAuroraDataBuffer) y.data()).getOpaqueDataBuffer();
if (op.isComplexAccumulation()) {
try {
loop.execReduce3All(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
(LongPointer) tadBuffers.getFirst().addressPointer(), new LongPointerWrapper(tadBuffers.getSecond().addressPointer()),
(LongPointer) yTadBuffers.getFirst().addressPointer(), new LongPointerWrapper(yTadBuffers.getSecond().addressPointer())
);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
} else if (ret.isScalar()) {
loop.execReduce3Scalar(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
} else {
try {
loop.execReduce3Tad(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
null, null, null, null);
} catch (Throwable t){
String str = opInfoString(op, Optional.of(dimension));
throw new RuntimeException("Native AccumulationOp execution (double) failed: " + str, t);
}
}
} else {
if (ret.isScalar()) {
switch (op.getOpType()) {
case REDUCE_FLOAT:
loop.execReduceFloat(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_BOOL:
loop.execReduceBool(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_SAME:
loop.execReduceSame(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_LONG:
loop.execReduceLong(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) ret.shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unsupported op used in reduce: "+ op.getOpType());
}
} else {
switch (op.getOpType()) {
case REDUCE_FLOAT:
loop.execReduceFloat2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_LONG:
loop.execReduceLong2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_SAME:
loop.execReduceSame2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case REDUCE_BOOL:
loop.execReduceBool2(null, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()),
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(),
(LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unsupported op used in reduce: "+ op.getOpType());
}
}
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
return getZ(op, oc);
}
/**
* ScalarOp execution
* @param op Op to execute
*/
private void invokeScalarAlongDimension(ScalarOp op) {
invokeScalarAlongDimension(op, null);
}
private void invokeScalarAlongDimension(ScalarOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
val dimension = op.dimensions().toIntVector();
//dimension = Shape.normalizeAxis(op.x().rank(), dimension);
// do tad magic
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(op.x(), dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
Pointer hostTadOffsets = tadBuffers.getSecond().addressPointer();
Pointer devTadShapeInfoZ = null;
Pointer devTadOffsetsZ = null;
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*
* Note that this is the *result* TAD information. An op is always input (x) and output (z)
* for result.
* This is for assigning the result to of the operation along
* the proper dimension.
*/
Pair<DataBuffer, DataBuffer> tadBuffersZ = tadManager.getTADOnlyShapeInfo(op.z(), dimension);
devTadShapeInfoZ = tadBuffersZ.getFirst().addressPointer();
devTadOffsetsZ = tadBuffersZ.getSecond().addressPointer();
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseAuroraDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case SCALAR:
loop.execScalarTad(null, op.opNum(),
xb, (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, op.z().dataType()),
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(),null,
(LongPointer) hostTadShapeInfo, (LongPointer) hostTadOffsets,
(LongPointer) devTadShapeInfoZ, (LongPointer) devTadOffsetsZ);
break;
case SCALAR_BOOL:
loop.execScalarBoolTad(null, op.opNum(),
xb, (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) op.y().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, op.z().dataType()),
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null,
(LongPointer) hostTadShapeInfo, (LongPointer) hostTadOffsets,
(LongPointer) devTadShapeInfoZ, (LongPointer) devTadOffsetsZ);
break;
default:
throw new UnsupportedOperationException();
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
}
public INDArray exec(ScalarOp op){
return exec(op, null);
}
public INDArray exec(ScalarOp op, OpContext oc) {
long st = profilingConfigurableHookIn(op);
//validateDataType(Nd4j.dataType(), op);
if((oc != null && oc.getOutputArray(0) == null) || getZ(op, oc) == null){
switch (op.getOpType()) {
case SCALAR:
setZ(getX(op, oc).ulike(), op, oc);
// op.setZ(op.x().ulike());
break;
case SCALAR_BOOL:
// op.setZ(Nd4j.createUninitialized(DataType.BOOL, op.x().shape()));
setZ(Nd4j.createUninitialized(DataType.BOOL, getX(op, oc).shape()), op, oc);
break;
default:
throw new ND4JIllegalStateException("Unknown op type: [" + op.getOpType() +"]");
}
}
// if (op.x().length() != op.z().length())
if (getX(op, oc).length() != getZ(op, oc).length())
throw new ND4JIllegalStateException("op.X length should be equal to op.Z length: " +
"x.length()=" + getX(op, oc).length() + ", z.length()=" + getZ(op, oc).length() + " - x shape info = ["
+ Arrays.toString(getX(op, oc).shapeInfoDataBuffer().asInt()) + "], z shape info = ["
+ Arrays.toString(getZ(op, oc).shapeInfoDataBuffer().asInt()) + "]");
if (op.dimensions() != null) {
invokeScalarAlongDimension(op);
return getZ(op, oc);
}
val x = ((BaseAuroraDataBuffer) getX(op, oc).data()).getOpaqueDataBuffer();
val scalar = ((BaseAuroraDataBuffer) op.scalar().data()).getOpaqueDataBuffer();
val z = ((BaseAuroraDataBuffer) getZ(op, oc).data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case SCALAR:
loop.execScalar(null,
op.opNum(),
x, (LongPointer) getX(op, oc).shapeInfoDataBuffer().addressPointer(), null,
z, (LongPointer) getZ(op, oc).shapeInfoDataBuffer().addressPointer(), null,
scalar, (LongPointer) op.scalar().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, getZ(op, oc).dataType()));
break;
case SCALAR_BOOL:
loop.execScalarBool(null,
op.opNum(),
x, (LongPointer) getX(op, oc).shapeInfoDataBuffer().addressPointer(), null,
z, (LongPointer) getZ(op, oc).shapeInfoDataBuffer().addressPointer(), null,
scalar, (LongPointer) op.scalar().shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, getX(op, oc).dataType()));
break;
default:
throw new ND4JIllegalStateException("Unknown op type: [" + op.getOpType() +"]");
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
return getZ(op, oc);
}
private Pointer getPointerForExtraArgs(Op op, DataType type) {
if (op.extraArgs() != null){
val eadb = op.extraArgsDataBuff(type);
if (eadb != null)
return eadb.addressPointer();
else
return null;
}
return null;
}
private void exec(TransformOp op) {
exec(op, null);
}
private void exec(TransformOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
long st = 0;
// validateDataType(Nd4j.dataType(), op);
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
PointerPointer dummy = extraz.get();
// Pow operations might be special
if (op.opNum() == 31) {
if (y != null && y.isScalar()) {
// op.setY(Nd4j.valueArrayOf(op.x().shape(), op.y().getDouble(0)));
setY(Nd4j.valueArrayOf(x.shape(), y.getDouble(0)), op, oc);
}
}
/**
* This is the {@link IsMax}
* operation.
*
* @see {@link Op#extraArgs()}
* for what an extra argument is in an op.
*
* The extra argument in the op here is the {@link IsMax#IsMax(INDArray, int...)}
* dimension to do the ismax along
*/
if (op.opName().equalsIgnoreCase("ismax") && op.extraArgs() != null && op.extraArgs().length > 0) {
int[] dimension = new int[(int) op.extraArgs()[0]];
for (int i = 0; i < dimension.length; i++) {
dimension[i] = (int) op.extraArgs()[i + 1];
}
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(op.z(), dimension);
Pointer tad = tadBuffers.getFirst().addressPointer();
DataBuffer offsets = tadBuffers.getSecond();
Pointer off = offsets == null ? null : offsets.addressPointer();
dummy.put(0, tad);
dummy.put(1, off);
st = profilingConfigurableHookIn(op, tadBuffers.getFirst());
} else
st = profilingConfigurableHookIn(op);
if (y != null) {
if (z == null) {
setZ(Nd4j.create(op.resultType(), x.shape()), op, oc);
z = getZ(op, oc);
}
op.validateDataTypes(oc, experimentalMode.get());
//log.info("X type: {}; Y type: {}; Z type: {}; OpNum: {}", op.x().dataType(), op.y().dataType(), op.z().dataType(), op.opNum());
if (x.length() != y.length() || x.length() != z.length())
throw new ND4JIllegalStateException("X, Y and Z arguments should have the same length for PairwiseTransform " +
op.opName() + ". x: length " + x.length() + ", shape " + Arrays.toString(x.shape()) +
"; y: " + y.length() + ", shape " + Arrays.toString(y.shape()) +
"; z: " + z.length() + ", shape " + Arrays.toString(z.shape()));
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseAuroraDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case TRANSFORM_ANY:
case TRANSFORM_FLOAT:
case TRANSFORM_STRICT:
case TRANSFORM_SAME:
if (!experimentalMode.get())
Preconditions.checkArgument(x.dataType() == y.dataType() || y.dataType() == DataType.BOOL,
"Op.X and Op.Y must have the same data type, but got %s vs. %s", x.dataType(), y.dataType());
loop.execPairwiseTransform(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, z.dataType()));
break;
case TRANSFORM_BOOL:
loop.execTransformBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()));
break;
case PAIRWISE_BOOL:
loop.execPairwiseTransformBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
getPointerForExtraArgs(op, x.dataType()));
break;
}
} else {
if (z == null) {
setZ(Nd4j.createUninitialized((oc != null ? op.resultType(oc) : op.resultType()), x.shape()), op, oc);
z = getZ(op, oc);
}
op.validateDataTypes(oc, experimentalMode.get());
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case TRANSFORM_FLOAT: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformFloat(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(),
null, xtraz);
break;
}
case TRANSFORM_STRICT: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformStrict(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_SAME: {
val xtraz = getPointerForExtraArgs(op, z.dataType());
loop.execTransformSame(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_ANY: {
val xtraz = getPointerForExtraArgs(op, x.dataType());
val opNum = op.opNum();
loop.execTransformAny(dummy, opNum,
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
case TRANSFORM_BOOL: {
val xtraz = getPointerForExtraArgs(op, x.dataType());
val opNum = op.opNum();
loop.execTransformBool(dummy, opNum,
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
xtraz);
break;
}
default:
throw new UnsupportedOperationException("Unknown transform type: [" + op.getOpType() + "]");
}
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
profilingConfigurableHookOut(op, oc, st);
}
public INDArray exec(BroadcastOp op) {
return exec(op, null);
}
public INDArray exec(BroadcastOp op, OpContext oc) {
INDArray x = getX(op, oc);
INDArray y = getY(op, oc);
INDArray z = getZ(op, oc);
long st = profilingConfigurableHookIn(op);
op.validateDataTypes(experimentalMode.get());
val dimension = op.dimensions().toIntVector();
/**
* Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}
* and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}
* The first item is the shape information. The second one is the offsets.
*/
Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(x, dimension);
Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer();
Pointer hostTadOffsets = tadBuffers.getSecond().addressPointer();
Pointer devTadShapeInfoZ = null;
Pointer devTadOffsetsZ = null;
// if (!Arrays.equals(x.shape(),z.shape()) || !Arrays.equals(x.stride(),z.stride()) || x.ordering() != z.ordering()) {
// that's the place where we're going to have second TAD in place
Pair<DataBuffer, DataBuffer> tadBuffersZ = tadManager.getTADOnlyShapeInfo(z, dimension);
devTadShapeInfoZ = tadBuffersZ.getFirst().addressPointer();
devTadOffsetsZ = tadBuffersZ.getSecond().addressPointer();
/*
log.info("Broascast dimension: {}", Arrays.toString(dimension));
log.info("x shape: {}; x TAD: {}; comp TAD: {}", Arrays.toString(x.shapeInfoDataBuffer().asInt()), Arrays.toString(tadBuffers.getFirst().asInt()), Arrays.toString(x.tensorAlongDimension(0, dimension).shapeInfoDataBuffer().asInt()));
log.info("z shape: {}; z TAD: {}", Arrays.toString(z.shapeInfoDataBuffer().asInt()), Arrays.toString(tadBuffersZ.getFirst().asInt()));
log.info("y shape: {}", Arrays.toString(y.shapeInfoDataBuffer().asInt()));
log.info("-------------");
*/
if (extraz.get() == null)
extraz.set(new PointerPointer(32));
PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets, devTadShapeInfoZ, devTadOffsetsZ);
Pointer dimensionAddress = constantHandler.getConstantBuffer(dimension, DataType.INT).addressPointer();
val xb = ((BaseAuroraDataBuffer) x.data()).getOpaqueDataBuffer();
val yb = ((BaseAuroraDataBuffer) y.data()).getOpaqueDataBuffer();
val zb = ((BaseAuroraDataBuffer) z.data()).getOpaqueDataBuffer();
switch (op.getOpType()) {
case BROADCAST:
loop.execBroadcast(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
case BROADCAST_BOOL:
loop.execBroadcastBool(dummy, op.opNum(),
xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null,
yb, (LongPointer) y.shapeInfoDataBuffer().addressPointer(), null,
zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), null,
null,
((BaseAuroraDataBuffer) op.dimensions().data()).getOpaqueDataBuffer(), (LongPointer) op.dimensions().shapeInfoDataBuffer().addressPointer(), null);
break;
default:
throw new UnsupportedOperationException("Unknown operation type: [" + op.getOpType() + "]");
}
if (loop.lastErrorCode() != 0)
throw new RuntimeException(loop.lastErrorMessage());
return z;
}
protected <T extends Aggregate> Pointer getPointer(Batch<T> batch) {
if (batchPointers.get() == null)
batchPointers.set(new HashMap<Integer, Pointer>());
if (!batchPointers.get().containsKey(batch.opNum())) {
val pointer = new IntPointer(batch.getSample().getRequiredBatchMemorySize() / 4 );
batchPointers.get().put(batch.opNum(), pointer);
return pointer;
}
return batchPointers.get().get(batch.opNum());
}
/**
* This method executes previously built batch
*
* @param batch
*/
@Override
public <T extends Aggregate> void exec(Batch<T> batch) {
//profilingHookIn(batch);
IntPointer pointer = (IntPointer) getPointer(batch);
int maxTypes = 5;