A seismometer records local earthquakes on top of noise: the ocean microseism at low frequencies, wind, traffic and machinery at higher frequencies. Two daily tasks of observational seismology are to clean the record (denoising) and to time the arrivals of the P and S waves (picking). Both take a time series in and give back a time series of the same length. An encoder-decoder is the network built for that. The encoder shrinks the record, step by step, into a short summary, the bottleneck; the decoder expands the summary back to the full length. Change what the decoder is asked to produce, and the same network compresses, denoises, picks, or does several of these at once.
This notebook follows the steps that led from autoencoders to foundation models, on one system: local earthquakes recorded at one seismic station.
| step | idea | section |
|---|---|---|
| autoencoder | rebuild the input through a bottleneck | 3 |
| U-Net | skip connections carry the detail of each scale past the bottleneck | 4 |
| multi-task | one encoder shared by one decoder per task | 5 |
| pretrain, then fine-tune | train the encoder on records without labels, then a task with few labels | 6 |
| mixture of experts (optional) | a router weights two decoders for each record | 7 |
Learning outcomes. After this notebook you can:
follow the shape of a record through an encoder and a decoder, and compute the compression of a bottleneck;
train an encoder-decoder to denoise a seismogram, and explain what skip connections change;
train a phase picker on probability-trace labels, alone and as one of two tasks sharing an encoder, and rank it against STA/LTA;
pretrain an encoder without labels, fine-tune it or freeze it, and measure what it gives when labels are few;
say how a mixture of experts differs from the skip connections and the task decoders of a U-Net.
From the literature. Networks that rebuild their input through a narrow layer date from the 1980s (Rumelhart et al., 1986; Kramer, 1991); Hinton & Salakhutdinov (2006) made deep ones trainable. The U-Net (Ronneberger et al., 2015) joins encoder and decoder at every scale. In seismology, PhaseNet (Zhu & Beroza, 2019) picks P and S with a U-Net, DeepDenoiser (Zhu, Mousavi & Beroza, 2019) separates earthquake from noise, and EQTransformer (Mousavi et al., 2020) shares one encoder among three decoders. Masked autoencoders (He et al., 2022) pretrain an encoder without labels, the recipe that foundation models for Earth data such as Prithvi (Jakubik et al., 2023) and Aurora (Bodnar et al., 2025) apply at scale. A mixture of experts (Jacobs et al., 1991; Shazeer et al., 2017; Fedus et al., 2022) lets a router choose among sub-networks for each input.
🖥️ Lecture slides: encoder-decoders (enrichment, session 26)
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
from scipy import signal
from obspy.signal.trigger import classic_sta_lta
import mlgeo_synth
# The networks are small (6,500 to 13,500 weights). On a CPU, one thread trains them
# fastest, and with one thread a rerun reproduces every number to the last digit.
torch.set_num_threads(1)
SEEDS = [0, 1, 2] # each network is trained three times, from three random starting weights
FS = 25.0 # samples per second
DURATION = 32.0 # seconds: 800 samples, a length that halves cleanly four times (800, 400, 200, 100, 50)
NS = int(FS * DURATION)
t = np.arange(NS) / FS1. The data: local earthquakes at one station¶
mlgeo_synth.synthetic_seismogram draws one vertical record of a local earthquake: a P wavelet at 5 Hz arriving at 5 s + distance / (6 km/s), an S wavelet twice as large at 3 Hz arriving at 5 s + distance / (3.5 km/s), and noise whose power falls with frequency as . The exponent is the noise color: is white noise, puts most of the noise power at low frequencies, as the ocean microseism does. The signal-to-noise ratio (SNR) is the peak of the signal divided by the standard deviation of the noise. Each record draws its own:
| parameter | range |
|---|---|
| magnitude | 1 to 3, uniform |
| distance | 5 to 60 km, uniform |
| SNR | 1.5 to 30, uniform in log |
| noise color | 0 to 2, uniform |
We sample at 25 Hz for 32 s, 800 samples. The clean signal is known exactly: we build each record a second time with the same seed and snr=1e12, which divides the noise by 1012. The P and S arrival times come with each record (t_p, t_s).
Split by record. Each record is its own earthquake with its own noise, and no part of a record appears in two sets: 500 records train, 200 validate, 400 test. In lecture 25 (case 1), overlapping windows cut from the same records fell on both sides of a split, and a detector that scored 0.97 on its test windows scored 0.76 on new records.
def make_records(n, seed, noise_colors=(0.0, 2.0)):
"""n records at one station: the noisy trace, the clean signal, and the parameters of each record.
Both traces are divided by the standard deviation of the noisy trace, as one would do
with a real record, whose clean signal is unknown."""
rng = np.random.default_rng(seed)
noisy, clean, rows = np.zeros((n, NS), np.float32), np.zeros((n, NS), np.float32), []
for i in range(n):
kw = dict(magnitude=rng.uniform(1, 3), distance_km=rng.uniform(5, 60),
snr=float(np.exp(rng.uniform(np.log(1.5), np.log(30)))),
noise_color=float(rng.uniform(*noise_colors)), seed=int(rng.integers(2**31)))
_, x, info = mlgeo_synth.synthetic_seismogram(DURATION, FS, **kw)
# the same record with the noise divided by 10^12: the clean signal
_, c, _ = mlgeo_synth.synthetic_seismogram(DURATION, FS, **{**kw, "snr": 1e12})
scale = x.std()
noisy[i], clean[i] = x / scale, c / scale
rows.append({**kw, "t_p": info["t_p"], "t_s": info["t_s"]})
return noisy, clean, pd.DataFrame(rows)
noisy, clean, meta = make_records(1100, seed=0)
split = {"train": np.arange(0, 500), "validation": np.arange(500, 700), "test": np.arange(700, 1100)}
tr, va, te = split["train"], split["validation"], split["test"]
t_p, t_s = meta["t_p"].to_numpy(), meta["t_s"].to_numpy()
for k, v in split.items():
print(f"{k:10s} {len(v)} records")
meta.drop(columns="seed").describe().loc[["min", "50%", "max"]].round(2)train 500 records
validation 200 records
test 400 records
fig, axes = plt.subplots(2, 1, figsize=(9, 4.6), sharex=True)
for ax, i in zip(axes, [te[np.argmax(meta["snr"].to_numpy()[te] > 15)], te[np.argmax(meta["snr"].to_numpy()[te] < 3)]]):
ax.plot(t, noisy[i], color="#BBBBBB", lw=0.7, label="recorded (noisy)")
ax.plot(t, clean[i], color="#222222", lw=0.9, label="clean signal")
ax.axvline(t_p[i], color="#4477AA", lw=1.5, label="P arrival")
ax.axvline(t_s[i], color="#EE6677", lw=1.5, label="S arrival")
ax.set_title(f"test record {i}: M{meta['magnitude'][i]:.1f}, {meta['distance_km'][i]:.0f} km, "
f"SNR {meta['snr'][i]:.1f}, noise color {meta['noise_color'][i]:.1f}", fontsize=10)
ax.set_ylabel("velocity\n(scaled)")
axes[0].legend(fontsize=8, loc="upper right", ncol=4)
axes[1].set_xlabel("time (s)")
plt.tight_layout()
plt.show()
Top: a record with an SNR above 15, where both waves stand out. Bottom: an SNR below 3, where the P wave is hidden in the noise. Half of the records have an SNR below 6.5 (the 50% row of the table), and the P wave has half the amplitude of the S wave, so on most records the P arrival is hard to see.
2. Baselines first¶
The methods a seismologist would use before any network, scored the way the networks will be.
Denoising: a band-pass filter. A zero-phase Butterworth filter of order 4. We try 20 bands and keep the one with the lowest error on the training records.
Denoising score: error against the clean signal. The rms of (output − clean signal) divided by the rms of the clean signal, averaged over the 400 test records; 0 is perfect. We also give the SNR gain, in dB: 20 log10 (rms of the noise in the record / rms of the error left in the output).
Two references, not baselines, built for each record from its own clean signal, which no method can know: the Wiener filter, built from the record’s own signal and noise power spectra, and the best gain per frequency, a number between 0 and 1 for each frequency, chosen to bring that record closest to its clean signal. Both weight each frequency the same way at every time.
Picking: STA/LTA (Allen, 1978), the ratio of the short-term to the long-term average of the squared trace. The P pick is the first sample where the ratio exceeds a threshold. STA, LTA, threshold, and whether to run it on the recorded or the band-passed trace are chosen on the training records.
Picking score: the percentage of test records whose P pick is within 0.5 s of the true arrival, and the median of |pick − true arrival|. A record without a trigger counts as a miss. The arrival times are exact, so the floor is 0 s, within one sample (0.04 s).
def rel_error(pred, clean):
"""rms of (prediction - clean signal) divided by rms of the clean signal: one number per record."""
return np.sqrt(((pred - clean) ** 2).sum(-1) / (clean ** 2).sum(-1))
def snr_gain_db(pred, noisy, clean):
"""20 log10(rms of the noise in the input / rms of the error of the output), in dB."""
return 20 * np.log10(np.linalg.norm(noisy - clean, axis=-1) / np.linalg.norm(pred - clean, axis=-1))
# choose the band on the training records only
best = None
for f_lo in [0.5, 1, 2, 3]:
for f_hi in [4, 6, 8, 10, 12]:
sos = signal.butter(4, [f_lo, f_hi], btype="band", fs=FS, output="sos")
err = rel_error(signal.sosfiltfilt(sos, noisy[tr]), clean[tr]).mean()
if best is None or err < best[0]:
best = (err, f_lo, f_hi)
band = best[1:]
sos = signal.butter(4, band, btype="band", fs=FS, output="sos")
bandpassed = signal.sosfiltfilt(sos, noisy[te])
# a reference no method can use: for each record, the Wiener filter built from its own clean and noise spectra
S, N = np.fft.rfft(clean[te]), np.fft.rfft(noisy[te] - clean[te])
wiener = np.fft.irfft(np.abs(S) ** 2 / (np.abs(S) ** 2 + np.abs(N) ** 2) * np.fft.rfft(noisy[te]), n=NS)
# a second reference: for each record and frequency, the gain that brings the filtered trace closest
# to the clean signal (least squares, Re(S X*) / |X|^2), kept between 0 and 1
Xf = np.fft.rfft(noisy[te])
best_gain = np.fft.irfft(np.clip(np.real(S * np.conj(Xf)) / np.abs(Xf) ** 2, 0, 1) * Xf, n=NS)
denoise_baselines = {
"recorded trace, unfiltered": noisy[te],
f"band-pass {band[0]}-{band[1]} Hz": bandpassed,
"reference: Wiener filter that knows the clean spectrum": wiener,
"reference: best gain per frequency, knows the clean signal": best_gain,
}
print(f"band chosen on the training records: {band[0]} to {band[1]} Hz")
for name, p in denoise_baselines.items():
print(f"{name:58s} error {rel_error(p, clean[te]).mean():.3f} SNR gain {snr_gain_db(p, noisy[te], clean[te]).mean():5.1f} dB")band chosen on the training records: 2 to 4 Hz
recorded trace, unfiltered error 1.982 SNR gain 0.0 dB
band-pass 2-4 Hz error 0.725 SNR gain 6.8 dB
reference: Wiener filter that knows the clean spectrum error 0.428 SNR gain 11.8 dB
reference: best gain per frequency, knows the clean signal error 0.391 SNR gain 12.6 dB
def stalta_pick(x, sta_s, lta_s, threshold):
"""Time (s) of the first sample where STA/LTA exceeds the threshold; NaN if it never does."""
ratio = classic_sta_lta(x.astype(np.float64), int(sta_s * FS), int(lta_s * FS))
above = np.flatnonzero(ratio > threshold)
return above[0] / FS if len(above) else np.nan
def pick_scores(picks, truth):
"""Median |pick - true arrival| in s, and the fraction of picks within 0.5 s. No pick counts as a miss."""
err = np.abs(picks - truth)
err[np.isnan(err)] = np.inf
return float(np.median(err)), float((err <= 0.5).mean())
# choose the trace, STA, LTA and threshold on the training records only
traces = {"recorded": noisy, f"band-passed {band[0]}-{band[1]} Hz": signal.sosfiltfilt(sos, noisy)}
best, best_by_trace = None, {}
for name, X in traces.items():
for sta in [0.2, 0.5, 1.0]:
for lta in [3.0, 5.0]:
for thr in [2, 3, 4, 6, 8]:
sc = pick_scores(np.array([stalta_pick(X[i], sta, lta, thr) for i in tr]), t_p[tr])
best_by_trace[name] = max(best_by_trace.get(name, 0), sc[1])
if best is None or sc[1] > best[0][1]:
best = (sc, (sta, lta, thr), name)
stalta_setting, stalta_trace = best[1], best[2]
for name, v in best_by_trace.items():
print(f"best on the training records, {name} trace: {100 * v:.1f}% of P picks within 0.5 s")
stalta_test = pick_scores(np.array([stalta_pick(traces[stalta_trace][i], *stalta_setting) for i in te]), t_p[te])
print(f"kept: {stalta_trace} trace, STA {stalta_setting[0]} s, LTA {stalta_setting[1]} s, threshold {stalta_setting[2]}")
print(f"test: median P pick error {stalta_test[0]:.2f} s, {100 * stalta_test[1]:.1f}% of P picks within 0.5 s")best on the training records, recorded trace: 44.2% of P picks within 0.5 s
best on the training records, band-passed 2-4 Hz trace: 34.2% of P picks within 0.5 s
kept: recorded trace, STA 0.2 s, LTA 5.0 s, threshold 4
test: median P pick error 1.53 s, 37.5% of P picks within 0.5 s
The 2 to 4 Hz band brings the error from 1.98 (the record as recorded: the noise is larger than the signal on most records) down to 0.725, an SNR gain of 6.8 dB. The Wiener filter reaches 0.428 (11.8 dB) and the best gain per frequency 0.391 (12.6 dB): a filter tuned to each record’s own clean signal still leaves about 40% of the signal’s rms as error, because the signal (3 and 5 Hz) and the noise share the same frequencies. STA/LTA puts 37.5% of the P picks within 0.5 s of the arrival, with a median error of 1.53 s. On the training records it does worse on the 2 to 4 Hz band-passed trace (34.2% against 44.2%), because the band cuts into the 5 Hz P wavelet, so the recorded trace is kept.
3. The encoder-decoder shape¶
The encoder is a stack of four 1-D convolution blocks (4.3). Each block slides 5-sample filters along the record and keeps every second output (a stride of 2), so the length halves while the number of channels grows: 800 → 400 → 200 → 100 → 50 samples, 1 → 8 → 16 → 16 → 32 channels. A 1 × 1 convolution then reduces the 32 channels to b: the bottleneck holds b × 50 numbers. The decoder mirrors the encoder with transposed convolutions. A transposed convolution spreads each input sample over a 4-sample kernel and places the outputs of neighboring input samples 2 samples apart, so 50 samples become 100. Four blocks bring the record back to 800 samples; a last convolution gives the output channels.
The shape after each block, for one record:
CHANNELS = (8, 16, 16, 32) # channels after each encoder block
class Encoder(nn.Module):
"""Four blocks. Each convolves (kernel of 5 samples) and keeps every second sample: the length halves."""
def __init__(self):
super().__init__()
dims = (1,) + CHANNELS
self.blocks = nn.ModuleList(nn.Sequential(nn.Conv1d(a, b, 5, stride=2, padding=2), nn.ReLU())
for a, b in zip(dims[:-1], dims[1:]))
def forward(self, x):
feats = [x] # the input and the output of every block, kept for the skips
for block in self.blocks:
feats.append(block(feats[-1]))
return feats
class Decoder(nn.Module):
"""Four blocks. Each transposed convolution doubles the length. With skips=True, the output of each block
is joined with the encoder output of the same length: a U-Net."""
def __init__(self, bottleneck=8, skips=False, n_out=1, width=1.0):
super().__init__()
self.skips = skips
outs = [round(c * width) for c in (16, 16, 8, 8)]
skip_channels = (16, 16, 8, 1) # encoder outputs of length 100, 200, 400 and the input (800)
self.ups, c_in = nn.ModuleList(), bottleneck
for c_out, c_skip in zip(outs, skip_channels):
self.ups.append(nn.Sequential(nn.ConvTranspose1d(c_in, c_out, 4, stride=2, padding=1), nn.ReLU()))
c_in = c_out + (c_skip if skips else 0)
self.out = nn.Conv1d(c_in, n_out, 5, padding=2)
def forward(self, z, feats):
h = z
for i, up in enumerate(self.ups):
h = up(h)
if self.skips:
h = join(h, feats[-2 - i]) # join() is section 4, Your turn (2)
return self.out(h)
class EncoderDecoder(nn.Module):
"""One encoder, a bottleneck of `bottleneck` channels x 50 samples, and one decoder per entry of `heads`
(the number of output channels of each decoder)."""
def __init__(self, bottleneck=8, skips=False, heads=(1,), width=1.0):
super().__init__()
self.encoder = Encoder()
self.squeeze = nn.Conv1d(CHANNELS[-1], bottleneck, 1) # 32 channels -> `bottleneck` channels
self.decoders = nn.ModuleList(Decoder(bottleneck, skips, k, width) for k in heads)
def forward(self, x):
feats = self.encoder(x)
z = self.squeeze(feats[-1])
return torch.cat([dec(z, feats) for dec in self.decoders], dim=1)
def n_weights(model, trained_only=False):
return sum(p.numel() for p in model.parameters() if p.requires_grad or not trained_only)
x = torch.tensor(noisy[te[:1]])[:, None, :] # one record: (1 record, 1 channel, 800 samples)
model = EncoderDecoder(bottleneck=8)
feats = model.encoder(x)
print("input ", tuple(x.shape))
for i, f in enumerate(feats[1:], 1):
print(f"encoder block {i} ", tuple(f.shape))
h = model.squeeze(feats[-1])
print("bottleneck ", tuple(h.shape))
for i, up in enumerate(model.decoders[0].ups, 1):
h = up(h)
print(f"decoder block {i} ", tuple(h.shape))
print("output ", tuple(model.decoders[0].out(h).shape))
print(f"{n_weights(model)} weights")input (1, 1, 800)
encoder block 1 (1, 8, 400)
encoder block 2 (1, 16, 200)
encoder block 3 (1, 16, 100)
encoder block 4 (1, 32, 50)
bottleneck (1, 8, 50)
decoder block 1 (1, 16, 100)
decoder block 2 (1, 16, 200)
decoder block 3 (1, 8, 400)
decoder block 4 (1, 8, 800)
output (1, 1, 800)
7249 weights
One training loop¶
Every network of this notebook trains with the loop of the training block (section 2.4 of 4.7). one_epoch shuffles the records and makes one update per batch with the same four lines; train_model keeps the weights of the epoch with the lowest validation loss (the checkpoint). The starting weights are random numbers drawn after torch.manual_seed(seed), never zeros. The optimizer is Adam, with a learning rate , batches of 32 records and 20 epochs. From section to section, only the data and the loss (criterion) change.
The autoencoder¶
An autoencoder is an encoder-decoder trained to give back its input: here the clean signal in, the clean signal out, and the mean squared error between the two as the loss. Nothing reaches the output except through the bottleneck, so the size of the bottleneck limits what the decoder can rebuild. We train two, with b = 1 channel (50 numbers) and b = 8 channels (400 numbers).
def one_epoch(model, opt, criterion, X, y, batch_size, g):
"""One pass over the training records in a new random order; one update per batch."""
order = torch.randperm(len(X), generator=g)
for i in range(0, len(X), batch_size):
idx = order[i:i + batch_size]
opt.zero_grad() # gradients from the last batch would add up
loss = criterion(model(X[idx]), y[idx]) # mean loss over the batch
loss.backward() # one gradient per weight
opt.step() # the update
def train_model(model, data, criterion, epochs=20, lr=3e-3, batch_size=32, seed=0, keep_best=True):
"""Train with one_epoch; keep the weights of the epoch with the lowest validation loss."""
Xtr, ytr, Xva, yva = data
opt = torch.optim.Adam(model.parameters(), lr=lr)
g = torch.Generator().manual_seed(seed) # the order of the batches, reproducible
hist = {"train_loss": [], "val_loss": [], "best_epoch": None}
best, best_state = np.inf, None
t0 = time.time()
for epoch in range(epochs):
model.train()
one_epoch(model, opt, criterion, Xtr, ytr, batch_size, g)
model.eval()
with torch.no_grad(): # measuring, not training
hist["train_loss"].append(criterion(model(Xtr[:200]), ytr[:200]).item()) # 200 records save time
hist["val_loss"].append(criterion(model(Xva), yva).item())
if hist["val_loss"][-1] < best: # the checkpoint
best, hist["best_epoch"] = hist["val_loss"][-1], epoch
best_state = {k: v.clone() for k, v in model.state_dict().items()}
if keep_best:
model.load_state_dict(best_state)
hist["time_s"] = time.time() - t0
return hist
def predict(model, X):
model.eval()
with torch.no_grad():
return model(X).numpy()
as_tensor = lambda a: torch.tensor(a[:, None, :]) # (records, 1 channel, 800 samples)
Xn = {k: as_tensor(noisy[v]) for k, v in split.items()} # recorded traces
Xc = {k: as_tensor(clean[v]) for k, v in split.items()} # clean signals
mse = nn.MSELoss()autoencoders = {}
for b in [1, 8]:
torch.manual_seed(0) # random starting weights, recorded seed
model = EncoderDecoder(bottleneck=b)
hist = train_model(model, (Xc["train"], Xc["train"], Xc["validation"], Xc["validation"]), mse)
rec = predict(model, Xc["test"])[:, 0]
autoencoders[b] = dict(model=model, hist=hist, rec=rec, weights=n_weights(model),
err=rel_error(rec, clean[te]).mean())
print(f"bottleneck {b} x 50 = {b * 50:3d} numbers: test error {autoencoders[b]['err']:.3f}, "
f"{autoencoders[b]['weights']} weights, {hist['time_s']:.1f} s, best epoch {hist['best_epoch']}")
i = 3 # one test record
fig, ax = plt.subplots(figsize=(9, 2.6))
ax.plot(t, clean[te[i]], color="#222222", lw=1.2, label="clean signal (input and target)")
for b, color in [(1, "#EE6677"), (8, "#4477AA")]:
ax.plot(t, autoencoders[b]["rec"][i], color=color, lw=0.9, label=f"rebuilt through {b * 50} numbers")
ax.set_xlim(t_p[te[i]] - 2, t_s[te[i]] + 6)
ax.set_xlabel("time (s)")
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()bottleneck 1 x 50 = 50 numbers: test error 0.422, 6570 weights, 3.7 s, best epoch 19
bottleneck 8 x 50 = 400 numbers: test error 0.264, 7249 weights, 3.2 s, best epoch 19

Through 400 numbers the autoencoder rebuilds the test records with an error of 0.261; through 50 numbers, 0.414. Both validation losses were still falling at the last epoch (best epoch 19, counted from 0): longer training would lower both errors, and we stop at 20 epochs to keep the notebook to about 3 minutes. In the figure, both rebuild the S wave; through 50 numbers, the first swings of the P wave come out smaller than they are.
Your turn (1): the compression ratio¶
How many times fewer numbers does the bottleneck hold than the input? Compute the ratio (numbers in the input / numbers in the bottleneck) for the two autoencoders. Read the shapes printed above: the input is 1 channel × 800 samples, the bottleneck b channels × 50 samples. One line.
ratio = {1: None, 8: None} # your code: input numbers / bottleneck numbers, for b = 1 and b = 8Answer below (click to open it).
Notebook Cell
ratio = {b: (1 * NS) / (b * 50) for b in (1, 8)}
print(ratio){1: 16.0, 8: 2.0}
4. Denoising, and skip connections: the U-Net¶
Keep the target, change the input: the noisy record in, the clean signal out. The network now has to learn which part of a record is earthquake and which is noise. We train the encoder-decoder of section 3 (b = 8) twice: as it is, and with skip connections. After each decoder block, the encoder output of the same length is joined to the decoder’s channels, so the detail of the record at each scale reaches the decoder without going through the bottleneck. An encoder-decoder with skip connections at every scale is a U-Net (Ronneberger et al., 2015); drawn with the encoder going down on the left and the decoder going up on the right, it has the shape of a U.
Your turn (2): join a skip connection¶
Decoder.forward calls join(h, skip) after each decoder block. h has shape (records, channels of the decoder, length) and skip, the encoder output of the same length, has shape (records, channels of the encoder, length). Write the one line that puts them side by side along the channel dimension. Hint: torch.cat([...], dim=1).
def join(h, skip):
"""Join the decoder tensor h and the encoder tensor skip of the same length, along the channels."""
return None # your lineAnswer below (click to open it).
Notebook Cell
def join(h, skip):
return torch.cat([h, skip], dim=1)unet = EncoderDecoder(bottleneck=8, skips=True)
feats = unet.encoder(x)
h = unet.squeeze(feats[-1])
print("bottleneck ", tuple(h.shape))
for i, up in enumerate(unet.decoders[0].ups, 1):
h = up(h)
skip = feats[-1 - i]
print(f"decoder block {i} ", tuple(h.shape), "+ encoder", tuple(skip.shape), end=" -> ")
h = join(h, skip)
print(tuple(h.shape))
print("output ", tuple(unet.decoders[0].out(h).shape))
print(f"{n_weights(unet)} weights, against {n_weights(EncoderDecoder(bottleneck=8))} without the skips")bottleneck (1, 8, 50)
decoder block 1 (1, 16, 100) + encoder (1, 16, 100) -> (1, 32, 100)
decoder block 2 (1, 16, 200) + encoder (1, 16, 200) -> (1, 32, 200)
decoder block 3 (1, 8, 400) + encoder (1, 8, 400) -> (1, 16, 400)
decoder block 4 (1, 8, 800) + encoder (1, 1, 800) -> (1, 9, 800)
output (1, 1, 800)
9046 weights, against 7249 without the skips
den_data = (Xn["train"], Xc["train"], Xn["validation"], Xc["validation"]) # noisy in, clean out
denoisers = {}
for name, skips in [("encoder-decoder, no skips", False), ("U-Net (encoder-decoder with skips)", True)]:
for seed in SEEDS:
torch.manual_seed(seed)
model = EncoderDecoder(bottleneck=8, skips=skips)
hist = train_model(model, den_data, mse, seed=seed)
out = predict(model, Xn["test"])[:, 0]
denoisers.setdefault(name, []).append(dict(
seed=seed, model=model, out=out, hist=hist, weights=n_weights(model),
err=rel_error(out, clean[te]).mean(), gain=snr_gain_db(out, noisy[te], clean[te]).mean()))
print(f"{name}, seed {seed}: test error {denoisers[name][-1]['err']:.3f}, "
f"SNR gain {denoisers[name][-1]['gain']:.1f} dB, {hist['time_s']:.1f} s, best epoch {hist['best_epoch']}")encoder-decoder, no skips, seed 0: test error 0.423, SNR gain 10.6 dB, 3.3 s, best epoch 19
encoder-decoder, no skips, seed 1: test error 0.410, SNR gain 10.9 dB, 3.3 s, best epoch 19
encoder-decoder, no skips, seed 2: test error 0.401, SNR gain 11.1 dB, 3.3 s, best epoch 19
U-Net (encoder-decoder with skips), seed 0: test error 0.327, SNR gain 14.4 dB, 5.0 s, best epoch 19
U-Net (encoder-decoder with skips), seed 1: test error 0.301, SNR gain 15.2 dB, 4.7 s, best epoch 19
U-Net (encoder-decoder with skips), seed 2: test error 0.298, SNR gain 15.3 dB, 4.2 s, best epoch 19
rows = []
for name, p in denoise_baselines.items():
rows.append({"method": name, "error": rel_error(p, clean[te]).mean(),
"SNR gain (dB)": snr_gain_db(p, noisy[te], clean[te]).mean(), "weights": 0, "train time (s)": 0.0})
for name, runs in denoisers.items(): # mean and sample standard deviation (ddof=1) over the 3 seeds
rows.append({"method": name, "error": np.mean([r["err"] for r in runs]),
"± std (3 seeds)": np.std([r["err"] for r in runs], ddof=1),
"SNR gain (dB)": np.mean([r["gain"] for r in runs]), "weights": runs[0]["weights"],
"train time (s)": np.mean([r["hist"]["time_s"] for r in runs])})
board_denoise = pd.DataFrame(rows).set_index("method").sort_values("error")
board_denoise = board_denoise[["error", "± std (3 seeds)", "SNR gain (dB)", "weights", "train time (s)"]]
board_denoise["weights"] = board_denoise["weights"].astype(int)
board_denoise.round(3)i = int(np.argmin(np.abs(meta["snr"].to_numpy()[te] - 4))) # a test record with SNR near 4
panels = [("recorded", noisy[te[i]]), (f"band-pass {band[0]}-{band[1]} Hz", bandpassed[i]),
("encoder-decoder, no skips", denoisers["encoder-decoder, no skips"][0]["out"][i]),
("U-Net", denoisers["U-Net (encoder-decoder with skips)"][0]["out"][i])]
fig, axes = plt.subplots(4, 1, figsize=(9, 6), sharex=True, sharey=True)
for ax, (name, p) in zip(axes, panels):
ax.plot(t, p, color="#4477AA", lw=0.8, label=name)
ax.plot(t, clean[te[i]], color="#222222", lw=0.8, alpha=0.7, label="clean signal")
ax.legend(fontsize=8, loc="upper right")
axes[0].set_title(f"test record {te[i]}, SNR {meta['snr'][te[i]]:.1f}", fontsize=10)
axes[-1].set_xlim(t_p[te[i]] - 3, t_s[te[i]] + 5) # from 3 s before P to 5 s after S
axes[-1].set_xlabel("time (s)")
plt.tight_layout()
plt.show()
Ranked by error against the clean signal (mean ± sample standard deviation over 3 seeds):
U-Net: 0.309 ± 0.017, an SNR gain of 14.9 dB, 9,046 weights.
References built from each record’s clean signal: best gain per frequency 0.391 (12.6 dB); Wiener filter 0.428 (11.8 dB).
Encoder-decoder without skips: 0.411 ± 0.011, 10.9 dB, 7,249 weights.
Band-pass 2 to 4 Hz: 0.725 (6.8 dB).
The skip connections add 1,797 weights and lower the error by a quarter, from 0.411 to 0.309. Only the U-Net beats both references. A filter weights each frequency the same way at every time, while the U-Net removes the noise before the P arrival and keeps the 3 to 5 Hz energy after it (figure). Without skips the network ties the Wiener filter: lower error (0.411 against 0.428), lower dB gain (10.9 against 11.8). The two scores average differently. The error is a mean of ratios, dominated by the hard, low-SNR records, where the network does better (0.53 against 0.65 on the third of the test records with the lowest SNR). The dB gain is a mean of logarithms, which counts halving the error on an easy record as much as on a hard one, and on the third with the highest SNR the Wiener filter does better (0.21 against 0.33). Both networks were still improving at epoch 20 (best epoch 19).
5. Multi-task: one encoder, two decoders¶
A phase picker is an encoder-decoder whose output is not a waveform but three probability traces: P, S and “no arrival”, which sum to 1 at each sample. The labels are Gaussian bumps of standard deviation 0.2 s centered on the true arrival times, as PhaseNet labels its records (Zhu & Beroza, 2019); the “no arrival” trace is what is left. The loss is the cross-entropy between the predicted and the label traces, the loss of classification (3.6), computed at every sample. The P pick is the time of the largest P probability.
A multi-task network shares one encoder between two decoders: one gives the clean waveform (the task of section 4), the other the three probability traces. EQTransformer (Mousavi et al., 2020) shares one encoder among three decoders in the same way. The loss is a weighted sum of the two task losses, , and the gradients of both reach the same encoder weights. Both decoders run on every record. We use . While building the notebook we also looked at the test scores of = 0.5 to 10, which a study should not do (choose it on the validation loss); none changed the result below.
SIGMA = 0.2 # s: the standard deviation of the Gaussian bump at each arrival
def phase_labels(t_p, t_s):
"""Three probability traces per record: P, S, and 'no arrival' (what is left), summing to 1 at each sample."""
P = np.exp(-(t[None] - t_p[:, None]) ** 2 / (2 * SIGMA ** 2))
S = np.exp(-(t[None] - t_s[:, None]) ** 2 / (2 * SIGMA ** 2))
lab = np.stack([P, S, np.clip(1 - P - S, 0, None)], 1)
return (lab / lab.sum(1, keepdims=True)).astype(np.float32)
labels = phase_labels(t_p, t_s)
Yp = {k: torch.tensor(labels[v]) for k, v in split.items()} # target of a picker
Ymt = {k: torch.cat([Xc[k], Yp[k]], dim=1) for k in split} # clean trace + 3 probability traces
def pick_loss(out, y):
"""Cross-entropy between the 3 predicted traces (softmax over the channels) and the 3 label traces."""
return -(y * F.log_softmax(out, dim=1)).sum(1).mean()
def p_picks(out, phase=0):
"""Pick: the time of the largest P probability (phase=0) or S probability (phase=1)."""
return torch.softmax(torch.tensor(out), dim=1).numpy()[:, phase].argmax(-1) / FS
print("targets of the multi-task network:", tuple(Ymt["train"].shape), "(records, 1 + 3 channels, samples)")targets of the multi-task network: (500, 4, 800) (records, 1 + 3 channels, samples)
Your turn (3): the multi-task loss¶
The multi-task network returns 4 channels: the clean waveform (channel 0) and the 3 probability traces (channels 1 to 3). Write the line that combines the two task losses into one: a weighted sum, with weight lam on the picking loss. Gradient descent then updates the shared encoder with the gradient of this sum.
def multitask_loss(out, y, lam=1.0):
loss_wave = F.mse_loss(out[:, :1], y[:, :1]) # task 1: the clean waveform
loss_pick = pick_loss(out[:, 1:], y[:, 1:]) # task 2: P, S and no-arrival probabilities
return None # your lineAnswer below (click to open it).
Notebook Cell
def multitask_loss(out, y, lam=1.0):
loss_wave = F.mse_loss(out[:, :1], y[:, :1])
loss_pick = pick_loss(out[:, 1:], y[:, 1:])
return loss_wave + lam * loss_pickpickers = {}
setups = {"picker alone (U-Net, 1 decoder)": ((3,), Yp, pick_loss),
"multi-task (U-Net, shared encoder, 2 decoders)": ((1, 3), Ymt, multitask_loss)}
for name, (heads, Y, crit) in setups.items():
for seed in SEEDS:
torch.manual_seed(seed)
model = EncoderDecoder(bottleneck=8, skips=True, heads=heads)
hist = train_model(model, (Xn["train"], Y["train"], Xn["validation"], Y["validation"]), crit, seed=seed)
out = predict(model, Xn["test"])
med, within = pick_scores(p_picks(out[:, -3:]), t_p[te])
run = dict(seed=seed, model=model, out=out, hist=hist, weights=n_weights(model), median=med, within=within,
s_within=pick_scores(p_picks(out[:, -3:], phase=1), t_s[te])[1],
p_at_s=pick_scores(p_picks(out[:, -3:]), t_s[te])[1]) # P picks that landed on the S arrival
if heads == (1, 3):
run["wave_err"] = rel_error(out[:, 0], clean[te]).mean()
pickers.setdefault(name, []).append(run)
print(f"{name}, seed {seed}: {100 * within:.1f}% of P picks within 0.5 s (median error {med:.2f} s), "
f"{100 * run['p_at_s']:.1f}% within 0.5 s of the S arrival; {100 * run['s_within']:.1f}% of S picks "
f"within 0.5 s; {hist['time_s']:.1f} s")
rows = [{"method": f"STA/LTA (STA {stalta_setting[0]} s, LTA {stalta_setting[1]} s, threshold {stalta_setting[2]})",
"% P picks within 0.5 s": 100 * stalta_test[1], "median P error (s)": stalta_test[0],
"weights": 0, "train time (s)": 0.0}]
for name, runs in pickers.items():
w = [100 * r["within"] for r in runs]
rows.append({"method": name, "% P picks within 0.5 s": np.mean(w), "± std (3 seeds)": np.std(w, ddof=1),
"median P error (s)": np.mean([r["median"] for r in runs]),
"% S picks within 0.5 s": np.mean([100 * r["s_within"] for r in runs]), "weights": runs[0]["weights"],
"train time (s)": np.mean([r["hist"]["time_s"] for r in runs])})
board_pick = pd.DataFrame(rows).set_index("method").sort_values("% P picks within 0.5 s", ascending=False)
board_pick = board_pick[["% P picks within 0.5 s", "± std (3 seeds)", "median P error (s)", "% S picks within 0.5 s",
"weights", "train time (s)"]]
print(f"waveform error of the multi-task network: "
f"{np.mean([r['wave_err'] for r in pickers['multi-task (U-Net, shared encoder, 2 decoders)']]):.3f}")
board_pick.round(2)picker alone (U-Net, 1 decoder), seed 0: 70.0% of P picks within 0.5 s (median error 0.11 s), 23.0% within 0.5 s of the S arrival; 97.2% of S picks within 0.5 s; 4.3 s
picker alone (U-Net, 1 decoder), seed 1: 68.2% of P picks within 0.5 s (median error 0.07 s), 22.0% within 0.5 s of the S arrival; 98.0% of S picks within 0.5 s; 4.4 s
picker alone (U-Net, 1 decoder), seed 2: 69.2% of P picks within 0.5 s (median error 0.10 s), 24.0% within 0.5 s of the S arrival; 96.2% of S picks within 0.5 s; 4.4 s
multi-task (U-Net, shared encoder, 2 decoders), seed 0: 68.2% of P picks within 0.5 s (median error 0.20 s), 22.8% within 0.5 s of the S arrival; 97.8% of S picks within 0.5 s; 7.3 s
multi-task (U-Net, shared encoder, 2 decoders), seed 1: 70.2% of P picks within 0.5 s (median error 0.10 s), 22.8% within 0.5 s of the S arrival; 97.8% of S picks within 0.5 s; 7.2 s
multi-task (U-Net, shared encoder, 2 decoders), seed 2: 7.0% of P picks within 0.5 s (median error 3.56 s), 89.2% within 0.5 s of the S arrival; 95.2% of S picks within 0.5 s; 7.2 s
waveform error of the multi-task network: 0.329
i = int(np.argmin(np.abs(meta["snr"].to_numpy()[te] - 6))) # a test record with SNR near 6
out = pickers["multi-task (U-Net, shared encoder, 2 decoders)"][0]["out"][i]
prob = torch.softmax(torch.tensor(out[1:]), dim=0).numpy()
fig, axes = plt.subplots(2, 1, figsize=(9, 4.2), sharex=True)
axes[0].plot(t, noisy[te[i]], color="#BBBBBB", lw=0.7, label="recorded")
axes[0].plot(t, out[0], color="#222222", lw=0.9, label="decoder 1: clean waveform")
axes[0].legend(fontsize=8, loc="upper right")
axes[1].plot(t, labels[te[i], 0], color="#4477AA", ls="--", lw=1, label="P label")
axes[1].plot(t, labels[te[i], 1], color="#EE6677", ls="--", lw=1, label="S label")
axes[1].plot(t, prob[0], color="#4477AA", lw=1.5, label="decoder 2: P probability")
axes[1].plot(t, prob[1], color="#EE6677", lw=1.5, label="decoder 2: S probability")
axes[1].legend(fontsize=8, loc="upper right", ncol=2)
axes[1].set_xlabel("time (s)")
axes[0].set_title(f"multi-task network, seed 0, test record {te[i]} (SNR {meta['snr'][te[i]]:.1f})", fontsize=10)
plt.tight_layout()
plt.show()
Figure: seed 0, test record 707 (SNR 6.0). The P probability reaches only about 0.35 at the P arrival. Even the runs that trained put 21 to 25% of their P picks within 0.5 s of the S arrival: on low-SNR records the P wave, half as large as the S wave, is not seen.
Ranked by the percentage of P picks within 0.5 s (mean ± sample standard deviation over 3 seeds):
The picker alone: 69.3 ± 1.4%, median error 0.09 s, against 37.5% and 1.53 s for STA/LTA.
The multi-task network: 68.5% and 70.8% on seeds 0 and 1, as good as the picker alone, but 5.8% on seed 2, so 48.3 ± 36.9%. Seed 2 put 90.5% of its P picks within 0.5 s of the S arrival while 95.8% of its S picks were right: it found the arrivals and swapped them. Seed 0 or seed 1 alone would have hidden this. Its waveform decoder scores 0.331 (mean of 3 seeds), close to the U-Net denoiser (0.309), and the network does both tasks with 13,328 weights, against 9,046 + 9,138 = 18,184 for two U-Nets.
6. Pretrain, then fine-tune: the foundation-model idea in miniature¶
Arrival-time labels are expensive: each needs an analyst, and a new station has none. Records without labels are cheap: a station writes them every day. A foundation model is trained once on a large amount of data without labels, then adapted to many tasks with few labels each. Training without labels needs a pretext task whose answer is in the data itself. Masked autoencoders (He et al., 2022) hide parts of the input and train the network to fill them in.
The same steps, in miniature:
Pretrain. A U-Net learns to fill in 1,500 new records without arrival times: four 1-s stretches of each record are set to 0, and the loss is the squared error on the hidden samples only.
Fine-tune with 20 labeled records (and 20 more for validation), batches of 5, 60 epochs. The picker starts from scratch, or from the pretrained encoder, which is either fine-tuned (all weights updated) or frozen (only the decoder is updated). Which 20 records an analyst happens to label changes the result, so each row repeats with three sets of 20 (training records 0-19, 20-39 and 40-59, each with its own 20 validation records) and three seeds: 9 runs per row. We chose 20 labels, 60 epochs and batches of 5 in trial runs that we scored on the test records; read the small differences below with that in mind.
A second pretext. The U-Net denoiser of section 4 (seed 0) was also trained without arrival times, but with clean signals as targets, which real data never give. DeepDenoiser builds such training pairs by adding recorded noise to earthquake records of high SNR (Zhu, Mousavi & Beroza, 2019). Its encoder is a second starting point.
unlabeled, _, _ = make_records(1500, seed=1) # 1500 more records; only the recorded traces are used
rng = np.random.default_rng(5)
hidden = np.zeros_like(unlabeled)
for k in range(len(unlabeled)):
for start in rng.integers(0, NS - 25, 4): # four 1-s stretches (25 samples) per record
hidden[k, start:start + 25] = 1
Xm = as_tensor(unlabeled * (1 - hidden)) # input: the record with the stretches set to 0
Ym = torch.tensor(np.stack([unlabeled, hidden], 1)) # target: the record, and where it was hidden
def masked_loss(out, y):
"""Mean squared error over the hidden samples only."""
return (((out[:, 0] - y[:, 0]) ** 2) * y[:, 1]).sum() / y[:, 1].sum()
torch.manual_seed(0)
masked_model = EncoderDecoder(bottleneck=8, skips=True)
hist_mask = train_model(masked_model, (Xm[200:], Ym[200:], Xm[:200], Ym[:200]), masked_loss, epochs=10)
print(f"masked pretraining on {len(unlabeled) - 200} records: validation loss {min(hist_mask['val_loss']):.3f} "
f"(the hidden samples have variance {unlabeled[:200][hidden[:200] == 1].var():.3f}), {hist_mask['time_s']:.1f} s")
k = 0
rec = predict(masked_model, Xm[k:k + 1])[0, 0]
fig, ax = plt.subplots(figsize=(9, 2.4))
ax.plot(t, unlabeled[k], color="#BBBBBB", lw=0.8, label="record")
ax.plot(t, np.where(hidden[k] == 1, rec, np.nan), color="#EE6677", lw=1.2, label="filled in by the network")
for s in np.flatnonzero(np.diff(np.r_[0, hidden[k]]) == 1):
ax.axvspan(t[s], t[s] + 1, color="#EE6677", alpha=0.12)
ax.set_xlabel("time (s)")
ax.legend(fontsize=8, loc="upper right")
plt.tight_layout()
plt.show()masked pretraining on 1300 records: validation loss 0.617 (the hidden samples have variance 1.011), 5.0 s

Your turn (4): freeze the encoder¶
make_picker builds a picker and, if a pretrained model is given, copies its encoder weights. Write the lines that freeze the encoder when freeze=True: its weights get no gradient, so the updates change only the decoder. Hint: a for loop over model.encoder.parameters(), setting .requires_grad = False. Two lines.
def make_picker(pretrained=None, freeze=False):
"""A U-Net picker; its encoder starts from the encoder of `pretrained` if one is given."""
model = EncoderDecoder(bottleneck=8, skips=True, heads=(3,))
if pretrained is not None:
model.encoder.load_state_dict(pretrained.encoder.state_dict()) # copy the encoder weights
if freeze:
pass # your code
return modelAnswer below (click to open it).
Notebook Cell
def make_picker(pretrained=None, freeze=False):
model = EncoderDecoder(bottleneck=8, skips=True, heads=(3,))
if pretrained is not None:
model.encoder.load_state_dict(pretrained.encoder.state_dict())
if freeze:
for w in model.encoder.parameters():
w.requires_grad = False
return model
print(f"{n_weights(make_picker(freeze=True), trained_only=True)} of {n_weights(make_picker())} weights are trained")4546 of 9138 weights are trained
DRAWS = [0, 20, 40] # three sets of 20 labeled records: training (and validation) records 0-19, 20-39, 40-59
denoiser = denoisers["U-Net (encoder-decoder with skips)"][0]["model"] # section 4, seed 0: trained without picks
starts = {"from scratch": (None, False),
"masked pretraining, fine-tuned": (masked_model, False),
"masked pretraining, encoder frozen": (masked_model, True),
"denoising pretraining, fine-tuned": (denoiser, False)}
few_label = {}
for name, (pretrained, freeze) in starts.items():
for lo in DRAWS:
few = (Xn["train"][lo:lo + 20], Yp["train"][lo:lo + 20], Xn["validation"][lo:lo + 20], Yp["validation"][lo:lo + 20])
for seed in SEEDS:
torch.manual_seed(seed) # the same starting decoder weights in every row
model = make_picker(pretrained, freeze)
hist = train_model(model, few, pick_loss, epochs=60, batch_size=5, seed=seed)
med, within = pick_scores(p_picks(predict(model, Xn["test"])), t_p[te])
few_label.setdefault(name, []).append(dict(draw=lo, seed=seed, hist=hist, median=med, within=within,
weights=n_weights(model, trained_only=True)))
w = np.array([100 * r["within"] for r in few_label[name]]).reshape(len(DRAWS), len(SEEDS)) # (draws, seeds)
print(f"{name:36s} {w.mean():5.1f} ± {w.std(ddof=1):4.1f}% of P picks within 0.5 s; mean of each draw: "
+ ", ".join(f"{v:.1f}" for v in w.mean(1)) + f"; lowest run {w.min():.1f}")
rows = [{"method": "STA/LTA (no training)", "% P picks within 0.5 s": 100 * stalta_test[1],
"median P error (s)": stalta_test[0], "weights trained": 0, "runs": 1}]
ref = pickers["picker alone (U-Net, 1 decoder)"]
rows.append({"method": "reference: picker alone, 500 labeled records (section 5)",
"% P picks within 0.5 s": np.mean([100 * r["within"] for r in ref]),
"± std": np.std([100 * r["within"] for r in ref], ddof=1),
"median P error (s)": np.mean([r["median"] for r in ref]), "weights trained": ref[0]["weights"], "runs": 3})
for name, runs in few_label.items():
w = [100 * r["within"] for r in runs]
rows.append({"method": name + ", 20 labeled records", "% P picks within 0.5 s": np.mean(w),
"± std": np.std(w, ddof=1), "median P error (s)": np.mean([r["median"] for r in runs]),
"weights trained": runs[0]["weights"], "runs": len(runs)})
board_few = pd.DataFrame(rows).set_index("method").sort_values("% P picks within 0.5 s", ascending=False)
board_few = board_few[["% P picks within 0.5 s", "± std", "runs", "median P error (s)", "weights trained"]]
board_few.round(2)from scratch 46.7 ± 10.3% of P picks within 0.5 s; mean of each draw: 42.4, 51.3, 46.2; lowest run 32.2
masked pretraining, fine-tuned 53.6 ± 5.0% of P picks within 0.5 s; mean of each draw: 50.9, 54.8, 54.9; lowest run 46.5
masked pretraining, encoder frozen 49.3 ± 4.9% of P picks within 0.5 s; mean of each draw: 50.9, 46.8, 50.2; lowest run 40.2
denoising pretraining, fine-tuned 59.1 ± 3.3% of P picks within 0.5 s; mean of each draw: 60.6, 59.7, 57.0; lowest run 51.7
With 20 labeled records (mean ± sample standard deviation over 9 runs: 3 sets of 20 labeled records × 3 seeds):
From scratch: 46.5 ± 10.2% of P picks within 0.5 s, above STA/LTA (37.5%); runs from 32.2 to 58.2%.
Masked pretraining: 52.3 ± 7.3% fine-tuned, 50.3 ± 6.0% with the encoder frozen (4,546 of 9,138 weights trained). Pretraining on records without a single arrival time raised the mean by 4 to 6 points.
Denoising pretraining, fine-tuned: 53.5 ± 16.5%. Eight of its nine runs fall between 53.0 and 62.5%, against 69.3% with 500 labels; the ninth (records 40-59, seed 1) fell to 10.2%.
The mean of each row also depends on which 20 records were labeled: from scratch, 42.4, 51.2 and 45.9% for the three sets; denoising pretraining, 58.8, 57.5 and 44.2%. With the first set alone (records 0-19) and three seeds, denoising pretraining looks 16 points better than training from scratch (58.8 against 42.4%); over the three sets the gap is 7 points, smaller than the spread of the runs. Pretraining helps on average here, but 20 labels are too few to rank the two pretexts. A frozen encoder keeps features learned for another task; fine-tuning lets the 20 labeled records adjust them. The masked network explains 39% of the variance of what it cannot see (validation loss 0.617, against a variance of 1.011 for the hidden samples): in the figure, the filled stretches follow the slow swings of the noise, which is most of a record.
Foundation models apply the same three choices at scale: what to pretrain on, which pretext, and how much of the encoder to update with the labels of each new task.
7. Optional: a mixture of experts¶
Optional; it runs in about 15 s and nothing after it depends on it.
A U-Net uses every weight on every record. A mixture of experts (Jacobs et al., 1991) holds several sub-networks, the experts, and a small router that reads the input and gives expert a weight , with . Ours is a soft mixture: both experts run on every record and the output is ; the Switch Transformer (Fedus et al., 2022) runs only the expert with the largest weight, to save computation.
The test: a station with two noise regimes, 400 records with low-frequency noise (color 2, like the ocean microseism) and 400 with high-frequency noise (color −1.5, like traffic). One encoder, two narrow decoders (the experts) and a router (one linear layer on the time average of each encoder output, then a softmax), never told the regime; against one decoder with about the same number of weights. The model returns the two experts’ outputs and the router’s two log-weights as 4 channels, so that train_model runs unchanged.
The loss of a record, where is the mean squared error of expert and the average weight of expert over the batch, for experts:
The first term (Jacobs et al., 1991) is small when the router puts its weight on the expert that fits the record best, so the experts compete instead of averaging. is the variance the error of an expert is assumed to have. The second term is smallest when the experts receive equal shares of the records; the Switch Transformer adds a load-balancing term for the same reason. We use balance = 1; we also looked at the test errors of 0.3 and 3 (which a study should not do), and the two-expert error moved by less than 0.01.
low, low_clean, _ = make_records(400, seed=3, noise_colors=(2.0, 2.0)) # noise power falls with frequency
high, high_clean, _ = make_records(400, seed=4, noise_colors=(-1.5, -1.5)) # noise power rises with frequency
order = np.random.default_rng(6).permutation(800)
X7 = as_tensor(np.concatenate([low, high])[order])
C7 = as_tensor(np.concatenate([low_clean, high_clean])[order])
regime = np.r_[np.zeros(400, int), np.ones(400, int)][order] # 0: low-frequency noise, 1: high-frequency noise
d7 = (X7[:500], C7[:500], X7[500:600], C7[500:600]) # 500 train, 100 validation, 200 test records
class MixtureOfExperts(nn.Module):
"""One encoder, two narrow decoders (the experts) and a router that weighs them for each record."""
def __init__(self, n_experts=2, width=0.5):
super().__init__()
self.encoder = Encoder()
self.squeeze = nn.Conv1d(CHANNELS[-1], 8, 1)
self.experts = nn.ModuleList(Decoder(8, skips=True, width=width) for _ in range(n_experts))
self.router = nn.Linear(sum(CHANNELS), n_experts)
def forward(self, x):
feats = self.encoder(x)
summary = torch.cat([f.mean(-1) for f in feats[1:]], dim=1) # each encoder output, averaged in time
log_w = torch.log_softmax(self.router(summary), dim=-1)
z = self.squeeze(feats[-1])
outs = torch.cat([e(z, feats) for e in self.experts], dim=1) # (records, experts, samples)
# the router's log-weights ride along as extra channels, so that train_model works unchanged
return torch.cat([outs, log_w[:, :, None].expand(-1, -1, x.shape[-1])], dim=1)
def experts_loss(out, y, s2=0.01, balance=1.0):
"""First term (Jacobs et al., 1991): each expert is scored on its own error, and the loss of a record is
small when the router gives a large weight to an expert that fits it well. Second term: smallest when,
averaged over the batch, the experts get equal shares of the records."""
n = out.shape[1] // 2
err = ((out[:, :n] - y) ** 2).mean(-1) # (records, experts)
log_w = out[:, n:, 0] # router log-weights, (records, experts)
share = log_w.exp().mean(0) # average weight of each expert
return -torch.logsumexp(log_w - err / (2 * s2), dim=1).mean() + balance * n * (share ** 2).sum()
torch.manual_seed(0)
moe = MixtureOfExperts()
hist_moe = train_model(moe, d7, experts_loss)
out = predict(moe, X7[600:])
w_router = np.exp(out[:, 2:, 0]) # router weights, (records, 2)
moe_out = (w_router[:, :, None] * out[:, :2]).sum(1)
torch.manual_seed(0)
single = EncoderDecoder(bottleneck=8, skips=True, width=0.85) # about as many weights as the two experts
hist_single = train_model(single, d7, mse)
single_out = predict(single, X7[600:])[:, 0]
c7 = C7[600:, 0].numpy()
chosen = w_router.argmax(1)
agreement = max((chosen == regime[600:]).mean(), (chosen != regime[600:]).mean()) # the expert numbering is arbitrary
print(f"one decoder: {n_weights(single)} weights, test error {rel_error(single_out, c7).mean():.3f}, {hist_single['time_s']:.1f} s")
print(f"two experts: {n_weights(moe)} weights, test error {rel_error(moe_out, c7).mean():.3f}, {hist_moe['time_s']:.1f} s")
print(f"router choice agrees with the noise regime for {100 * agreement:.1f}% of the 200 test records")
pd.crosstab(pd.Series(np.where(regime[600:] == 0, "low-frequency noise", "high-frequency noise"), name="true regime"),
pd.Series(chosen, name="expert chosen by the router"))one decoder: 8327 weights, test error 0.216, 3.9 s
two experts: 8302 weights, test error 0.204, 5.5 s
router choice agrees with the noise regime for 100.0% of the 200 test records
For seed 0, the router sends every one of the 200 test records to the expert of its noise regime (expert 0 takes the 117 low-frequency records, expert 1 the 83 high-frequency records), although it was never told the regime. The two experts reach an error of 0.204, against 0.216 for one decoder with about the same number of weights (8,302 and 8,327).
Exercise. Rerun the cell above with seeds 1 and 2 (torch.manual_seed(1) before both models), then without the balance term: train_model(moe, d7, lambda out, y: experts_loss(out, y, balance=0.0)). Our runs: 100% agreement again, but the experts scored 0.236 and 0.215 against 0.228 and 0.199 for one decoder, so over three seeds they do not lower the error; without the balance term, seeds 1 and 2 sent every record to one expert (58.5% agreement, the share of the larger regime). What the mixture gives here is a choice that can be read: the kind of noise the network found in each record.
Are the skip connections of a U-Net experts? No. Every record takes every skip and every decoder block: the path does not depend on the input. The two decoders of the multi-task network of section 5 are not experts either: both run on every record and their losses are summed. A task decoder acts as a router set by hand only when a task label picks which decoder runs, as when a foundation model gets one fine-tuned head per task. The multi-gate mixture of experts (Ma et al., 2018) joins the two ideas: several task decoders, each with its own learned router over shared experts.
8. Summary¶
| network | record in → out | test score (mean ± std, 3 seeds) | weights | baseline |
|---|---|---|---|---|
| autoencoder, bottleneck 50 / 400 numbers | clean → clean | error 0.414 / 0.261 (1 seed) | 6,570 / 7,249 | |
| encoder-decoder, no skips | noisy → clean | error 0.411 ± 0.011 (10.9 dB) | 7,249 | band-pass 0.725; references: Wiener 0.428, best gain 0.391 |
| U-Net | noisy → clean | error 0.309 ± 0.017 (14.9 dB) | 9,046 | band-pass 6.8 dB |
| U-Net picker, 500 labels | noisy → P, S, no-arrival | 69.3 ± 1.4% P picks within 0.5 s | 9,138 | STA/LTA 37.5% |
| multi-task U-Net, 500 labels | noisy → clean + probabilities | 48.3 ± 36.9% (seeds: 68.5, 70.8, 5.8) | 13,328 | STA/LTA 37.5% |
| U-Net picker, 20 labels: scratch / masked pretraining / denoising pretraining (fine-tuned) | noisy → probabilities | 46.5 ± 10.2 / 52.3 ± 7.3 / 53.5 ± 16.5% (9 runs: 3 label sets × 3 seeds) | 9,138 | STA/LTA 37.5% |
| two experts and a router (optional) | noisy → clean, 2 noise regimes | error 0.204, router right on 100% (seed 0) | 8,302 | one decoder 0.216 |
An encoder-decoder maps a record to a record of the same length through a bottleneck. The target sets what the output means: the same record (autoencoder), the clean signal (denoiser), arrival probabilities (picker).
Skip connections carry the detail of each scale past the bottleneck: the U-Net cut the denoising error by a quarter for 1,797 more weights, and only the U-Net beat the filters built from each record’s clean signal.
One encoder can serve one decoder per task (EQTransformer). Report every seed: one start out of three called the S wave P, which seed 0 or seed 1 alone would have hidden.
Pretraining on records without labels made 20 labels go further on average: 47% of P picks within 0.5 s from scratch, 52% after masked pretraining, 54% after denoising pretraining (9 runs each). Which 20 records were labeled moved the means as much as the choice of pretext did.
Foundation models for Earth data, such as Prithvi and Aurora, apply this recipe at scale, with attention layers (4.4; Vaswani et al., 2017) in their encoders.
A mixture of experts learns a router that weights its decoders record by record. Skip connections and the decoders of a multi-task network make no such choice: every record takes every path.
The training loop, the checkpoint, the seeds and the leaderboards of this notebook are those of the training block, 4.7.
Now on real data. The homework (Homework_DL) trains a convolutional detector on real seismograms. On real records the clean signal is never known: DeepDenoiser builds its training pairs from high-SNR earthquake records and recorded noise, and PhaseNet trains on picks made by analysts, so a picker is scored against picks that have errors of their own.
Reflect on this notebook¶
As for every assignment in this course (1.8), a few sentences each:
What did you learn from this exercise? Name the scientific or technical idea, with one example from your own work in this notebook.
What did you learn from interacting with agents or chatbots? Say what you asked, what the tool got right, what it got wrong, and how you checked it.
What would you suggest to improve this notebook so it meets its learning goals? Be specific.
References¶
Allen, R. V. (1978). Automatic earthquake recognition and timing from single traces. Bulletin of the Seismological Society of America, 68(5), 1521–1532. Allen (1978)
Bodnar, C., Bruinsma, W. P., Lucic, A., Stanley, M., Allen, A., Brandstetter, J., et al. (2025). A foundation model for the Earth system. Nature, 641(8065), 1180–1187. Bodnar et al. (2025)
Fedus, W., Zoph, B., & Shazeer, N. (2022). Switch Transformers: scaling to trillion parameter models with simple and efficient sparsity. Journal of Machine Learning Research, 23(120), 1–39. https://
jmlr .org /papers /v23 /21 -0998 .html (arXiv:2101.03961) He, K., Chen, X., Xie, S., Li, Y., Dollár, P., & Girshick, R. (2022). Masked autoencoders are scalable vision learners. IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 15979–15988. He et al. (2022)
Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the dimensionality of data with neural networks. Science, 313(5786), 504–507. Hinton & Salakhutdinov (2006)
Jacobs, R. A., Jordan, M. I., Nowlan, S. J., & Hinton, G. E. (1991). Adaptive mixtures of local experts. Neural Computation, 3(1), 79–87. Jacobs et al. (1991)
Jakubik, J., Roy, S., Phillips, C. E., Fraccaro, P., Godwin, D., et al. (2023). Foundation models for generalist geospatial artificial intelligence. arXiv:2310.18660. https://
arxiv .org /abs /2310 .18660 Kramer, M. A. (1991). Nonlinear principal component analysis using autoassociative neural networks. AIChE Journal, 37(2), 233–243. Kramer (1991)
Ma, J., Zhao, Z., Yi, X., Chen, J., Hong, L., & Chi, E. H. (2018). Modeling task relationships in multi-task learning with multi-gate mixture-of-experts. Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, 1930–1939. Ma et al. (2018)
Mousavi, S. M., Ellsworth, W. L., Zhu, W., Chuang, L. Y., & Beroza, G. C. (2020). Earthquake transformer: an attentive deep-learning model for simultaneous earthquake detection and phase picking. Nature Communications, 11, 3952. Mousavi et al. (2020)
Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: convolutional networks for biomedical image segmentation. Medical Image Computing and Computer-Assisted Intervention (MICCAI), Lecture Notes in Computer Science 9351, 234–241. Ronneberger et al. (2015), arXiv:1505.04597
Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning internal representations by error propagation. In D. E. Rumelhart & J. L. McClelland (Eds.), Parallel Distributed Processing, Vol. 1, 318–362. MIT Press.
Shazeer, N., Mirhoseini, A., Maziarz, K., Davis, A., Le, Q., Hinton, G., & Dean, J. (2017). Outrageously large neural networks: the sparsely-gated mixture-of-experts layer. International Conference on Learning Representations. https://
arxiv .org /abs /1701 .06538 Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems, 30. https://
arxiv .org /abs /1706 .03762 Zhu, W., & Beroza, G. C. (2019). PhaseNet: a deep-neural-network-based seismic arrival-time picking method. Geophysical Journal International, 216(1), 261–273. https://
doi .org /10 .1093 /gji /ggy423 Zhu, W., Mousavi, S. M., & Beroza, G. C. (2019). Seismic signal denoising and decomposition using deep neural networks. IEEE Transactions on Geoscience and Remote Sensing, 57(11), 9476–9488. Zhu et al. (2019)
- Allen, R. V. (1978). Automatic earthquake recognition and timing from single traces. Bulletin of the Seismological Society of America, 68(5), 1521–1532. 10.1785/bssa0680051521
- Bodnar, C., Bruinsma, W. P., Lucic, A., Stanley, M., Allen, A., Brandstetter, J., Garvan, P., Riechert, M., Weyn, J. A., Dong, H., Gupta, J. K., Thambiratnam, K., Archibald, A. T., Wu, C.-C., Heider, E., Welling, M., Turner, R. E., & Perdikaris, P. (2025). A foundation model for the Earth system. Nature, 641(8065), 1180–1187. 10.1038/s41586-025-09005-y
- He, K., Chen, X., Xie, S., Li, Y., Dollar, P., & Girshick, R. (2022). Masked Autoencoders Are Scalable Vision Learners. 2022 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 15979–15988. 10.1109/cvpr52688.2022.01553
- Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the Dimensionality of Data with Neural Networks. Science, 313(5786), 504–507. 10.1126/science.1127647
- Jacobs, R. A., Jordan, M. I., Nowlan, S. J., & Hinton, G. E. (1991). Adaptive Mixtures of Local Experts. Neural Computation, 3(1), 79–87. 10.1162/neco.1991.3.1.79
- Kramer, M. A. (1991). Nonlinear principal component analysis using autoassociative neural networks. AIChE Journal, 37(2), 233–243. 10.1002/aic.690370209
- Ma, J., Zhao, Z., Yi, X., Chen, J., Hong, L., & Chi, E. H. (2018). Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts. Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, 1930–1939. 10.1145/3219819.3220007
- Mousavi, S. M., Ellsworth, W. L., Zhu, W., Chuang, L. Y., & Beroza, G. C. (2020). Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking. Nature Communications, 11(1). 10.1038/s41467-020-17591-w
- Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: Convolutional Networks for Biomedical Image Segmentation. In Lecture Notes in Computer Science (pp. 234–241). Springer International Publishing. 10.1007/978-3-319-24574-4_28
- Zhu, W., Mousavi, S. M., & Beroza, G. C. (2019). Seismic Signal Denoising and Decomposition Using Deep Neural Networks. IEEE Transactions on Geoscience and Remote Sensing, 57(11), 9476–9488. 10.1109/tgrs.2019.2926772