-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
AutoDiff.swift
1016 lines (868 loc) · 30.5 KB
/
AutoDiff.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
//===--- AutoDiff.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// SWIFT_ENABLE_TENSORFLOW
//
// This file defines support for automatic differentiation.
//
//===----------------------------------------------------------------------===//
infix operator .* : MultiplicationPrecedence
infix operator .*= : AssignmentPrecedence
//===----------------------------------------------------------------------===//
// Compiler Protocols
//===----------------------------------------------------------------------===//
/// A type with values that support pointwise multiplication.
// TODO: Add API documentation.
public protocol PointwiseMultiplicative : AdditiveArithmetic {
/// The one value.
///
/// One is the identity element for multiplication. For any value,
/// `x .* .one == x` and `.one .* x == x`.
static var one: Self { get }
/// The multiplicative inverse of self.
///
/// For any value, `x .* x.reciprocal == .one` and
/// `x.reciprocal .* x == .one`.
var reciprocal: Self { get }
/// Multiplies two values and produces their product.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func .*(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and produces their product.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func .*=(lhs: inout Self, rhs: Self)
}
public extension PointwiseMultiplicative {
static func .*=(lhs: inout Self, rhs: Self) {
lhs = lhs .* rhs
}
}
public extension PointwiseMultiplicative
where Self : ExpressibleByIntegerLiteral {
static var one: Self {
return 1
}
}
/// A type that represents an unranked vector space. Values of this type are
/// elements in this vector space and have either no shape or a static shape.
public protocol VectorProtocol : AdditiveArithmetic {
/// The type of scalars in the vector space.
associatedtype VectorSpaceScalar : AdditiveArithmetic
func adding(_ x: VectorSpaceScalar) -> Self
mutating func add(_ x: VectorSpaceScalar)
func subtracting(_ x: VectorSpaceScalar) -> Self
mutating func subtract(_ x: VectorSpaceScalar)
/// Returns `self` multiplied by the given scalar.
func scaled(by scalar: VectorSpaceScalar) -> Self
/// Multiplies `self` by the given scalar.
mutating func scale(by scalar: VectorSpaceScalar)
}
public extension VectorProtocol {
mutating func add(_ x: VectorSpaceScalar) {
self = adding(x)
}
mutating func subtract(_ x: VectorSpaceScalar) {
self = subtracting(x)
}
mutating func scale(by scalar: VectorSpaceScalar) {
self = scaled(by: scalar)
}
}
/* Note: These default-implemented operators will slow down type-checking
performance and break existing code.
public extension VectorProtocol {
static func + (lhs: Self, rhs: VectorSpaceScalar) -> Self {
lhs.adding(rhs)
}
static func + (lhs: VectorSpaceScalar, rhs: Self) -> Self {
rhs.adding(lhs)
}
static func += (lhs: inout Self, rhs: VectorSpaceScalar) {
lhs.add(rhs)
}
static func - (lhs: Self, rhs: VectorSpaceScalar) -> Self {
lhs.subtracting(rhs)
}
static func -= (lhs: inout Self, rhs: VectorSpaceScalar) {
lhs.subtract(rhs)
}
static func * (lhs: Self, rhs: VectorSpaceScalar) -> Self {
lhs.scaled(by: rhs)
}
static func * (lhs: VectorSpaceScalar, rhs: Self) -> Self {
rhs.scaled(by: lhs)
}
static func *= (lhs: inout Self, rhs: VectorSpaceScalar) {
lhs.scale(by: rhs)
}
}
public extension VectorProtocol where VectorSpaceScalar : SignedNumeric {
static func - (lhs: VectorSpaceScalar, rhs: Self) -> Self {
-rhs.adding(lhs)
}
static prefix func - (x: Self) -> Self {
.zero - x
}
}
*/
/// A type that mathematically represents a differentiable manifold whose
/// tangent spaces are finite-dimensional.
public protocol Differentiable {
associatedtype TangentVector: Differentiable & AdditiveArithmetic
where TangentVector.TangentVector == TangentVector,
AllDifferentiableVariables.AllDifferentiableVariables ==
AllDifferentiableVariables,
AllDifferentiableVariables.TangentVector == TangentVector
/// The type of all differentiable variables in this type.
associatedtype AllDifferentiableVariables : Differentiable
/// All differentiable variables of this value.
var allDifferentiableVariables: AllDifferentiableVariables { get set }
/// Moves `self` along the value space towards the given tangent vector. In
/// Riemannian geometry (mathematics), this represents an exponential map.
mutating func move(along direction: TangentVector)
@available(*, deprecated,
message: "'CotangentVector' is now equal to 'TangentVector' and will be removed")
typealias CotangentVector = TangentVector
}
public extension Differentiable where AllDifferentiableVariables == Self {
var allDifferentiableVariables: AllDifferentiableVariables {
get { return self }
set { self = newValue }
}
}
public extension Differentiable where TangentVector == Self {
mutating func move(along direction: TangentVector) {
self += direction
}
}
/// Returns `x` like an identity function. When used in a context where `x` is
/// being differentiated with respect to, this function will not produce any
/// derivative at `x`.
@inlinable
@inline(__always)
@_semantics("autodiff.nonvarying")
public func withoutDerivative<T>(at x: T) -> T {
x
}
/// Applies the given closure `body` to `x`. When used in a context where `x` is
/// being differentiated with respect to, this function will not produce any
/// derivative at `x`.
// FIXME: Support throws-rethrows.
@inlinable
@inline(__always)
@_semantics("autodiff.nonvarying")
public func withoutDerivative<T, R>(at x: T, in body: (T) -> R) -> R {
body(x)
}
//===----------------------------------------------------------------------===//
// Functional utilities
//===----------------------------------------------------------------------===//
/// Create a differentiable function from a vector-Jacobian products function.
@inlinable
public func differentiableFunction<T : Differentiable, R : Differentiable>(
from vjp: @escaping (T)
-> (value: R, pullback: (R.TangentVector) -> T.TangentVector)
) -> @differentiable (T) -> R {
func original(_ x: T) -> R {
return vjp(x).value
}
@differentiating(original)
func derivative(_ x: T)
-> (value: R, pullback: (R.TangentVector) -> T.TangentVector) {
return vjp(x)
}
return original
}
/// Create a differentiable function from a vector-Jacobian products function.
@inlinable
public func differentiableFunction<T, U, R>(
from vjp: @escaping (T, U)
-> (value: R, pullback: (R.TangentVector)
-> (T.TangentVector, U.TangentVector))
) -> @differentiable (T, U) -> R
where T : Differentiable, U : Differentiable, R : Differentiable {
func original(_ x: T, _ y: U) -> R {
return vjp(x, y).value
}
@differentiating(original)
func derivative(_ x: T, _ y: U)
-> (value: R,
pullback: (R.TangentVector)
-> (T.TangentVector, U.TangentVector)) {
return vjp(x, y)
}
return original
}
public extension Differentiable {
@differentiable(wrt: self, vjp: _vjpWithDerivative)
func withDerivative(_ body: @escaping (inout TangentVector) -> Void) -> Self {
return self
}
@inlinable
internal func _vjpWithDerivative(
_ body: @escaping (inout TangentVector) -> Void
) -> (Self, (TangentVector) -> TangentVector) {
return (self, { grad in
var grad = grad
body(&grad)
return grad
})
}
}
/// Make a function be recomputed in its pullback, known as "checkpointing" in
/// traditional automatic differentiation.
@inlinable
public func withRecomputationInPullbacks<T, U>(
_ body: @escaping @differentiable (T) -> U
) -> @differentiable (T) -> U where T : Differentiable, U : Differentiable {
return differentiableFunction { x in
(value: body(x), pullback: { v in pullback(at: x, in: body)(v) })
}
}
public extension Differentiable {
@inlinable
@differentiable(wrt: self, vjp: _vjp_withRecomputationInPullbacks)
func withRecomputationInPullbacks<Result : Differentiable>(
_ body: @escaping @differentiable (Self) -> Result
) -> Result {
return body(self)
}
@inlinable
internal func _vjp_withRecomputationInPullbacks<Result : Differentiable>(
_ body: @escaping @differentiable (Self) -> Result
) -> (Result, (Result.TangentVector) -> TangentVector) {
return valueWithPullback(in: Swift.withRecomputationInPullbacks(body))
}
}
//===----------------------------------------------------------------------===//
// Method-style differential operators
//===----------------------------------------------------------------------===//
public extension Differentiable {
@inlinable
func valueWithPullback<R>(
in f: @differentiable (Self) -> R
) -> (value: R, pullback: (R.TangentVector) -> TangentVector) {
return Builtin.autodiffApply_vjp_arity1(f, self)
}
@inlinable
func pullback<R>(
in f: @differentiable (Self) -> R
) -> (R.TangentVector) -> TangentVector {
return Builtin.autodiffApply_vjp_arity1(f, self).1
}
@inlinable
func gradient<R>(
in f: @differentiable (Self) -> R
) -> TangentVector
where R : FloatingPoint, R.TangentVector == R {
return self.pullback(in: f)(R(1))
}
@inlinable
func valueWithGradient<R>(
in f: @differentiable (Self) -> R
) -> (value: R, gradient: TangentVector)
where R : FloatingPoint, R.TangentVector == R {
let (y, pb) = self.valueWithPullback(in: f)
return (y, pb(R(1)))
}
@inlinable
func valueWithPullback<T, R>(
at x: T, in f: @differentiable (Self, T) -> R
) -> (value: R,
pullback: (R.TangentVector) -> (TangentVector, T.TangentVector)) {
return Builtin.autodiffApply_vjp_arity2(f, self, x)
}
@inlinable
func pullback<T, R>(
at x: T, in f: @differentiable (Self, T) -> R
) -> (R.TangentVector) -> (TangentVector, T.TangentVector) {
return Builtin.autodiffApply_vjp_arity2(f, self, x).1
}
@inlinable
func gradient<T, R>(
at x: T, in f: @differentiable (Self, T) -> R
) -> (TangentVector, T.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return self.pullback(at: x, in: f)(R(1))
}
@inlinable
func valueWithGradient<T, R>(
at x: T, in f: @differentiable (Self, T) -> R
) -> (value: R, gradient: (TangentVector, T.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
let (y, pb) = self.valueWithPullback(at: x, in: f)
return (y, pb(R(1)))
}
}
//===----------------------------------------------------------------------===//
// Free-function-style differential operators
//===----------------------------------------------------------------------===//
// Transpose
@available(*, unavailable)
@inlinable
public func transpose<T, R>(
of body: @escaping @differentiable/*(linear)*/ (T) -> R
) -> @differentiable/*(linear)*/ (R) -> T {
fatalError()
}
// Value with differential
@inlinable
public func valueWithDifferential<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, differential: (T.TangentVector) -> R.TangentVector) {
return Builtin.autodiffApply_jvp(f, x)
}
@inlinable
public func valueWithDifferential<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R,
differential: (T.TangentVector, U.TangentVector) -> R.TangentVector) {
return Builtin.autodiffApply_jvp_arity2(f, x, y)
}
@inlinable
public func valueWithDifferential<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
differential: (T.TangentVector, U.TangentVector, V.TangentVector)
-> (R.TangentVector)) {
return Builtin.autodiffApply_jvp_arity3(f, x, y, z)
}
// Value with pullback
@inlinable
public func valueWithPullback<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, pullback: (R.TangentVector) -> T.TangentVector) {
return Builtin.autodiffApply_vjp(f, x)
}
@inlinable
public func valueWithPullback<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R,
pullback: (R.TangentVector) -> (T.TangentVector, U.TangentVector)) {
return Builtin.autodiffApply_vjp_arity2(f, x, y)
}
@inlinable
public func valueWithPullback<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
pullback: (R.TangentVector)
-> (T.TangentVector, U.TangentVector, V.TangentVector)) {
return Builtin.autodiffApply_vjp_arity3(f, x, y, z)
}
// Differential
@inlinable
public func differential<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (T.TangentVector) -> R.TangentVector {
return valueWithDifferential(at: x, in: f).1
}
@inlinable
public func differential<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (T.TangentVector, U.TangentVector) -> R.TangentVector {
return valueWithDifferential(at: x, y, in: f).1
}
@inlinable
public func differential<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (T.TangentVector, U.TangentVector, V.TangentVector) -> (R.TangentVector) {
return valueWithDifferential(at: x, y, z, in: f).1
}
// Pullback
@inlinable
public func pullback<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (R.TangentVector) -> T.TangentVector {
return Builtin.autodiffApply_vjp(f, x).1
}
@inlinable
public func pullback<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (R.TangentVector) -> (T.TangentVector, U.TangentVector) {
return Builtin.autodiffApply_vjp_arity2(f, x, y).1
}
@inlinable
public func pullback<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (R.TangentVector)
-> (T.TangentVector, U.TangentVector, V.TangentVector) {
return Builtin.autodiffApply_vjp_arity3(f, x, y, z).1
}
// Derivative
@inlinable
public func derivative<T: FloatingPoint, R>(
at x: T, in f: @escaping @differentiable (T) -> R
) -> R.TangentVector
where T.TangentVector == T {
return differential(at: x, in: f)(T(1))
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, R>(
at x: T, _ y: U, in f: @escaping @differentiable (T, U) -> R
) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U {
return differential(at: x, y, in: f)(T(1), U(1))
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
at x: T, _ y: U, _ z: V, in f: @escaping @differentiable (T, U, V) -> R
) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return differential(at: x, y, z, in: f)(T(1), U(1), V(1))
}
// Gradient
@inlinable
public func gradient<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> T.TangentVector
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, in: f)(R(1))
}
@inlinable
public func gradient<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (T.TangentVector, U.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, y, in: f)(R(1))
}
@inlinable
public func gradient<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (T.TangentVector, U.TangentVector, V.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return pullback(at: x, y, z, in: f)(R(1))
}
// Value with derivative
@inlinable
public func valueWithDerivative<T: FloatingPoint, R>(
at x: T, in f: @escaping @differentiable (T) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T {
let (y, differential) = valueWithDifferential(at: x, in: f)
return (y, differential(T(1)))
}
@inlinable
public func valueWithDerivative<T: FloatingPoint, U: FloatingPoint, R>(
at x: T, _ y: U, in f: @escaping @differentiable (T, U) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U {
let (y, differential) = valueWithDifferential(at: x, y, in: f)
return (y, differential(T(1), U(1)))
}
@inlinable
public func valueWithDerivative<
T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
at x: T, _ y: U, _ z: V, in f: @escaping @differentiable (T, U, V) -> R
) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
let (y, differential) = valueWithDifferential(at: x, y, z, in: f)
return (y, differential(T(1), U(1), V(1)))
}
// Value with gradient
@inlinable
public func valueWithGradient<T, R>(
at x: T, in f: @differentiable (T) -> R
) -> (value: R, gradient: T.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, in: f)
return (y, pullback(R(1)))
}
@inlinable
public func valueWithGradient<T, U, R>(
at x: T, _ y: U, in f: @differentiable (T, U) -> R
) -> (value: R, gradient: (T.TangentVector, U.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, y, in: f)
return (y, pullback(R(1)))
}
@inlinable
public func valueWithGradient<T, U, V, R>(
at x: T, _ y: U, _ z: V, in f: @differentiable (T, U, V) -> R
) -> (value: R,
gradient: (T.TangentVector, U.TangentVector, V.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
let (y, pullback) = valueWithPullback(at: x, y, z, in: f)
return (y, pullback(R(1)))
}
// Derivative (curried)
@inlinable
public func derivative<T: FloatingPoint, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> R.TangentVector
where T.TangentVector == T {
return { x in derivative(at: x, in: f) }
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U {
return { (x, y) in derivative(at: x, y, in: f) }
}
@inlinable
public func derivative<T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> R.TangentVector
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return { (x, y, z) in derivative(at: x, y, z, in: f) }
}
// Gradient (curried)
@inlinable
public func gradient<T, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> T.TangentVector
where R : FloatingPoint, R.TangentVector == R {
return { x in gradient(at: x, in: f) }
}
@inlinable
public func gradient<T, U, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (T.TangentVector, U.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x, y in gradient(at: x, y, in: f) }
}
@inlinable
public func gradient<T, U, V, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> (T.TangentVector, U.TangentVector, V.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x, y, z in gradient(at: x, y, z, in: f) }
}
// Value with derivative (curried)
@inlinable
public func valueWithDerivative<T: FloatingPoint, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T {
return { x in valueWithDerivative(at: x, in: f) }
}
@inlinable
public func valueWithDerivative<T: FloatingPoint, U: FloatingPoint, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U {
return { (x, y) in valueWithDerivative(at: x, y, in: f) }
}
@inlinable
public func valueWithDerivative<
T: FloatingPoint, U: FloatingPoint, V: FloatingPoint, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V) -> (value: R, derivative: R.TangentVector)
where T.TangentVector == T,
U.TangentVector == U,
V.TangentVector == V {
return { (x, y, z) in valueWithDerivative(at: x, y, z, in: f) }
}
// Value with gradient (curried)
@inlinable
public func valueWithGradient<T, R>(
of f: @escaping @differentiable (T) -> R
) -> (T) -> (value: R, gradient: T.TangentVector)
where R : FloatingPoint, R.TangentVector == R {
return { x in valueWithGradient(at: x, in: f) }
}
@inlinable
public func valueWithGradient<T, U, R>(
of f: @escaping @differentiable (T, U) -> R
) -> (T, U) -> (value: R, gradient: (T.TangentVector, U.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
return { x, y in valueWithGradient(at: x, y, in: f) }
}
@inlinable
public func valueWithGradient<T, U, V, R>(
of f: @escaping @differentiable (T, U, V) -> R
) -> (T, U, V)
-> (value: R,
gradient: (T.TangentVector, U.TangentVector, V.TangentVector))
where R : FloatingPoint, R.TangentVector == R {
return { x, y, z in valueWithGradient(at: x, y, z, in: f) }
}
//===----------------------------------------------------------------------===//
// Type-erased `AnyDerivative`
//===----------------------------------------------------------------------===//
internal protocol _AnyDerivativeBox {
// `Equatable` requirements (implied by `AdditiveArithmetic`).
func _isEqual(to other: _AnyDerivativeBox) -> Bool
func _isNotEqual(to other: _AnyDerivativeBox) -> Bool
// `AdditiveArithmetic` requirements.
static var _zero: _AnyDerivativeBox { get }
func _adding(_ x: _AnyDerivativeBox) -> _AnyDerivativeBox
func _subtracting(_ x: _AnyDerivativeBox) -> _AnyDerivativeBox
// `Differentiable` requirements.
var _allDifferentiableVariables: _AnyDerivativeBox { get }
mutating func _move(along direction: _AnyDerivativeBox)
/// The underlying base value, type-erased to `Any`.
var _typeErasedBase: Any { get }
/// Returns the underlying value unboxed to the given type, if possible.
func _unboxed<U>(to type: U.Type) -> U?
where U : Differentiable, U.TangentVector == U,
U.AllDifferentiableVariables == U
}
extension _AnyDerivativeBox {
/// Returns true if the underlying value has type `AnyDerivative.OpaqueZero`.
func _isOpaqueZero() -> Bool {
return _unboxed(to: AnyDerivative.OpaqueZero.self) != nil
}
}
@inline(never)
@usableFromInline
internal func _derivativeTypeMismatch(
_ x: Any.Type, _ y: Any.Type, file: StaticString = #file, line: UInt = #line
) -> Never {
preconditionFailure("""
Derivative type mismatch: \
\(String(reflecting: x)) and \(String(reflecting: y))
""", file: file, line: line)
}
internal struct _ConcreteDerivativeBox<T> : _AnyDerivativeBox
where T : Differentiable, T.TangentVector == T,
T.AllDifferentiableVariables == T
{
/// The underlying base value.
var _base: T
init(_ base: T) {
self._base = base
}
/// The underlying base value, type-erased to `Any`.
var _typeErasedBase: Any {
return _base
}
func _unboxed<U>(to type: U.Type) -> U?
where U : Differentiable, U.TangentVector == U,
U.AllDifferentiableVariables == U
{
return (self as? _ConcreteDerivativeBox<U>)?._base
}
// `Equatable` requirements (implied by `AdditiveArithmetic`).
func _isEqual(to other: _AnyDerivativeBox) -> Bool {
return _base == other._unboxed(to: T.self)
}
func _isNotEqual(to other: _AnyDerivativeBox) -> Bool {
return _base != other._unboxed(to: T.self)
}
// `AdditiveArithmetic` requirements.
static var _zero: _AnyDerivativeBox {
return _ConcreteDerivativeBox(T.zero)
}
func _adding(_ x: _AnyDerivativeBox) -> _AnyDerivativeBox {
// 0 + x = x
if _isOpaqueZero() {
return x
}
// y + 0 = y
if x._isOpaqueZero() {
return self
}
guard let xBase = x._unboxed(to: T.self) else {
_derivativeTypeMismatch(T.self, type(of: x._typeErasedBase))
}
return _ConcreteDerivativeBox(_base + xBase)
}
func _subtracting(_ x: _AnyDerivativeBox) -> _AnyDerivativeBox {
// y - 0 = y
if x._isOpaqueZero() {
return self
}
// 0 - x = -x
if _isOpaqueZero() {
return type(of: x)._zero._subtracting(x)
}
guard let xBase = x._unboxed(to: T.self) else {
_derivativeTypeMismatch(T.self, type(of: x._typeErasedBase))
}
return _ConcreteDerivativeBox(_base - xBase)
}
// `Differentiable` requirements.
var _allDifferentiableVariables: _AnyDerivativeBox {
return _ConcreteDerivativeBox(_base.allDifferentiableVariables)
}
mutating func _move(along direction: _AnyDerivativeBox) {
if direction._isOpaqueZero() {
return
}
// The case where `self._isOpaqueZero()` returns true is handled in
// `AnyDerivative.move(along:)`.
guard let directionBase =
direction._unboxed(to: T.TangentVector.self) else {
_derivativeTypeMismatch(T.self, type(of: direction._typeErasedBase))
}
_base.move(along: directionBase)
}
}
/// A type-erased derivative value.
///
/// The `AnyDerivative` type forwards its operations to an arbitrary underlying
/// base derivative value conforming to `Differentiable` and
/// `AdditiveArithmetic`, hiding the specifics of the underlying value.
public struct AnyDerivative : Differentiable & AdditiveArithmetic {
internal var _box: _AnyDerivativeBox
internal init(_box: _AnyDerivativeBox) {
self._box = _box
}
/// The underlying base value.
public var base: Any {
return _box._typeErasedBase
}
/// Creates a type-erased derivative from the given derivative.
@differentiable(vjp: _vjpInit(_:))
public init<T>(_ base: T)
where T : Differentiable, T.TangentVector == T,
T.AllDifferentiableVariables == T
{
self._box = _ConcreteDerivativeBox<T>(base)
}
@usableFromInline internal static func _vjpInit<T>(
_ base: T
) -> (AnyDerivative, (AnyDerivative) -> T.TangentVector)
where T : Differentiable, T.TangentVector == T,
T.AllDifferentiableVariables == T
{
return (AnyDerivative(base), { v in v.base as! T.TangentVector })
}
public typealias TangentVector = AnyDerivative
public typealias AllDifferentiableVariables = AnyDerivative
// `Equatable` requirements (implied by `AdditiveArithmetic`).
public static func == (lhs: AnyDerivative, rhs: AnyDerivative) -> Bool {
return lhs._box._isEqual(to: rhs._box)
}
public static func != (lhs: AnyDerivative, rhs: AnyDerivative) -> Bool {
return lhs._box._isNotEqual(to: rhs._box)
}
// `AdditiveArithmetic` requirements.
/// Internal struct representing an opaque zero value.
@frozen
@usableFromInline
internal struct OpaqueZero : Differentiable & AdditiveArithmetic {}
public static var zero: AnyDerivative {
return AnyDerivative(
_box: _ConcreteDerivativeBox<OpaqueZero>(OpaqueZero.zero))
}
public static func + (
lhs: AnyDerivative, rhs: AnyDerivative
) -> AnyDerivative {
return AnyDerivative(_box: lhs._box._adding(rhs._box))
}
@differentiating(+)
@usableFromInline internal static func _vjpAdd(
lhs: AnyDerivative, rhs: AnyDerivative
) -> (value: AnyDerivative,
pullback: (AnyDerivative) -> (AnyDerivative, AnyDerivative)) {
return (lhs + rhs, { v in (v, v) })
}
public static func - (
lhs: AnyDerivative, rhs: AnyDerivative
) -> AnyDerivative {
return AnyDerivative(_box: lhs._box._subtracting(rhs._box))
}
@differentiating(-)
@usableFromInline internal static func _vjpSubtract(
lhs: AnyDerivative, rhs: AnyDerivative
) -> (value: AnyDerivative,
pullback: (AnyDerivative) -> (AnyDerivative, AnyDerivative)) {
return (lhs - rhs, { v in (v, .zero - v) })
}
// `Differentiable` requirements.
public var allDifferentiableVariables: AllDifferentiableVariables {
get { return AnyDerivative(_box: _box._allDifferentiableVariables) }
// set { _box._allDifferentiableVariables = newValue._box }
}
public mutating func move(along direction: TangentVector) {
if _box._isOpaqueZero() {
_box = direction._box
return
}
_box._move(along: direction._box)
}
}
//===----------------------------------------------------------------------===//
// Differentiable higher order functions for collections
//===----------------------------------------------------------------------===//
public extension Array where Element: Differentiable {
@differentiable(wrt: (self, initialResult), vjp: _vjpDifferentiableReduce)
func differentiableReduce<Result: Differentiable>(
_ initialResult: Result,
_ nextPartialResult: @differentiable (Result, Element) -> Result
) -> Result {
reduce(initialResult, nextPartialResult)
}
@usableFromInline
internal func _vjpDifferentiableReduce<Result: Differentiable>(
_ initialResult: Result,
_ nextPartialResult: @differentiable (Result, Element) -> Result
) -> (value: Result,
pullback: (Result.TangentVector)
-> (Array.TangentVector, Result.TangentVector)) {
var pullbacks:
[(Result.TangentVector) -> (Result.TangentVector, Element.TangentVector)]
= []
let count = self.count
pullbacks.reserveCapacity(count)
var result = initialResult
for element in self {
let (y, pb) =
Swift.valueWithPullback(at: result, element, in: nextPartialResult)
result = y
pullbacks.append(pb)
}
return (value: result, pullback: { tangent in
var resultTangent = tangent
var elementTangents = TangentVector([])
elementTangents.base.reserveCapacity(count)
for pullback in pullbacks.reversed() {
let (newResultTangent, elementTangent) = pullback(resultTangent)
resultTangent = newResultTangent
elementTangents.base.append(elementTangent)
}
return (TangentVector(elementTangents.base.reversed()), resultTangent)
})
}
}
public extension Array where Element: Differentiable {
@differentiable(wrt: self, vjp: _vjpDifferentiableMap)
func differentiableMap<Result: Differentiable>(
_ body: @differentiable (Element) -> Result
) -> [Result] {
map(body)
}
@usableFromInline
internal func _vjpDifferentiableMap<Result: Differentiable>(