[AutoDiff] Make @noDerivative
attribute imply non-varying semantics.
#29543
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Previously,
@noDerivative
could only be declared on stored properties inDifferentiable
-conforming structs and classes.Now,
@noDerivative
can be declared on all function-like declarations:func
,var
,init
, andsubscript
.@noDerivative
attribute now also implies@_semantics("autodiff.nonvarying")
.SIL values produced from
@noDerivative
declarations will never be marked asvarying by differentiable activity analysis. These values do not need a
derivative.
Marking declarations as
@noDerivative
is a usability improvement over usingwithoutDerivative(at:)
at use sites. However,@noDerivative
is invasivebecause it requires annotation on original declarations. There may exist a more
elegant solution.
Example:
Array.indices
calls the default protocol implementationRandomAccessCollection.indices
, which is defined in the stdlib and currently has no differentiation-related annotations.Thus, the code above triggers a non-differentiability error:
Old workaround: use
withoutDerivative(at: array.indices
.withoutDerivative(at:)
has non-varying semantics.However, applying
withoutDerivative(at:)
is cumbersome for properties/functions likeArray.indices
orArray.count
, which are always expected to have non-varying semantics.Example of excessive
withoutDerivative(at:)
usage: poor usability.New workaround: annotate
RandomAccessCollection.indices
with@noDerivative
. This is an alternative to applyingwithoutDerivative(at:)
, achieving the same effect.Note that this patch does not actually add
@noDerivative
toRandomAccessCollection.indices
in the stdlib. But adding@noDerivative
toRandomAccessCollection.indices
is verified to work.