Gradients#
Every operation in the integration is a PyTorch operation, so the integral can be differentiated with respect to anything the integrand depends on. There are two ways to compute \(\nabla_\theta \int f_\theta(t)\,dt\):
Every operation of the integration is differentiable, so you can take gradients of the result with respect to anything the integrand depends on. There are two equivalent ways to compute \(\nabla_\theta \int f_\theta(t)\,dt\):
import torch
from padaquad import adaptive_quadrature, steps
theta = torch.tensor(1.7, dtype=torch.float64, requires_grad=True)
mesh_init = torch.tensor([0.0])
mesh_final = torch.tensor([torch.pi])
# (A) Backprop through the integral.
solver = adaptive_quadrature(
sampling_type=steps.ADAPTIVE_UNIFORM,
method="gk21",
atol=1e-8,
rtol=1e-8,
)
solver.integrate(
f=lambda t: theta * torch.sin(t),
mesh_init=mesh_init,
mesh_final=mesh_final,
take_gradient=True, # per-batch backward; accumulates into theta.grad
)
print(theta.grad) # 2.0
# (B) Integrate the gradient of the integrand directly.
df_dtheta = lambda t: torch.sin(t) # closed-form derivative
out_b = solver.integrate(f=df_dtheta, mesh_init=mesh_init, mesh_final=mesh_final)
print(out_b.integral) # also 2.0
The two paths agree to machine precision on smooth integrands; this
consistency is verified in tests/test_autodiff_consistency.py.
Memory-bounded gradients. Setting take_gradient=True makes the
solver call loss.backward() after each accepted batch instead of
holding the full autograd graph until the end. This is essential when
the number of integrand evaluations is large enough that the graph would
otherwise exceed GPU memory.
Path B uses the fact that differentiation and integration can be exchanged when the integration domain does not depend on \(\theta\) and \(f_\theta\) is smooth in \(\theta\). The script Two ways to differentiate an integral runs both paths.
take_gradient#
With take_gradient=True (the default), loss.backward() runs after each
batch, so gradients accumulate in the parameters’ .grad without the autograd
graph of the whole integration being held in memory. The recorded results are
then detached: result.integral cannot be differentiated again, and the
gradient is already in .grad. Call the optimizer’s zero_grad before each
integration, as for any loss.
With take_gradient=False, the graph is kept, so the returned
result.integral can be differentiated like any tensor. This needs memory for
the graph of every evaluation of the integrand.
loss_fxn#
loss_fxn maps one batch’s IntegrationResult to a scalar tensor; with
take_gradient=True its result is back-propagated after each batch, and
result.loss is the sum over batches. If it is None, the loss is the batch’s
integral, so the accumulated gradient is the gradient of the integral. Because
the loss is applied batch by batch, a loss that is not linear in the integral
(for example its square) gives the sum of the batches’ losses, not the loss of
the total: compute such a loss from result.integral with
take_gradient=False instead.