-
Notifications
You must be signed in to change notification settings - Fork 35
/
onnxruntime_test.go
1822 lines (1693 loc) · 56.1 KB
/
onnxruntime_test.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
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
package onnxruntime_go
import (
"fmt"
"math"
"math/rand"
"os"
"runtime"
"testing"
)
// Always use the same RNG seed for benchmarks, so we can compare the
// performance on the same random input data.
const benchmarkRNGSeed = 12345678
// If the ONNXRUNTIME_SHARED_LIBRARY_PATH environment variable is set, then
// we'll try to use its contents as the location of the shared library for
// these tests. Otherwise, we'll fall back to trying the shared library copies
// in the test_data directory.
func getTestSharedLibraryPath(t testing.TB) string {
toReturn := os.Getenv("ONNXRUNTIME_SHARED_LIBRARY_PATH")
if toReturn != "" {
return toReturn
}
if runtime.GOOS == "windows" {
return "test_data/onnxruntime.dll"
}
if runtime.GOARCH == "arm64" {
if runtime.GOOS == "darwin" {
return "test_data/onnxruntime_arm64.dylib"
}
return "test_data/onnxruntime_arm64.so"
}
if runtime.GOARCH == "amd64" && runtime.GOOS == "darwin" {
return "test_data/onnxruntime_amd64.dylib"
}
return "test_data/onnxruntime.so"
}
// This must be called prior to running each test.
func InitializeRuntime(t testing.TB) {
if IsInitialized() {
return
}
SetSharedLibraryPath(getTestSharedLibraryPath(t))
e := InitializeEnvironment()
if e != nil {
t.Fatalf("Failed setting up onnxruntime environment: %s\n", e)
}
}
// Should be called at the end of each test to de-initialize the runtime.
func CleanupRuntime(t testing.TB) {
e := DestroyEnvironment()
if e != nil {
t.Fatalf("Error cleaning up environment: %s\n", e)
}
}
// Returns nil if a and b are within a small delta of one another, otherwise
// returns an error indicating their values.
func floatsEqual(a, b float32) error {
diff := a - b
if diff < 0 {
diff = -diff
}
// Arbitrarily chosen precision. (Unfortunately, going higher than this may
// cause test failures, since the Sum operator doesn't have the same
// results as doing sums purely in Go.)
if diff >= 0.000001 {
return fmt.Errorf("Values differ by too much: %f vs %f", a, b)
}
return nil
}
// Returns an error if any element between a and b don't match.
func allFloatsEqual(a, b []float32) error {
if len(a) != len(b) {
return fmt.Errorf("Length mismatch: %d vs %d", len(a), len(b))
}
for i := range a {
e := floatsEqual(a[i], b[i])
if e != nil {
return fmt.Errorf("Data element %d doesn't match: %s", i, e)
}
}
return nil
}
// Returns an empty tensor with the given type and shape, or fails the test on
// error.
func newTestTensor[T TensorData](t testing.TB, s Shape) *Tensor[T] {
toReturn, e := NewEmptyTensor[T](s)
if e != nil {
t.Fatalf("Failed creating empty tensor with shape %s: %s\n", s, e)
}
return toReturn
}
func TestGetVersion(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
version := GetVersion()
if version == "" {
t.Fatalf("Not found version onnxruntime library")
}
t.Logf("Found onnxruntime library version: %s\n", version)
}
func TestTensorTypes(t *testing.T) {
type myFloat float64
dataType := TensorElementDataType(GetTensorElementDataType[myFloat]())
expected := TensorElementDataType(TensorElementDataTypeDouble)
if dataType != expected {
t.Fatalf("Expected float64 data type to be %d (%s), got %d (%s)\n",
expected, expected, dataType, dataType)
}
t.Logf("Got data type for float64-based double: %d (%s)\n",
dataType, dataType)
}
func TestCreateTensor(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
s := NewShape(1, 2, 3)
tensor1, e := NewEmptyTensor[uint8](s)
if e != nil {
t.Fatalf("Failed creating %s uint8 tensor: %s\n", s, e)
}
defer tensor1.Destroy()
if len(tensor1.GetData()) != 6 {
t.Logf("Incorrect data length for tensor1: %d\n",
len(tensor1.GetData()))
}
// Make sure that the underlying tensor created a copy of the shape we
// passed to NewEmptyTensor.
s[1] = 3
if tensor1.GetShape()[1] == s[1] {
t.Fatalf("Modifying the original shape incorrectly changed the " +
"tensor's shape.\n")
}
// Try making a tensor with a different data type.
s = NewShape(2, 5)
data := []float32{1.0}
_, e = NewTensor(s, data)
if e == nil {
t.Fatalf("Didn't get error when creating a tensor with too little " +
"data.\n")
}
t.Logf("Got expected error when creating a tensor without enough data: "+
"%s\n", e)
// It shouldn't be an error to create a tensor with too *much* underlying
// data; we'll just use the first portion of it.
data = []float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
tensor2, e := NewTensor(s, data)
if e != nil {
t.Fatalf("Error creating tensor with data: %s\n", e)
}
defer tensor2.Destroy()
// Make sure the tensor's internal slice only refers to the part we care
// about, and not the entire slice.
if len(tensor2.GetData()) != 10 {
t.Fatalf("New tensor data contains %d elements, when it should "+
"contain 10.\n", len(tensor2.GetData()))
}
}
func TestBadTensorShapes(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
s := NewShape()
_, e := NewEmptyTensor[float64](s)
if e == nil {
t.Fatalf("Didn't get an error when creating a tensor with an empty " +
"shape.\n")
}
t.Logf("Got expected error when creating a tensor with an empty shape: "+
"%s\n", e)
s = NewShape(10, 0, 10)
_, e = NewEmptyTensor[uint16](s)
if e == nil {
t.Fatalf("Didn't get an error when creating a tensor with a shape " +
"containing a 0 dimension.\n")
}
t.Logf("Got expected error when creating a tensor with a 0 dimension: "+
"%s\n", e)
s = NewShape(10, 10, -10)
_, e = NewEmptyTensor[int32](s)
if e == nil {
t.Fatalf("Didn't get an error when creating a tensor with a negative" +
" dimension.\n")
}
t.Logf("Got expected error when creating a tensor with a negative "+
"dimension: %s\n", e)
s = NewShape(10, -10, -10)
_, e = NewEmptyTensor[uint64](s)
if e == nil {
t.Fatalf("Didn't get an error when creating a tensor with two " +
"negative dimensions.\n")
}
t.Logf("Got expected error when creating a tensor with two negative "+
"dimensions: %s\n", e)
s = NewShape(int64(1)<<62, 1, int64(1)<<62)
_, e = NewEmptyTensor[float32](s)
if e == nil {
t.Fatalf("Didn't get an error when creating a tensor with an " +
"overflowing shape.\n")
}
t.Logf("Got expected error when creating a tensor with an overflowing "+
"shape: %s\n", e)
}
func TestCloneTensor(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
originalData := []float32{1, 2, 3, 4}
originalTensor, e := NewTensor(NewShape(2, 2), originalData)
if e != nil {
t.Fatalf("Error creating tensor: %s\n", e)
}
clone, e := originalTensor.Clone()
if e != nil {
t.Fatalf("Error cloning tensor: %s\n", e)
}
if !clone.GetShape().Equals(originalTensor.GetShape()) {
t.Fatalf("Clone shape (%s) doesn't match original shape (%s)\n",
clone.GetShape(), originalTensor.GetShape())
}
cloneData := clone.GetData()
for i := range originalData {
if cloneData[i] != originalData[i] {
t.Fatalf("Clone data incorrect at index %d: %f (expected %f)\n",
i, cloneData[i], originalData[i])
}
}
cloneData[2] = 1337
if originalData[2] != 3 {
t.Fatalf("Modifying clone data effected the original.\n")
}
}
func TestZeroTensorContents(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
a := newTestTensor[float64](t, NewShape(3, 4, 5))
defer a.Destroy()
data := a.GetData()
for i := range data {
data[i] = float64(i)
}
t.Logf("Before zeroing: a[%d] = %f\n", len(data)-1, data[len(data)-1])
a.ZeroContents()
for i, v := range data {
if v != 0.0 {
t.Fatalf("a[%d] = %f, expected it to be set to 0.\n", i, v)
}
}
// Do the same basic test with a CustomDataTensor
shape := NewShape(2, 3, 4, 5)
customData := randomBytes(123, 2*shape.FlattenedSize())
b, e := NewCustomDataTensor(shape, customData, TensorElementDataTypeUint16)
if e != nil {
t.Fatalf("Error creating custom data tensor: %s\n", e)
}
defer b.Destroy()
for i := range customData {
// This will wrap around, but doesn't matter. We just need arbitrary
// nonzero data for the test.
customData[i] = uint8(i)
}
t.Logf("Start of custom data before zeroing: % x\n", customData[0:10])
b.ZeroContents()
for i, v := range customData {
if v != 0 {
t.Fatalf("b[%d] = %d, expected it to be set to 0.\n", i, v)
}
}
}
// This test makes sure that functions taking .onnx data don't crash when
// passed an empty slice. (This used to be a bug.)
func TestEmptyONNXFiles(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
inputNames := []string{"whatever"}
outputNames := []string{"whatever_out"}
dummyIn := newTestTensor[float32](t, NewShape(1))
defer dummyIn.Destroy()
dummyOut := newTestTensor[float32](t, NewShape(1))
defer dummyOut.Destroy()
inputTensors := []Value{dummyIn}
outputTensors := []Value{dummyOut}
_, e := NewAdvancedSessionWithONNXData([]byte{}, inputNames, outputNames,
inputTensors, outputTensors, nil)
if e == nil {
// Really we're checking for a panic due to the empty slice, rather
// than a nil error.
t.Fatalf("Didn't get expected error when creating session.\n")
}
t.Logf("Got expected error creating session with no ONNX content: %s\n", e)
_, e = NewDynamicAdvancedSessionWithONNXData([]byte{}, inputNames,
outputNames, nil)
if e == nil {
t.Fatalf("Didn't get expected error when creating dynamic advanced " +
"session.\n")
}
t.Logf("Got expected error when creating dynamic session with no ONNX "+
"content: %s\n", e)
_, _, e = GetInputOutputInfoWithONNXData([]byte{})
if e == nil {
t.Fatalf("Didn't get expected error when getting input/output info " +
"with no ONNX content.\n")
}
t.Logf("Got expected error when getting input/output info with no "+
"ONNX content: %s\n", e)
_, e = GetModelMetadataWithONNXData([]byte{})
if e == nil {
t.Fatalf("Didn't get expected error when getting metadata with no " +
"ONNX content.\n")
}
t.Logf("Got expected error when getting metadata with no ONNX "+
"content: %s\n", e)
}
func TestLegacyAPI(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
// We'll use this network simply due to its simple input and output format,
// as well as it using the same data type for inputs and outputs. See
// TestNonAsciiPath for more comments.
filePath := "test_data/example ż 大 김.onnx"
inputData := []int32{12, 21}
input, e := NewTensor(NewShape(1, 2), inputData)
if e != nil {
t.Fatalf("Error creating input tensor: %s\n", e)
}
defer input.Destroy()
output := newTestTensor[int32](t, NewShape(1))
defer output.Destroy()
session, e := NewSession[int32](filePath, []string{"in"}, []string{"out"},
[]*Tensor[int32]{input}, []*Tensor[int32]{output})
if e != nil {
t.Fatalf("Error creating sesion via legacy API: %s\n", e)
}
e = session.Run()
if e != nil {
t.Fatalf("Error running session: %s\n", e)
}
expected := inputData[0] + inputData[1]
result := output.GetData()[0]
if result != expected {
t.Errorf("Incorrect result. Expected %d, got %d.\n", expected, result)
}
}
func TestLegacyAPIDynamic(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
filePath := "test_data/example ż 大 김.onnx"
inputData := []int32{12, 21}
input, e := NewTensor(NewShape(1, 2), inputData)
if e != nil {
t.Fatalf("Error creating input tensor: %s\n", e)
}
defer input.Destroy()
output := newTestTensor[int32](t, NewShape(1))
defer output.Destroy()
session, e := NewDynamicSession[int32, int32](filePath,
[]string{"in"}, []string{"out"})
if e != nil {
t.Fatalf("Error creating sesion via legacy API: %s\n", e)
}
e = session.Run([]*Tensor[int32]{input}, []*Tensor[int32]{output})
if e != nil {
t.Fatalf("Error running session: %s\n", e)
}
expected := inputData[0] + inputData[1]
result := output.GetData()[0]
if result != expected {
t.Errorf("Incorrect result. Expected %d, got %d.\n", expected, result)
}
}
func TestEnableDisableTelemetry(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
e := EnableTelemetry()
if e != nil {
t.Errorf("Error enabling onnxruntime telemetry: %s\n", e)
}
e = DisableTelemetry()
if e != nil {
t.Errorf("Error disabling onnxruntime telemetry: %s\n", e)
}
e = EnableTelemetry()
if e != nil {
t.Errorf("Error re-enabling onnxruntime telemetry after "+
"disabling: %s\n", e)
}
}
func TestArbitraryTensors(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
tensorShape := NewShape(2, 2)
tensorA, e := NewTensor(tensorShape, []uint8{1, 2, 3, 4})
if e != nil {
t.Fatalf("Error creating uint8 tensor: %s\n", e)
}
defer tensorA.Destroy()
tensorB, e := NewTensor(tensorShape, []float64{5, 6, 7, 8})
if e != nil {
t.Fatalf("Error creating float64 tensor: %s\n", e)
}
defer tensorB.Destroy()
tensorC, e := NewTensor(tensorShape, []int16{9, 10, 11, 12})
if e != nil {
t.Fatalf("Error creating int16 tensor: %s\n", e)
}
defer tensorC.Destroy()
tensorList := []ArbitraryTensor{tensorA, tensorB, tensorC}
for i, v := range tensorList {
ortValue := v.GetInternals().ortValue
t.Logf("ArbitraryTensor %d: Data type %d, shape %s, OrtValue %p\n",
i, v.DataType(), v.GetShape(), ortValue)
}
}
// Used for testing the operation of test_data/example_multitype.onnx
func randomMultitypeInputs(t *testing.T, seed int64) (*Tensor[uint8],
*Tensor[float64]) {
rng := rand.New(rand.NewSource(seed))
inputA := newTestTensor[uint8](t, NewShape(1, 1, 1))
// We won't use newTestTensor here, otherwise we won't have a chance to
// destroy inputA on failure.
inputB, e := NewEmptyTensor[float64](NewShape(1, 2, 2))
if e != nil {
inputA.Destroy()
t.Fatalf("Failed creating input B: %s\n", e)
}
inputA.GetData()[0] = uint8(rng.Intn(256))
for i := 0; i < 4; i++ {
inputB.GetData()[i] = rng.Float64()
}
return inputA, inputB
}
// Used when checking the output produced by test_data/example_multitype.onnx
func getExpectedMultitypeOutputs(inputA *Tensor[uint8],
inputB *Tensor[float64]) ([]int16, []int64) {
outputA := make([]int16, 4)
dataA := inputA.GetData()[0]
dataB := inputB.GetData()
for i := 0; i < len(outputA); i++ {
outputA[i] = int16((dataB[i] * float64(dataA)) - 512)
}
return outputA, []int64{int64(dataA) * 1234}
}
// Verifies that the given tensor's data matches the expected content. Prints
// an error and fails the test if anything doesn't match.
func verifyTensorData[T TensorData](t *testing.T, tensor *Tensor[T],
expectedContent []T) {
data := tensor.GetData()
if len(data) != len(expectedContent) {
t.Fatalf("Expected tensor to contain %d elements, got %d elements.\n",
len(expectedContent), len(data))
}
for i, v := range expectedContent {
if v != data[i] {
t.Fatalf("Data mismatch at index %d: expected %v, got %v\n", i, v,
data[i])
}
}
}
// Tests a session taking multiple input tensors of different types and
// producing multiple output tensors of different types.
func TestDifferentInputOutputTypes(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
inputA, inputB := randomMultitypeInputs(t, 9999)
defer inputA.Destroy()
defer inputB.Destroy()
outputA := newTestTensor[int16](t, NewShape(1, 2, 2))
defer outputA.Destroy()
outputB := newTestTensor[int64](t, NewShape(1, 1, 1))
defer outputB.Destroy()
// Decided to toss in an "ArbitraryTensor" here to ensure that it remains
// compatible with Value in the future.
session, e := NewAdvancedSession("test_data/example_multitype.onnx",
[]string{"InputA", "InputB"}, []string{"OutputA", "OutputB"},
[]Value{inputA, inputB}, []ArbitraryTensor{outputA, outputB}, nil)
if e != nil {
t.Fatalf("Failed creating session: %s\n", e)
}
defer session.Destroy()
e = session.Run()
if e != nil {
t.Fatalf("Error running session: %s\n", e)
}
expectedA, expectedB := getExpectedMultitypeOutputs(inputA, inputB)
verifyTensorData(t, outputA, expectedA)
verifyTensorData(t, outputB, expectedB)
}
func TestDynamicDifferentInputOutputTypes(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
session, e := NewDynamicAdvancedSession("test_data/example_multitype.onnx",
[]string{"InputA", "InputB"}, []string{"OutputA", "OutputB"}, nil)
defer session.Destroy()
numTests := 100
aInputs := make([]*Tensor[uint8], numTests)
bInputs := make([]*Tensor[float64], numTests)
aOutputs := make([]*Tensor[int16], numTests)
bOutputs := make([]*Tensor[int64], numTests)
// Make sure we clean up all the tensors created for this test, even if we
// somehow fail before we've created them all.
defer func() {
for i := 0; i < numTests; i++ {
if aInputs[i] != nil {
aInputs[i].Destroy()
}
if bInputs[i] != nil {
bInputs[i].Destroy()
}
if aOutputs[i] != nil {
aOutputs[i].Destroy()
}
if bOutputs[i] != nil {
bOutputs[i].Destroy()
}
}
}()
// Actually create the inputs and run the tests.
for i := 0; i < numTests; i++ {
aInputs[i], bInputs[i] = randomMultitypeInputs(t, 999+int64(i))
aOutputs[i] = newTestTensor[int16](t, NewShape(1, 2, 2))
bOutputs[i] = newTestTensor[int64](t, NewShape(1, 1, 1))
e = session.Run([]Value{aInputs[i], bInputs[i]},
[]Value{aOutputs[i], bOutputs[i]})
if e != nil {
t.Fatalf("Failed running session for test %d: %s\n", i, e)
}
}
// Now that all the tests ran, check the outputs. If the
// DynamicAdvancedSession worked properly, each run should have only
// modified its given outputs.
for i := 0; i < numTests; i++ {
expectedA, expectedB := getExpectedMultitypeOutputs(aInputs[i],
bInputs[i])
verifyTensorData(t, aOutputs[i], expectedA)
verifyTensorData(t, bOutputs[i], expectedB)
}
}
func TestDynamicAllocatedOutputTensor(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
session, e := NewDynamicAdvancedSession("test_data/example_multitype.onnx",
[]string{"InputA", "InputB"}, []string{"OutputA", "OutputB"}, nil)
if e != nil {
t.Fatalf("Error creating session: %s\n", e)
}
defer session.Destroy()
// Actually create the inputs and run the tests.
aInput, bInput := randomMultitypeInputs(t, 999)
var outputs [2]Value
e = session.Run([]Value{aInput, bInput}, outputs[:])
if e != nil {
t.Fatalf("Failed running session: %s\n", e)
}
defer func() {
for _, output := range outputs {
output.Destroy()
}
}()
expectedA, expectedB := getExpectedMultitypeOutputs(aInput, bInput)
expectedShape := NewShape(1, 2, 2)
outputA, ok := outputs[0].(*Tensor[int16])
if !ok {
t.Fatalf("Expected outputA to be of type %T, got of type %T\n",
outputA, outputs[0])
}
if !outputA.shape.Equals(expectedShape) {
t.Fatalf("Expected outputA to be of shape %s, got of shape %s\n",
expectedShape, outputA.shape)
}
verifyTensorData(t, outputA, expectedA)
outputB, ok := outputs[1].(*Tensor[int64])
expectedShape = NewShape(1, 1, 1)
if !ok {
t.Fatalf("Expected outputB to be of type %T, got of type %T\n",
outputB, outputs[1])
}
if !outputB.shape.Equals(expectedShape) {
t.Fatalf("Expected outputB to be of shape %s, got of shape %s\n",
expectedShape, outputB.shape)
}
verifyTensorData(t, outputB, expectedB)
}
// Makes sure that the sum of each vector in the input tensor matches the
// corresponding scalar in the output tensor. Used when testing tensors with
// unknown batch dimensions.
// NOTE: Destroys the input and output tensors before returning, regardless of
// test success.
func checkVectorSum(input *Tensor[float32], output *Tensor[float32],
t testing.TB) {
defer input.Destroy()
defer output.Destroy()
// Make sure the sizes are what we expect.
inputShape := input.GetShape()
outputShape := output.GetShape()
if len(inputShape) != 2 {
t.Fatalf("Expected a 2-dimensional input shape, got %v\n", inputShape)
}
if len(outputShape) != 1 {
t.Fatalf("Expected 1-dimensional output shape, got %v\n", outputShape)
}
if inputShape[0] != outputShape[0] {
t.Fatalf("Input and output batch dimensions don't match (%d vs %d)\n",
inputShape[0], outputShape[0])
}
// Compute the sums in Go
batchSize := inputShape[0]
vectorLength := inputShape[1]
expectedSums := make([]float32, batchSize)
for i := int64(0); i < batchSize; i++ {
inputVector := input.GetData()[i*vectorLength : (i+1)*vectorLength]
sum := float32(0.0)
for _, v := range inputVector {
sum += v
}
expectedSums[i] = sum
}
e := allFloatsEqual(expectedSums, output.GetData())
if e != nil {
t.Fatalf("ONNX-produced sums don't match CPU-produced sums: %s\n", e)
}
}
func TestDynamicInputOutputAxes(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
netPath := "test_data/example_dynamic_axes.onnx"
session, e := NewDynamicAdvancedSession(netPath,
[]string{"input_vectors"}, []string{"output_scalars"}, nil)
if e != nil {
t.Fatalf("Error loading %s: %s\n", netPath, e)
}
defer session.Destroy()
maxBatchSize := 99
// The example network takes a dynamic batch size of vectors containing 10
// elements each.
dataBuffer := make([]float32, maxBatchSize*10)
// Try running the session with many different batch sizes
for i := 11; i <= maxBatchSize; i += 11 {
// Create an input with the new batch size.
inputShape := NewShape(int64(i), 10)
input, e := NewTensor(inputShape, dataBuffer)
if e != nil {
t.Fatalf("Error creating input tensor with shape %v: %s\n",
inputShape, e)
}
// Populate the input with new random floats.
fillRandomFloats(input.GetData(), 1234)
// Run the session; make onnxruntime allocate the output tensor for us.
outputs := []Value{nil}
e = session.Run([]Value{input}, outputs)
if e != nil {
input.Destroy()
t.Fatalf("Error running the session with batch size %d: %s\n",
i, e)
}
// The checkVectorSum function will destroy the input and output tensor
// regardless of their correctness.
checkVectorSum(input, outputs[0].(*Tensor[float32]), t)
input.Destroy()
t.Logf("Batch size %d seems OK!\n", i)
}
}
func TestWrongInputs(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
session, e := NewDynamicAdvancedSession("test_data/example_multitype.onnx",
[]string{"InputA", "InputB"}, []string{"OutputA", "OutputB"}, nil)
defer session.Destroy()
inputA, inputB := randomMultitypeInputs(t, 123456)
defer inputA.Destroy()
defer inputB.Destroy()
outputA := newTestTensor[int16](t, NewShape(1, 2, 2))
defer outputA.Destroy()
outputB := newTestTensor[int64](t, NewShape(1, 1, 1))
defer outputB.Destroy()
// Make sure that passing a tensor with the wrong type but correct shape
// will correctly cause an error rather than a crash, whether used as an
// input or output.
wrongTypeTensor := newTestTensor[float32](t, NewShape(1, 2, 2))
defer wrongTypeTensor.Destroy()
e = session.Run([]Value{inputA, inputB}, []Value{wrongTypeTensor, outputB})
if e == nil {
t.Fatalf("Didn't get expected error when passing a float32 tensor in" +
" place of an int16 output tensor.\n")
}
t.Logf("Got expected error when passing a float32 tensor in place of an "+
"int16 output tensor: %s\n", e)
e = session.Run([]Value{inputA, wrongTypeTensor},
[]Value{outputA, outputB})
if e == nil {
t.Fatalf("Didn't get expected error when passing a float32 tensor in" +
" place of a float64 input tensor.\n")
}
t.Logf("Got expected error when passing a float32 tensor in place of a "+
"float64 input tensor: %s\n", e)
// Make sure that passing a tensor with the wrong shape but correct type
// will cause an error rather than a crash, when using as an input or an
// output.
wrongShapeInput := newTestTensor[uint8](t, NewShape(22))
defer wrongShapeInput.Destroy()
e = session.Run([]Value{wrongShapeInput, inputB},
[]Value{outputA, outputB})
if e == nil {
t.Fatalf("Didn't get expected error when running with an incorrectly" +
" shaped input.\n")
}
t.Logf("Got expected error when running with an incorrectly shaped "+
"input: %s\n", e)
wrongShapeOutput := newTestTensor[int64](t, NewShape(1, 1, 1, 1, 1, 1))
defer wrongShapeOutput.Destroy()
e = session.Run([]Value{inputA, inputB},
[]Value{outputA, wrongShapeOutput})
if e == nil {
t.Fatalf("Didn't get expected error when running with an incorrectly" +
" shaped output.\n")
}
t.Logf("Got expected error when running with an incorrectly shaped "+
"output: %s\n", e)
e = session.Run([]Value{inputA, inputB}, []Value{outputA, outputB})
if e != nil {
t.Fatalf("Got error attempting to (correctly) Run a session after "+
"attempting to use incorrect inputs or outputs: %s\n", e)
}
}
func TestGetInputOutputInfo(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
file := "test_data/example_several_inputs_and_outputs.onnx"
inputs, outputs, e := GetInputOutputInfo(file)
if e != nil {
t.Fatalf("Error getting input and output info for %s: %s\n", file, e)
}
if len(inputs) != 3 {
t.Fatalf("Expected 3 inputs, got %d\n", len(inputs))
}
if len(outputs) != 2 {
t.Fatalf("Expected 2 outputs, got %d\n", len(outputs))
}
for i, v := range inputs {
t.Logf("Input %d: %s\n", i, &v)
}
for i, v := range outputs {
t.Logf("Output %d: %s\n", i, &v)
}
if outputs[1].Name != "output 2" {
t.Errorf("Incorrect output 1 name: %s, expected \"output 2\"\n",
outputs[1].Name)
}
expectedShape := NewShape(1, 2, 3, 4, 5)
if !outputs[1].Dimensions.Equals(expectedShape) {
t.Errorf("Incorrect output 1 shape: %s, expected %s\n",
outputs[1].Dimensions, expectedShape)
}
var expectedType TensorElementDataType = TensorElementDataTypeDouble
if outputs[1].DataType != expectedType {
t.Errorf("Incorrect output 1 data type: %s, expected %s\n",
outputs[1].DataType, expectedType)
}
if inputs[0].Name != "input 1" {
t.Errorf("Incorrect input 0 name: %s, expected \"input 1\"\n",
inputs[0].Name)
}
expectedShape = NewShape(2, 5, 2, 5)
if !inputs[0].Dimensions.Equals(expectedShape) {
t.Errorf("Incorrect input 0 shape: %s, expected %s\n",
inputs[0].Dimensions, expectedShape)
}
expectedType = TensorElementDataTypeInt32
if inputs[0].DataType != expectedType {
t.Errorf("Incorrect input 0 data type: %s, expected %s\n",
inputs[0].DataType, expectedType)
}
}
func TestModelMetadata(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
file := "test_data/example_big_compute.onnx"
metadata, e := GetModelMetadata(file)
if e != nil {
t.Fatalf("Error getting metadata for %s: %s\n", file, e)
}
// We'll just test Destroy once; after this we won't check its return value
e = metadata.Destroy()
if e != nil {
t.Fatalf("Error destroying metadata: %s\n", e)
}
// Try getting the metadata from a session instead of from a file.
// NOTE: All of the expected values here were manually set using the
// test_data/modify_metadata.py script after generating the network. See
// that script for the expected values of each of the metadata accesors.
session, e := NewDynamicAdvancedSession(file, []string{"Input"},
[]string{"Output"}, nil)
if e != nil {
t.Fatalf("Error creating session: %s\n", e)
}
defer session.Destroy()
metadata, e = session.GetModelMetadata()
if e != nil {
t.Fatalf("Error getting metadata from DynamicAdvancedSession: %s\n", e)
}
defer metadata.Destroy()
producerName, e := metadata.GetProducerName()
if e != nil {
t.Errorf("Error getting producer name: %s\n", e)
} else {
t.Logf("Got producer name: %s\n", producerName)
}
graphName, e := metadata.GetGraphName()
if e != nil {
t.Errorf("Error getting graph name: %s\n", e)
} else {
t.Logf("Got graph name: %s\n", graphName)
}
domainStr, e := metadata.GetDomain()
if e != nil {
t.Errorf("Error getting domain: %s\n", e)
} else {
t.Logf("Got domain: %s\n", domainStr)
if domainStr != "test domain" {
t.Errorf("Incorrect domain string, expected \"test domain\"\n")
}
}
description, e := metadata.GetDescription()
if e != nil {
t.Errorf("Error getting description: %s\n", e)
} else {
t.Logf("Got description: %s\n", description)
}
version, e := metadata.GetVersion()
if e != nil {
t.Errorf("Error getting version: %s\n", e)
} else {
t.Logf("Got version: %d\n", version)
if version != 1337 {
t.Errorf("Incorrect version number, expected 1337\n")
}
}
mapKeys, e := metadata.GetCustomMetadataMapKeys()
if e != nil {
t.Fatalf("Error getting custom metadata keys: %s\n", e)
}
t.Logf("Got %d custom metadata map keys.\n", len(mapKeys))
if len(mapKeys) != 2 {
t.Errorf("Incorrect number of custom metadata keys, expected 2")
}
for _, k := range mapKeys {
value, present, e := metadata.LookupCustomMetadataMap(k)
if e != nil {
t.Errorf("Error looking up key %s in custom metadata: %s\n", k, e)
} else {
if !present {
t.Errorf("LookupCustomMetadataMap didn't return true for a " +
"key that should be present in the map\n")
}
t.Logf(" Metadata key \"%s\" = \"%s\"\n", k, value)
}
}
badValue, present, e := metadata.LookupCustomMetadataMap("invalid key")
if len(badValue) != 0 {
t.Fatalf("Didn't get an empty string when looking up an invalid "+
"metadata key, got \"%s\" instead\n", badValue)
}
if present {
t.Errorf("LookupCustomMetadataMap didn't return false for a key that" +
" isn't in the map\n")
}
// Tossing in this check, since the docs aren't clear on this topic. (The
// docs specify returning an empty string, but do not mention a non-NULL
// OrtStatus.) At the time of writing, it does _not_ return an error.
if e == nil {
t.Logf("Informational: looking up an invalid metadata key doesn't " +
"return an error\n")
} else {
t.Logf("Informational: got error when looking up an invalid "+
"metadata key: %s\n", e)
}
}
func randomBytes(seed, n int64) []byte {
toReturn := make([]byte, n)
rng := rand.New(rand.NewSource(seed))
rng.Read(toReturn)
return toReturn
}
func fillRandomFloats(dst []float32, seed int64) {
rng := rand.New(rand.NewSource(seed))
for i := range dst {
dst[i] = rng.Float32()
}
}
func TestCustomDataTensors(t *testing.T) {
InitializeRuntime(t)
defer CleanupRuntime(t)
shape := NewShape(2, 3, 4, 5)
tensorData := randomBytes(123, 2*shape.FlattenedSize())
// This could have been created using a Tensor[uint16], but we'll make sure
// it works this way, too.
v, e := NewCustomDataTensor(shape, tensorData, TensorElementDataTypeUint16)
if e != nil {
t.Fatalf("Error creating uint16 CustomDataTensor: %s\n", e)
}
shape[0] = 6
if v.GetShape().Equals(shape) {
t.Fatalf("CustomDataTensor didn't properly clone its shape")
}
e = v.Destroy()
if e != nil {
t.Fatalf("Error destroying CustomDataTensor: %s\n", e)
}
tensorData = randomBytes(1234, 2*shape.FlattenedSize())
v, e = NewCustomDataTensor(shape, tensorData, TensorElementDataTypeFloat16)
if e != nil {
t.Fatalf("Error creating float16 tensor: %s\n", e)
}
e = v.Destroy()
if e != nil {
t.Fatalf("Error destroying float16 tensor: %s\n", e)
}
// Make sure we don't fail if providing more data than necessary
shape[0] = 1
v, e = NewCustomDataTensor(shape, tensorData,
TensorElementDataTypeBFloat16)
if e != nil {
t.Fatalf("Got error when creating a tensor with more data than "+
"necessary: %s\n", e)
}
v.Destroy()
// Make sure we fail when using a bad shape
shape = NewShape(0, -1, -2)
v, e = NewCustomDataTensor(shape, tensorData, TensorElementDataTypeFloat16)
if e == nil {
v.Destroy()
t.Fatalf("Didn't get error when creating custom tensor with an " +
"invalid shape\n")
}
t.Logf("Got expected error creating tensor with invalid shape: %s\n", e)
shape = NewShape(1, 2, 3, 4, 5)
tensorData = []byte{1, 2, 3, 4}
v, e = NewCustomDataTensor(shape, tensorData, TensorElementDataTypeUint8)
if e == nil {