Skip to content

[AutoDiff] [TF-1288] Supporting differentiable functions with multiple semantic results #38781

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 12 commits into from
Closed
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
9 changes: 5 additions & 4 deletions include/swift/AST/AutoDiff.h
Original file line number Diff line number Diff line change
@@ -32,6 +32,7 @@

namespace swift {

class AbstractFunctionDecl;
class AnyFunctionType;
class SourceFile;
class SILFunctionType;
@@ -398,9 +399,6 @@ class DerivativeFunctionTypeError
enum class Kind {
/// Original function type has no semantic results.
NoSemanticResults,
/// Original function type has multiple semantic results.
// TODO(TF-1250): Support function types with multiple semantic results.
MultipleSemanticResults,
/// Differentiability parmeter indices are empty.
NoDifferentiabilityParameters,
/// A differentiability parameter does not conform to `Differentiable`.
@@ -429,7 +427,6 @@ class DerivativeFunctionTypeError
explicit DerivativeFunctionTypeError(AnyFunctionType *functionType, Kind kind)
: functionType(functionType), kind(kind), value(Value()) {
assert(kind == Kind::NoSemanticResults ||
kind == Kind::MultipleSemanticResults ||
kind == Kind::NoDifferentiabilityParameters);
};

@@ -579,6 +576,10 @@ void getFunctionSemanticResultTypes(
SmallVectorImpl<AutoDiffSemanticFunctionResultType> &result,
GenericEnvironment *genericEnv = nullptr);

/// Returns the indices of all semantic results for a given function.
IndexSubset *getAllFunctionSemanticResultIndices(
const AbstractFunctionDecl *AFD);

/// Returns the lowered SIL parameter indices for the given AST parameter
/// indices and `AnyfunctionType`.
///
3 changes: 0 additions & 3 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
@@ -3496,9 +3496,6 @@ NOTE(autodiff_attr_original_decl_not_same_type_context,none,
(DescriptiveDeclKind))
ERROR(autodiff_attr_original_void_result,none,
"cannot differentiate void function %0", (DeclName))
ERROR(autodiff_attr_original_multiple_semantic_results,none,
"cannot differentiate functions with both an 'inout' parameter and a "
"result", ())
ERROR(autodiff_attr_result_not_differentiable,none,
"can only differentiate functions with results that conform to "
"'Differentiable', but %0 does not conform to 'Differentiable'", (Type))
25 changes: 20 additions & 5 deletions lib/AST/AutoDiff.cpp
Original file line number Diff line number Diff line change
@@ -196,8 +196,16 @@ void autodiff::getFunctionSemanticResultTypes(
functionType->getResult()->getAs<AnyFunctionType>()) {
formalResultType = resultFunctionType->getResult();
}
if (!formalResultType->isEqual(ctx.TheEmptyTupleType))
result.push_back({remap(formalResultType), /*isInout*/ false});
if (!formalResultType->isEqual(ctx.TheEmptyTupleType)) {
// Separate tuple elements into individual results.
if (formalResultType->is<TupleType>()) {
for (auto elt : formalResultType->castTo<TupleType>()->getElements()) {
result.push_back({remap(elt.getType()), /*isInout*/ false});
}
} else {
result.push_back({remap(formalResultType), /*isInout*/ false});
}
}

// Collect `inout` parameters as semantic results.
for (auto param : functionType->getParams())
@@ -211,6 +219,16 @@ void autodiff::getFunctionSemanticResultTypes(
}
}

IndexSubset *
autodiff::getAllFunctionSemanticResultIndices(const AbstractFunctionDecl *AFD) {
auto originalFn = AFD->getInterfaceType()->castTo<AnyFunctionType>();
SmallVector<AutoDiffSemanticFunctionResultType, 1> semanticResults;
autodiff::getFunctionSemanticResultTypes(originalFn, semanticResults);
auto numResults = semanticResults.size();
return IndexSubset::getDefault(
AFD->getASTContext(), numResults, /*includeAll*/ true);
}

// TODO(TF-874): Simplify this helper. See TF-874 for WIP.
IndexSubset *
autodiff::getLoweredParameterIndices(IndexSubset *parameterIndices,
@@ -395,9 +413,6 @@ void DerivativeFunctionTypeError::log(raw_ostream &OS) const {
case Kind::NoSemanticResults:
OS << "has no semantic results ('Void' result)";
break;
case Kind::MultipleSemanticResults:
OS << "has multiple semantic results";
break;
case Kind::NoDifferentiabilityParameters:
OS << "has no differentiability parameters";
break;
148 changes: 115 additions & 33 deletions lib/AST/Type.cpp
Original file line number Diff line number Diff line change
@@ -6432,31 +6432,86 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
getSubsetParameters(parameterIndices, diffParams,
/*reverseCurryLevels*/ !makeSelfParamFirst);

// Get the original semantic result type.
// Get the original non-inout semantic result types.
SmallVector<AutoDiffSemanticFunctionResultType, 1> originalResults;
autodiff::getFunctionSemanticResultTypes(this, originalResults);
// Error if no original semantic results.
if (originalResults.empty())
return llvm::make_error<DerivativeFunctionTypeError>(
this, DerivativeFunctionTypeError::Kind::NoSemanticResults);
// Error if multiple original semantic results.
// TODO(TF-1250): Support functions with multiple semantic results.
if (originalResults.size() > 1)
return llvm::make_error<DerivativeFunctionTypeError>(
this, DerivativeFunctionTypeError::Kind::MultipleSemanticResults);
auto originalResult = originalResults.front();
auto originalResultType = originalResult.type;

// Get the original semantic result type's `TangentVector` associated type.
auto resultTan =
originalResultType->getAutoDiffTangentSpace(lookupConformance);
// Error if original semantic result has no tangent space.
if (!resultTan) {
// Accumulate non-inout result tangent spaces.
SmallVector<Type, 1> resultTanTypes;
bool hasInoutResult = false;
for (auto i : range(originalResults.size())) {
auto originalResult = originalResults[i];
auto originalResultType = originalResult.type;
// Voids currently have a defined tangent vector, so ignore them.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please clarify what this comment means exactly?

// Voids currently have a defined tangent vector, so ignore them.

Copy link
Contributor Author

@BradLarson BradLarson Aug 6, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm specifically thinking of this test case: https://github.com/apple/swift/blob/72866b6dd9e6024ab97469cafb56333800bbeb67/test/AutoDiff/Sema/derivative_attr_type_checking.swift#L867 involving an inout Void. getAutoDiffTangentSpace() returns an empty tuple for Void: https://github.com/apple/swift/blob/main/lib/AST/Type.cpp#L5359 rather than None, so we can't rely on the if (!resultTan) check to filter them out in that one case. I didn't want to alter the behavior of getAutoDiffTangentSpace() for this one edge case, so I opted for detecting Voids as a special case.

if (originalResultType->isVoid())
continue;
if (originalResult.isInout) {
hasInoutResult = true;
continue;
}
// Get the original semantic result type's `TangentVector` associated type.
auto resultTan =
originalResultType->getAutoDiffTangentSpace(lookupConformance);
if (!resultTan)
continue;
auto resultTanType = resultTan->getType();
resultTanTypes.push_back(resultTanType);
}
// Append non-wrt inout result tangent spaces.
// This uses the logic from getSubsetParameters(), only operating over all
// parameter indices and looking for non-wrt indices.
SmallVector<AnyFunctionType *, 2> curryLevels;
// An inlined version of unwrapCurryLevels().
Copy link
Contributor

@dan-zheng dan-zheng Aug 6, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: unwrapCurryLevels is hacky – it would be good to refactor it some point.

Without going too deep into implementation details: we only need to handle one potential "curry level" for method declarations – no need for loops or confusing ad-hoc terminology.

AnyFunctionType *fnTy = this;
while (fnTy != nullptr) {
curryLevels.push_back(fnTy);
fnTy = fnTy->getResult()->getAs<AnyFunctionType>();
}

SmallVector<unsigned, 2> curryLevelParameterIndexOffsets(curryLevels.size());
unsigned currentOffset = 0;
for (unsigned curryLevelIndex : llvm::reverse(indices(curryLevels))) {
curryLevelParameterIndexOffsets[curryLevelIndex] = currentOffset;
currentOffset += curryLevels[curryLevelIndex]->getNumParams();
}

if (!makeSelfParamFirst) {
std::reverse(curryLevels.begin(), curryLevels.end());
std::reverse(curryLevelParameterIndexOffsets.begin(),
curryLevelParameterIndexOffsets.end());
}

for (unsigned curryLevelIndex : indices(curryLevels)) {
auto *curryLevel = curryLevels[curryLevelIndex];
unsigned parameterIndexOffset =
curryLevelParameterIndexOffsets[curryLevelIndex];
for (unsigned paramIndex : range(curryLevel->getNumParams())) {
if (parameterIndices->contains(parameterIndexOffset + paramIndex))
continue;

auto param = curryLevel->getParams()[paramIndex];
if (param.isInOut()) {
auto resultType = param.getPlainType();
if (resultType->isVoid())
continue;
auto resultTan = resultType->getAutoDiffTangentSpace(lookupConformance);
if (!resultTan)
continue;
auto resultTanType = resultTan->getType();
resultTanTypes.push_back(resultTanType);
}
}
}

// Error if no semantic result has a tangent space.
if (resultTanTypes.empty() && !hasInoutResult) {
return llvm::make_error<DerivativeFunctionTypeError>(
this, DerivativeFunctionTypeError::Kind::NonDifferentiableResult,
std::make_pair(originalResultType, /*index*/ 0));
std::make_pair(originalResults.front().type, /*index*/ 0));
}
auto resultTanType = resultTan->getType();

// Compute the result linear map function type.
FunctionType *linearMapType;
@@ -6472,11 +6527,10 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
// - Original: `(T0, inout T1, ...) -> Void`
// - Differential: `(T0.Tan, ...) -> T1.Tan`
//
// Case 3: original function has a wrt `inout` parameter.
// - Original: `(T0, inout T1, ...) -> Void`
// - Differential: `(T0.Tan, inout T1.Tan, ...) -> Void`
// Case 3: original function has wrt `inout` parameters.
// - Original: `(T0, inout T1, ...) -> R`
// - Differential: `(T0.Tan, inout T1.Tan, ...) -> R.Tan`
SmallVector<AnyFunctionType::Param, 4> differentialParams;
bool hasInoutDiffParameter = false;
for (auto i : range(diffParams.size())) {
auto diffParam = diffParams[i];
auto paramType = diffParam.getPlainType();
@@ -6491,11 +6545,22 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
}
differentialParams.push_back(AnyFunctionType::Param(
paramTan->getType(), Identifier(), diffParam.getParameterFlags()));
if (diffParam.isInOut())
hasInoutDiffParameter = true;
}
auto differentialResult =
hasInoutDiffParameter ? Type(ctx.TheEmptyTupleType) : resultTanType;
Type differentialResult;
if (resultTanTypes.empty()) {
differentialResult = ctx.TheEmptyTupleType;
} else if (resultTanTypes.size() == 1) {
differentialResult = resultTanTypes.front();
} else {
SmallVector<TupleTypeElt, 2> differentialResults;
for (auto i : range(resultTanTypes.size())) {
auto resultTanType = resultTanTypes[i];
differentialResults.push_back(
TupleTypeElt(resultTanType, Identifier()));
}
differentialResult = TupleType::get(differentialResults, ctx);
}

// FIXME: Verify ExtInfo state is correct, not working by accident.
FunctionType::ExtInfo info;
linearMapType =
@@ -6513,11 +6578,11 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
// - Original: `(T0, inout T1, ...) -> Void`
// - Pullback: `(T1.Tan) -> (T0.Tan, ...)`
//
// Case 3: original function has a wrt `inout` parameter.
// - Original: `(T0, inout T1, ...) -> Void`
// - Pullback: `(inout T1.Tan) -> (T0.Tan, ...)`
// Case 3: original function has wrt `inout` parameters.
// - Original: `(T0, inout T1, ...) -> R`
// - Pullback: `(R.Tan, inout T1.Tan) -> (T0.Tan, ...)`
SmallVector<TupleTypeElt, 4> pullbackResults;
bool hasInoutDiffParameter = false;
SmallVector<AnyFunctionType::Param, 2> inoutParams;
for (auto i : range(diffParams.size())) {
auto diffParam = diffParams[i];
auto paramType = diffParam.getPlainType();
@@ -6531,7 +6596,9 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
std::make_pair(paramType, i));
}
if (diffParam.isInOut()) {
hasInoutDiffParameter = true;
if (paramType->isVoid())
continue;
inoutParams.push_back(diffParam);
continue;
}
pullbackResults.emplace_back(paramTan->getType());
@@ -6544,12 +6611,27 @@ AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType(
} else {
pullbackResult = TupleType::get(pullbackResults, ctx);
}
auto flags = ParameterTypeFlags().withInOut(hasInoutDiffParameter);
auto pullbackParam =
AnyFunctionType::Param(resultTanType, Identifier(), flags);
// First accumulate non-inout results as pullback parameters.
SmallVector<FunctionType::Param, 2> pullbackParams;
for (auto i : range(resultTanTypes.size())) {
auto resultTanType = resultTanTypes[i];
auto flags = ParameterTypeFlags().withInOut(false);
pullbackParams.push_back(AnyFunctionType::Param(
resultTanType, Identifier(), flags));
}
// Then append inout parameters.
for (auto i : range(inoutParams.size())) {
auto inoutParam = inoutParams[i];
auto inoutParamType = inoutParam.getPlainType();
auto inoutParamTan =
inoutParamType->getAutoDiffTangentSpace(lookupConformance);
auto flags = ParameterTypeFlags().withInOut(true);
pullbackParams.push_back(AnyFunctionType::Param(
inoutParamTan->getType(), Identifier(), flags));
}
// FIXME: Verify ExtInfo state is correct, not working by accident.
FunctionType::ExtInfo info;
linearMapType = FunctionType::get({pullbackParam}, pullbackResult, info);
linearMapType = FunctionType::get(pullbackParams, pullbackResult, info);
break;
}
}
8 changes: 6 additions & 2 deletions lib/IRGen/IRGenMangler.h
Original file line number Diff line number Diff line change
@@ -57,9 +57,11 @@ class IRGenMangler : public Mangle::ASTMangler {
AutoDiffDerivativeFunctionIdentifier *derivativeId) {
beginManglingWithAutoDiffOriginalFunction(func);
auto kind = Demangle::getAutoDiffFunctionKind(derivativeId->getKind());
auto *resultIndices =
autodiff::getAllFunctionSemanticResultIndices(func);
AutoDiffConfig config(
derivativeId->getParameterIndices(),
IndexSubset::get(func->getASTContext(), 1, {0}),
resultIndices,
derivativeId->getDerivativeGenericSignature());
appendAutoDiffFunctionParts("TJ", kind, config);
appendOperator("Tj");
@@ -86,9 +88,11 @@ class IRGenMangler : public Mangle::ASTMangler {
AutoDiffDerivativeFunctionIdentifier *derivativeId) {
beginManglingWithAutoDiffOriginalFunction(func);
auto kind = Demangle::getAutoDiffFunctionKind(derivativeId->getKind());
auto *resultIndices =
autodiff::getAllFunctionSemanticResultIndices(func);
AutoDiffConfig config(
derivativeId->getParameterIndices(),
IndexSubset::get(func->getASTContext(), 1, {0}),
resultIndices,
derivativeId->getDerivativeGenericSignature());
appendAutoDiffFunctionParts("TJ", kind, config);
appendOperator("Tq");
3 changes: 2 additions & 1 deletion lib/SIL/IR/SILDeclRef.cpp
Original file line number Diff line number Diff line change
@@ -853,7 +853,8 @@ std::string SILDeclRef::mangle(ManglingKind MKind) const {
auto *silParameterIndices = autodiff::getLoweredParameterIndices(
derivativeFunctionIdentifier->getParameterIndices(),
getDecl()->getInterfaceType()->castTo<AnyFunctionType>());
auto *resultIndices = IndexSubset::get(getDecl()->getASTContext(), 1, {0});
auto *resultIndices = autodiff::getAllFunctionSemanticResultIndices(
asAutoDiffOriginalFunction().getAbstractFunctionDecl());
AutoDiffConfig silConfig(
silParameterIndices, resultIndices,
derivativeFunctionIdentifier->getDerivativeGenericSignature());
13 changes: 3 additions & 10 deletions lib/SIL/IR/SILFunctionType.cpp
Original file line number Diff line number Diff line change
@@ -238,8 +238,6 @@ IndexSubset *SILFunctionType::getDifferentiabilityResultIndices() {
resultIndices.push_back(resultAndIndex.index());
// Check `inout` parameters.
for (auto inoutParamAndIndex : enumerate(getIndirectMutatingParameters()))
// FIXME(TF-1305): The `getResults().empty()` condition is a hack.
//
// Currently, an `inout` parameter can either be:
// 1. Both a differentiability parameter and a differentiability result.
// 2. `@noDerivative`: neither a differentiability parameter nor a
@@ -251,13 +249,8 @@ IndexSubset *SILFunctionType::getDifferentiabilityResultIndices() {
// cases, so supporting it is a non-goal.
//
// See TF-1305 for solution ideas. For now, `@noDerivative` `inout`
// parameters are not treated as differentiability results, unless the
// original function has no formal results, in which case all `inout`
// parameters are treated as differentiability results.
if (getResults().empty() ||
inoutParamAndIndex.value().getDifferentiability() !=
SILParameterDifferentiability::NotDifferentiable)
resultIndices.push_back(getNumResults() + inoutParamAndIndex.index());
resultIndices.push_back(getNumResults() + inoutParamAndIndex.index());
auto numSemanticResults =
getNumResults() + getNumIndirectMutatingParameters();
return IndexSubset::get(getASTContext(), numSemanticResults, resultIndices);
@@ -574,7 +567,7 @@ static CanSILFunctionType getAutoDiffDifferentialType(
differentialResults.push_back({resultTanType, resultConv});
continue;
}
// Handle original `inout` parameter.
// Handle original `inout` parameters.
auto inoutParamIndex = resultIndex - originalFnTy->getNumResults();
auto inoutParamIt = std::next(
originalFnTy->getIndirectMutatingParameters().begin(), inoutParamIndex);
@@ -709,7 +702,7 @@ static CanSILFunctionType getAutoDiffPullbackType(
pullbackParams.push_back({resultTanType, paramConv});
continue;
}
// Handle original `inout` parameter.
// Handle `inout` parameters.
auto inoutParamIndex = resultIndex - originalFnTy->getNumResults();
auto inoutParamIt = std::next(
originalFnTy->getIndirectMutatingParameters().begin(), inoutParamIndex);
6 changes: 4 additions & 2 deletions lib/SILGen/SILGen.cpp
Original file line number Diff line number Diff line change
@@ -1252,11 +1252,12 @@ void SILGenModule::emitDifferentiabilityWitnessesForFunction(
auto *AFD = constant.getAbstractFunctionDecl();
auto emitWitnesses = [&](DeclAttributes &Attrs) {
for (auto *diffAttr : Attrs.getAttributes<DifferentiableAttr>()) {
auto *resultIndices = IndexSubset::get(getASTContext(), 1, {0});
assert((!F->getLoweredFunctionType()->getSubstGenericSignature() ||
diffAttr->getDerivativeGenericSignature()) &&
"Type-checking should resolve derivative generic signatures for "
"all original SIL functions with generic signatures");
auto *resultIndices =
autodiff::getAllFunctionSemanticResultIndices(AFD);
auto witnessGenSig =
autodiff::getDifferentiabilityWitnessGenericSignature(
AFD->getGenericSignature(),
@@ -1285,7 +1286,8 @@ void SILGenModule::emitDifferentiabilityWitnessesForFunction(
auto witnessGenSig =
autodiff::getDifferentiabilityWitnessGenericSignature(
origAFD->getGenericSignature(), AFD->getGenericSignature());
auto *resultIndices = IndexSubset::get(getASTContext(), 1, {0});
auto *resultIndices =
autodiff::getAllFunctionSemanticResultIndices(origAFD);
AutoDiffConfig config(derivAttr->getParameterIndices(), resultIndices,
witnessGenSig);
emitDifferentiabilityWitness(origAFD, origFn,
Loading