diff options
| -rw-r--r-- | source/slang/slang-ir-autodiff.cpp | 10 | ||||
| -rw-r--r-- | tests/autodiff/high-order-forward-diff-struct.slang | 50 | ||||
| -rw-r--r-- | tests/autodiff/high-order-forward-diff-struct.slang.expected.txt | 5 |
3 files changed, 65 insertions, 0 deletions
diff --git a/source/slang/slang-ir-autodiff.cpp b/source/slang/slang-ir-autodiff.cpp index 024d31fd8..3257ee102 100644 --- a/source/slang/slang-ir-autodiff.cpp +++ b/source/slang/slang-ir-autodiff.cpp @@ -399,6 +399,16 @@ void DifferentiableTypeConformanceContext::setFunc(IRGlobalValueWithCode* func) else { differentiableWitnessDictionary.Add((IRType*)item->getConcreteType(), item->getWitness()); + + // Also register the type's differential type with the same witness. + IRBuilder subBuilder(item->getConcreteType()); + if (!as<IRInterfaceType>(item->getConcreteType())) + { + differentiableWitnessDictionary.AddIfNotExists( + (IRType*)_lookupWitness(&subBuilder, item->getWitness(), sharedContext->differentialAssocTypeStructKey), + item->getWitness()); + } + if (auto diffPairType = as<IRDifferentialPairTypeBase>(item->getConcreteType())) { // For differential pair types, register the differential type as well. diff --git a/tests/autodiff/high-order-forward-diff-struct.slang b/tests/autodiff/high-order-forward-diff-struct.slang new file mode 100644 index 000000000..7e39640a1 --- /dev/null +++ b/tests/autodiff/high-order-forward-diff-struct.slang @@ -0,0 +1,50 @@ +//TEST(compute):COMPARE_COMPUTE_EX:-slang -compute -shaderobj -output-using-type +//TEST(compute, vulkan):COMPARE_COMPUTE_EX:-vk -compute -shaderobj -output-using-type + +//TEST_INPUT:ubuffer(data=[0 0 0 0], stride=4):out,name=outputBuffer +RWStructuredBuffer<float> outputBuffer; + +struct MyStruct : IDifferentiable +{ + float x; + uint i; + + [ForwardDifferentiable] + __init(float x, uint i) + { + this.x = x; + this.i = i; + } +}; + +[ForwardDifferentiable] +float mySqr(MyStruct s) +{ + if (s.i >= 1) + return s.x * s.x; + else + return 0.f; +} + +[ForwardDifferentiable] +float f(float x) +{ + MyStruct ms = MyStruct(x * x, 1); + return mySqr(ms); +} + +[ForwardDifferentiable] +float df(float x) +{ + return __fwd_diff(f)(DifferentialPair<float>(x, 1.0)).d; +} + +[numthreads(1, 1, 1)] +void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID) +{ + // Given f(x) = x^4, + // f''(x) = 12 * x^2 + // Expect f''(4) = 192 + outputBuffer[0] = __fwd_diff(df)(DifferentialPair<float>(4.0, 1.0)).d; +} + diff --git a/tests/autodiff/high-order-forward-diff-struct.slang.expected.txt b/tests/autodiff/high-order-forward-diff-struct.slang.expected.txt new file mode 100644 index 000000000..0f08247f0 --- /dev/null +++ b/tests/autodiff/high-order-forward-diff-struct.slang.expected.txt @@ -0,0 +1,5 @@ +type: float +192.000000 +0.000000 +0.000000 +0.000000 |
