Skip to content
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

Don't initialize temp var for out parameters when generating the backward diff function #6076

Merged
merged 1 commit into from
Jan 13, 2025
Merged
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
10 changes: 6 additions & 4 deletions source/slang/slang-ir-autodiff-rev.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -528,10 +528,12 @@ InstPair BackwardDiffTranscriber::transcribeFuncHeader(IRBuilder* inBuilder, IRF
// If primal parameter is mutable, we need to pass in a temp var.
auto tempVar = builder.emitVar(primalParamPtrType->getValueType());

// We also need to setup the initial value of the temp var, otherwise
// the temp var will be uninitialized which could cause undefined behavior
// in the primal function.
builder.emitStore(tempVar, primalArg);
// If the parameter is not a pure 'out' param, we also need to setup the initial
// value of the temp var, otherwise the temp var will be uninitialized which could
// cause undefined behavior in the primal function.
//
if (!as<IROutType>(primalParamType))
builder.emitStore(tempVar, primalArg);

primalArgs.add(tempVar);
}
Expand Down
49 changes: 49 additions & 0 deletions tests/autodiff/out-parameters-2.slang
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//TEST(compute):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-slang -compute -shaderobj -output-using-type
//TEST(compute, vulkan):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-vk -compute -shaderobj -output-using-type

//TEST_INPUT:ubuffer(data=[0 0 0 0], stride=4):out,name=outputBuffer
RWStructuredBuffer<float> outputBuffer;

typedef DifferentialPair<float> dpfloat;

struct Foo : IDifferentiable
{
float a;
int b;
}

[PreferCheckpoint]
float k()
{
return outputBuffer[3] + 1;
}

[Differentiable]
void h(float x, float y, out Foo result)
{
float p = no_diff k();
float m = x + y + p;
float n = x - y;
float r = m * n + 2 * x * y;

result = {r, 2};
}

[numthreads(1, 1, 1)]
void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
float x = 2.0;
float y = 3.5;
float dx = 1.0;
float dy = 0.5;

dpfloat dresult;
dpfloat dpx = diffPair(x);
dpfloat dpy = diffPair(y);
Foo.Differential dFoo;
dFoo.a = 1.0;
bwd_diff(h)(dpx, dpy, dFoo);

outputBuffer[0] = dpx.d; // CHECK: 12.0
outputBuffer[1] = dpy.d; // CHECK: -4.0
}
Loading