Stochastic Batches
Mini-batch SPG with shot sampling
Large surveys rarely fit in memory, so gradients must be estimated from a subset of shots. This example shows how to configure reproducible mini-batches and plug them into SPG.
2. Run SPG with Mini-Batches
Use SamplingConfig to configure shot sampling. The optimizer draws a fresh random batch each iteration.
from devitohorizon.optimization import SPG
from devitohorizon.config import SamplingConfig
optimizer = SPG(maxiter=20, ftol=1e-6, gtol=1e-8, verbose=True)
model_opt, f_opt, info = optimizer.fwi(
physics=physics,
dataset=dataset,
model0=physics.model,
bounds={'vp': (1.4, 5.5)},
sampling=SamplingConfig(batch_size=8, seed=42),
)Equivalently, sampling parameters can be passed directly to the optimizer constructor so they apply as the default for every fwi() call:
optimizer = SPG(maxiter=20, batch_size=8, seed=42, verbose=True)The gradient always comes from the sampled subset, so the objective values reported in info are mini-batch values. Use physics.objective(dataset) afterwards to obtain the full-batch misfit if needed.
3. Per-Iteration Callback
The callback receives the current model after each iteration:
import numpy as np
def on_iteration(model):
grad_norm = np.linalg.norm(model.vp.data)
print(f"Current vp range: [{model.vp.data.min():.3f}, {model.vp.data.max():.3f}]")
model_opt, f_opt, info = optimizer.fwi(
physics=physics,
dataset=dataset,
model0=physics.model,
bounds={'vp': (1.4, 5.5)},
sampling=SamplingConfig(batch_size=8, seed=42),
callback=on_iteration,
)Within the callback you can also save intermediate models or plot stacked gradients.
4. Tips
- Use
mute_taper_widthinGradientProcessingConfigto stabilize gradients when batches change significantly. - Enable
source_estimation=Trueto mitigate amplitude differences between shots. - When running on Dask, pass a
DaskSchedulerto distribute shot computation across workers.