Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Deep Random Feature Expansions — Stacked Spectral GPs (Cutajar et al. 2017)

Open In Colab

This notebook is the deep companion to the RFF → SSGP → VSSGP notebook. The single-layer methods covered there can only represent functions in the RKHS of one stationary kernel. Stacking gives non-stationary, hierarchical representations — long-range trends and short-range texture in the same model. Cutajar, Bonilla, Michiardi & Filippone (ICML 2017) made this practical by stacking RFF layers and fitting them with the doubly-stochastic reparameterised ELBO.

Three deep methods, each the depth-LL analogue of one single-layer method from the companion notebook:

Single layerThis notebookΩl\Omega_lWlW_lObjective
Learned RFF MAPDeep RFF MAPtrained (point)trained (point)regularised MSE
SSGPDeep SSGPtrained (point) per layertrained (point) for l<Ll < L, marginalised at l=Ll = Llog marginal likelihood
VSSGPDeep VSSGPvariational q(Ωl)q(\Omega_l)variational q(Wl)q(W_l)tempered ELBO

The architecture is the same in all three:

F0=X,Fl+1=Φl(Fl; Ωl,ℓl) Wl,l=0,…,L−1,F_0 = X, \qquad F_{l+1} = \Phi_l(F_l;\, \Omega_l, \ell_l)\, W_l, \qquad l = 0, \dots, L-1,

with Φl(F;Ωl,ℓl)=1/M [cos⁡(FΩl/ℓl),sin⁡(FΩl/ℓl)]∈RN×2M\Phi_l(F; \Omega_l, \ell_l) = \sqrt{1/M}\,[\cos(F\Omega_l/\ell_l), \sin(F\Omega_l/\ell_l)] \in \mathbb{R}^{N \times 2M}.

Forward-pointers: the single-layer versions live in the SSGP notebook; the fixed-Ω + ensemble alternatives are in the RFF as Neural Networks notebook.

When might depth help, and at what cost?

A single-layer SSGP/VSSGP is a stationary model: the kernel is the same function of x−x′x - x' everywhere in input space. The linear head β\beta is a constant set of weights on the features Φ(x)\Phi(x) — it cannot say “here, weight the high-frequency features more; over there, weight the low-frequency ones.” For some non-stationary targets, this is a real limitation.

Stacking LL RFF blocks builds an amortised kind of non-stationarity: the input to layer l+1l+1 is itself a learned nonlinear transform of xx, so the effective kernel in the deep model is position-dependent. The canonical demonstration target — used here and in Damianou & Lawrence (AISTATS 2013) — is the compositional warp

f(x)=sin⁡ ⁣(3π sin⁡(πx)).f(x) = \sin\!\bigl(3\pi\,\sin(\pi x)\bigr).

Its instantaneous frequency ∣f′(x)∣=3π2 ∣cos⁡(πx)∣|f'(x)| = 3\pi^2\,|\cos(\pi x)| varies from ∼30\sim 30 at x=0x = 0 to 0 at x=±12x = \pm \tfrac{1}{2} and back to ∼30\sim 30 at x=±1x = \pm 1. A single-layer model with one global lengthscale must compromise; a depth-2 model can in principle learn sin⁡(πx)\sin(\pi x) in the first layer and sin⁡(3πz)\sin(3\pi z) in the second.

The catch. The per-layer Gaussian conjugacy of single-layer SSGP is broken by stacking — the input to layer ll is itself a stochastic function of Ω0:l−1,W0:l−1\Omega_{0:l-1}, W_{0:l-1}, so the marginal likelihood at the top is no longer Gaussian. We need either (a) a deterministic deep features stack with a closed-form SSGP only on the readout (deep SSGP), or (b) a fully variational doubly-stochastic ELBO over all (Ωl,Wl)(\Omega_l, W_l) (deep VSSGP). The second is harder to optimise — see §3.

Honest expectation. Depth-2 with modest hidden width on a 1D toy is not always a clear win over a well-tuned single-layer SSGP (covered in the SSGP notebook) — for moderate problems the single-layer methods are usually enough. Treat this notebook as a recipe for building the deep stack; whether you actually need it for your problem should be settled by benchmarking against the single-layer baseline.

Setup

Python implementation: CPython
Python version       : 3.13.5
IPython version      : 9.10.0

jax       : 0.9.2
equinox   : 0.13.6
numpyro   : 0.20.1
pyrox     : 0.0.6
matplotlib: 3.10.8

Compiler    : GCC 11.2.0
OS          : Linux
Release     : 6.8.0-1044-azure
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

Dataset — Damianou-Lawrence compositional warp

We use the canonical 1D deep-GP demo target

f⋆(x)=sin⁡ ⁣(3π sin⁡(πx)),x∈[−1,1],f^\star(x) = \sin\!\bigl(3\pi\,\sin(\pi x)\bigr), \qquad x \in [-1, 1],

observed with Gaussian noise σ=0.05\sigma = 0.05. The function has position-dependent effective frequency: oscillates rapidly near x=0x = 0 and x=±1x = \pm 1 (where the warp sin⁡(πx)\sin(\pi x) has maximum slope) and is locally flat at x=±12x = \pm \tfrac{1}{2} (where the warp’s slope vanishes).

observations: N = 140 (gap removed from x ∈ (-0.2, 0.4))
<Figure size 1100x400 with 1 Axes>

All three deep methods use the same architecture:

  • Din=1D_{\mathrm{in}} = 1, Dout=1D_{\mathrm{out}} = 1

  • hidden dimension Dh=16D_h = 16

  • M=32M = 32 Fourier features per layer

  • depth L=2L = 2 (stacked SSGP blocks; one is the readout)

  • prior lengthscale ℓ=0.3\ell = 0.3

This keeps the per-method parameter count comparable so depth is what differs, not capacity.

1. Deep RFF (MAP) — the deterministic baseline

Math. Same architecture as the deep VSSGP, but every parameter is a PyTree leaf trained by gradient descent on the regularised MSE

L(Θ)=12σn2 ∥y−FL(X;Θ)∥2+M2σW2∑l=0L−1∥Wl∥F2+12∑l=0L−1∥Ωl∥F2/σΩ2,\mathcal{L}(\Theta) = \tfrac{1}{2\sigma_n^2}\,\bigl\|y - F_L(X; \Theta)\bigr\|^2 + \tfrac{M}{2\sigma_W^2}\sum_{l=0}^{L-1}\|W_l\|_F^2 + \tfrac{1}{2}\sum_{l=0}^{L-1}\|\Omega_l\|_F^2 / \sigma_\Omega^2,

where Θ={Ωl,Wl,ℓl}l=0L−1\Theta = \{\Omega_l, W_l, \ell_l\}_{l=0}^{L-1}. The frequency L2 acts as a soft prior pulling each Ωl\Omega_l toward the lengthscale-1 RBF spectral density.

What MAP cannot give you. A point estimate of the deep network — no per-prediction uncertainty. The fit through the held-out gap is whatever the optimiser settled on, with no signal that the model is uncertain there.

Wide initialisation matters per layer. Same saddle issue as the single-layer learned RFF: cos⁡(FΩ/ℓ)\cos(F\Omega/\ell) has zero gradient at Ω=0\Omega = 0. We initialise each Ωl∼N(0,σ2)\Omega_l \sim \mathcal{N}(0, \sigma^2) with σ=5\sigma = 5 to escape the saddle.

deep RFF MAP: final loss = 0.0092, MSE = 0.1837
<Figure size 1100x450 with 1 Axes>

Clean fit at the data, but the curve through the held-out gap is just whatever the optimiser found — no uncertainty. The depth here gives the model enough capacity to track the warp’s varying instantaneous frequency without adjusting features per-region; we still have no posterior to read from.

2. Deep SSGP — analytic readout, deterministic deep features

Math. Layer-wise marginalisation of WlW_l in the deep stack is not closed-form because FlF_l depends stochastically on W0:l−1W_{0:l-1}. The clean compromise: treat the first L−1L - 1 layers as deterministic feature extractors with point-estimate (Ωl,Wl)(\Omega_l, W_l), and apply the closed-form SSGP marginal likelihood only at the readout.

Concretely, for a depth-LL network:

FL−1=ΦL−2(ΦL−3(⋯Φ0(X)⋯ ))(deterministic),y=ΦL−1(FL−1;ΩL−1,ℓL−1) β+ε,F_{L-1} = \Phi_{L-2}(\Phi_{L-3}(\cdots \Phi_0(X)\cdots))\quad\text{(deterministic)}, \qquad y = \Phi_{L-1}(F_{L-1}; \Omega_{L-1}, \ell_{L-1})\, \beta + \varepsilon,

where β∼N(0,σβ2I)\beta \sim \mathcal{N}(0, \sigma_\beta^2 I) is marginalised analytically as in single-layer SSGP. The marginal likelihood becomes

log⁡p(y∣X,Θdeep,ΩL−1,ℓL−1,σβ,σn)=log⁡N ⁣(y ∣ 0,  KL−1+σn2I),KL−1=σβ2ΦL−1ΦL−1⊤.\log p(y \mid X, \Theta_{\mathrm{deep}}, \Omega_{L-1}, \ell_{L-1}, \sigma_\beta, \sigma_n) = \log \mathcal{N}\!\bigl(y \,\big|\, 0,\; K_{L-1} + \sigma_n^2 I\bigr), \qquad K_{L-1} = \sigma_\beta^2 \Phi_{L-1} \Phi_{L-1}^\top.

All hyperparameters Θ={Ωl,Wl,ℓl}l<L−1∪{ΩL−1,ℓL−1,σβ,σn}\Theta = \{\Omega_l, W_l, \ell_l\}_{l < L-1} \cup \{\Omega_{L-1}, \ell_{L-1}, \sigma_\beta, \sigma_n\} are trained jointly by maximising this objective. Predictive mean and variance use the same closed-form formulas as single-layer SSGP, applied to FL−1F_{L-1}.

Why this works. The marginal likelihood acts as both a model selection criterion (Occam’s razor on σβ,σn\sigma_\beta, \sigma_n) and as a regulariser on the deep features (preferring features that produce a Gram matrix ΦΦ⊤\Phi\Phi^\top that matches the data covariance well). The trade-off vs. the full deep VSSGP: we get closed-form predictive variance for free, but uncertainty in the lower-layer features is collapsed to a point estimate.

deep SSGP: final neg-log-ML = -182.11, σ_n = 0.0525, MSE = 0.2645
<Figure size 1100x450 with 1 Axes>

Same fit quality as deep MAP, plus a closed-form predictive band on the readout uncertainty. The band opens visibly across the gap — the deep features map gap inputs to readout-feature locations far from any training point, and the SSGP variance formula picks that up automatically. Hyperparameters σn\sigma_n, σβ\sigma_\beta, all ℓl\ell_l tuned by ML-II for free.

What this band misses. The lower-layer parameters are point estimates, so the band reflects only the readout uncertainty. If the deep features themselves were ambiguous (multiple lower-layer solutions consistent with the data), this method couldn’t say so. That is what deep VSSGP adds.

3. Deep VSSGP — full variational stack

Math. Variational posteriors on every layer’s (Ωl,Wl)(\Omega_l, W_l):

q(Ωl)=N ⁣(μΩ,l,diag(σΩ,l2)),q(Wl)=N ⁣(μW,l,diag(σW,l2)).q(\Omega_l) = \mathcal{N}\!\bigl(\mu_{\Omega,l}, \mathrm{diag}(\sigma_{\Omega,l}^2)\bigr), \qquad q(W_l) = \mathcal{N}\!\bigl(\mu_{W,l}, \mathrm{diag}(\sigma_{W,l}^2)\bigr).

Doubly-stochastic ELBO (Cutajar et al. 2017, Eq. 7-12, building on Salimbeni & Deisenroth 2017’s general framework):

Lβ(ϕ)=Eq(Θ) ⁣[∑ilog⁡p(yi∣xi,Θ)]−β ∑l=0L−1(KL ⁣[q(Ωl) ∥ p(Ωl)]+KL ⁣[q(Wl) ∥ p(Wl)]),\mathcal{L}_\beta(\phi) = \mathbb{E}_{q(\Theta)}\!\left[\sum_i \log p(y_i \mid x_i, \Theta)\right] - \beta\,\sum_{l=0}^{L-1}\Bigl(\mathrm{KL}\!\bigl[q(\Omega_l) \,\Vert\, p(\Omega_l)\bigr] + \mathrm{KL}\!\bigl[q(W_l) \,\Vert\, p(W_l)\bigr]\Bigr),

with one MC sample of the full Θ={Ωl,Wl}l=0L−1\Theta = \{\Omega_l, W_l\}_{l=0}^{L-1} per minibatch step (the “doubly stochastic” trick). Reparameterise both each step:

Ωl=μΩ,l+σΩ,l⊙εΩ,l,Wl=μW,l+σW,l⊙εW,l,ε∼N(0,I).\Omega_l = \mu_{\Omega,l} + \sigma_{\Omega,l} \odot \varepsilon_{\Omega,l}, \qquad W_l = \mu_{W,l} + \sigma_{W,l} \odot \varepsilon_{W,l}, \qquad \varepsilon \sim \mathcal{N}(0, I).

All KLs are closed-form Gaussian-Gaussian. We use the tempered ELBO with β=0.05\beta = 0.05 — the same KL annealing from the single-layer VSSGP notebook.

Implementation. pyrox_nn.DeepVSSGP registers exactly 3L3L sample sites — layer_{l}.W_freq, layer_{l}.lengthscale, layer_{l}.W_proj — with NumPyro priors, and is the production path described in §5. The notebook code below uses an inline manual class with reparameterised sampling so the tempered ELBO, the KL-warmup schedule, and the MAP warm-start trick are visible.

MAP warm-start. A direct cold start on the deep variational ELBO routinely fails to fit the training data: MC sampling noise plus KL pressure on μΩ\mu_\Omega overwhelms the data fit gradient before a sensible solution is established. The fix that consistently works in deep variational GPs (see Salimbeni & Deisenroth 2017, Cutajar et al. 2017) is to initialise the variational means at a trained MAP solution (with very tight initial σ\sigma, so qq starts as a near-delta around MAP) and then continue training with the tempered ELBO. The variational training then only has to learn appropriate σ\sigma — the means already start at a good fit. We use this trick below.

deep VSSGP: final tempered-ELBO loss = 67.15
deep VSSGP: trained ℓ = 0.286, 1.074
deep VSSGP: predictive MSE = 0.2094
<Figure size 1100x450 with 1 Axes>

Grey traces are independent draws from ∏lq(Ωl) q(Wl)\prod_l q(\Omega_l)\,q(W_l), run end-to-end through the deep stack. They agree at the data and pull apart in the gap and extrapolation regions — the band reflects uncertainty in every layer’s parameters, not just the readout. The MC band is necessarily noisier than SSGP’s closed-form band but captures the richer hierarchical uncertainty.

4. Three deep methods, one plot

Same target, same data, three predictive bands.

<Figure size 1800x450 with 3 Axes>
deep SSGP: gap/data std ratio = 3.2x
deep VSSGP: gap/data std ratio = 1.1x

Reading the figure. What changes between methods is mostly the uncertainty, not the point fit:

  • Deep MAP — point estimate, no band; whatever curve the optimiser chose.

  • Deep SSGP — closed-form band on the readout posterior, ML-II hyperparameters. Band opens across the gap.

  • Deep VSSGP — MC band over the full 3L3L-site posterior. Captures lower-layer uncertainty too; band is noisier than SSGP’s because it’s MC, and tighter when warm-started from MAP (which we did to get a usable optimisation — see §3).

Whether depth itself wins on this target is best judged by comparing to the single-layer SSGP / VSSGP from the SSGP notebook. The architecture used here is much harder to optimise than a single-layer model — depth is worth reaching for when the target has clear compositional structure (warps of warps, hierarchical scales) that a stationary kernel cannot represent.

5. Implementation note — pyrox_nn.DeepVSSGP is the production path

The notebook’s ManualDeepVSSGP above is written inline so the tempered ELBO and the per-layer reparameterisation are visible — same pedagogical choice as the single-layer VSSGP class in the SSGP notebook. For production use, the same model is packaged as pyrox_nn.DeepVSSGP:

from pyrox_nn import DeepVSSGP
import numpyro
from numpyro.infer import SVI, Trace_ELBO
from numpyro.infer.autoguide import AutoNormal

def model(x, y=None):
    net = DeepVSSGP.init(
        in_features=1, hidden_features=HIDDEN, out_features=1,
        depth=DEPTH, n_features=M_FEAT, lengthscale=LENGTHSCALE_INIT,
        pyrox_name="dgp",
    )
    pred = net(x)[:, 0]
    sigma_n = numpyro.sample("sigma_n", numpyro.distributions.LogNormal(jnp.log(0.05), 0.5))
    numpyro.sample("y", numpyro.distributions.Normal(pred, sigma_n), obs=y)

guide = AutoNormal(model, init_scale=0.1)
svi = SVI(model, guide, numpyro.optim.Adam(5e-3), loss=Trace_ELBO(num_particles=1))
state = svi.init(key, x_obs, y_obs)
# ... training loop ...

Each forward call to DeepVSSGP registers 3L3L NumPyro sample sites (layer_{l}.W_freq, layer_{l}.lengthscale, layer_{l}.W_proj for l=0,…,L−1l = 0, \dots, L-1) with the pyrox sampling protocol. Standard NumPyro AutoNormal + SVI on top discovers all sites and learns mean-field Gaussian posteriors with no custom variational bookkeeping. The price for that elegance is more JIT-compile overhead than the manual loop above; both are correct.

Sanity check at L=1L = 1. A DeepVSSGP of depth 1 reduces to a single VSSGP layer with the same architecture as VariationalFourierFeatures composed with DenseReparameterization. The unit test tests/nn/test_deep_vssgp.py::test_depth_one_reduces_to_single_vssgp enforces this — at depth 1 there are exactly 3 sample sites and the output dimension is out_features directly.

Takeaways

  • Stacking RFF layers gives a path toward non-stationary kernels. The composition ΦL−1(ΦL−2(⋯Φ0(x)⋯ ))\Phi_{L-1}(\Phi_{L-2}(\cdots \Phi_0(x) \cdots)) produces an effective kernel whose dependence on xx is no longer translation-invariant. Whether your problem benefits from this depends on whether it has the kind of compositional / hierarchical structure that a stationary kernel cannot represent.

  • Layer-wise marginalisation breaks at depth >1> 1. The Gaussian conjugacy that gives single-layer SSGP its closed form only works because the input to the readout is deterministic. Stacking makes that input itself stochastic, so the marginal likelihood is no longer Gaussian — hence the deep VSSGP doubly-stochastic ELBO.

  • Three deep flavors, three trade-offs.

    • Deep MAP — cheapest, no uncertainty.

    • Deep SSGP — closed-form readout band + ML-II hyperparameters, but lower layers are point estimates (no uncertainty in the deep features).

    • Deep VSSGP (Cutajar et al. 2017) — variational posterior over every layer; MC predictive band that captures hierarchical uncertainty. Hardest to fit: the data fit gradient on the deep ELBO routinely loses to the KL when started cold, so we warm-start the variational means from a trained MAP solution (and start log-sigma very tight). Without this trick, the deep ELBO objective routinely fails to fit even the training data.

  • pyrox_nn.DeepVSSGP packages the full variational stack as a single PyroxModule. Standard NumPyro AutoNormal + SVI on top.

  • Benchmark before reaching for depth. For a moderate 1D problem, a single-layer SSGP with a wide enough MM usually fits as well or better than depth-2, with a fraction of the optimisation pain. Treat depth as a tool for high-dim non-stationary problems with clear hierarchical structure — not as a default upgrade from single-layer.

Where to next.

  • For the single-layer versions and the apples-to-apples baseline, see the RFF → SSGP → VSSGP notebook.

  • For fixed-Ω + ensemble RFF, see the RFF as Neural Networks notebook.

  • The industrial-strength cousin of deep VSSGP for large datasets is doubly-stochastic Deep GPs with inducing points (Salimbeni & Deisenroth, NeurIPS 2017) — the inducing-point analogue of the random-feature stack here.