Skip to content

[SR-14881] [AutoDiff] Convert from Double to optional Double could be differentiable #57228

Closed
@swift-ci

Description

@swift-ci
Previous ID SR-14881
Radar rdar://problem/80278722
Original Reporter bjschoenfeld (JIRA User)
Type New Feature
Additional Detail from JIRA
Votes 0
Component/s
Labels New Feature, AutoDiff
Assignee None
Priority Medium

md5: bb0718bed6418e286a744ca920d5ef3a

Issue Description:

Converting from Double to Double? is essentially an identity operator. This probably generalizes to other differentiable types. Here is a minimal example.

import _Differentiation

/// should be differentiable without explicitly defining a derivative
func convertToOptional(_ a: Double) -> Double? {
    return a
}

/// expected derivative
@derivative(of: convertToOptional)
func convertToOptionalVJP(
    _ a: Double
) -> (value: Double?, pullback: (Optional<Double>.TangentVector) -> Double) {
    func pullback(_ backwardValue: Optional<Double>.TangentVector) -> Double {
        return backwardValue.value ?? 0.0
    }
    return (value: a, pullback: pullback)
}

An application of this is creating a closure around a function that accepts a Double? as input, as follows:

/// differentiable
func f(x: Double?) -> Double {
    if x == nil {
        return 0.0
    }
    else {
        return 2.0 * x!
    }
}

/// differentiable
let fClosureOptionalInput: @differentiable(reverse) (Double?) -> Double = {
    y in f(x: y)
}

// should be differentiable
let fClosure: @differentiable(reverse) (Double) -> Double = {
    // y is of type Double
    // x is expecting a Double? value
    // so the compiler currently complains that this is not differentiable
    y in f(x: y)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions