Julius Ikkala

Leveraging Slang's automatic differentiation for computing PDFs

The probability density functions (PDFs) used in Monte Carlo integration (such as path tracing), can be derived using Jacobian determinants. For example, if we have a function f(ξ)f(\xi) that maps our "primary sample space" sample ξ∈[0,1]N\xi \in [0, 1]^N (uniformly distributed) value into some distribution that we wish to use for importance sampling, the PDF is

p(f(ξ))=p(ξ)∣Jf(ξ)∣=1∣Jf(ξ)∣ p(f(\xi)) = \frac{p(\xi)}{|J_f(\xi)|} = \frac{1}{|J_f(\xi)|}

Where ∣Jf(ξ)∣|J_f(\xi)| is the absolute value of the Jacobian determinant for f(ξ)f(\xi).

One notable snag here is that we do need the Jacobian matrix to be square so that we can compute the determinant. This can be a bit confusing if your function is f:R2→R3f: \Reals^2 \to \Reals^3, which is pretty common in a path tracer. You often want to map a 2D random value to a 3D unit vector. You have two options here. You can represent the unit vector as two angles to make the mapping be f:R2→R2f: \Reals^2 \to \Reals^2, or you could add a new parameter, length:

g(l,ξ)=l⋅f(ξ) g(l, \xi) = l \cdot f(\xi)

Now, g:R3→R3g: \Reals^3 \to \Reals^3, which is also square and we don't have to mess with any extra sines or cosines. We can assign l=1l = 1 after the automatic differentiation, and partial derivatives of ll are trivial:

∂gi(l,ξ)∂l=∂l⋅fi(ξ)∂l=fi(ξ) \frac{\partial g_i(l, \xi)}{\partial l} = \frac{\partial l \cdot f_i(\xi)}{\partial l} = f_i(\xi)

Since the Jacobian matrix Jf(ξ)J_f(\xi) is simply a bunch of partial derivatives, we can actually use Slang's autodiff functionality to figure out the PDF corresponding to a mapping f(ξ)f(\xi)!

Here's an example of doing that with a function float3 octahedralMapping(float2 uv) that maps a [0,1]2[0,1]^2 coordinate to a vector on the unit sphere:

// If the PDF of 'uv' is 1, the PDF of the octahedral sampling is
//    PDF = 1.0f / octahedralJacobianAbsDet(uv)
float octahedralJacobianAbsDet(float2 uv)
{
    DifferentialPair<float2> du_v = diffPair(uv, float2(1.0, 0.0));
    DifferentialPair<float2> u_dv = diffPair(uv, float2(0.0, 1.0));

    DifferentialPair<float3> df_du = fwd_diff(octahedralMapping)(du_v);
    DifferentialPair<float3> df_dv = fwd_diff(octahedralMapping)(u_dv);

    float3x3 jacobian = float3x3(
        // The first vector here represents the jacobians from the "scale" of the
        // vector: octahedralMapping(u, v) * scale. The derivative of that w.r.t.
        // scale is just octahedralMapping(u, v), so we can use the primal value.
        df_du.p,
        df_du.d,
        df_dv.d
    );

    return abs(determinant(jacobian));
}

Cool, right?