/
Tensor.java
735 lines (644 loc) · 24.9 KB
/
Tensor.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
package org.pytorch;
import com.facebook.jni.HybridData;
import com.facebook.jni.annotations.DoNotStrip;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.util.Arrays;
import java.util.Locale;
/**
* Representation of a Tensor. Behavior is similar to PyTorch's tensor objects.
*
* <p>Most tensors will be constructed as {@code Tensor.fromBlob(data, shape)}, where {@code data}
* can be an array or a direct {@link Buffer} (of the proper subclass). Helper methods are provided
* to allocate buffers properly.
*
* <p>To access Tensor data, see {@link #dtype()}, {@link #shape()}, and various {@code getDataAs*}
* methods.
*
* <p>When constructing {@code Tensor} objects with {@code data} as an array, it is not specified
* whether this data is copied or retained as a reference so it is recommended not to modify it
* after constructing. {@code data} passed as a {@link Buffer} is not copied, so it can be modified
* between {@link Module} calls to avoid reallocation. Data retrieved from {@code Tensor} objects
* may be copied or may be a reference to the {@code Tensor}'s internal data buffer. {@code shape}
* is always copied.
*/
public abstract class Tensor {
private static final String ERROR_MSG_DATA_BUFFER_NOT_NULL = "Data buffer must be not null";
private static final String ERROR_MSG_DATA_ARRAY_NOT_NULL = "Data array must be not null";
private static final String ERROR_MSG_SHAPE_NOT_NULL = "Shape must be not null";
private static final String ERROR_MSG_SHAPE_NON_NEGATIVE = "Shape elements must be non negative";
private static final String ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER =
"Data buffer must have native byte order (java.nio.ByteOrder#nativeOrder)";
private static final String ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT =
"Data buffer must be direct (java.nio.ByteBuffer#allocateDirect)";
@DoNotStrip final long[] shape;
final MemoryFormat memoryFormat;
private static final int INT_SIZE_BYTES = 4;
private static final int FLOAT_SIZE_BYTES = 4;
private static final int LONG_SIZE_BYTES = 8;
private static final int DOUBLE_SIZE_BYTES = 8;
/**
* Allocates a new direct {@link java.nio.ByteBuffer} with native byte order with specified
* capacity that can be used in {@link Tensor#fromBlob(ByteBuffer, long[])}, {@link
* Tensor#fromBlobUnsigned(ByteBuffer, long[])}.
*
* @param numElements capacity (number of elements) of result buffer.
*/
public static ByteBuffer allocateByteBuffer(int numElements) {
return ByteBuffer.allocateDirect(numElements).order(ByteOrder.nativeOrder());
}
/**
* Allocates a new direct {@link java.nio.IntBuffer} with native byte order with specified
* capacity that can be used in {@link Tensor#fromBlob(IntBuffer, long[])}.
*
* @param numElements capacity (number of elements) of result buffer.
*/
public static IntBuffer allocateIntBuffer(int numElements) {
return ByteBuffer.allocateDirect(numElements * INT_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
}
/**
* Allocates a new direct {@link java.nio.FloatBuffer} with native byte order with specified
* capacity that can be used in {@link Tensor#fromBlob(FloatBuffer, long[])}.
*
* @param numElements capacity (number of elements) of result buffer.
*/
public static FloatBuffer allocateFloatBuffer(int numElements) {
return ByteBuffer.allocateDirect(numElements * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer();
}
/**
* Allocates a new direct {@link java.nio.LongBuffer} with native byte order with specified
* capacity that can be used in {@link Tensor#fromBlob(LongBuffer, long[])}.
*
* @param numElements capacity (number of elements) of result buffer.
*/
public static LongBuffer allocateLongBuffer(int numElements) {
return ByteBuffer.allocateDirect(numElements * LONG_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asLongBuffer();
}
/**
* Allocates a new direct {@link java.nio.DoubleBuffer} with native byte order with specified
* capacity that can be used in {@link Tensor#fromBlob(DoubleBuffer, long[])}.
*
* @param numElements capacity (number of elements) of result buffer.
*/
public static DoubleBuffer allocateDoubleBuffer(int numElements) {
return ByteBuffer.allocateDirect(numElements * DOUBLE_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asDoubleBuffer();
}
/**
* Creates a new Tensor instance with dtype torch.uint8 with specified shape and data as array of
* bytes.
*
* @param data Tensor elements
* @param shape Tensor shape
*/
public static Tensor fromBlobUnsigned(byte[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final ByteBuffer byteBuffer = allocateByteBuffer((int) numel(shape));
byteBuffer.put(data);
return new Tensor_uint8(byteBuffer, shape, memoryFormat);
}
public static Tensor fromBlobUnsigned(byte[] data, long[] shape) {
return fromBlobUnsigned(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int8 with specified shape and data as array of
* bytes.
*
* @param data Tensor elements
* @param shape Tensor shape
*/
public static Tensor fromBlob(byte[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final ByteBuffer byteBuffer = allocateByteBuffer((int) numel(shape));
byteBuffer.put(data);
return new Tensor_int8(byteBuffer, shape, memoryFormat);
}
public static Tensor fromBlob(byte[] data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int32 with specified shape and data as array of
* ints.
*
* @param data Tensor elements
* @param shape Tensor shape
*/
public static Tensor fromBlob(int[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final IntBuffer intBuffer = allocateIntBuffer((int) numel(shape));
intBuffer.put(data);
return new Tensor_int32(intBuffer, shape, memoryFormat);
}
public static Tensor fromBlob(int[] data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.float32 with specified shape and data as array
* of floats.
*
* @param data Tensor elements
* @param shape Tensor shape
*/
public static Tensor fromBlob(float[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final FloatBuffer floatBuffer = allocateFloatBuffer((int) numel(shape));
floatBuffer.put(data);
return new Tensor_float32(floatBuffer, shape, memoryFormat);
}
public static Tensor fromBlob(float[] data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int64 with specified shape and data as array of
* longs.
*
* @param data Tensor elements
* @param shape Tensor shape
*/
public static Tensor fromBlob(long[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final LongBuffer longBuffer = allocateLongBuffer((int) numel(shape));
longBuffer.put(data);
return new Tensor_int64(longBuffer, shape, memoryFormat);
}
public static Tensor fromBlob(long[] data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.float64 with specified shape and data as array
* of doubles.
*
* @param shape Tensor shape
* @param data Tensor elements
*/
public static Tensor fromBlob(double[] data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.length, shape);
final DoubleBuffer doubleBuffer = allocateDoubleBuffer((int) numel(shape));
doubleBuffer.put(data);
return new Tensor_float64(doubleBuffer, shape, memoryFormat);
}
public static Tensor fromBlob(double[] data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.uint8 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlobUnsigned(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_uint8(data, shape, memoryFormat);
}
public static Tensor fromBlobUnsigned(ByteBuffer data, long[] shape) {
return fromBlobUnsigned(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int8 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlob(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_int8(data, shape, memoryFormat);
}
public static Tensor fromBlob(ByteBuffer data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int32 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlob(IntBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_int32(data, shape, memoryFormat);
}
public static Tensor fromBlob(IntBuffer data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.float32 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlob(FloatBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_float32(data, shape, memoryFormat);
}
public static Tensor fromBlob(FloatBuffer data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.int64 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlob(LongBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_int64(data, shape, memoryFormat);
}
public static Tensor fromBlob(LongBuffer data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
/**
* Creates a new Tensor instance with dtype torch.float64 with specified shape and data.
*
* @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)}
* elements. The buffer is used directly without copying, and changes to its content will
* change the tensor.
* @param shape Tensor shape
*/
public static Tensor fromBlob(DoubleBuffer data, long[] shape, MemoryFormat memoryFormat) {
checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL);
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
checkShape(shape);
checkShapeAndDataCapacityConsistency(data.capacity(), shape);
checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT);
checkArgument(
(data.order() == ByteOrder.nativeOrder()),
ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER);
return new Tensor_float64(data, shape, memoryFormat);
}
public static Tensor fromBlob(DoubleBuffer data, long[] shape) {
return fromBlob(data, shape, MemoryFormat.CONTIGUOUS);
}
@DoNotStrip private HybridData mHybridData;
private Tensor(long[] shape, MemoryFormat memoryFormat) {
checkShape(shape);
this.shape = Arrays.copyOf(shape, shape.length);
this.memoryFormat = memoryFormat;
}
/** Returns the number of elements in this tensor. */
public long numel() {
return numel(this.shape);
}
/** Calculates the number of elements in a tensor with the specified shape. */
public static long numel(long[] shape) {
checkShape(shape);
int result = 1;
for (long s : shape) {
result *= s;
}
return result;
}
/** Returns the shape of this tensor. (The array is a fresh copy.) */
public long[] shape() {
return Arrays.copyOf(shape, shape.length);
}
/** Returns the memory format of this tensor. */
public MemoryFormat memoryFormat() {
return memoryFormat;
}
/** @return data type of this tensor. */
public abstract DType dtype();
// Called from native
@DoNotStrip
int dtypeJniCode() {
return dtype().jniCode;
}
// Called from native
@DoNotStrip
int memoryFormatJniCode() {
return memoryFormat.jniCode;
}
/**
* @return a Java byte array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-int8 tensor.
*/
public byte[] getDataAsByteArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as byte array.");
}
/**
* @return a Java byte array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-uint8 tensor.
*/
public byte[] getDataAsUnsignedByteArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as byte array.");
}
/**
* @return a Java int array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-int32 tensor.
*/
public int[] getDataAsIntArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as int array.");
}
/**
* @return a Java float array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-float32 tensor.
*/
public float[] getDataAsFloatArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as float array.");
}
/**
* @return a Java long array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-int64 tensor.
*/
public long[] getDataAsLongArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as long array.");
}
/**
* @return a Java double array that contains the tensor data. This may be a copy or reference.
* @throws IllegalStateException if it is called for a non-float64 tensor.
*/
public double[] getDataAsDoubleArray() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot return data as double array.");
}
@DoNotStrip
Buffer getRawDataBuffer() {
throw new IllegalStateException(
"Tensor of type " + getClass().getSimpleName() + " cannot " + "return raw data buffer.");
}
static class Tensor_uint8 extends Tensor {
private final ByteBuffer data;
private Tensor_uint8(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public DType dtype() {
return DType.UINT8;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public byte[] getDataAsUnsignedByteArray() {
data.rewind();
byte[] arr = new byte[data.remaining()];
data.get(arr);
return arr;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.uint8)", Arrays.toString(shape));
}
}
static class Tensor_int8 extends Tensor {
private final ByteBuffer data;
private Tensor_int8(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public DType dtype() {
return DType.INT8;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public byte[] getDataAsByteArray() {
data.rewind();
byte[] arr = new byte[data.remaining()];
data.get(arr);
return arr;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.int8)", Arrays.toString(shape));
}
}
static class Tensor_int32 extends Tensor {
private final IntBuffer data;
private Tensor_int32(IntBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public DType dtype() {
return DType.INT32;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public int[] getDataAsIntArray() {
data.rewind();
int[] arr = new int[data.remaining()];
data.get(arr);
return arr;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.int32)", Arrays.toString(shape));
}
}
static class Tensor_float32 extends Tensor {
private final FloatBuffer data;
Tensor_float32(FloatBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public float[] getDataAsFloatArray() {
data.rewind();
float[] arr = new float[data.remaining()];
data.get(arr);
return arr;
}
@Override
public DType dtype() {
return DType.FLOAT32;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.float32)", Arrays.toString(shape));
}
}
static class Tensor_int64 extends Tensor {
private final LongBuffer data;
private Tensor_int64(LongBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public DType dtype() {
return DType.INT64;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public long[] getDataAsLongArray() {
data.rewind();
long[] arr = new long[data.remaining()];
data.get(arr);
return arr;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.int64)", Arrays.toString(shape));
}
}
static class Tensor_float64 extends Tensor {
private final DoubleBuffer data;
private Tensor_float64(DoubleBuffer data, long[] shape, MemoryFormat memoryFormat) {
super(shape, memoryFormat);
this.data = data;
}
@Override
public DType dtype() {
return DType.FLOAT64;
}
@Override
Buffer getRawDataBuffer() {
return data;
}
@Override
public double[] getDataAsDoubleArray() {
data.rewind();
double[] arr = new double[data.remaining()];
data.get(arr);
return arr;
}
@Override
public String toString() {
return String.format("Tensor(%s, dtype=torch.float64)", Arrays.toString(shape));
}
}
// region checks
private static void checkArgument(boolean expression, String errorMessage, Object... args) {
if (!expression) {
throw new IllegalArgumentException(String.format(Locale.US, errorMessage, args));
}
}
private static void checkShape(long[] shape) {
checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL);
for (int i = 0; i < shape.length; i++) {
checkArgument(shape[i] >= 0, ERROR_MSG_SHAPE_NON_NEGATIVE);
}
}
private static void checkShapeAndDataCapacityConsistency(int dataCapacity, long[] shape) {
final long numel = numel(shape);
checkArgument(
numel == dataCapacity,
"Inconsistent data capacity:%d and shape number elements:%d shape:%s",
dataCapacity,
numel,
Arrays.toString(shape));
}
// endregion checks
// Called from native
@DoNotStrip
private static Tensor nativeNewTensor(
ByteBuffer data, long[] shape, int dtype, int memoryFormatCode, HybridData hybridData) {
Tensor tensor = null;
MemoryFormat memoryFormat = MemoryFormat.CONTIGUOUS;
if (MemoryFormat.CHANNELS_LAST.jniCode == memoryFormatCode) {
memoryFormat = MemoryFormat.CHANNELS_LAST;
} else if (MemoryFormat.CHANNELS_LAST_3D.jniCode == memoryFormatCode) {
memoryFormat = MemoryFormat.CHANNELS_LAST_3D;
}
if (DType.FLOAT32.jniCode == dtype) {
tensor = new Tensor_float32(data.asFloatBuffer(), shape, memoryFormat);
} else if (DType.INT32.jniCode == dtype) {
tensor = new Tensor_int32(data.asIntBuffer(), shape, memoryFormat);
} else if (DType.INT64.jniCode == dtype) {
tensor = new Tensor_int64(data.asLongBuffer(), shape, memoryFormat);
} else if (DType.FLOAT64.jniCode == dtype) {
tensor = new Tensor_float64(data.asDoubleBuffer(), shape, memoryFormat);
} else if (DType.UINT8.jniCode == dtype) {
tensor = new Tensor_uint8(data, shape, memoryFormat);
} else if (DType.INT8.jniCode == dtype) {
tensor = new Tensor_int8(data, shape, memoryFormat);
} else {
new IllegalArgumentException("Unknown Tensor dtype");
}
tensor.mHybridData = hybridData;
return tensor;
}
}