Skip to content

03 · Block-diagonal GGN: exact affine-layer blocks

A standalone tutorial using the maintained laplace_hypopinn package. Tutorial index · Method definitions

Goal

Learn the full path from synthetic receiver observations to a trained travel-time field, a local parameter distribution, and sampled source locations. The figures and checks below are generated by the displayed code.

Keep each affine layer's full weighted residual GGN block and discard couplings between layers: $$ \widehat F=\operatorname{blockdiag}(F_{11},\ldots,F_{LL}), \qquad P_\ell=sF_{\ell\ell}+\lambda I=C_\ell C_\ell^\top. $$ Each block includes the layer's weights and biases in row-major augmented [W|b] order. These are exact blocks of the selected GGN, not Kronecker-factor approximations. Storage is \(\sum_\ell p_\ell^2\) entries; the largest layers can dominate its memory and factorization cost. Draws use \(\delta_\ell=C_\ell^{-\top}\xi_\ell\) with independent standard normal vectors across blocks. Solving \(C_\ell\delta_\ell=\xi_\ell\) would generally give the wrong covariance.

The fixed residual plan supplies rows of \(\widetilde J=\operatorname{diag}(\sqrt{\alpha})J\), with \(\alpha_i=2w_f/n_f\) based on global family counts. The target is \(F=\widetilde J^\top\widetilde J\) and precision \(P=s\widehat F+\lambda I\). Residual values do not multiply these Jacobian rows. This is a positive-semidefinite generalized Gauss–Newton (GGN) approximation; it omits the residual-weighted second-derivative term of the exact loss Hessian.

Here training uses prior_precision=0, so the tutorial's Laplace prior_precision=1000 is post-hoc damping, not a matched training prior. scale=1, the finite residual sample, training steps, and posterior draw count are teaching budgets. They do not reproduce a paper or establish uncertainty calibration. The local Gaussian is centered at the final trained iterate, which need not be the MAP of a posterior with this damping. Parameter diagnostics use the recorded row-major, layerwise augmented [W|b] ordering; their units are native parameter-coordinate units, not seconds or kilometres.

Read here; run the notebook locally

This page displays the committed notebook's code, saved output and six figures. Documentation builds do not rerun experiments. The recorded results use a short teaching budget.

View the source notebook or download the notebook to run it.

Setup

From the repository root, install python -m pip install -e ".[notebooks]" jupyterlab, then register/select that environment’s kernel with python -m ipykernel install --sys-prefix --name laplace-hypopinn. Open this notebook in JupyterLab or an editor and Restart Kernel → Run All. No downloads, GPU, external dataset, or previous tutorial outputs are required.

This synthetic example uses (z, x) coordinates in km, velocity in km/s, and travel time in s.

%matplotlib inline
from dataclasses import replace
import importlib.metadata
import platform
import time

import matplotlib.pyplot as plt
import numpy as np
import torch
from IPython.display import Markdown, display

from laplace_hypopinn.config import LaplaceConfig, resolve_dtype
from laplace_hypopinn.curvature.residuals import make_residual_plan
from laplace_hypopinn.data import prepare_problem, sample_training_batch
from laplace_hypopinn.losses import loss_terms
from laplace_hypopinn.model import flatten_parameters, initialize_model, make_mlp_forward
from laplace_hypopinn.prediction import grid_location, predict_grid, sample_locations
from laplace_hypopinn.presets import load_preset
from laplace_hypopinn.training import train
from laplace_hypopinn.types import RandomStreams

torch.set_num_threads(1)
plt.rcParams.update({"figure.dpi": 110, "font.size": 10, "axes.spines.top": False,
                     "axes.spines.right": False, "axes.grid": False})
colors = {"map": "#0072B2", "truth": "#222222", "posterior": "#56B4E9",
          "receiver": "#E69F00"}

def as_numpy(tensor):
    return tensor.detach().cpu().numpy()

def spatial_axes(ax):
    ax.set(xlabel="Horizontal distance x (km)", ylabel="Depth z (km)",
           xlim=(x[0], x[-1]), ylim=(z[-1], z[0]))
    ax.set_aspect("equal")

def source_markers(ax, *, include_center=False):
    ax.scatter(receivers[:, 1], receivers[:, 0], marker="v", s=45,
               color=colors["receiver"], edgecolors="black", clip_on=False,
               zorder=4, label="Receivers")
    ax.scatter(truth[1], truth[0], marker="X", s=75, facecolor="white",
               edgecolor=colors["truth"], zorder=5, label="Known source")
    if include_center:
        ax.scatter(center_location[1], center_location[0], marker="*", s=120,
                   color=colors["map"], edgecolors="black", zorder=6,
                   label="Trained minimum")

print(f"Python {platform.python_version()} | torch {torch.__version__} | "
      f"NumPy {np.__version__} | laplace-hypopinn "
      f"{importlib.metadata.version('laplace-hypopinn')}")
Python 3.12.14 | torch 2.5.1+cpu | NumPy 1.26.4 | laplace-hypopinn 0.1.0

Choose an explicit teaching budget

The architecture and grid are the EX2 notebook preset: (2,16,16,32,32,16,16,1) with Mish and a 101 × 151 grid. We use 800 training updates, 512 collocation points, and 64 posterior draws for a short CPU lesson. Historical reproduction uses 3,001 updates, 2,501 collocations and 1,000 draws; the legacy curvature budget is also reduced here. These changes affect fitted fields and uncertainty.

Training has no parameter prior. The positive posterior regularizer is therefore post-hoc damping, not a claim that the trained center is the MAP of that regularized posterior. Values are demonstration settings, not calibrated physical noise or prior estimates.

base = load_preset("ex2")
config = replace(
    base, name="tutorial_block_diagonal", device="cpu", dtype="float32",
    data=replace(base.data, collocation_count=512),
    training=replace(base.training, steps=800, log_every=20),
    laplace=LaplaceConfig(
    method="block_diagonal", samples=64,
    prior_precision=1000.0, scale=1.0, chunk_size=32, max_dense_bytes=256*1024**2,
    ),
    prediction_chunk_size=4096, posterior_batch_size=4,
)
print(f"Widths: {config.model.widths}; activation: {config.model.activation}")
print(f"Training updates: {config.training.steps}; samples: {config.laplace.samples}; seed: {config.seed}")
Widths: (2, 16, 16, 32, 32, 16, 16, 1); activation: mish
Training updates: 800; samples: 64; seed: 4321

Steps

1. Prepare data and initialize the model

The gradient-velocity problem generates analytic travel times and receiver observations. Training uses receiver observations, known velocity through the eikonal residual, and the positivity penalty; the known source and complete reference field are evaluation aids. A fixed collocation batch and local random streams make top-to-bottom execution reproducible.

problem = prepare_problem(config)
streams = RandomStreams(config.seed, config.device)
initial_parameters = initialize_model(
    config.model.widths, config.model.initialization, streams,
    dtype=resolve_dtype(config.dtype), device=config.device,
)
forward = make_mlp_forward(config.model.activation)
batch = sample_training_batch(problem, config.data.collocation_count, streams)
z, x = as_numpy(problem.grid.z), as_numpy(problem.grid.x)
receivers = as_numpy(problem.receiver_coordinates)
truth = as_numpy(problem.true_source)
reference = as_numpy(problem.reference_times)
parameter_count = flatten_parameters(initial_parameters)[1].numel
print(f"{parameter_count:,} parameters; {len(z)} × {len(x)} grid; "
      f"{len(batch.coordinates)} fixed collocation points; {len(receivers)} receivers")
print(f"Grid spacing: dz={z[1]-z[0]:.3f} km, dx={x[1]-x[0]:.3f} km")

fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
mesh = ax.pcolormesh(x, z, as_numpy(problem.grid.velocity), shading="auto", cmap="viridis")
source_markers(ax)
spatial_axes(ax)
ax.set_title("Synthetic velocity and receiver geometry")
ax.legend(loc="lower right", fontsize=9)
fig.colorbar(mesh, ax=ax, label="Velocity (km/s)")
plt.show()
plt.close(fig)
2,737 parameters; 101 × 151 grid; 512 fixed collocation points; 11 receivers
Grid spacing: dz=0.020 km, dx=0.020 km

Block diagonal: Known velocity field, receiver geometry and reference source location

2. Train the shared center

train returns new parameters and an optimizer/RNG snapshot. The input mapping remains unchanged. History records pre-update objectives; the final metrics below recompute the objective at the returned parameters.

started = time.perf_counter()
training = train(initial_parameters, batch, config.training, streams, forward=forward)
training_seconds = time.perf_counter() - started
parameters = training.parameters
center_field = predict_grid(parameters, problem.grid, config.prediction_chunk_size, forward=forward)
center_location = as_numpy(grid_location(center_field, problem.grid))
final_terms = loss_terms(parameters, batch, config.training, forward=forward)
field_rmse = float((center_field - problem.reference_times).square().mean().sqrt())
location_error = float(np.linalg.norm(center_location - truth))
with torch.no_grad():
    receiver_prediction = as_numpy(forward(parameters, problem.receiver_coordinates)).reshape(-1)
print(f"Training: {training_seconds:.2f} s; recomputed final objective: {float(final_terms.total.detach()):.3e}")
print(f"Field RMSE: {field_rmse:.5f} s; grid-minimum error: {location_error:.5f} km")
print(f"Trained minimum (z, x): {center_location.round(4)} km")
Training: 3.93 s; recomputed final objective: 5.503e-05
Field RMSE: 0.02246 s; grid-minimum error: 0.05657 km
Trained minimum (z, x): [1.04 1.54] km
fig, axes = plt.subplots(1, 2, figsize=(11, 3.5), layout="constrained")
steps = [entry["step"] for entry in training.history]
for key, label, color, style in (
    ("total", "Total", "#222222", "-"),
    ("pde", "Eikonal", "#0072B2", "--"),
    ("data", "Receivers", "#D55E00", ":"),
):
    axes[0].semilogy(steps, [entry[key] for entry in training.history],
                     label=label, color=color, linestyle=style)
axes[0].set(xlabel="Completed-update index (pre-update loss)",
            ylabel="Objective terms (configured scaling)", title="Training convergence")
axes[0].legend()
axes[0].grid(alpha=.2)
axes[1].plot(receivers[:, 1], as_numpy(problem.receiver_times).reshape(-1),
             "o", color=colors["receiver"], label="Synthetic observations")
axes[1].plot(receivers[:, 1], receiver_prediction, "x--", color=colors["map"],
             label="Trained prediction")
axes[1].set(xlabel="Receiver x (km)", ylabel="Travel time (s)", title="Receiver fit")
axes[1].legend()
plt.show()
plt.close(fig)

Block diagonal: Training objectives and observed versus predicted receiver travel times

Receiver agreement alone does not establish an accurate interior field. Compare the trained field with the analytic reference using one shared color scale, and inspect the signed error separately. A white X marks the known source; a blue star marks the trained grid minimum.

trained = as_numpy(center_field)
low, high = min(reference.min(), trained.min()), max(reference.max(), trained.max())
error = trained - reference
error_limit = max(float(np.abs(error).max()), np.finfo(float).eps)
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8), layout="constrained")
for ax, values, title in zip(axes[:2], (reference, trained),
                            ("Analytic reference", "Trained center"), strict=True):
    mesh = ax.pcolormesh(x, z, values, shading="auto", cmap="viridis", vmin=low, vmax=high)
    source_markers(ax, include_center=True)
    spatial_axes(ax)
    ax.set_title(title)
fig.colorbar(mesh, ax=axes[:2], label="Travel time (s)", shrink=.85)
mesh = axes[2].pcolormesh(x, z, error, shading="auto", cmap="RdBu_r",
                         vmin=-error_limit, vmax=error_limit)
spatial_axes(axes[2])
axes[2].set_title(f"Trained − reference; RMSE {field_rmse:.4f} s")
fig.colorbar(mesh, ax=axes[2], label="Signed travel-time error (s)", shrink=.85)
plt.show()
plt.close(fig)

Block diagonal: Analytic reference travel times, trained PINN field and signed field error

3. Fit the selected curvature approximation

Corrected methods use a fixed residual plan, with global family weights applied before chunking. The legacy method instead resamples coordinates and squares the total loss gradient. The following cell calls the method’s public API directly; it does not execute archived notebook code.

from laplace_hypopinn.curvature.dense import fit_ggn

plan = make_residual_plan(batch, config.training)
# Separate streams keep curvature selection independent of training and prediction.
streams = RandomStreams(config.seed + 1, config.device)
started = time.perf_counter()

posterior = fit_ggn(
    parameters,
    plan,
    structure="block_diagonal",
    prior_precision=config.laplace.prior_precision,
    scale=config.laplace.scale,
    chunk_size=config.laplace.chunk_size,
    max_dense_bytes=config.laplace.max_dense_bytes,
    forward=forward,
)
print(f"Representation: {posterior.representation}; affine-layer blocks: {len(posterior.blocks)}")
print(f"Post-hoc damping: {config.laplace.prior_precision:g}; GGN scale: {config.laplace.scale:g}")

fit_seconds = time.perf_counter() - started
print(f"Curvature fit: {fit_seconds:.2f} s; representation: {posterior.representation}")
Representation: block_diagonal; affine-layer blocks: 7
Post-hoc damping: 1000; GGN scale: 1
Curvature fit: 0.29 s; representation: block_diagonal

Inspect the method’s structure

The bar chart divides each layer's precision trace by both its parameter count and damping. Values near one indicate a layer whose average diagonal precision is dominated by damping. Traces are computed from the squared entries of the stored lower Cholesky factors, not from their diagonals alone.

The heatmap displays a small exact portion of normalized precision, \(P_{ij}/\sqrt{P_{ii}P_{jj}}\), within the final layer. It is not a posterior correlation matrix; covariance is \(P^{-1}\). The displayed subset and its size are stated in the title, and the color range covers every displayed value. Other layers are independent by construction, although nonlinear sampled fields can have substantial spatial correlation. Exact within-layer GGN blocks do not imply exact full curvature or calibrated localization spread.

damping = config.laplace.prior_precision
block_labels = [f"Layer {i + 1}" for i in range(len(posterior.layout.blocks))]
# C is lower triangular and P = C @ C.T: row-square sums are diag(P).
# diag(C)**2 would omit the off-diagonal contributions to diag(P).
block_diagonals = [factor.square().sum(dim=1) for factor in posterior.blocks]
block_traces = [float(diagonal.sum()) for diagonal in block_diagonals]
mean_ratios = [trace / block.numel / damping for trace, block in zip(block_traces, posterior.layout.blocks, strict=True)]
storage_mib = sum(f.numel() * f.element_size() for f in posterior.blocks) / 2**20

# Show the final layer's first <=24 coordinates; do not build a global matrix.
preview_factor = posterior.blocks[-1]
preview_count = min(24, preview_factor.shape[0])
preview_rows = preview_factor[:preview_count, :]
preview_precision = preview_rows @ preview_rows.T
normalizer = preview_precision.diagonal().sqrt()
normalized = as_numpy(preview_precision / normalizer[:, None] / normalizer[None, :])
color_limit = float(np.max(np.abs(normalized)))

fig, axes = plt.subplots(1, 2, figsize=(11.5, 4.5), layout="constrained")
axes[0].bar(block_labels, mean_ratios, color=colors["posterior"])
axes[0].set_yscale("log")
axes[0].tick_params(axis="x", rotation=35)
axes[0].set_ylabel(r"$\operatorname{tr}(P_\ell)/(p_\ell\lambda)$ (dimensionless)")
axes[0].set_title("Mean precision per affine layer")
image = axes[1].imshow(normalized, origin="lower", cmap="RdBu_r", vmin=-color_limit, vmax=color_limit)
axes[1].set_xlabel("Local parameter index ([W|b] ordering)")
axes[1].set_ylabel("Local parameter index ([W|b] ordering)")
axes[1].set_title(f"Final layer: first {preview_count} of {preview_factor.shape[0]} coordinates")
fig.colorbar(image, ax=axes[1], label=r"$P_{ij}/\sqrt{P_{ii}P_{jj}}$ (dimensionless)")
plt.show()
plt.close(fig)

print(f"Stored block factors: {storage_mib:.3f} MiB; dense allocation guard: {config.laplace.max_dense_bytes / 2**20:.1f} MiB")
print("Roundoff jitter by block:", posterior.metadata["jitter"])
for block, trace in zip(posterior.layout.blocks, block_traces, strict=True):
    print(f"{block.name}: {block.numel:,} coordinates; trace(P)={trace:.6g}; mean diagonal={trace / block.numel:.6g} (native precision units)")

Block diagonal: Method-specific curvature and posterior approximation diagnostics

Stored block factors: 7.021 MiB; dense allocation guard: 256.0 MiB
Roundoff jitter by block: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
layers.0: 48 coordinates; trace(P)=48001; mean diagonal=1000.02 (native precision units)
layers.1: 272 coordinates; trace(P)=272013; mean diagonal=1000.05 (native precision units)
layers.2: 544 coordinates; trace(P)=544003; mean diagonal=1000.01 (native precision units)
layers.3: 1,056 coordinates; trace(P)=1.05601e+06; mean diagonal=1000.01 (native precision units)
layers.4: 528 coordinates; trace(P)=528008; mean diagonal=1000.01 (native precision units)
layers.5: 272 coordinates; trace(P)=272022; mean diagonal=1000.08 (native precision units)
layers.6: 17 coordinates; trace(P)=17007.6; mean diagonal=1000.45 (native precision units)

4. Sample complete fields and source locations

sample_locations keeps each parameter perturbation fixed across all grid chunks. It stores grid minima and online field moments instead of a sample-by-grid array. This method evaluates the nonlinear model at each sampled parameter vector. Every inferred source is a grid minimum; this finite grid limits localization resolution.

# A fresh explicit stream makes this cell reproducible when rerun.
prediction_streams = RandomStreams(config.seed + 2, config.device)
started = time.perf_counter()
summary = sample_locations(posterior, problem.grid, config, prediction_streams.torch)
prediction_seconds = time.perf_counter() - started
locations = as_numpy(summary.locations)
field_mean, field_std = as_numpy(summary.field_mean), as_numpy(summary.field_std)
print(f"Prediction convention: {posterior.prediction_kind}")
print(f"{len(locations)} coherent fields sampled in {prediction_seconds:.2f} s")
print(f"Source-location sample mean (z, x): {as_numpy(summary.mean).round(4)} km")
print(f"Source-location population SD (z, x): {as_numpy(summary.std).round(4)} km")
Prediction convention: travel_time
64 coherent fields sampled in 0.78 s
Source-location sample mean (z, x): [1.1131 1.5563] km
Source-location population SD (z, x): [0.2319 0.1667] km
fig, axes = plt.subplots(1, 2, figsize=(11, 4.4), layout="constrained")
mesh = axes[0].pcolormesh(x, z, field_std, shading="auto", cmap="magma", vmin=0)
spatial_axes(axes[0])
source_markers(axes[0], include_center=True)
axes[0].set_title("Pointwise sampled travel-time spread")
fig.colorbar(mesh, ax=axes[0], label="Sample standard deviation (s)")
axes[1].scatter(locations[:, 1], locations[:, 0], s=24, alpha=.45,
                color=colors["posterior"], edgecolors=colors["map"], clip_on=False,
                label=f"Grid minima ({len(locations)} draws)")
source_markers(axes[1], include_center=True)
location_mean = as_numpy(summary.mean)
axes[1].scatter(location_mean[1], location_mean[0], marker="+", s=110,
                linewidths=2, color="#D55E00", label="Sample mean")
spatial_axes(axes[1])
axes[1].set_title("Source locations from complete sampled fields")
handles, labels = axes[1].get_legend_handles_labels()
fig.legend(handles, labels, loc="outside lower center", ncol=3, fontsize=9)
plt.show()
plt.close(fig)

Block diagonal: Sampled travel-time standard deviation and source-location samples

Compare uncertainty with field error

The band below is the sample mean ± two sample standard deviations at each grid point. It is descriptive spread, not a 95% credible interval or a simultaneous confidence band. Negative sampled times are left visible; a Gaussian parameter approximation does not enforce physical positivity. Nonlinearity means the predictive mean can differ from the trained center.

row = int(np.argmin(np.abs(z - truth[0])))
mean_row, std_row = field_mean[row], field_std[row]
fig, ax = plt.subplots(figsize=(9, 3.5), layout="constrained")
ax.fill_between(x, mean_row - 2*std_row, mean_row + 2*std_row,
                 color=colors["posterior"], alpha=.35, label="Sample mean ± 2 sample SD")
ax.plot(x, reference[row], color=colors["truth"], label="Analytic reference")
ax.plot(x, trained[row], "--", color=colors["map"], label="Trained center")
ax.plot(x, mean_row, ":", color="#D55E00", label="Sample mean")
ax.set(xlabel="Horizontal distance x (km)", ylabel="Travel time (s)",
        title=f"Cross-section at z={z[row]:.2f} km — descriptive pointwise spread")
ax.grid(alpha=.2)
ax.legend(ncol=2, fontsize=9)
plt.show()
plt.close(fig)

Block diagonal: Travel-time cross-section with reference, trained center and descriptive sample spread

Checks

These checks establish finite, internally consistent calculations. They do not test calibration, convergence to a global optimum, or agreement with a full research run.

center_vector, layout = flatten_parameters(parameters)
torch.testing.assert_close(posterior.mean, center_vector.detach(), rtol=0, atol=0)
assert summary.locations.shape == (config.laplace.samples, 2)
assert summary.field_mean.shape == summary.field_std.shape == problem.grid.shape
for value in (center_field, summary.locations, summary.field_mean, summary.field_std):
    assert torch.isfinite(value).all()
assert (summary.field_std >= 0).all()
assert np.isin(locations[:, 0], z).all() and np.isin(locations[:, 1], x).all()
for factor in (posterior.factor, *posterior.blocks):
    if factor is not None:
        assert torch.isfinite(factor).all() and (factor.diag() > 0).all()
if posterior.diagonal is not None:
    assert torch.isfinite(posterior.diagonal).all() and (posterior.diagonal > 0).all()
for _, _, precision in posterior.eigenbasis:
    assert torch.isfinite(precision).all() and (precision > 0).all()
print("Checks passed: finite fields, positive precision, preserved center, and grid-based samples.")
display(Markdown(
    f"**Observed in this run:** field RMSE **{field_rmse:.5f} s**, "
    f"trained grid-minimum error **{location_error:.5f} km**, and "
    f"**{len(locations)}** posterior draws. These are tutorial results; "
    "they do not establish uncertainty calibration or reproduce the paper's full experiments."
))
Checks passed: finite fields, positive precision, preserved center, and grid-based samples.

Observed in this run: field RMSE 0.02246 s, trained grid-minimum error 0.05657 km, and 64 posterior draws. These are tutorial results; they do not establish uncertainty calibration or reproduce the paper's full experiments.

Next steps

  • Compare with full using the same center and residual plan to measure the predictive effect of dropping correlations between layers.
  • Change architecture widths and inspect sum(p_layer**2) before fitting; a single wide layer can make this method nearly as expensive as full curvature.
  • Compare layer blocks with kfac and efb, which replace each exact block by different structured approximations.
  • Sweep damping and family weights while recording source-location error and spread over repeated synthetic problems; one fitted example does not establish coverage.

  • Change config.model.widths or activation, then restart and rerun training and curvature. For a custom pointwise model, see the extension example and model contract. Structured methods need a compatible jet adapter.

  • For saved configurations, checkpoints, result arrays and standard plots, use the orchestration API with a new output directory:
from laplace_hypopinn.experiment import run_experiment
result = run_experiment(config, output="results/block_diagonal-new-run")

This starts a new experiment with its own seed schedule; it is not a serializer for the manually computed objects above. Use the reproducibility guide and measured performance before increasing research budgets.