summaryrefslogtreecommitdiffstats
path: root/tests/autodiff/diff-assoctype-generic-interface.slang
blob: dff55eae9358396d3b729db3f3c60efd44ccab34 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Test calling differentiable function through dynamic dispatch.

//TEST(compute, vulkan):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-vk -compute -shaderobj -output-using-type -compile-arg -skip-spirv-validation -emit-spirv-directly
//TEST(compute):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-cuda -compute -shaderobj -output-using-type

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

interface IGetter : IDifferentiable
{
    [Differentiable]
    float get(uint id);
}

struct GetterImpl : IGetter
{
    float[8] data;

    [Differentiable]
    __init(float[8] data)
    { this.data = data; }

    [Differentiable]
    float get(uint id)
    {
        return data[id];
    }
}
interface IFoo<int N>
{
    associatedtype Params : IGetter;

    [Differentiable]
    Params bar();
}

[BackwardDerivative(load_bwd)]
[ForwardDerivative(load_fwd)]
float load(uint id)
{
    return outputBuffer[id] + 2;
}

DifferentialPair<float> load_fwd(uint id)
{
    return DifferentialPair<float>(load(id), 3.f);
}

void load_bwd(uint id, float.Differential dOut)
{
    outputBuffer[id + 8] = dOut;
}

struct FooImpl1: IFoo<8>
{   
    typealias Params = GetterImpl;

    __init()
    { }

    [Differentiable]
    Params bar()
    {
        float x = load(0);
        return GetterImpl({x, x+1, x+2, x+3, x+4, x+5, x+6, x+7});
    }
}

/*
// There's a slight issue with dynamic dispatch over generic interfaces. Uncomment after that is fixed.

struct FooImpl2: IFoo<8>
{
    typealias Params = GetterImpl;

    __init()
    { }

    [Differentiable]
    Params bar()
    {
        float x = 2 * load(0);
        return GetterImpl({x, x+5, x+7, x+9, x+11, x+13, x+15, x+17});
    }
}
*/

IFoo<8> getFoo(uint id)
{
    /*if (id == 0)
        return FooImpl1();
    else
        return FooImpl2();*/
    return FooImpl1();
}

[Differentiable]
float doThing(uint id)
{
    IFoo<8> foo = getFoo(id);
    return foo.bar().get(0);
}

[shader("compute")]
void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
    outputBuffer[0] = doThing(0); // CHECK: 2.0
    outputBuffer[1] = doThing(1); // CHECK: 4.0

    outputBuffer[2] = fwd_diff(doThing)(0).d; // CHECK: 3.0
    outputBuffer[3] = fwd_diff(doThing)(1).d; // CHECK: 3.0
}