-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathforward_mode_simple.swift
1403 lines (1223 loc) · 39.1 KB
/
forward_mode_simple.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
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-forward-mode-differentiation)
// REQUIRES: executable_test
import StdlibUnittest
import DifferentiationUnittest
var ForwardModeTests = TestSuite("ForwardModeDifferentiation")
//===----------------------------------------------------------------------===//
// Basic tests.
//===----------------------------------------------------------------------===//
ForwardModeTests.test("Identity") {
func func_to_diff(x: Float) -> Float {
return x
}
let (y, differential) = valueWithDifferential(at: 4, of: func_to_diff)
expectEqual(4, y)
expectEqual(1, differential(1))
}
ForwardModeTests.test("Unary") {
func func_to_diff(x: Float) -> Float {
return x * x
}
let (y, differential) = valueWithDifferential(at: 4, of: func_to_diff)
expectEqual(16, y)
expectEqual(8, differential(1))
}
ForwardModeTests.test("Binary") {
func func_to_diff(x: Float, y: Float) -> Float {
return x * y
}
let (y, differential) = valueWithDifferential(at: 4, 5, of: func_to_diff)
expectEqual(20, y)
expectEqual(9, differential(1, 1))
}
ForwardModeTests.test("BinaryWithLets") {
func func_to_diff(x: Float, y: Float) -> Float {
let a = x + y
let b = a
return b * -y
}
let (y, differential) = valueWithDifferential(at: 4, 5, of: func_to_diff)
expectEqual(-45, y)
expectEqual(-19, differential(1, 1))
}
ForwardModeTests.test("SubsetParametersDiff") {
func func_to_diff1(x: Int, y: Float, z: Int) -> Float {
return y
}
let (y1, differential1) = valueWithDifferential(at: 5) { y in
func_to_diff1(x: 0, y: y, z: 0)
}
expectEqual(5, y1)
expectEqual(1, differential1(1))
func func_to_diff2(x: Float, y: Int, z: Int) -> Float {
return 2 * x
}
let (y2, differential2) = valueWithDifferential(at: 6) { x in
func_to_diff2(x: x, y: 0, z: 0)
}
expectEqual(12, y2)
expectEqual(2, differential2(1))
func func_to_diff3(x: Int, y: Int, z: Float) -> Float {
return 3 * z
}
let (y3, differential3) = valueWithDifferential(at: 7) { z in
func_to_diff3(x: 0, y: 0, z: z)
}
expectEqual(21, y3)
expectEqual(3, differential3(1))
}
//===----------------------------------------------------------------------===//
// Functions with variables
//===----------------------------------------------------------------------===//
ForwardModeTests.test("UnaryWithVars") {
func unary(x: Float) -> Float {
var a = x
a = x
var b = a + 2
b = b - 1
let c: Float = 3
var d = a + b + c - 1
d = d + d
return d
}
let (y, differential) = valueWithDifferential(at: 4, of: unary)
expectEqual(22, y)
expectEqual(4, differential(1))
}
//===----------------------------------------------------------------------===//
// Functions with basic struct
//===----------------------------------------------------------------------===//
struct A: Differentiable & AdditiveArithmetic {
var x: Float
}
ForwardModeTests.test("StructInit") {
func structInit(x: Float) -> A {
return A(x: 2 * x)
}
let (y, differential) = valueWithDifferential(at: 4, of: structInit)
expectEqual(A(x: 8), y)
expectEqual(A(x: 2), differential(1))
}
ForwardModeTests.test("StructExtract") {
func structExtract(x: A) -> Float {
return 2 * x.x
}
let (y, differential) = valueWithDifferential(
at: A(x: 4),
of: structExtract)
expectEqual(8, y)
expectEqual(2, differential(A(x: 1)))
}
ForwardModeTests.test("LocalStructVariable") {
func structExtract(x: A) -> A {
let a = A(x: 2 * x.x) // 2x
var b = A(x: a.x + 2) // 2x + 2
b = A(x: b.x + a.x) // 2x + 2 + 2x = 4x + 2
return b
}
let (y, differential) = valueWithDifferential(
at: A(x: 4),
of: structExtract)
expectEqual(A(x: 18), y)
expectEqual(A(x: 4), differential(A(x: 1)))
}
//===----------------------------------------------------------------------===//
// Functions with methods
//===----------------------------------------------------------------------===//
extension A {
func noParamMethodA() -> A {
return A(x: 2 * x)
}
func noParamMethodx() -> Float {
return 2 * x
}
static func *(lhs: A, rhs: A) -> A {
return A(x: lhs.x * rhs.x)
}
func complexBinaryMethod(u: A, v: Float) -> A {
var b: A = u * A(x: 2) // A(x: u * 2)
b.x = b.x * v // A(x: u * 2 * v)
let c = b.x + 1 // u * 2 * v + 1
// A(x: u * 2 * v + 1 + u * 2 * v) = A(x: x * (4uv + 1))
return A(x: x * (c + b.x))
}
}
ForwardModeTests.test("noParamMethodA") {
let (y, differential) = valueWithDifferential(at: A(x: 4)) { x in
x.noParamMethodA()
}
expectEqual(A(x: 8), y)
expectEqual(A(x: 2), differential(A(x: 1)))
}
ForwardModeTests.test("noParamMethodx") {
let (y, differential) = valueWithDifferential(at: A(x: 4)) { x in
x.noParamMethodx()
}
expectEqual(8, y)
expectEqual(2, differential(A(x: 1)))
}
ForwardModeTests.test("complexBinaryMethod") {
let (y, differential) = valueWithDifferential(at: A(x: 4), A(x: 5), 3) {
(x, y, z) in
// derivative = A(x: 4uv + 4xv + 4ux + 1) = 4*5*3 + 4*4*3 + 4*5*4 + 1 = 189
x.complexBinaryMethod(u: y, v: z)
}
expectEqual(A(x: 244), y)
expectEqual(A(x: 189), differential(A(x: 1), A(x: 1), 1))
}
//===----------------------------------------------------------------------===//
// Tracked struct
//===----------------------------------------------------------------------===//
ForwardModeTests.testWithLeakChecking("TrackedIdentity") {
func identity(x: Tracked<Float>) -> Tracked<Float> {
return x
}
let (y, differential) = valueWithDifferential(at: 4, of: identity)
expectEqual(4, y)
expectEqual(1, differential(1))
}
ForwardModeTests.testWithLeakChecking("TrackedAddition") {
func add(x: Tracked<Float>, y: Tracked<Float>) -> Tracked<Float> {
return x + y
}
let (y, differential) = valueWithDifferential(at: 4, 5, of: add)
expectEqual(9, y)
expectEqual(2, differential(1, 1))
}
ForwardModeTests.testWithLeakChecking("TrackedDivision") {
func divide(x: Tracked<Float>, y: Tracked<Float>) -> Tracked<Float> {
return x / y
}
let (y, differential) = valueWithDifferential(at: 10, 5, of: divide)
expectEqual(2, y)
expectEqual(-0.2, differential(1, 1))
}
ForwardModeTests.testWithLeakChecking("TrackedMultipleMultiplication") {
func add(x: Tracked<Float>, y: Tracked<Float>) -> Tracked<Float> {
return x * y * x
}
let (y, differential) = valueWithDifferential(at: 4, 5, of: add)
expectEqual(80, y)
// 2yx+xx
expectEqual(56, differential(1, 1))
}
ForwardModeTests.testWithLeakChecking("TrackedWithLets") {
func add(x: Tracked<Float>, y: Tracked<Float>) -> Tracked<Float> {
let a = x + y
let b = a * a // (x+y)^2
let c = b / x + y // (x+y)^2/x+y
return c
}
// (3x^2+2xy-y^2)/x^2+1
let (y, differential) = valueWithDifferential(at: 4, 5, of: add)
expectEqual(25.25, y)
expectEqual(4.9375, differential(1, 1))
}
//===----------------------------------------------------------------------===//
// Tuples
//===----------------------------------------------------------------------===//
ForwardModeTests.test("TupleLet") {
do {
func tupleLet(_ x: Float) -> Float {
let tuple = (2 * x, x)
return tuple.0
}
let (value, derivative) = valueWithDerivative(at: 4, of: tupleLet)
expectEqual(8, value)
expectEqual(2, derivative)
}
}
ForwardModeTests.test("TupleVar") {
do {
func tupleVar(_ x: Float) -> Float {
var tuple = (2 * x, x)
return tuple.0
}
let (value, derivative) = valueWithDerivative(at: 4, of: tupleVar)
expectEqual(8, value)
expectEqual(2, derivative)
}
do {
// TF-964: Test tuple with non-tuple-typed adjoint value.
func TF_964(_ x: Float) -> Float {
var tuple = (2 * x, 1)
return tuple.0
}
let (value, derivative) = valueWithDerivative(at: 4, of: TF_964)
expectEqual(8, value)
expectEqual(2, derivative)
}
}
ForwardModeTests.test("TupleMutation") {
func foo(_ x: Float) -> Float {
var tuple = (x, x)
tuple.0 = tuple.0 * x
return x * tuple.0
}
expectEqual(27, derivative(at: 3, of: foo))
func fifthPower(_ x: Float) -> Float {
var tuple = (x, x)
tuple.0 = tuple.0 * x
tuple.1 = tuple.0 * x
return tuple.0 * tuple.1
}
expectEqual(405, derivative(at: 3, of: fifthPower))
func nested(_ x: Float) -> Float {
var tuple = ((x, x), x)
tuple.0.0 = tuple.0.0 * x
tuple.0.1 = tuple.0.0 * x
return tuple.0.0 * tuple.0.1
}
expectEqual(405, derivative(at: 3, of: nested))
func generic<T: Differentiable & AdditiveArithmetic>(_ x: T) -> T {
var tuple = (x, x)
return tuple.0
}
expectEqual(1, derivative(at: 3.0, of: generic))
// FIXME(TF-1033): Fix forward-mode ownership error for tuple with non-active
// initial values.
/*
func genericInitialNonactive<T: Differentiable & AdditiveArithmetic>(
_ x: T
) -> T {
var tuple = (T.zero, T.zero)
tuple.0 = x
tuple.1 = x
return tuple.0
}
expectEqual(1, derivative(at: 3.0, of: genericInitialNonactive))
*/
}
// Tests TF-321.
ForwardModeTests.test("TupleNonDifferentiableElements") {
// TF-964: Test tuple with non-tuple-typed adjoint value.
func tupleLet(_ x: Tracked<Float>) -> Tracked<Float> {
let tuple = (2 * x, 1)
return tuple.0
}
expectEqual((8, 2), valueWithDerivative(at: 4, of: tupleLet))
func tupleVar(_ x: Tracked<Float>) -> Tracked<Float> {
var tuple = (x, 1)
tuple.0 = x
tuple.1 = 1
return tuple.0
}
expectEqual((3, 1), valueWithDerivative(at: 3, of: tupleVar))
@differentiable(reverse)
func nested(_ x: Tracked<Float>) -> Tracked<Float> {
// Convoluted function computing `x * x`.
var tuple: (Int, (Int, Tracked<Float>), Tracked<Float>) = (1, (1, 0), 0)
tuple.0 = 1
tuple.1.0 = 1
tuple.1.1 = x
tuple.2 = x
return tuple.1.1 * tuple.2
}
// FIXME(SR-12911): Fix runtime segfault.
// expectEqual((16, 8), valueWithDerivative(at: 4, of: nested))
struct Wrapper<T> {
@differentiable(reverse where T : Differentiable)
func baz(_ x: T) -> T {
var tuple = (1, 1, x, 1)
tuple.0 = 1
tuple.2 = x
tuple.3 = 1
return tuple.2
}
}
func wrapper(_ x: Tracked<Float>) -> Tracked<Float> {
let w = Wrapper<Tracked<Float>>()
return w.baz(x)
}
expectEqual((3, 1), valueWithDerivative(at: 3, of: wrapper))
}
//===----------------------------------------------------------------------===//
// Generics
//===----------------------------------------------------------------------===//
struct Tensor<Scalar : FloatingPoint & Differentiable>
: AdditiveArithmetic, Differentiable {
// NOTE: `value` must have type with known size (e.g. `Float`, not `Scalar`)
// until differentiation has indirect passing support.
var value: Float
init(_ value: Float) { self.value = value }
}
ForwardModeTests.test("GenericIdentity") {
func identity<T : Differentiable>(_ x: T) -> T {
return x
}
let (y, differential) = valueWithDifferential(at: 4) { (x: Float) in
identity(x)
}
expectEqual(4, y)
expectEqual(1, differential(1))
}
ForwardModeTests.test("GenericTensorIdentity") {
func identity<T : FloatingPoint & Differentiable>(
_ x: Tensor<T>) -> Tensor<T> {
return x
}
let (y, differential) = valueWithDifferential(at: 4) { (x: Float) in
identity(Tensor<Float>(x))
}
expectEqual(Tensor<Float>(4), y)
expectEqual(Tensor<Float>(1), differential(1))
}
ForwardModeTests.test("GenericTensorPlus") {
func plus<T : FloatingPoint & Differentiable>(_ x: Tensor<T>) -> Float {
return x.value + x.value
}
let (y, differential) = valueWithDifferential(at: 4) { (x: Float) in
plus(Tensor<Float>(x))
}
expectEqual(8, y)
expectEqual(2, differential(1))
}
ForwardModeTests.test("GenericTensorBinaryInput") {
func binary<T : FloatingPoint & Differentiable>(
_ x: Tensor<T>, _ y: Tensor<T>) -> Float {
return x.value * y.value
}
let (y, differential) = valueWithDifferential(at: 4, 5) {
(x: Float, y: Float) in
binary(Tensor<Float>(x), Tensor<Float>(y))
}
expectEqual(20, y)
expectEqual(9, differential(1, 1))
}
ForwardModeTests.test("GenericTensorWithLets") {
func binary<T : FloatingPoint & Differentiable>(
_ x: Tensor<T>, _ y: Tensor<T>) -> Float {
let a = Tensor<T>(x.value)
let b = Tensor<T>(y.value)
return a.value * b.value
}
let (y, differential) = valueWithDifferential(at: 4, 5) {
(x: Float, y: Float) in
binary(Tensor<Float>(x), Tensor<Float>(y))
}
expectEqual(20, y)
expectEqual(9, differential(1, 1))
}
ForwardModeTests.test("GenericTensorWithVars") {
func binary<T : FloatingPoint & Differentiable>(
_ x: Tensor<T>, _ y: Tensor<T>) -> Float {
var a = Tensor<T>(x.value)
var b = Tensor<T>(y.value)
b = a
a = Tensor<T>(y.value)
return a.value * b.value
}
let (y, differential) = valueWithDifferential(at: 4, 5) {
(x: Float, y: Float) in
binary(Tensor<Float>(x), Tensor<Float>(y))
}
expectEqual(20, y)
expectEqual(9, differential(1, 1))
}
// Test case where associated derivative function's requirements are met.
extension Tensor where Scalar : Numeric {
@differentiable(reverse, wrt: self where Scalar : Differentiable & FloatingPoint)
func mean() -> Tensor {
return self
}
@differentiable(reverse, wrt: self where Scalar : Differentiable & FloatingPoint)
func variance() -> Tensor {
return mean() // ok
}
}
_ = differential(at: Tensor<Float>(1), of: { $0.variance() })
// Tests TF-508: differentiation requirements with dependent member types.
protocol TF_508_Proto {
associatedtype Scalar
}
extension TF_508_Proto where Scalar : FloatingPoint {
@differentiable(
where Self : Differentiable, Scalar : Differentiable,
// Conformance requirement with dependent member type.
Self.TangentVector : TF_508_Proto
)
static func +(lhs: Self, rhs: Self) -> Self {
return lhs
}
@differentiable(
where Self : Differentiable, Scalar : Differentiable,
// Same-type requirement with dependent member type.
Self.TangentVector == Float
)
static func -(lhs: Self, rhs: Self) -> Self {
return lhs
}
}
extension TF_508_Proto where Self : Differentiable,
Scalar : FloatingPoint & Differentiable,
Self.TangentVector : TF_508_Proto {
@derivative(of: +)
static func jvpAdd(lhs: Self, rhs: Self)
-> (value: Self, differential: (TangentVector, TangentVector) -> TangentVector) {
return (lhs, { (dlhs, drhs) in dlhs })
}
}
extension TF_508_Proto where Self : Differentiable,
Scalar : FloatingPoint & Differentiable,
Self.TangentVector == Float {
@derivative(of: -)
static func jvpSubtract(lhs: Self, rhs: Self)
-> (value: Self, differential: (TangentVector, TangentVector) -> TangentVector) {
return (lhs, { (dlhs, drhs) in dlhs })
}
}
struct TF_508_Struct<Scalar : AdditiveArithmetic>
: TF_508_Proto, AdditiveArithmetic {}
extension TF_508_Struct : Differentiable where Scalar : Differentiable {
typealias TangentVector = TF_508_Struct
}
// func TF_508() {
// let x = TF_508_Struct<Float>()
// // Test conformance requirement with dependent member type.
// _ = differential(at: x, of: {
// (x: TF_508_Struct<Float>) -> TF_508_Struct<Float> in
// return x + x
// })
// // Test same-type requirement with dependent member type.
// _ = differential(at: x, of: {
// (x: TF_508_Struct<Float>) -> TF_508_Struct<Float> in
// return x - x
// })
// }
// TF-523
struct TF_523_Struct : Differentiable & AdditiveArithmetic {
var a: Float = 1
typealias TangentVector = TF_523_Struct
typealias AllDifferentiableVariables = TF_523_Struct
}
@differentiable(reverse)
func TF_523_f(_ x: TF_523_Struct) -> Float {
return x.a * 2
}
// TF-534: Thunk substitution map remapping.
protocol TF_534_Layer : Differentiable {
associatedtype Input : Differentiable
associatedtype Output : Differentiable
@differentiable(reverse)
func callAsFunction(_ input: Input) -> Output
}
struct TF_534_Tensor<Scalar> : Differentiable {}
func TF_534<Model: TF_534_Layer>(
_ model: inout Model, inputs: Model.Input
) -> TF_534_Tensor<Float> where Model.Output == TF_534_Tensor<Float> {
return valueWithDifferential(at: model) { model -> Model.Output in
return model(inputs)
}.0
}
// TODO: uncomment once control flow is supported in forward mode.
// TF-652: Test VJPEmitter substitution map generic signature.
// The substitution map should have the VJP's generic signature, not the
// original function's.
// struct TF_652<Scalar> {}
// extension TF_652 : Differentiable where Scalar : FloatingPoint {}
// @differentiable(reverse, wrt: x where Scalar: FloatingPoint)
// func test<Scalar: Numeric>(x: TF_652<Scalar>) -> TF_652<Scalar> {
// for _ in 0..<10 {
// let _ = x
// }
// return x
// }
//===----------------------------------------------------------------------===//
// Tracked Generic.
//===----------------------------------------------------------------------===//
ForwardModeTests.test("GenericTrackedIdentity") {
func identity<T : Differentiable>(_ x: Tracked<T>) -> Tracked<T> {
return x
}
let (y, differential) = valueWithDifferential(at: 4) { (x: Float) in
identity(Tracked(x))
}
expectEqual(4, y)
expectEqual(1, differential(1))
}
ForwardModeTests.test("GenericTrackedBinaryAdd") {
func add<T>(_ x: Tracked<T>, _ y: Tracked<T>) -> Tracked<T>
where T: Differentiable, T == T.TangentVector {
return x + y
}
let (y, differential) = valueWithDifferential(at: 4, 5) {
(x: Float, y: Float) in
add(Tracked(x), Tracked(y))
}
expectEqual(9, y)
expectEqual(2, differential(1, 1))
}
ForwardModeTests.test("GenericTrackedBinaryLets") {
func add<T>(_ x: Tracked<T>, _ y: Tracked<T>) -> Tracked<T>
where T: Differentiable & SignedNumeric,
T == T.TangentVector,
T == T.Magnitude {
let a = x * y // xy
let b = a + a // 2xy
return b + b // 4xy
}
// 4y + 4x
let (y, differential) = valueWithDifferential(at: 4, 5) { (x: Float, y: Float) in
add(Tracked(x), Tracked(y))
}
expectEqual(80, y)
expectEqual(36, differential(1, 1))
}
ForwardModeTests.test("GenericTrackedBinaryVars") {
func add<T>(_ x: Tracked<T>, _ y: Tracked<T>) -> Tracked<T>
where T: Differentiable & SignedNumeric,
T == T.TangentVector,
T == T.Magnitude {
var a = x * y // xy
a = a + a // 2xy
var b = x
b = a
return b + b // 4xy
}
// 4y + 4x
let (y, differential) = valueWithDifferential(at: 4, 5) { (x: Float, y: Float) in
add(Tracked(x), Tracked(y))
}
expectEqual(80, y)
expectEqual(36, differential(1, 1))
}
ForwardModeTests.testWithLeakChecking("TrackedDifferentiableFuncType") {
func valAndDeriv(
f: @escaping @differentiable(reverse) (Tracked<Float>) -> Tracked<Float>
) -> (Tracked<Float>, Tracked<Float>) {
let (y, diff) = valueWithDifferential(at: 5, of: f)
return (y, diff(1))
}
func func1(_ x: Tracked<Float>) -> Tracked<Float> {
let a = x + x // 2x
let b = a + a // 4x
return b * b // 16x^2
}
let (val1, dv1) = valAndDeriv(f: func1)
expectEqual(400, val1)
expectEqual(160, dv1)
}
//===----------------------------------------------------------------------===//
// Classes
//===----------------------------------------------------------------------===//
ForwardModeTests.test("Final") {
final class Final : Differentiable {
func method(_ x: Float) -> Float {
return x * x
}
}
for i in -5...5 {
expectEqual(
Float(i) * 2,
derivative(at: Float(i)) { x in Final().method(x) })
}
}
ForwardModeTests.test("Simple") {
class Super {
@differentiable(reverse, wrt: x)
func f(_ x: Float) -> Float {
return 2 * x
}
@derivative(of: f)
final func jvpf(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (f(x), { v in 2 * v })
}
@derivative(of: f)
final func vjpf(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (f(x), { v in 2 * v })
}
}
class SubOverride : Super {
@differentiable(reverse, wrt: x)
override func f(_ x: Float) -> Float {
return 3 * x
}
}
class SubOverrideCustomDerivatives : Super {
@differentiable(reverse, wrt: x)
override func f(_ x: Float) -> Float {
return 3 * x
}
@derivative(of: f)
final func jvpf2(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (f(x), { v in 3 * v })
}
@derivative(of: f)
final func vjpf2(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (f(x), { v in 3 * v })
}
}
func classValueWithDerivative(_ c: Super) -> (Float, Float) {
return valueWithDerivative(at: 1) { c.f($0) }
}
expectEqual((2, 2), classValueWithDerivative(Super()))
expectEqual((3, 3), classValueWithDerivative(SubOverride()))
expectEqual((3, 3), classValueWithDerivative(SubOverrideCustomDerivatives()))
}
ForwardModeTests.test("SimpleWrtSelf") {
class Super : Differentiable {
var base: Float
// FIXME(TF-648): Dummy to make `Super.AllDifferentiableVariables` be nontrivial.
var _nontrivial: [Float] = []
// FIXME(SR-12175): Fix forward-mode differentiation tangent buffer crash.
// @differentiable(reverse)
required init(base: Float) {
self.base = base
}
@differentiable(reverse, wrt: (self, x))
func f(_ x: Float) -> Float {
return base * x
}
@derivative(of: f)
final func jvpf(_ x: Float) -> (value: Float, differential: (TangentVector, Float) -> Float) {
return (f(x), { (dself, dx) in dself.base * dx })
}
@derivative(of: f)
final func vjpf(_ x: Float) -> (value: Float, pullback: (Float) -> (TangentVector, Float)) {
let base = self.base
return (f(x), { v in
(TangentVector(base: v * x, _nontrivial: []), base * v)
})
}
}
class SubOverride : Super {
@differentiable(reverse, wrt: (self, x))
override func f(_ x: Float) -> Float {
return 3 * x
}
}
class SubOverrideCustomDerivatives : Super {
@differentiable(reverse, wrt: (self, x))
@differentiable(reverse, wrt: x)
override func f(_ x: Float) -> Float {
return 3 * x
}
@derivative(of: f, wrt: x)
final func jvpf2(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (f(x), { v in 3 * v })
}
@derivative(of: f, wrt: x)
final func vjpf2(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (f(x), { v in 3 * v })
}
}
// FIXME(SR-12175): Fix forward-mode differentiation tangent buffer crash.
// let v = Super.TangentVector(base: 100, _nontrivial: [])
// expectEqual(100, pullback(at: 1337) { x in Super(base: x) }(v))
// expectEqual(100, pullback(at: 1337) { x in SubOverride(base: x) }(v))
// expectEqual(100, pullback(at: 1337) { x in SubOverrideCustomDerivatives(base: x) }(v))
// `valueWithDerivative` is not used because the derivative requires `Super`
// to conform to `FloatingPoint`.
func classDifferential(
_ c: Super
) -> (Float, (Super.TangentVector, Float) -> Float) {
return valueWithDifferential(at: c, 10) { (c: Super, x: Float) in c.f(x) }
}
let (y1, diff1) = classDifferential(Super(base: 5))
expectEqual(50, y1)
let c1 = Super.TangentVector(base: 1, _nontrivial: [])
expectEqual(1, diff1(c1, 1))
let (y2, diff2) = classDifferential(SubOverride(base: 5))
expectEqual(30, y2)
let c2 = SubOverride.TangentVector(base: 1, _nontrivial: [])
expectEqual(3, diff2(c2, 1))
let (y3, diff3) = classDifferential(SubOverrideCustomDerivatives(base: 5))
expectEqual(30, y3)
let c3 = SubOverrideCustomDerivatives.TangentVector(base: 1, _nontrivial: [])
expectEqual(3, diff3(c3, 1))
}
//===----------------------------------------------------------------------===//
// Protocols
//===----------------------------------------------------------------------===//
protocol Prot : Differentiable {
@differentiable(reverse, wrt: x)
func foo(x: Float) -> Float
}
ForwardModeTests.test("Simple Protocol") {
struct Linear: Prot, AdditiveArithmetic {
typealias TangentVector = Linear
let m: Float
let b: Float
@differentiable(reverse, wrt: x)
func foo(x: Float) -> Float {
return m * x + b
}
}
func genericFoo<T: Prot>(_ t: T, _ x: Float) -> Float {
t.foo(x: x)
}
let inst = Linear(m: 5, b: -2)
let (y1, diff1) = valueWithDifferential(at: 5) { x in genericFoo(inst, x) }
expectEqual(23, y1)
expectEqual(5, diff1(1))
}
protocol DiffReq : Differentiable {
@differentiable(reverse, wrt: (self, x))
func f(_ x: Float) -> Float
}
extension DiffReq where TangentVector : AdditiveArithmetic {
@inline(never) // Prevent specialization, to test all witness code.
func derivF(at x: Float) -> Float {
return (valueWithDifferential(at: x) { x in self.f(x) }).1(1)
}
}
struct Quadratic : DiffReq, AdditiveArithmetic {
typealias TangentVector = Quadratic
@differentiable(reverse)
let a: Float
@differentiable(reverse)
let b: Float
@differentiable(reverse)
let c: Float
init(_ a: Float, _ b: Float, _ c: Float) {
self.a = a
self.b = b
self.c = c
}
@differentiable(reverse, wrt: (self, x))
func f(_ x: Float) -> Float {
return a * x * x + b * x + c
}
}
ForwardModeTests.test("ProtocolFunc") {
expectEqual(12, Quadratic(11, 12, 13).derivF(at: 0))
expectEqual(2 * 11 + 12, Quadratic(11, 12, 13).derivF(at: 1))
expectEqual(2 * 11 * 2 + 12, Quadratic(11, 12, 13).derivF(at: 2))
}
// MARK: Constructor, accessor, and subscript requirements.
protocol FunctionsOfX: Differentiable {
@differentiable(reverse)
init(x: Float)
@differentiable(reverse)
var x: Float { get }
@differentiable(reverse)
var y: Float { get }
@differentiable(reverse)
var z: Float { get }
@differentiable(reverse)
subscript() -> Float { get }
}
struct TestFunctionsOfX: FunctionsOfX {
@differentiable(reverse)
init(x: Float) {
self.x = x
self.y = x * x
}
/// x = x
var x: Float
/// y = x * x
var y: Float
/// z = x * x + x
var z: Float {
return y + x
}
@differentiable(reverse)
subscript() -> Float {
return z
}
}
@inline(never) // Prevent specialization, to test all witness code.
func derivatives<F: FunctionsOfX>(at x: Float, of: F.Type)
-> (Float, Float, Float, Float)
{
let dxdx = derivative(at: x) { x in F(x: x).x }
let dydx = derivative(at: x) { x in F(x: x).y }
let dzdx = derivative(at: x) { x in F(x: x).z }
let dsubscriptdx = derivative(at: x) { x in F(x: x)[] }
return (dxdx, dydx, dzdx, dsubscriptdx)
}
ForwardModeTests.test("constructor, accessor, subscript") {
expectEqual(
(1.0, 4.0, 5.0, 5.0),
derivatives(at: 2.0, of: TestFunctionsOfX.self))
}
// MARK: - Test witness method SIL type computation.
protocol P : Differentiable {
@differentiable(reverse, wrt: (x, y))
func foo(_ x: Float, _ y: Double) -> Float
}
struct S : P {
@differentiable(reverse, wrt: (x, y))
func foo(_ x: Float, _ y: Double) -> Float {
return x
}
}
// MARK: - Overridden protocol method adding differentiable attribute.
public protocol Distribution {
associatedtype Value
func logProbability(of value: Value) -> Float
}
public protocol DifferentiableDistribution: Differentiable, Distribution {
@differentiable(reverse, wrt: self)
func logProbability(of value: Value) -> Float
}
struct Foo: DifferentiableDistribution {
@differentiable(reverse, wrt: self)
func logProbability(of value: Float) -> Float {
.zero
}
}
@differentiable(reverse)
func blah<T: DifferentiableDistribution>(_ x: T) -> Float where T.Value: AdditiveArithmetic {
x.logProbability(of: .zero)
}
// Adding a more general `@differentiable` attribute.
public protocol DoubleDifferentiableDistribution: DifferentiableDistribution
where Value: Differentiable {
@differentiable(reverse, wrt: self)
@differentiable(reverse, wrt: (self, value))
func logProbability(of value: Value) -> Float
}
@differentiable(reverse)