Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions backlog/features/2026-11-27_uncollapsed-whitened-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,103 @@ The gate (L=3: RMSE <= 0.26, NLL <= 0, beats one layer) is met. GPc's RBF number
**CMU** subject 35 walk 01 (358 frames, 62-D; train on even frames, predict odd frames from interpolated top latents, `[62, 5, 3]`, M=25; held-out RMSE on standardised data, predicting the mean gives 0.95): collapsed 0.438, doubly stochastic 0.281, with natgrad 0.265.

Caveats: single seeds; the collapsed model used the repository's example initialisation and is probably under-tuned (seed 1 landed in a poor optimum), so these runs do not show that doubly stochastic inference is better in general, only that it trains reliably here. Wall time is much longer for the doubly stochastic runs (100-870 s versus 8-225 s) because it is pure NumPy with per-sample Python loops. The CMU metric tests latent smoothness, not dynamics.

### 2026-11-27 (tuning slice 1: speed and seeds)

`fit_minibatch` recomputed the bound after every parameter write; it now defers that to the next
`resample`. A step is about 1.8x faster (profile: 0.97 s to 0.53 s for 20 steps, N=1000, M=64, two
layers), and `fit_minibatch` results are unchanged in kind (123 tests pass). The remaining cost is
mostly GPy kernel gradient routing, so a further gain needs batched kernel calls.

V8, 3000 iterations, batch 256, seeds 0 to 2 (test RMSE / NLL):

| L | seed 0 | seed 1 | seed 2 | seconds per run |
|---|--------|--------|--------|-----------------|
| 1 | 0.772 / 1.151 | 0.766 / 1.144 | 0.766 / 1.144 | 40 to 48 |
| 2 | 0.204 / -0.193 | 0.212 / -0.180 | 0.207 / -0.192 | 50 to 102 |
| 3 | 0.207 / -0.188 | 0.210 / -0.190 | 0.218 / -0.159 | 120 to 172 |

The gate is met on every seed, and the spread across seeds is about 0.01 in RMSE. A third layer
does not improve on two on this task. GPc-style initialisation (chi = 1/L) is not yet tried.

### 2026-11-27 (tuning slice 2: chi initialisation and a converged collapsed baseline)

`DoublyStochasticDeepGP(..., chi=c)` (also through `DeepGP(..., inference_method='doubly_stochastic')`)
starts hidden-layer kernels at variance `c/(L-1)`, GPc's CIP-0035 default scale. One test covers it.
The collapsed baseline in `examples/compare_collapsed_vs_doubly_stochastic.py` now restarts L-BFGS in
blocks of 1000 iterations, up to 5000, until the bound stops improving by 0.1%.

V8, `chi=1`, 3000 iterations, seeds 0 to 2 (test RMSE / NLL):

| L | seed 0 | seed 1 | seed 2 |
|---|--------|--------|--------|
| 2 | 0.204 / -0.193 | 0.212 / -0.180 | 0.207 / -0.192 |
| 3 | 0.235 / -0.091 | 0.215 / -0.151 | 0.199 / -0.185 |

At L=2, `chi/(L-1) = 1` is already our default, so the L=2 rows reproduce the earlier ones exactly.
At L=3 the hidden variance halves. It is worse on seed 0, better on seed 2, and the seed spread
(0.199 to 0.235) is larger than before (0.207 to 0.218). We see no benefit from `chi=1` on this task,
so the default stays `chi=None` (kernel variance 1).

Oil (`[12, 5, 2]`, M=30), seeds 0 to 2: leave-one-out 1-NN error / reconstruction RMSE.

| model | seed 0 | seed 1 | seed 2 |
|-------|--------|--------|--------|
| collapsed | 0.28 / 1.002 | 0.32 / 0.788 | 0.27 / 0.649 |
| doubly stochastic | 0.03 / 0.197 | 0.03 / 0.184 | 0.03 / 0.192 |
| + natgrad (0.1) | 0.03 / 0.178 | 0.03 / 0.172 | 0.03 / 0.182 |

CMU subject 35 walk, held-out RMSE, seed 0: collapsed 0.429, doubly stochastic 0.281, with natgrad
0.265; predicting the mean of the training frames gives 0.950.

Caveats. All hidden-layer `chi` settings here are no-ops for the two-layer oil and CMU stacks
(`chi/(L-1)=1`), so the `+ chi=1` variant equals `+ natgrad` and is not shown. The collapsed oil
model reaches a reconstruction RMSE near 1.0 on seed 0 (the level of predicting the mean), which
points to a poor local optimum; five thousand iterations from one initialisation per seed does not
rule out a better collapsed fit from other initialisations or noise settings. The oil and CMU
comparisons are three seeds and one seed respectively.

### 2026-11-27 (tuning slice 3: several collapsed initialisations)

The collapsed baseline now trains four initialisations per seed (seed offset 0 or 1000, initial noise
0.01 or 0.1 of the output variance; each converged as in slice 2) and keeps the one with the highest
variational bound, never the best metric. All four are printed. Two-layer `chi` is a no-op, so that
variant is dropped from the script.

Oil, seeds 0 to 2. Per initialisation: bound, leave-one-out 1-NN error, reconstruction RMSE.

| seed | init (offset, noise) | bound | 1-NN | RMSE |
|------|------|-------|------|------|
| 0 | 0, 0.01 | -879.9 | 0.28 | 1.002 |
| 0 | 1000, 0.01 | -916.2 | 0.20 | 1.001 |
| 0 | 0, 0.1 | **-846.6** | 0.53 | 1.003 |
| 0 | 1000, 0.1 | -882.5 | 0.38 | 1.002 |
| 1 | 0, 0.01 | -972.7 | 0.32 | 0.788 |
| 1 | 1000, 0.01 | -865.6 | 0.05 | 1.004 |
| 1 | 0, 0.1 | -968.9 | 0.41 | 0.800 |
| 1 | 1000, 0.1 | **-843.0** | 0.40 | 1.003 |
| 2 | 0, 0.01 | **-862.0** | 0.27 | 0.649 |
| 2 | 1000, 0.01 | -890.2 | 0.40 | 1.002 |
| 2 | 0, 0.1 | -869.4 | 0.31 | 0.663 |
| 2 | 1000, 0.1 | -945.0 | 0.01 | 0.483 |

Best by bound (bold) against the doubly stochastic model (1-NN / RMSE):

| seed | collapsed, best bound | doubly stochastic | + natgrad |
|------|------|------|------|
| 0 | 0.53 / 1.003 | 0.03 / 0.197 | 0.03 / 0.178 |
| 1 | 0.40 / 1.003 | 0.03 / 0.184 | 0.03 / 0.172 |
| 2 | 0.27 / 0.649 | 0.03 / 0.192 | 0.03 / 0.182 |

CMU walk, seed 0, held-out RMSE per collapsed initialisation: 0.429, 0.307, 0.390, 0.499 (bounds
-4309, -4252, -4239, -4293). Best by bound: 0.390. Doubly stochastic 0.281; with natgrad 0.265; mean
of training frames 0.950.

Findings. Extra initialisations do not close the oil gap. Even the best collapsed run by any metric
(seed 2, init 4: 1-NN 0.01, RMSE 0.483) reconstructs much worse than the doubly stochastic model
(0.18 to 0.20), and most collapsed runs reconstruct at the level of the data mean (RMSE about 1.0).
The bound does not rank the collapsed runs by quality: the highest bound picked the worst
reconstruction on seeds 0 and 1. On CMU the best collapsed initialisation (0.307) comes closer to the
doubly stochastic result (0.281) but still does not match it. The optimiser and initialisation
choices are one family (PCA start, default kernels, L-BFGS); a collapsed model tuned by the original
DeepGP recipe (staged layer training, fixed noise early) could do better, and we have not tried that.
11 changes: 9 additions & 2 deletions deepgp/models/uncollapsed.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,14 @@ class DoublyStochasticDeepGP(Model):
:param n_samples: Monte Carlo samples per evaluation.
:param batch_size: default minibatch size for :meth:`fit_minibatch` (``None`` = all).
:param seed: seed of the model's random generator.
:param chi: if given (and ``kernels`` is not), hidden-layer kernels start with variance
``chi / (L - 1)``, the GPc CIP-0035 default scale (``chi = 1``) that keeps the prior
end-to-end Jacobian well conditioned with identity means.
"""

def __init__(self, nDims, Y, X=None, num_inducing=20, kernels=None, noise_var=0.1,
n_samples=1, residual=True, batch_size=None, seed=0, jitter=1e-6,
q_sqrt_hidden=1e-2, q_sqrt_x=0.5, name='doubly_stochastic_deepgp'):
q_sqrt_hidden=1e-2, q_sqrt_x=0.5, chi=None, name='doubly_stochastic_deepgp'):
super(DoublyStochasticDeepGP, self).__init__(name=name)
dims = list(nDims)[::-1] # input side first
self.Y_all = np.asarray(Y, float)
Expand Down Expand Up @@ -109,6 +112,8 @@ def __init__(self, nDims, Y, X=None, num_inducing=20, kernels=None, noise_var=0.
M = num_inducing if np.isscalar(num_inducing) else num_inducing[i]
M = min(M, self.N)
kern = kernels[i] if kernels is not None else GPy.kern.RBF(Q, ARD=True)
if kernels is None and chi is not None and i < L - 1:
kern.variance = float(chi) / (L - 1)
Z = H[i][self.rng.permutation(self.N)[:M]].copy()
hidden = i < L - 1
s = q_sqrt_hidden if hidden else 1.
Expand Down Expand Up @@ -143,7 +148,7 @@ def set_batch(self, idx=None):

# --- GPy model interface ---------------------------------------------
def parameters_changed(self):
if not hasattr(self, 'eps'):
if not hasattr(self, 'eps') or getattr(self, '_defer_update', False):
return
Y = self.Y_all[self.idx]
layers = [l.as_dict() for l in self.layers]
Expand Down Expand Up @@ -199,6 +204,7 @@ def fit_minibatch(self, steps=200, batch_size=None, lr=0.01, beta1=0.9, beta2=0.
top.q_mu.values, top.q_chol, self._natgrad['g_m'], self._natgrad['g_S'],
natgrad_gamma)
new_flat = choleskies.triang_to_flat(new_chol)
self._defer_update = True # the bound is recomputed at the next resample
m = beta1 * m + (1 - beta1) * obj_grad
v = beta2 * v + (1 - beta2) * obj_grad ** 2
theta = theta - lr * (m / (1 - beta1 ** t)) / (np.sqrt(v / (1 - beta2 ** t)) + 1e-8)
Expand All @@ -207,6 +213,7 @@ def fit_minibatch(self, steps=200, batch_size=None, lr=0.01, beta1=0.9, beta2=0.
top.q_mu[:] = new_mu
top.q_chol_flat[:] = new_flat
theta = self.optimizer_array.copy()
self._defer_update = False
history.append(self._log_marginal_likelihood)
if callback is not None:
callback(t, history[-1])
Expand Down
9 changes: 9 additions & 0 deletions deepgp/testing/test_doubly_stochastic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ def test_checkgrad_residual_hidden(self):
self.assertTrue(m.layers[0].residual)
self.assertTrue(m.checkgrad(tolerance=1e-3))

def test_chi_sets_hidden_kernel_variance(self):
X, Y = _data(12)
m = DoublyStochasticDeepGP([1, 1, 1, 1], Y, X, num_inducing=4, chi=1.0)
v = [float(l.kern.variance.values[0]) for l in m.layers]
self.assertEqual(v, [0.5, 0.5, 1.0])
m1 = DoublyStochasticDeepGP([1, 1], Y, X, num_inducing=4, chi=1.0)
self.assertEqual(float(m1.layers[0].kern.variance.values[0]), 1.0)
self.assertTrue(m.checkgrad(tolerance=1e-3))

def test_checkgrad_minibatch(self):
X, Y = _data(12)
m = DoublyStochasticDeepGP([1, 2, 1], Y, X, num_inducing=4, seed=3)
Expand Down
65 changes: 52 additions & 13 deletions examples/compare_collapsed_vs_doubly_stochastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,58 @@ def loo_1nn_error(X, labels):
return float(np.mean(labels[D.argmin(1)] != labels))


def collapsed(Y, nDims, M, iters, seed):
def collapsed_once(Y, nDims, M, iters, seed, noise_factor):
np.random.seed(seed)
m = deepgp.DeepGP(nDims, Y, num_inducing=M)
for i, layer in enumerate(m.layers):
out_var = layer.Y.var() if i == 0 else layer.Y.mean.var()
layer.Gaussian_noise.variance = out_var * 0.01
layer.Gaussian_noise.variance = out_var * noise_factor
# Restart L-BFGS until it stops improving the bound (or the iteration budget is spent), so the
# baseline is converged rather than cut off by a single call.
best, used = -np.inf, 0
while used < iters:
m.optimize(max_iters=min(1000, iters - used), messages=False)
used += 1000
if m.log_likelihood() < best + 1e-3 * abs(best):
break
best = m.log_likelihood()
m.iters_used = min(used, iters)
return m


INITS = [(0, 0.01), (1000, 0.01), (0, 0.1), (1000, 0.1)] # (seed offset, noise / output variance)


def collapsed(Y, nDims, M, iters, seed, inits=INITS):
"""Best of several initialisations, chosen by the variational bound (never by the metric).

``m.all_bounds`` lists the bound of every initialisation.
"""
t0 = time.time()
m.optimize(max_iters=iters, messages=False)
models = [collapsed_once(Y, nDims, M, iters, seed + off, nf) for off, nf in inits]
bounds = [m.log_likelihood() for m in models]
m = models[int(np.argmax(bounds))]
m.all_bounds, m.all_models = bounds, models
return m, time.time() - t0


def doubly_stochastic(Y, nDims, M, iters, seed, natgrad_gamma=0.):
def doubly_stochastic(Y, nDims, M, iters, seed, natgrad_gamma=0., chi=None):
m = deepgp.DeepGP(nDims, Y, num_inducing=M, inference_method='doubly_stochastic',
seed=seed, noise_var=0.05, n_samples=1)
seed=seed, noise_var=0.05, n_samples=1, chi=chi)
t0 = time.time()
m.fit_minibatch(steps=iters, batch_size=min(len(Y), 128), lr=0.01, seed=seed,
natgrad_gamma=natgrad_gamma)
m.set_batch(None)
return m, time.time() - t0


VARIANTS = [(0., None), (0.1, None)] # chi is a no-op for two-layer stacks


def label(gamma, chi):
return 'doubly stochastic' + (' + natgrad' if gamma else '') + (' + chi=%g' % chi if chi else '')


def top_latent(m):
return m.X_mean.values if hasattr(m, 'X_mean') else np.asarray(m.layers[-1].X.mean)

Expand All @@ -66,12 +97,16 @@ def oil(seed=0, iters=(5000, 3000)):
nDims, M = [Y.shape[1], 5, 2], 30
rows = []
mc, tc = collapsed(Y, nDims, M, iters[0], seed)
rows.append(('collapsed', loo_1nn_error(top_latent(mc), labels),
rows.append(('collapsed (%d iters)' % mc.iters_used, loo_1nn_error(top_latent(mc), labels),
float(np.sqrt(np.mean((mc.predict(top_latent(mc))[0] - Y) ** 2))), tc))
for gamma in (0., 0.1):
md, td = doubly_stochastic(Y, nDims, M, iters[1], seed, natgrad_gamma=gamma)
for k, mk in enumerate(mc.all_models):
print(' collapsed init %s: bound %.1f, 1-NN %.2f, RMSE %.3f' % (
INITS[k], mc.all_bounds[k], loo_1nn_error(top_latent(mk), labels),
float(np.sqrt(np.mean((mk.predict(top_latent(mk))[0] - Y) ** 2)))), flush=True)
for gamma, chi in VARIANTS:
md, td = doubly_stochastic(Y, nDims, M, iters[1], seed, natgrad_gamma=gamma, chi=chi)
mean, _ = md.predict(top_latent(md), n_samples=20, seed=0)
rows.append(('doubly stochastic' + (' + natgrad' if gamma else ''),
rows.append((label(gamma, chi),
loo_1nn_error(top_latent(md), labels),
float(np.sqrt(np.mean((mean - Y) ** 2))), td))
return rows
Expand All @@ -93,11 +128,15 @@ def held_out(model, X, predict):

mc, tc = collapsed(train, nDims, M, iters[0], seed)
Xc = top_latent(mc)
rows.append(('collapsed', held_out(mc, Xc, lambda X: mc.predict(X)[0]), tc))
for gamma in (0., 0.1):
md, td = doubly_stochastic(train, nDims, M, iters[1], seed, natgrad_gamma=gamma)
rows.append(('collapsed (%d iters)' % mc.iters_used, held_out(mc, Xc, lambda X: mc.predict(X)[0]), tc))
for k, mk in enumerate(mc.all_models):
print(' collapsed init %s: bound %.1f, held-out RMSE %.3f' % (
INITS[k], mc.all_bounds[k], held_out(mk, top_latent(mk), lambda X: mk.predict(X)[0])),
flush=True)
for gamma, chi in VARIANTS:
md, td = doubly_stochastic(train, nDims, M, iters[1], seed, natgrad_gamma=gamma, chi=chi)
Xd = top_latent(md)
rows.append(('doubly stochastic' + (' + natgrad' if gamma else ''),
rows.append((label(gamma, chi),
held_out(md, Xd, lambda X: md.predict(X, n_samples=20, seed=0)[0]), td))
rows.append(('mean of train frames', float(np.sqrt(np.mean(test ** 2))), 0.))
return rows
Expand Down
13 changes: 7 additions & 6 deletions examples/composite_v8.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
GPc's V8 gate is a three-layer inducing-point model with test RMSE <= 0.26 and
NLL <= 0 that beats the one-layer model; the prototype reached 0.229 / -0.25.

python examples/composite_v8.py [iters] [seeds]
python examples/composite_v8.py [iters] [seeds] [chi]
"""
import sys
import time
Expand Down Expand Up @@ -37,22 +37,23 @@ def evaluate(model, Xt, yt, n_samples=50):
return rmse, nll


def run(L, M=64, hidden=5, iters=3000, seed=0, natgrad_gamma=0., batch=256):
def run(L, M=64, hidden=5, iters=3000, seed=0, natgrad_gamma=0., batch=256, chi=None):
X, y, Xt, yt = task()
nDims = [1] + [hidden] * (L - 1) + [10]
m = deepgp.DeepGP(nDims, y, X, num_inducing=M, inference_method='doubly_stochastic',
seed=seed, noise_var=0.1)
seed=seed, noise_var=0.1, chi=chi)
t0 = time.time()
m.fit_minibatch(steps=iters, batch_size=batch, lr=0.01, seed=seed, natgrad_gamma=natgrad_gamma)
sec = time.time() - t0
m.set_batch(None)
rmse, nll = evaluate(m, Xt, yt)
return dict(L=L, M=M, rmse=rmse, nll=nll, elbo_per_n=m.log_likelihood() / len(X), sec=sec)
return dict(L=L, M=M, chi=chi, rmse=rmse, nll=nll, elbo_per_n=m.log_likelihood() / len(X), sec=sec)


if __name__ == '__main__':
iters = int(sys.argv[1]) if len(sys.argv) > 1 else 3000
seeds = int(sys.argv[2]) if len(sys.argv) > 2 else 1
for L in (1, 2, 3):
chi = float(sys.argv[3]) if len(sys.argv) > 3 else None
for L in (2, 3) if chi is not None else (1, 2, 3):
for s in range(seeds):
print(run(L, iters=iters, seed=s), flush=True)
print(run(L, iters=iters, seed=s, chi=chi), flush=True)
Loading