summaryrefslogtreecommitdiffstats
path: root/tests/autodiff/was/warped-sampling-1d.slang
blob: c533f7caa5c9201a42f2a788d931bf1167cfd432 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//TEST(compute):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-slang -compute -shaderobj -output-using-type -profile cs_5_1 -dx12 -use-dxbc -compute-dispatch 4,1,1
//TEST(compute):COMPARE_COMPUTE_EX(filecheck-buffer=CHECK):-slang -compute -shaderobj -output-using-type -profile cs_5_1 -cuda -use-dxbc -compute-dispatch 4,1,1

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

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

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

typedef float Color;

struct PRNG
{
    __init(uint seed)
    {
        this.state = seed;
    }

    [mutating] uint next()
    {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        return state;
    }

    [mutating] float nextFloat1D()
    {
        return float(next()) / float(4294967295.0);
    }

    uint state;
};

struct LineSegment : IDifferentiable
{
    float x0;
    float x1;

    Color color;

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

struct Intersection : IDifferentiable
{
    LineSegment ls;
    float x;
    bool isIntersected;
    float wt;

    [BackwardDifferentiable]
    __init(LineSegment _ls, float _x, bool _isIntersected, float _wt)
    {
        this.ls = _ls;
        this.x = _x;
        this.isIntersected = _isIntersected;
        this.wt = _wt;
    }
};

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

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

void accumulateDifferentialFixedPoint(
    RWStructuredBuffer<int> buffer, 
    uint index,
    float.Differential df,
    float scale = 1000000.f)
{
    InterlockedAdd(buffer[index], (int)round(df * scale));
}

void d_loadLineSegment(uint id, LineSegment.Differential d_ls)
{
    accumulateDifferentialFixedPoint(endpointDifferentialBufferInt, id * 2, d_ls.x0);
    accumulateDifferentialFixedPoint(endpointDifferentialBufferInt, id * 2 + 1, d_ls.x1);
}

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

int getIntersectionID(float x)
{
    // Line segments are ordered by z-index so return the first intersection.
    for (int id = 0; id < 2; id++)
    {
        LineSegment ls = loadLineSegment(id);
        if (x > ls.x0 && x < ls.x1)
            return id;
    }
    return -1;
}

[BackwardDifferentiable]
Intersection intersect(float x)
{
    int id = getIntersectionID(x);
    if (id >= 0)
        return Intersection(loadLineSegment((uint)id), x, true, 1.0);

    return Intersection(LineSegment(0, 0, 0), x, false, 0.0);
}

[BackwardDifferentiable]
float shadeIntersection(Intersection isect)
{
    return isect.ls.color;
}

float sample1DNormal(inout PRNG prng, float mu, float sigma)
{
    float u = prng.nextFloat1D();
    float v = prng.nextFloat1D();
    return mu + (sqrt(-2 * log(u))*cos(2*3.1415*v) * sigma);
}

[BackwardDifferentiable]
float pdf1DNormal(no_diff float x, float mu, no_diff float sigma)
{  
    float k = ((x - mu) / sigma);
    return exp(-0.5 * (k * k)) / (sigma * 2.506628);
}

float boundaryTerm(Intersection isect)
{
    if (!isect.isIntersected)
        return 100.0; // Large default value for missed rays.
    
    float leftDist = abs(isect.x - isect.ls.x0);
    float rightDist = abs(isect.ls.x1 - isect.x);

    if (leftDist > rightDist)
        return rightDist * 30.f;
    else
        return leftDist * 30.f;
}

[BackwardDifferentiable]
DifferentialPair<float> infinitesimal(DifferentialPair<float> x)
{
    return diffPair(x.p - detach(x.p), x.d - detach(x.d));
}

[BackwardDifferentiable]
float harmonicWeight(Intersection isect, no_diff Intersection aux_isect)
{
    float x_dist = isect.x - aux_isect.x;
    float k = 1.0 / (((x_dist * x_dist) + no_diff(boundaryTerm(aux_isect))));
    return k;
}

[BackwardDifferentiable]
float attachToGeometry(Intersection isect)
{
    float leftWt = detach(isect.ls.x1 - isect.x);
    float rightWt = detach(isect.x - isect.ls.x0);

    return (leftWt * isect.ls.x0 + rightWt * isect.ls.x1) / (leftWt + rightWt);
}

[BackwardDifferentiable]
float warp(Intersection isect, inout PRNG prng)
{
    float totalWeight = 0.f;
    float totalWarpedPoint = 0.f;

    float aux_sigma = 0.01;

    for (int i = 0; i < 32; i++)
    {
        float y = no_diff(sample1DNormal(prng, isect.x, aux_sigma));
        float y_flipped = 2 * isect.x - y;

        Intersection aux_isect_left = intersect(y);

        if (aux_isect_left.isIntersected)
        {
            float pdf = pdf1DNormal(y, isect.x, aux_sigma);
            float wt = harmonicWeight(isect, aux_isect_left) * (pdf / detach(pdf));
            totalWarpedPoint += attachToGeometry(aux_isect_left) * wt;
            totalWeight += wt;
        }
        
        Intersection aux_isect_right = intersect(detach(y_flipped));

        if (aux_isect_right.isIntersected)
        {
            float pdf = pdf1DNormal(y_flipped, isect.x, aux_sigma);
            float wt = harmonicWeight(isect, aux_isect_right) * (pdf / detach(pdf));
            totalWarpedPoint += attachToGeometry(aux_isect_right) * wt;
            totalWeight += wt;
        }
    }

    return totalWarpedPoint / totalWeight;
}

[BackwardDifferentiable]
Intersection warpedIntersect(float x, inout PRNG prng)
{   
    // TODO: For now the jacobian here is 1.0, 
    // but we will need to adjust the warp by the jacobian for
    // more complex intersection models.
    //
    Intersection isect = intersect(x);

    Intersection.Differential d_isect = Intersection.Differential.dzero();
    d_isect.x = 1.0;

    var dpwarp = infinitesimal(
        __fwd_diff(warp)(diffPair(isect, d_isect), prng));

    isect.x = detach(isect.x) + dpwarp.p;
    isect.wt = isect.wt * (1 + dpwarp.d);

    return isect;
}

[BackwardDifferentiable]
float renderSample(inout PRNG prng) 
{
    float u = no_diff(prng.nextFloat1D());
    
    float leftBound = 0.0;
    float rightBound = 1.0;

    float sample = leftBound * u + rightBound * (1 - u);
    float weight = 1.0/(rightBound - leftBound);
 
    Intersection isect = warpedIntersect(sample, prng);

    return shadeIntersection(isect) * isect.wt;
}

[numthreads(256, 1, 1)]
void computeMain(uint3 threadIdx : SV_DispatchThreadID,)
{
    uint seed = (threadIdx.x * threadIdx.x) * 30 + 3;
    PRNG prng = PRNG(seed);
    
    float d_color = 1.0 / 1000.0;
    __bwd_diff(renderSample)(prng, d_color);

    AllMemoryBarrierWithGroupSync();
    
    // Convert to floating point (but with 2 fewer digits of precision to 
    // avoid platform-specific differences in floating point precision)
    // 
    if (threadIdx.x < 10)
        endpointDifferentialBuffer[threadIdx.x] =
            ((endpointDifferentialBufferInt[threadIdx.x]/1000) / 1000000.f) * 1000.f;

// Note that this specific derivative estimation method is biased, so the
// expected results are approximate. (We've fixed the RNG seed to generate
// repeatable results)
//
// Expect: Approximately -1.0 in endpointDifferentialBuffer[0]
// Expect: Approximately 1.0 in endpointDifferentialBuffer[1]
//
// Expect: Approximately 0.0 in endpointDifferentialBuffer[2]
// Expect: Approximately 0.0 in endpointDifferentialBuffer[3]
//
}
// CHECK: type: float
// CHECK-NEXT: -0.{{9[5-9][0-9]}}000
// CHECK-NEXT: 0.{{9[5-9][0-9]}}000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.004000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.000000
// CHECK-NEXT: 0.000000