Skip to content

[AutoDiff] [stdlib] Add a JVP for 'differentiableMap(_:)'. #32769

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions stdlib/public/Differentiation/ArrayDifferentiation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,27 @@ extension Array where Element: Differentiable {
}
return (value: values, pullback: pullback)
}

@inlinable
@derivative(of: differentiableMap)
internal func _jvpDifferentiableMap<Result: Differentiable>(
_ body: @differentiable (Element) -> Result
) -> (
value: [Result],
differential: (Array.TangentVector) -> Array<Result>.TangentVector
) {
var values: [Result] = []
var differentials: [(Element.TangentVector) -> Result.TangentVector] = []
for x in self {
let (y, df) = valueWithDifferential(at: x, in: body)
values.append(y)
differentials.append(df)
}
func differential(_ tans: Array.TangentVector) -> Array<Result>.TangentVector {
.init(zip(tans.base, differentials).map { tan, df in df(tan) })
}
return (value: values, differential: differential)
}
}

extension Array where Element: Differentiable {
Expand Down
19 changes: 19 additions & 0 deletions test/AutoDiff/validation-test/forward_mode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1319,4 +1319,23 @@ ForwardModeTests.test("ForceUnwrapping") {
expectEqual(5, forceUnwrap(Float(2)))
}

//===----------------------------------------------------------------------===//
// Array methods from ArrayDifferentiation.swift
//===----------------------------------------------------------------------===//

ForwardModeTests.test("Array.differentiableMap") {
let x: [Float] = [1, 2, 3]
let tan = Array<Float>.TangentVector([1, 1, 1])

func multiplyMap(_ a: [Float]) -> [Float] {
return a.differentiableMap({ x in 3 * x })
}
expectEqual([3, 3, 3], differential(at: x, in: multiplyMap)(tan))

func squareMap(_ a: [Float]) -> [Float] {
return a.differentiableMap({ x in x * x })
}
expectEqual([2, 4, 6], differential(at: x, in: squareMap)(tan))
}

runAllTests()