summaryrefslogtreecommitdiffstats
path: root/tests/autodiff/high-order-user-defined-derivative.slang
blob: 10c3c12dc9d6f3ccb4ef66575fdf327e9b654607 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//TEST(compute):COMPARE_COMPUTE_EX:-slang -compute -shaderobj -output-using-type
//TEST(compute, vulkan):COMPARE_COMPUTE_EX:-vk -compute -shaderobj -output-using-type
//TEST(compute):COMPARE_COMPUTE_EX:-cuda -compute -shaderobj -output-using-type

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

//TEST_INPUT:ubuffer(data=[0.0 1.0 2.0 3.0], stride=4):name=endpointBuffer
RWStructuredBuffer<float> endpointBuffer;

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

struct LineSegment : IDifferentiable
{
    float x0;
    float x1;

    [BackwardDifferentiable]
    __init(float _x0, float _x1)
    {
        x0 = _x0;
        x1 = _x1;
    }
};

[BackwardDerivative(d_loadLineSegment)]
[ForwardDerivative(fwd_loadLineSegment)]
LineSegment loadLineSegment(uint id)
{
    return {endpointBuffer[id * 2], endpointBuffer[id * 2 + 1]};
}

[BackwardDerivative(d_fwd_loadLineSegment)]
DifferentialPair<LineSegment> fwd_loadLineSegment(uint id)
{
    return DifferentialPair<LineSegment>(loadLineSegment(id), LineSegment.dzero());
}

void d_loadLineSegment(uint id, LineSegment.Differential d_ls)
{
    endpointDifferentialBuffer[id * 2] += d_ls.x0;
    endpointDifferentialBuffer[id * 2 + 1] += d_ls.x1;
}

void d_fwd_loadLineSegment(uint id, DifferentialPair<LineSegment>.Differential dp_ls)
{
    endpointDifferentialBuffer[id * 2] += dp_ls.p.x0;
    endpointDifferentialBuffer[id * 2 + 1] += dp_ls.p.x1;
}

[BackwardDifferentiable]
float something()
{
    LineSegment ls = __fwd_diff(loadLineSegment)(1).p;
    return ls.x0 + ls.x1;
}

[numthreads(1, 1, 1)]
void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
    {
        LineSegment ls = __fwd_diff(loadLineSegment)(0).p;
        outputBuffer[0] = ls.x0; // Expect: 0
        outputBuffer[1] = ls.x1; // Expect: 1
    }

    {
        LineSegment.Differential d_ls = __fwd_diff(loadLineSegment)(0).d;
        outputBuffer[2] = d_ls.x1; // Expect: 0
    }

    {
        // Expect: 2.0 in endpointDifferentialBuffer[2]
        // Expect: 2.0 in endpointDifferentialBuffer[3]
        __bwd_diff(something)(2.0); 
    }
}