FDTD for Room Acoustics, Part 3: Recovering a Source Position with Differentiable FDTD in Dr.Jit
Introduction:
In Part 1 and Part 2 of this series we derived the math for a simple 2D FDTD solver and implemented it in Dr.Jit. We could have also done this in Numpy or directly in C++. However, Dr.Jit is an interesting library, as it allows for writing one body of code which gets Just in Time compiled for CPU, multi-CPU, CUDA GPUs or even Apple's Metal. The feature which really sets it apart though is the inbuilt differentiability which allows for optimisation of input parameters based on the results of a computation. This feature we would like to test in this Part 3 and see if we are able to recover an input parameter from simulation results.
Generally, this kind of optimisation requires a computation graph with all involved variables stored in memory. The influence of each variable on this graph is determined by calculating its partial derivative. As there is usually more than one variable involved, several partial derivatives are evaluated and multiplied using the chain rule. After evaluating the forward pass, we calculate the loss on the outputs. Then we propagate gradients back with reverse-mode automatic differentiation (AD). An optimiser like gradient descent or Adam follows steepest gradients in search for minima in the optimisation landscape in order to identify inputs which yield low losses.
Unlike training a neural net, we aren't fitting abstract weights in a black box. The computational graph is fixed by the physics, and we adjust real, physical input parameters to it.
Methods:
Now for our case that computational chain is the computation from input parameters, via the update formula solving the PDE, to our output, which are the resulting frames with our pressure field.
The most basic optimisation experiment is to recover the source position coordinates. Imagine you ran this simulation, and you would just get to see a few frames at known timesteps and use these results to estimate the position of the source at time 0. This is exactly what we ask our setup to do.
In terms of the code we do not have to make great changes to achieve this. Most important here is to import our variables as differentiable using the ad variants such as:
from drjit.cuda.ad import Float, UInt
In our Gaussian impulse we have to make sure that we add 2 optimisable variables which determine the source position, ensuring that we do not use detach as previously when setting the values for u_prev for the first time and returning frames as jit arrays instead of numpy arrays to avoid breaking the gradients of the graph.
Then, we enable gradients on our optimisation variables and run our solver one time to save reference field frames as an optimisation goal. Here we explicitly want to detach results from the graph as these references should be static.
rpx,rpy = Float(0.5), Float(0.5)
dr.enable_grad(rpx,rpy)
dt, nsteps, u_ref, frames, jitframes = run_sim_frames(
rpx,rpy,
xL=xL_s, xR=xR_s,
yB=yB_s, yT=yT_s,
nx=400, ny=600,
te=timeEnd,
record_every=record_every,
source="gaussian")
u_ref_frames = dr.detach(jitframes)
A loss function compares frames of the current iteration with the reference frame. Two different loss functions were tested: A vanilla Mean Square Error (MSE) and an amplitude-based MSE as in code below:
# vanilla MSE
def loss_fn_mse(u_opt_frames,u_ref_frames):
loss = 0.0
for a,b in zip(u_opt_frames,u_ref_frames):
loss = loss+ dr.mean(dr.square(a - b))
return loss/len(u_opt_frames)
# amplitude MSE
def loss_fn_amse(u_opt_frames,u_ref_frames):
loss = 0.0
for a,b in zip(u_opt_frames,u_ref_frames):
loss = loss+ dr.mean(dr.square(dr.abs(a) - dr.abs(b)))
return loss/len(u_opt_frames)
The optimisation starts from relative positions \(x = 0.67\) and \(y = 0.11\) . The source position is optimised with a hand-written Adam optimiser (β₁ = 0.9, β₂ = 0.999, learning rate 0.01) over 79 iterations. After each step, the position is clipped to the domain and detached, and gradients are re-enabled for the next iteration.
gx = dr.grad(rpx)
gy = dr.grad(rpy)
m_x = beta1 * m_x + (1.0 - beta1) * gx
m_y = beta1 * m_y + (1.0 - beta1) * gy
v_x = beta2 * v_x + (1.0 - beta2) * dr.square(gx)
v_y = beta2 * v_y + (1.0 - beta2) * dr.square(gy)
m_x_hat = m_x / (1.0 - beta1 ** it)
m_y_hat = m_y / (1.0 - beta1 ** it)
v_x_hat = v_x / (1.0 - beta2 ** it)
v_y_hat = v_y / (1.0 - beta2 ** it)
rpx = dr.detach(dr.clip(rpx - lr * m_x_hat / (dr.sqrt(v_x_hat) + eps), 0.0, 1.0))
rpy = dr.detach(dr.clip(rpy - lr * m_y_hat / (dr.sqrt(v_y_hat) + eps), 0.0, 1.0))
history.append((Float(rpx),Float(rpy)))
dr.enable_grad(rpx, rpy)Results:
The described setup yields different outcomes based on the chosen loss. With the vanilla MSE, the estimate moves away from the reference within the first few iterations and is pushed against the lower domain boundary (y = 0), where it remains for the rest of the run while the gradient stays roughly constant.

The amplitude MSE is able to quickly match estimated source position to reference source position. Starting from the same relative position as the MSE simulation it converges in about 40 iterations as can be seen below.

In the amplitude MSE run, oscillations can be observed both in the loss (while it is descending overall) and in the gradients in x and y. In the animation, positive (red) and negative (blue) regions of the field appear right next to each other.
Discussion:
The above results suggest that the choice of a suitable loss function is crucial. The vanilla MSE did not converge in this case, whereas an earlier test (not shown above) with a starting position close to the reference position did converge.
The reason lies in the alternating polarity of the propagating wave. As the estimated source moves, positive and negative regions of the field slide past those of the reference, so the vanilla MSE alternately rewards and penalises the shift. The optimisation landscape therefore contains many local minima, and the further the starting position is from the reference, the more likely the optimiser is to get stuck in one of them. An amplitude-based loss discards the polarity of the field. This makes the landscape considerably smoother and removes many of these local minima. Physically, we are then optimising for something closer to an energy envelope than to the signed pressure field.
In this run, the vanilla MSE found an even simpler way to reduce the loss: pushing the source into the Dirichlet boundary, where the field is forced to zero, weakens the simulated wave. When simulated and reference fields barely overlap, a weaker field lowers the squared error, even though the position moves away from the true one.
Note that the reference was generated by the same solver at the same resolution, so this is a best-case scenario. Further investigation should look at how the number of recorded intermediate frames influences the reconstruction, and at the robustness of the setup when reference and optimisation use different resolutions. In reality, a sound field is only sampled at a few points in a room. To get closer to real applications, it would therefore be valuable to test whether the optimisation yields similar results using virtual microphones with directivity, rather than knowing the whole field.
This behaviour closely resembles cycle skipping, a well-known problem in seismic full waveform inversion, where similar remedies such as envelope-based losses are used. The memory and runtime cost of differentiating through the full simulation is another open question, especially with 3D in mind.
If you work on inverse problems in acoustics or differentiable simulation, I'd be glad to hear from you, and happy to share more details.
If you work on inverse problems in acoustics or differentiable simulation, or have an acoustic problem you'd like to solve, I'd be glad to hear from you. Reach out via blog[at]ph-os.com or in the comments below.