-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPerfectTensorFlowTests.swift
1448 lines (1265 loc) · 49.7 KB
/
PerfectTensorFlowTests.swift
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
//
// PerfectTensorFlowTests.swift
// Perfect-TensorFlow
//
// Created by Rockford Wei on 2017-05-18.
// Copyright © 2017 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import XCTest
@testable import PerfectTensorFlow
import TensorFlowAPI
public typealias TF = TensorFlow
struct SavedModel {
/// SavedModel assets directory.
public static let kSavedModelAssetsDirectory = "assets"
/// SavedModel assets key for graph collection-def.
public static let kSavedModelAssetsKey = "saved_model_assets"
/// SavedModel proto filename.
public static let kSavedModelFilenamePb = "saved_model.pb"
/// SavedModel text format proto filename.
public static let kSavedModelFilenamePbTxt = "saved_model.pbtxt"
/// SavedModel legacy init op key.
public static let kSavedModelLegacyInitOpKey = "legacy_init_op"
/// SavedModel main op key.
public static let kSavedModelMainOpKey = "saved_model_main_op"
/// Directory in which to save the SavedModel variables.
public static let kSavedModelVariablesDirectory = "variables"
/// SavedModel variables filename.
public static let kSavedModelVariablesFilename = "variables"
/// Key in the signature def map for `default` serving signatures. The default
/// signature is used in inference requests where a specific signature was not
/// specified.
public static let kDefaultServingSignatureDefKey = "serving_default"
////////////////////////////////////////////////////////////////////////////////
/// Classification API constants.
/// Classification inputs.
public static let kClassifyInputs = "inputs"
/// Classification method name used in a SignatureDef.
public static let kClassifyMethodName = "tensorflow/serving/classify"
/// Classification classes output.
public static let kClassifyOutputClasses = "classes"
/// Classification scores output.
public static let kClassifyOutputScores = "scores"
////////////////////////////////////////////////////////////////////////////////
/// Predict API constants.
/// Predict inputs.
public static let kPredictInputs = "inputs"
/// Predict method name used in a SignatureDef.
public static let kPredictMethodName = "tensorflow/serving/predict"
/// Predict outputs.
public static let kPredictOutputs = "outputs"
////////////////////////////////////////////////////////////////////////////////
/// Regression API constants.
/// Regression inputs.
public static let kRegressInputs = "inputs"
/// Regression method name used in a SignatureDef.
public static let kRegressMethodName = "tensorflow/serving/regress"
/// Regression outputs.
public static let kRegressOutputs = "outputs"
/// Tag for the `serving` graph.
public static let kSavedModelTagServe = "serve"
/// Tag for the `training` graph.`
public static let kSavedModelTagTrain = "train"
}//end struct
public extension Data {
static func Load(_ localFile: String) -> Data? {
var st = stat()
guard let f = fopen(localFile, "rb"), stat(localFile, &st) == 0, st.st_size > 0 else { return nil }
let size = Int(st.st_size)
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
guard size == fread(buf, 1, size, f) else {
#if swift(>=4.1)
buf.deallocate()
#else
buf.deallocate(capacity: size)
#endif
return nil
}//end guard
return Data(bytesNoCopy: buf, count: size, deallocator: .free)
}
}
extension Array where Element == TF.Output {
func useHelper(graph: TF.Graph, _ operationType: String, _ name: String)
throws -> TF.Operation {
var desc = try TF.OperationBuilder(graph: graph, name: name, type: operationType)
self.forEach { inp in
desc = desc.add(input: inp)
}
return try desc.set(device: "/cpu:0").build()
}
}
class PerfectTensorFlowTests: XCTestCase {
static var allTests = [
("testVersion", testVersion),
("testSize", testSize),
("testStatus", testStatus),
("testBuffer", testBuffer),
("testTensorScalarConst", testTensorScalarConst),
//("testSessionOptions", testSessionOptions),
("testGraph", testGraph),
("testGraph2", testGraph2),
("testImportGraphDef", testImportGraphDef),
("testOpList", testOpList),
("testSetShapePlaceHolder", testSetShapePlaceHolder),
("testSetShape", testSetShape),
("testSession", testSession),
("testSessionExpress", testSessionExpress),
("testPSession", testPSession),
("testShapeInference", testShapeInference),
("testSavedModel", testSavedModel),
("testBasicLoop", testBasicLoop),
("testAttributes", testAttributes),
("testEncodeDecode", testEncodeDecode),
("testHelloWorld", testHelloWorld),
("testHelloWorldUTF8", testHelloWorldUTF8),
("testHelloExpress", testHelloExpress),
("testBasic", testBasic),
("testBasicExpress", testBasicExpress),
("testLabels", testLabels),
("testSessionLeak", testSessionLeak),
("testGradients", testGradients),
("testMatrix", testMatrix),
("testBasicImproved",testBasicImproved),
("testDevices", testDevices),
("testEventAndSummary", testEventAndSummary),
("testFunctionBasic", testFunctionBasic),
("testUniquify", testUniquify)
]
func testGraphDefWithResults() {
do {
let g0 = try TF.Graph()
_ = try g0.placeholder()
_ = try g0.scalar(3)
guard let def = g0.definition else {
XCTFail("graph definition failure")
return
}
let g = try TF.Graph()
let o = try TF.GraphDefOptions()
_ = try g.import(definition: def, options: o)
let scalar = try g.searchOperation(forName: "scalar")
let opt = try TF.GraphDefOptions()
opt.set(prefix: "imported")
opt.addInputMapping(sourceName: "scalar", sourceIndex: 0, destination: scalar.asOutput(0))
opt.addInputMapping(sourceName: "fake", sourceIndex: 0, destination: scalar.asOutput(0))
guard let results = try g.import(definition: def, options: opt, withResults: true) else {
XCTFail("import with results failure")
return
}
let r = results.missingUnusedInputMappings()
XCTAssertEqual(r.count, 1)
XCTAssertEqual(r.first?.name ?? "failure", "fake")
XCTAssertEqual(r.first?.index ?? -1, 0)
} catch TF.Panic.FAULT(let reason){
XCTFail(reason)
} catch {
XCTFail(error.localizedDescription)
}
}
func testUniquify() {
do {
let o = try TF.GraphDefOptions()
o.setNames(uniquified: true)
o.setPrefix(uniquified: true)
} catch {
XCTFail("\(error)")
}
}
func testFunctionBasic() {
do {
let funcName = "MyFunc"
let nodeName = "MyFunc_0"
let attrName = "foo_attr"
let funcGraph = try TF.Graph()
let hostGraph = try TF.Graph()
let c = try funcGraph.scalar(10, name: "scalar10")
let function = try funcGraph.toFunction(funcName, outputs: [c.asOutput(0)])
try hostGraph.copy(function: function)
let nullInput: [TF.Output] = []
let funOp = try nullInput.useHelper(graph: hostGraph, funcName, nodeName)
let s = try hostGraph.runner().fetch(funOp).run()
XCTAssertEqual(s.count, 1)
let res:[Int32] = try s[0].asArray()
XCTAssertEqual(res[0], 10)
guard let def = function.definition else {
XCTFail("function definition failure")
return
}
let node = def.nodeDef[0]
XCTAssertEqual(node.name, "scalar10_0")
guard let value = node.attr["value"] else {
XCTFail("function invalid value")
return
}
XCTAssertEqual( value.tensor.intVal, [10])
guard let ret = def.ret["scalar10"] else {
XCTFail("function return fault")
return
}
XCTAssertEqual(ret, "scalar10_0:output:0")
let function2 = try TF.Graph.Function(importDefinition: def)
guard let def2 = function2.definition else {
XCTFail("function import / export failure")
return
}
let node2 = def2.nodeDef[0]
XCTAssertEqual(node, node2)
try function2.setAttributeFor(attrName, value: value)
let value2 = try function2.getAttributeFor(attrName)
XCTAssertEqual(value, value2)
}catch {
XCTFail("functions: \(error)")
}
}
func testDevices() {
do {
let g = try TF.Graph()
let dev = try g.runner().session.devices
print("default devices:", dev)
XCTAssertGreaterThan(dev.count, 0)
}catch {
XCTFail("hello: \(error)")
}
}
func testMatrix() {
let x = [[1, 2, 3], [4, 5, 6]]
let y = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]],[[13,14],[15,16],[17,18]],[[19,20],[21,22],[23,24]]]
XCTAssertEqual(x.shape, [2, 3])
XCTAssertEqual(y.shape, [4, 3, 2])
XCTAssertEqual(x[1][2], 6)
XCTAssertEqual(x.column(index: 1) as! [Int], [2, 5])
}
func testGradients() {
do {
let grad = TestGradients()
try grad.test(true)
try grad.test(false)
}catch {
XCTFail("gradients: \(error)")
}
}
class TestGradients {
public func test(_ providingDX: Bool) throws {
let success = try buildSuccessGraph()
let expected = try buildExpectedGraph(providingDX)
let _ = try addGradients(providingDX, graph: success.graph, inputs: success.inputs, outputs: success.outputs)
guard let def0 = success.graph.definition,
let def1 = expected.graph.definition else {
throw TF.Panic.FAULT(reason: "Unexpected Graph Definition after Adding Gradients")
}
let n0 = def0.node
let n1 = def1.node
XCTAssertEqual(n0.count, n1.count)
for i in 0 ..< n0.count {
let n = n0[i]
let m = n1[i]
//XCTAssertEqual(n.name, m.name)
XCTAssertEqual(n.op, m.op)
for key in n.attr.keys {
let v = n.attr[key]
let w = m.attr[key]
XCTAssertEqual(v, w)
}
}
}
public func buildSuccessGraph() throws ->
(graph: TF.Graph, inputs:[TF.Output], outputs: [TF.Output])
{
// Construct the following graph:
// |
// z|
// |
// MatMul
// / \
// ^ ^
// | |
// x| y|
// | |
// | |
// Const_0 Const_1
//
let srcA:[[Float]] = [[1,2],[3,4]]
let srcB:[[Float]] = [[1,0],[0,1]]
// create tensors for these matrices
let tA = try TF.Tensor.Matrix(srcA)
let tB = try TF.Tensor.Matrix(srcB)
let g = try TF.Graph()
// adding tensors to graph
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")
let M = try g.matMul(l: A, r: B, name: "MatMul")
return (graph: g, inputs:[A.asOutput(0), B.asOutput(0)], outputs:[M.asOutput(0)])
}
public func buildExpectedGraph(_ providingDX: Bool) throws ->
(graph: TF.Graph, dy: [TF.Output])
{
// The expected graph looks like this if grad_inputs_provided.
// If grad_inputs_provided is false, Const_0 will be a OnesLike op.
// ^ ^
// dy| dx| // MatMul Gradient Graph
// | |
// MatMul_2 MatMul_1
// ^ ^ ^ ^
// | |----------| |
// | ^ |
// | dz| |
// | | |
// | Const_3 |
// | |
// | ^ |
// | z| | // MatMul Forward Graph
// | | |
// | MatMul |
// | / \ |
// | ^ ^ |
// | | | |
// |---x| y|----|
// | |
// | |
// Const_0 Const_1
let srcA:[[Float]] = [[1,2],[3,4]]
let srcB:[[Float]] = [[1,0],[0,1]]
// create tensors for these matrices
let tA = try TF.Tensor.Matrix(srcA)
let tB = try TF.Tensor.Matrix(srcB)
let g = try TF.Graph()
// adding tensors to graph
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")
let M = try g.matMul(l: A, r: B, name: "MatMul")
let C: TF.Operation
if providingDX {
let srcC: [[Float]] = [[1, 1], [1, 1]]
let tC = try TF.Tensor.Matrix(srcC)
C = try g.const(tensor: tC, name: "GradInputs")
} else {
C = try g.OnesLike(inp: M, name: "OnesLike")
}//end if
let M1 = try g.matMul(l: C, r: B, name: "MatMul_1", transposeA: false, transposeB: true)
let M2 = try g.matMul(l: A, r: C, name: "MatMul_2", transposeA: true, transposeB: false)
return (graph: g, dy: [M1.asOutput(0), M2.asOutput(0)])
}
public func addGradients(_ providingDX: Bool, graph: TF.Graph, inputs: [TF.Output], outputs: [TF.Output]) throws -> [TF.Output] {
if providingDX {
let dxArray:[[Float]] = [[1, 1], [1, 1]]
let dxValue = try TF.Tensor.Matrix(dxArray)
let dx = try graph.const(tensor: dxValue, name: "GradInputs").asOutput(0)
return try graph.addGradients(y: outputs, x: inputs, dx: [dx])
} else {
return try graph.addGradients(y: outputs, x: inputs)
}
}
}
func testLabels() {
do {
let img = try LabelImage()
guard let eight = Data.Load("/tmp/testdata/8.jpg") else
{ throw TF.Panic.FAULT(reason: "hand write file 8.jpg not found")}
#if os(Linux)
let x = try img.match(image: eight)
XCTAssertEqual(x, 536)
#else
autoreleasepool(invoking: {
do {
let x = try img.match(image: eight)
XCTAssertEqual(x, 536)
}catch {
XCTFail("label loop: \(error)")
}
})
#endif
}catch {
XCTFail("label: \(error)")
}
}
class LabelImage {
let def: TF.GraphDef
public init(_ modelPath:String = "/tmp/testdata/tensorflow_inception_graph.pb") throws {
guard let bytes = Data.Load(modelPath) else { throw TF.Panic.INVALID }
def = try TF.GraphDef(serializedData: bytes)
}
public func match(image: Data) throws -> Int {
let g = try TF.Graph()
_ = try g.import(definition: def)
let normalized = try constructAndExecuteGraphToNormalizeImage(g, imageBytes: image)
let possibilities = try executeInceptionGraph(g, image: normalized)
#if swift(>=5.0)
guard let m = possibilities.max(), let i = possibilities.firstIndex(of: m) else {
throw TF.Panic.INVALID
}//end guard
#else
guard let m = possibilities.max(), let i = possibilities.index(of: m) else {
throw TF.Panic.INVALID
}//end guard
#endif
return i
}
private func executeInceptionGraph(_ g: TF.Graph, image: TF.Tensor) throws -> [Float] {
let results = try g.runner().feed("input", tensor: image).fetch("output").run()
guard results.count > 0 else { throw TF.Panic.INVALID }
let result = results[0]
guard result.dimensionCount == 2 else { throw TF.Panic.INVALID }
let shape = result.dim
guard shape[0] == 1 else { throw TF.Panic.INVALID }
let res: [Float] = try result.asArray()
return res
}//end exec
public func constructAndExecuteGraphToNormalizeImage(_ g: TF.Graph, imageBytes: Data) throws -> TF.Tensor{
let H:Int32 = 224
let W:Int32 = 224
let mean:Float = 117
let scale:Float = 1
let input = try g.constant(name: "input2", value: imageBytes)
let batch = try g.constant( name: "make_batch", value: Int32(0))
let scale_v = try g.constant(name: "scale", value: scale)
let mean_v = try g.constant(name: "mean", value: mean)
let size = try g.constantArray(name: "size", value: [H,W])
let jpeg = try g.decodeJpeg(content: input, channels: 3)
let cast = try g.cast(value: jpeg, dtype: TF.DataType.dtFloat)
let images = try g.expandDims(input: cast, dim: batch)
let resizes = try g.resizeBilinear(images: images, size: size)
let subbed = try g.sub(x: resizes, y: mean_v)
let output = try g.div(x: subbed, y: scale_v)
let s = try g.runner().fetch(TF.Operation(output)).run()
guard s.count > 0 else { throw TF.Panic.INVALID }
return s[0]
}//end normalize
}
func testBasicImproved() {
do {
/*
Matrix Test:
| 1 2 | |0 1| |0 1|
| |* | |= | |
| 3 4 | |0 0| |0 3|
*/
let tA = try TF.Tensor.Matrix([[1, 2], [3, 4]])
let tB = try TF.Tensor.Matrix([[0, 0], [1, 0]])
let g = try TF.Graph()
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")
let v = try g.matMul(l: A, r: B, name: "v", transposeB: true)
let o = try g.runner().fetch(v).addTarget(v).run()
let m:[Float] = try o[0].asArray()
let r:[Float] = [0, 1, 0, 3]
XCTAssertEqual(m, r)
}catch {
XCTFail("improved: \(error)")
}
}
func testBasicExpress() {
do {
/*
Matrix Test:
| 1 2 | |0 1| |0 1|
| |* | |= | |
| 3 4 | |0 0| |0 3|
*/
let srcA:[Float] = [[1, 2], [3, 4]].flatMap { $0 }
let srcB:[Float] = [[0, 0], [1, 0]].flatMap { $0 }
let tA = try TF.Tensor.Array(dimensions: [2,2], value: srcA)
let tB = try TF.Tensor.Array(dimensions: [2,2], value: srcB)
let tgtA:[Float] = try tA.asArray()
let tgtB:[Float] = try tB.asArray()
XCTAssertEqual(srcA, tgtA)
XCTAssertEqual(srcB, tgtB)
let g = try TF.Graph()
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")
let v = try g.matMul(l: A, r: B, name: "v", transposeB: true)
let o = try g.runner().fetch(v).addTarget(v).run()
let m:[Float] = try o[0].asArray()
let r:[Float] = [0, 1, 0, 3]
XCTAssertEqual(m, r)
}catch {
XCTFail("basic: \(error)")
}
}
func testBasic() {
do {
/*
Matrix Test:
| 1 2 | |0 1| |0 1|
| |* | |= | |
| 3 4 | |0 0| |0 3|
*/
let srcA:[Float] = [1, 2, 3, 4]
let srcB:[Float] = [0, 0, 1, 0]
let tA = try TF.Tensor.Array(dimensions: [2,2], value: srcA)
let tB = try TF.Tensor.Array(dimensions: [2,2], value: srcB)
let tgtA:[Float] = try tA.asArray()
let tgtB:[Float] = try tB.asArray()
XCTAssertEqual(srcA, tgtA)
XCTAssertEqual(srcB, tgtB)
let g = try TF.Graph()
let A = try g.const(tensor: tA, name: "Const_0")
let B = try g.const(tensor: tB, name: "Const_1")
let v = try g.matMul(l: A, r: B, name: "v", transposeB: true)
let sess = try g.newSession()
let o = try sess.run(outputs: [v.output(0)], targets:[v])
let m:[Float] = try o[0].asArray()
let r:[Float] = [0, 1, 0, 3]
XCTAssertEqual(m, r)
}catch {
XCTFail("basic: \(error)")
}
}
func testSessionLeak() {
let hello = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
for _ in 0 ... 100 {
#if os(Linux)
do {
let g = try TF.Graph()
let tensor = try TF.Tensor.Scalar(hello)
let op = try g.const(tensor: tensor, name: "hello")
let o = try g.runner().fetch(op).addTarget(op).run()
let data = o[0].data
let decoded = try TF.Decode(strings: data, count: 1)
let s2 = decoded[0].string
XCTAssertEqual(hello, s2)
}catch {
XCTFail("hello: \(error)")
}
#else
autoreleasepool(invoking: {
do {
let g = try TF.Graph()
let tensor = try TF.Tensor.Scalar(hello)
let op = try g.const(tensor: tensor, name: "hello")
let o = try g.runner().fetch(op).addTarget(op).run()
let data = o[0].data
let decoded = try TF.Decode(strings: data, count: 1)
let s2 = decoded[0].string
XCTAssertEqual(hello, s2)
}catch {
XCTFail("hello: \(error)")
}
})
#endif
}
}
func testHelloExpress() {
do {
let hello = "你好! 完美的 TensorFlow! 🇨🇳🇨🇦"
let g = try TF.Graph()
let tensor = try TF.Tensor.Scalar(hello)
let op = try g.const(tensor: tensor, name: "hello")
let o = try g.runner().fetch(op).addTarget(op).run()
let data = o[0].data
let decoded = try TF.Decode(strings: data, count: 1)
let s2 = decoded[0].string
XCTAssertEqual(hello, s2)
}catch {
XCTFail("hello: \(error)")
}
}
func testHelloWorldUTF8 () {
do {
let hello = "你好! 完美的 TensorFlow! 🇨🇳🇨🇦"
let g = try TF.Graph()
let tensor = try TF.Tensor.Scalar(hello)
let op = try g.const(tensor: tensor, name: "hello")
let s = try g.newSession()
let o = try s.run(outputs: [op.output(0)], targets: [op])
let data = o[0].data
let decoded = try TF.Decode(strings: data, count: 1)
let s2 = decoded[0].string
XCTAssertEqual(hello, s2)
}catch {
XCTFail("hello: \(error)")
}
}
func testHelloWorld () {
do {
let hello = "Hello TensorFlow!"
let g = try TF.Graph()
let tensor = try TF.Tensor.Scalar(hello)
let op = try g.const(tensor: tensor, name: "hello")
let s = try g.newSession()
let o = try s.run(outputs: [op.output(0)], targets: [op])
let data = o[0].data
let decoded = try TF.Decode(strings: data, count: 1)
let s2 = decoded[0].string
XCTAssertEqual(hello, s2)
}catch {
XCTFail("hello: \(error)")
}
}
class CWhileLoopTest {
let status: TF.Status
let graph: TF.Graph
var inputs_ :[TF.Output] = []
var outputs_ :[TF.Output] = []
let params_: TF.GraphWhile
var original_graph_description_ = ""
let session: TF.Session
var output_tensors:[TF.Tensor] = []
public init(ninputs: Int) throws {
status = try TF.Status()
graph = try TF.Graph()
session = try graph.newSession()
guard ninputs > 0 else { throw TF.Panic.INVALID }
for i in 0 ... ninputs - 1 {
let placeholder = try graph.placeholder(name: "p\(i)")
inputs_.append(placeholder.output(0))
}//next
params_ = try TF.GraphWhile(graph: graph, inputs: inputs_)
params_.param.name = UnsafePointer<CChar>(strdup("test_loop"))
original_graph_description_ = self.graphDebugString
}//init
var graphDebugString: String {
guard let def = graph.definition else { return "" }
return def.debugDescription
}
func expectOK() -> Bool {
do {
outputs_ = try params_.finish()
return true
}catch {
return false
}
}
func expectError(msg: String) -> Bool {
do {
_ = try params_.finish()
return false
} catch TF.Panic.FAULT(reason: let rs) {
return msg == rs
} catch {
return false
}
}
func run(input_values: [Int]) {
do {
XCTAssertEqual(inputs_.count, input_values.count)
var inputs:[(TF.Output, TF.Tensor)] = []
for i in 0 ... inputs_.count - 1 {
let op = TF.Operation(inputs_[i].oper)
let tensor = try TF.Tensor.Scalar(Int32(input_values[i]))
inputs.append((op.output(0), tensor))
}//next
output_tensors = try session.run(inputs: inputs, outputs: outputs_)
}catch {
XCTFail("CWhileLoopTest:\(error)")
}
}//end fun
func expectOutput(idx: Int, value: Int) -> Bool {
do {
XCTAssertGreaterThan(idx, -1)
XCTAssertGreaterThan(output_tensors.count, idx)
let tensor = output_tensors[idx]
XCTAssertEqual(tensor.type ?? TF.DataType.dtInvalid, TF.DataType.dtInt32)
XCTAssertEqual(tensor.dimensionCount, 0)
XCTAssertEqual(MemoryLayout<Int32>.size, tensor.bytesCount)
let array: [Int32] = try tensor.asArray()
XCTAssertEqual(array[0], Int32(value))
return true
}catch {
XCTFail("CWhileLoopTest:\(error)")
return false
}
}
func createConGraph() {
do {
let one = try TF.Graph(handle: params_.param.cond_graph).scalar(1)
let less_than = try self.graph.lessThan(left: params_.param.cond_inputs.pointee, right: one.output(0))
params_.param.cond_output = less_than.output(0)
}catch {
XCTFail("CWhileLoopTest:\(error)")
}
}
}
func testBasicLoop() {
do {
let loop = try CWhileLoopTest(ninputs: 2)
XCTAssertNotNil(loop.params_.param.body_graph)
XCTAssertNotNil(loop.params_.param.cond_graph)
XCTAssertEqual(2, loop.params_.param.ninputs)
XCTAssertNotNil(loop.params_.param.cond_inputs)
XCTAssertNotNil(loop.params_.param.cond_inputs.advanced(by: 0))
XCTAssertNotNil(loop.params_.param.cond_inputs.advanced(by: 1))
XCTAssertNotNil(loop.params_.param.body_outputs)
let cond_graph = TF.Graph(handle: loop.params_.param.cond_graph)
let body_graph = TF.Graph(handle: loop.params_.param.body_graph)
let less_than = try cond_graph.lessThan(left: loop.params_.param.cond_inputs.advanced(by: 0).pointee, right: loop.params_.param.cond_inputs.advanced(by: 1).pointee)
loop.params_.param.cond_output = less_than.output(0)
let add1 = try body_graph.add(left: loop.params_.param.body_inputs.pointee, right: loop.params_.param.body_inputs.advanced(by: 1).pointee, name: "add1")
let one = try body_graph.scalar(1)
let add2 = try body_graph.add(left: add1, right: one, name: "add2")
loop.params_.param.body_outputs.pointee = add2.output(0)
loop.params_.param.body_outputs.advanced(by: 1).pointee = loop.params_.param.body_inputs.advanced(by: 1).pointee
XCTAssertTrue(loop.expectOK())
let o = loop.outputs_
let o0 = o[0]
let o1 = o[1]
XCTAssertNotNil(o0.oper)
XCTAssertGreaterThanOrEqual(o0.index, 0)
XCTAssertNotNil(o1.oper)
XCTAssertGreaterThanOrEqual(o1.index, 0)
loop.run(input_values: [-9,2])
XCTAssertTrue(loop.expectOutput(idx: 0, value: 3))
XCTAssertTrue(loop.expectOutput(idx: 1, value: 2))
}catch {
XCTFail("basic loop: \(error)")
}
}
class AttrTest {
public init(_ dataType: TF.DataType, value: Any) {
do {
let graph = try TF.Graph()
let builder = try graph.opBuilder(name: "feed", type: "Placehodler")
_ = try builder.set(attributes: ["attr": value, "dtype": dataType])
}catch{
XCTFail("attributes (\(value)): \(error)")
}
}
}
func testAttributes () {
_ = AttrTest(TF.DataType.dtInt64, value: Int64(0))
_ = AttrTest(TF.DataType.dtInt64, value: [Int64(0), Int64(1)])
_ = AttrTest(TF.DataType.dtFloat, value: 1.1)
_ = AttrTest(TF.DataType.dtFloat, value: [1.1, 2.2])
_ = AttrTest(TF.DataType.dtBool, value: true)
_ = AttrTest(TF.DataType.dtBool, value: [true, false])
_ = AttrTest(TF.DataType.dtString, value: "hello")
_ = AttrTest(TF.DataType.dtString, value: ["hello", "world"])
}//end func
func testSavedModel () {
do {
let graph = try TF.Graph()
let metaBuf = try TF.Buffer()
let runner = try graph.load(exportDir: "/tmp/testdata/half_plus_two/00000123", tags: [SavedModel.kSavedModelTagServe], metaGraphDef: metaBuf)
guard let data = metaBuf.data else {
XCTFail("saved model: no data")
return
}
let meta = try TF.MetaGraphDef(serializedData: data)
guard let signature_def = meta.signatureDef["regress_x_to_y"] else {
XCTFail("saved model: bad signature")
return
}
guard
let input_name = signature_def.inputs[SavedModel.kRegressInputs]?.name,
let output_name = signature_def.outputs[SavedModel.kRegressOutputs]?.name
else {
XCTFail("saved model: bad signature name")
return
}
XCTAssertEqual(input_name, "tf_example:0")
XCTAssertEqual(output_name, "y:0")
var dataArray = [Data]()
for i in 0 ... 3 {
var example = Tensorflow_Example()
var fList = Tensorflow_FloatList()
fList.value.append(Float(i))
var feature = Tensorflow_Feature()
feature.floatList = fList
example.features.feature["x"] = feature
let dat = try example.serializedData()
dataArray.append(dat)
}//next
let input_op = try graph.searchOperation(forName: "tf_example").output(0)
let input_op_value = try TF.Tensor.Array(dimensions: [Int64(4)], value: dataArray)
let output_op = try graph.searchOperation(forName: "y").output(0)
let outArray = try runner
.feed(input_op, tensor: input_op_value)
.fetch(output_op)
.run()
XCTAssertGreaterThan(outArray.count, 0)
let out = outArray[0]
XCTAssertEqual(out.type ?? TF.DataType.dtInvalid, TF.DataType.dtFloat)
XCTAssertEqual(2, out.dimensionCount)
XCTAssertEqual(4, try out.dimension(0))
XCTAssertEqual(1, try out.dimension(1))
let value:[Float] = try out.asArray()
let expected : [Float] = [2, 2.5, 3, 3.5]
XCTAssertEqual(value, expected)
}catch {
XCTFail("saved model: \(error)")
}
}
func testShapeInference() {
do {
let graph = try TF.Graph()
let vec2Tensor = try TF.Tensor.Array(dimensions: [Int64(2)], value: [Int8(1), Int8(2)])
let vec3Tensor = try TF.Tensor.Array(dimensions: [Int64(3)], value: [Int8(1), Int8(2), Int8(3)])
let vec2 = try graph.const(tensor: vec2Tensor, name: "vec2")
let vec3 = try graph.const(tensor: vec3Tensor, name: "vec3")
let x = try graph.add(left: vec2, right: vec3)
XCTAssertNil(x)
}catch {
XCTAssertNotNil(error)
}
}//end test
func testPSession() {
do {
let graph = try TF.Graph()
let a = try graph.placeholder(name: "A")
let b = try graph.placeholder(name: "B")
let two = try graph.scalar(2)
let plus2 = try graph.add(left: a, right: two, name: "plus2")
let plusB = try graph.add(left: plus2, right: b, name: "plusB")
let sess = try graph.newSession()
let feeds = [a.output(0), b.output(0)]
let fetches = [plus2.output(0), plusB.output(0)]
let handle = try sess.partial(inputs: feeds, outputs: fetches)
let oneTensor = try TF.Tensor.Scalar(Int32(1))
let feeds1 = [(input: a.output(0), tensor: oneTensor)]
let fetches1 = [ plus2.output(0)]
let fetchValues1 = try handle.run(inputs: feeds1, outputs: fetches1)
let out1Value: Int32 = try fetchValues1[0].asArray()[0]
XCTAssertEqual(3, out1Value)
let fourTensor = try TF.Tensor.Scalar(Int32(4))
let feeds2 = [(input: b.output(0), tensor: fourTensor)]
let fetches2 = [plusB.output(0)]
let fetchValues2 = try handle.run(inputs: feeds2, outputs: fetches2)
let out2Value: Int32 = try fetchValues2[0].asArray()[0]
XCTAssertEqual(7, out2Value)
}catch {
XCTFail("partial: \(error)")
}
}
func testSessionExpress() {
do {
let graph = try TF.Graph()
let feed = try graph.placeholder()
let two = try graph.scalar(2)
let add = try graph.add(left: feed, right: two)
let threeTensor = try TF.Tensor.Scalar(Int32(3))
let outs = try graph.runner().feed(feed, tensor: threeTensor).fetch(add).run()
XCTAssertFalse(outs.isEmpty)
let out = outs[0]
XCTAssertEqual(out.type ?? TF.DataType.dtInvalid, TF.DataType.dtInt32)
XCTAssertEqual(0, out.dimensionCount)
XCTAssertEqual(MemoryLayout<Int32>.size, out.bytesCount)
let outValue:Int32 = try out.asArray()[0]
XCTAssertEqual(3 + 2, outValue)
let neg = try graph.neg(add)
let sevenTensor = try TF.Tensor.Scalar(Int32(7))
let outs2 = try graph.runner().feed(feed, tensor: sevenTensor).fetch(neg).run()
let out2 = outs2[0]
XCTAssertEqual(out2.type ?? TF.DataType.dtInvalid, TF.DataType.dtInt32)
XCTAssertEqual(0, out2.dimensionCount)
XCTAssertEqual(MemoryLayout<Int32>.size, out.bytesCount)
let outValue2:Int32 = try out2.asArray()[0]
XCTAssertEqual(-(7 + 2), outValue2)
}catch {
XCTFail("session express: \(error)")
}
}
func testSession() {
do {
let graph = try TF.Graph()
let feed = try graph.placeholder()
let two = try graph.scalar(2)
let add = try graph.add(left: feed, right: two)
let s = try graph.newSession()
let threeTensor = try TF.Tensor.Scalar(Int32(3))
let outs = try s.run(
inputs: [(input: feed.output(0), tensor:threeTensor)],
outputs: [add.output(0)])
XCTAssertFalse(outs.isEmpty)
let out = outs[0]
XCTAssertEqual(out.type ?? TF.DataType.dtInvalid, TF.DataType.dtInt32)
XCTAssertEqual(0, out.dimensionCount)
XCTAssertEqual(MemoryLayout<Int32>.size, out.bytesCount)
let outValue:Int32 = try out.asArray()[0]
XCTAssertEqual(3 + 2, outValue)
let neg = try graph.neg(add)
let sevenTensor = try TF.Tensor.Scalar(Int32(7))
let outs2 = try s.run(inputs: [(input: feed.output(0), tensor: sevenTensor)], outputs: [neg.output(0)])