diff --git a/.coveragerc b/.coveragerc index afaa1a8..ab121f0 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,16 +1,14 @@ # Coverage config for PyDeepGP # # Measured surface is the maintained serial DeepGP path, including MRD -# (CIP-0002). Remaining omits are MPI / prediction-only SVI helpers (CIP-0001). +# (CIP-0002). Remaining omits are prediction-only SVI helpers (CIP-0001). [run] branch = True source = deepgp omit = */deepgp/testing/* - */deepgp/inference/vardtc_parallel.py */deepgp/inference/inferenceX.py */deepgp/inference/svi_ratio.py - */deepgp/util/parallel.py [report] exclude_lines = diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2efc1b0..d4f2cc3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -58,30 +58,3 @@ jobs: name: ubuntu-3.12 fail_ci_if_error: false token: ${{ secrets.CODECOV_TOKEN }} - - # CIP-0001 R11: optional MPI parity while mpi4py support still exists. - mpi: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - - name: Install MPI and Python deps - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends libopenmpi-dev openmpi-bin - python -m pip install --upgrade pip setuptools wheel - python -m pip install "numpy>=1.7" "scipy>=0.12" matplotlib h5py tables mpi4py - python -m pip install "git+https://github.com/SheffieldML/GPy.git@main" - python -m pip install -e . --no-deps - - - name: MPI parity (2 ranks vs serial) - env: - OMPI_MCA_btl_vader_single_copy_mechanism: none - OMPI_MCA_rmaps_base_oversubscribe: 'true' - run: mpiexec -n 2 python -m deepgp.testing.mpi_parity diff --git a/MANIFEST.in b/MANIFEST.in index 0aac02d..351bb52 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ include AUTHORS.txt include LICENSE include README.md -recursive-include deepgp/testing *.txt *.h5 +recursive-include deepgp/testing *.txt *.h5 *.json diff --git a/README.md b/README.md index 7da25d1..bbf4ce4 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,8 @@ tox ``` Coverage is gated on the maintained serial DeepGP path, including the NumPy -encoder and MRD (see `.coveragerc`). MPI parallel inference and prediction-only -SVI helpers remain omitted until those paths are removed or revived -(CIP-0001 Phases 2–4). +encoder and MRD (see `.coveragerc`). Prediction-only SVI helpers remain +omitted until those paths are removed or revived (CIP-0001 Phases 2–4). Pre-commit (notebooks) ---------------------- @@ -83,15 +82,32 @@ hidden widths (e.g. ``[[[4], [4]], [3]]``); higher indices feed the usual ``EncoderLayer`` stack for layers above the MRD leaf. See ``examples/example_mrd.py``. -MPI (deprecated) ----------------- - -Passing ``mpi_comm`` to ``DeepGP`` emits a ``FutureWarning`` (CIP-0001). Use -serial models for now; chunked psi-statistics (Phase 3) will replace the -single-machine role of MPI. ``mpi_comm`` with ``back_constraint=False`` raises -``ValueError`` (that configuration produced silently wrong results). - -An optional GitHub Actions job runs a 2-rank parity check while MPI remains. +MPI (removed) +------------- + +MPI parallel inference has been removed (CIP-0001, CIP-0003). Passing a +non-``None`` ``mpi_comm`` to ``DeepGP``, a layer or an inference method raises +``TypeError``; ``mpi_comm=None`` is still accepted. Use chunked psi-statistics +(``psi_chunk_size``, ``psi_threads``) for single-machine scaling. The old +``SparseGP_MPI`` class name is now an alias of ``SparseGPLayer`` and emits a +``FutureWarning``. + +Doubly stochastic inference (new) +--------------------------------- + +``DeepGP(nDims, Y, X, inference_method='doubly_stochastic', ...)`` returns a +``DoublyStochasticDeepGP`` (Salimbeni and Deisenroth, 2017): a whitened ``q(u)`` +per layer, reparameterised samples through hidden layers, and a minibatch +trainer. The likelihood is Gaussian, and the default collapsed ``DeepGP`` is +unchanged. Pass ``X=None`` for the unsupervised model, with a Gaussian ``q(X)`` +(``m.X_mean``, ``m.X_var``) initialised by PCA of ``Y``. Training can give the top +layer natural-gradient steps (``fit_minibatch(..., natgrad_gamma=0.1)``):: + + m = deepgp.DeepGP([1, 2, 1], Y, X, num_inducing=20, + inference_method='doubly_stochastic', seed=0) + m.optimize(max_iters=200) # fixed samples: deterministic + m.fit_minibatch(steps=500, batch_size=50) # fresh batch and samples each step + mean, var = m.predict(Xnew) Psi chunking (optional) ----------------------- diff --git a/backlog/bugs/2026-11-27_mrd-back-constraint-gradients.md b/backlog/bugs/2026-11-27_mrd-back-constraint-gradients.md new file mode 100644 index 0000000..788d777 --- /dev/null +++ b/backlog/bugs/2026-11-27_mrd-back-constraint-gradients.md @@ -0,0 +1,55 @@ +--- +id: "2026-11-27_mrd-back-constraint-gradients" +title: "Back-constrained MRD layer fails checkgrad (encoder and X_var gradients)" +status: "Completed" +priority: "High" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "bugs" +related_cips: ["0003", "0002"] +owner: "Neil Lawrence" +dependencies: [] +tags: +- backlog +- bug +- mrd +--- + +# Bug: Back-constrained MRD layer fails checkgrad + +## Description + +Found while adding MRD `checkgrad` tests for CIP-0003 Phase 2. For `DeepGP([[3, 3], 2], [Y1, Y2], kernels=[[k1, k2]], num_inducing=4, back_constraint=True)`, `checkgrad` fails. It fails identically at commit 65dba79, before the q(X) extraction, so the extraction did not cause it. Non-back-constrained MRD (single layer and with a hidden layer) passes. + +Observed with `m.checkgrad(verbose=True)`: + +- Kernel, inducing-input and noise gradients are correct. +- Encoder (`view_i.mlp.*`) gradients: numerical is exactly 0.2 times analytical, for every weight (so the analytical gradient is 5x too large; 5 does not equal the number of views). +- `view_i.X_var` (shared variance): analytical is about 1e-6, numerical is large (about -272); the gradient is lost. +- `latent_space.mean/variance` are derived from the encoders in this mode and are overwritten on every update; their analytical gradients are non-zero but should be excluded (fixed) or ignored. + +## Acceptance Criteria + +- [ ] `MRDCheckgradTest.test_mrd_back_constrained_checkgrad` passes without `expectedFailure` +- [ ] Root cause recorded (candidates: `MRDView.scale` handling in `update_gradients`, `update_encoder_gradients` ordering against `X_var_common`, and `latent_space` being a free parameter) + +## Related + +- CIP: 0003 (Phase 3: MRD), 0002 +- Test: `deepgp/testing/test_functional.py` + +## Progress Updates + +### 2026-11-27 + +Found; test marked `expectedFailure` so CI records it without blocking the maintained path. + +## Progress Updates + +### 2026-11-27 +Fixed. Two independent causes: + +1. `MLP.update_gradient` accumulated into the layer gradient buffers, which were only reset by `predict`. Each repeated `parameters_changed` between two `predict` calls added another copy of the encoder gradient, so the analytic gradient was an integer multiple of the true one (5x in the repro). `update_gradient` now resets the buffers first and is idempotent. +2. In back-constrained mode the aggregate q(X) (`latent_space`) is derived from the view encoders on every update but was a free parameter, so `checkgrad` (and any optimiser) saw nonzero analytic gradients against zero numerical ones. It is now fixed. + +The `X_var` gradients were correct throughout. `test_mrd_back_constrained_checkgrad` is no longer an expected failure; full suite 75 passed. diff --git a/backlog/features/2026-11-27_ard-scales-and-init.md b/backlog/features/2026-11-27_ard-scales-and-init.md new file mode 100644 index 0000000..5b7490a --- /dev/null +++ b/backlog/features/2026-11-27_ard-scales-and-init.md @@ -0,0 +1,47 @@ +--- +id: "2026-11-27_ard-scales-and-init" +title: "ARD scale inspection, pruning, and initialisation options" +status: "Completed" +priority: "Medium" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "features" +related_cips: ["0003", "0002"] +owner: "Neil Lawrence" +dependencies: [] +tags: +- backlog +- matlab-parity +--- + +# Task: ARD scale inspection, pruning, and initialisation options + +## Description + +Phase 3 of CIP-0003. Recover the workflow of Matlab `hsvargplvmShowScales`, `PruneModel` / `RestorePrunedModel` and `InitXOptions` as small tested features: per-layer ARD relevance report, pruning of near-zero dimensions with restore, and named initialisers for `X` (PCA, per-view concatenation, random). We reproduce the capability, not the Matlab interface. + +## Acceptance Criteria + +- [x] Per-layer ARD scale report and plot helper +- [x] Prune and restore round-trip leaves the objective unchanged to tolerance +- [x] Initialiser selectable by name; default unchanged +- [x] Tests run in CI; the toy example from Damianou 2013 shows the relevant scales + +## Related + +- CIP: 0003 (Phase 3), 0002 + +## Progress Updates + +### 2026-11-27 + +Task created from CIP-0003 (Accepted). + +### 2026-11-27 + +Implemented in `deepgp/diagnostics.py` (`ard_scales`, `show_scales`, `prune_model`, `restore_model`) and `validate_init` / `INITIALISERS` in `deepgp/util/util.py`, with tests in `deepgp/testing/test_diagnostics.py` (85 passed overall). + +Scope decisions: +- Pruning masks dimensions (kernel parameter set to its off value and fixed) rather than removing columns, so there is no speed-up. Restore is exact. Structural removal is not implemented. +- Unknown initialiser names used to fall through silently to random; they now raise `ValueError`. `random` is a new synonym for `rand`. The default (`PCA`) is unchanged. +- The toy example is a one-layer model on a 1-D curve, not the Damianou 2013 data; it shows one of three offered dimensions switched off (scales 1.00, 0.48, 0.01). Reproducing the paper's own figure belongs to Phase 5. diff --git a/backlog/features/2026-11-27_pure-layer-functions.md b/backlog/features/2026-11-27_pure-layer-functions.md new file mode 100644 index 0000000..532e535 --- /dev/null +++ b/backlog/features/2026-11-27_pure-layer-functions.md @@ -0,0 +1,52 @@ +--- +id: "2026-11-27_pure-layer-functions" +title: "Extract pure layer functions and define the layer interface" +status: "In Progress" +priority: "Medium" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "features" +related_cips: ["0003"] +owner: "Neil Lawrence" +dependencies: ["2026-11-27_remove-mpi"] +tags: +- backlog +- refactor +--- + +# Task: Extract pure layer functions and define the layer interface + +## Description + +Phase 2 of CIP-0003. Move the layer bound, psi-statistic propagation and gradients into array-in / array-out functions (public but provisional; name `deepgp/functional/` provisional), following GPy CIP-000F Stage 2. `Layer` classes become a thin shell holding parameters. Define the per-layer interface that both inference families will implement: forward marginals at supplied inputs, accept upstream gradients, expose parameters. + +## Acceptance Criteria + +- [x] Functions take and return arrays only: no `Param`, observers or communicators +- [x] Layer classes call the functions; public class names and constructors unchanged +- [x] Objective and gradient identical to current values on the reference models (tolerance recorded) +- [x] `checkgrad` passes for every layer type +- [x] Interface documented in the module docstrings + +## Related + +- CIP: 0003 (Phase 2) +- GPy CIP-000F + +## Progress Updates + +### 2026-11-27 + +Task created from CIP-0003 (Accepted). Blocked on MPI removal. + +### 2026-11-27 (first slice) + +Added `deepgp/functional/`: `collapsed_bound` (statistics in, bound, posterior arrays and gradients w.r.t. statistics and outputs out; certain or uncertain outputs) and `route_gradients` (gradients w.r.t. statistics to kernel and inducing-input gradients). `VarDTC._inference_uncertain_outputs` and `SparseGPLayer._inference_vardtc` now call them; dead `psicov` branches removed. Reference tests unchanged (63 pass before, 70 now), so objective and gradients are identical to within the stored-value tolerances. `checkgrad` passes for unsupervised, supervised and back-constrained stacks; finite-difference tests cover the bound. + +Honest limits: `route_gradients` still takes a GPy kernel object (GPy kernels are not pure until GPy CIP-000F Stage 2) and the shell assigns the returned arrays. The q(X) gradient routing in `Layer.update_qX_gradients`, MRD layers and the encoder layers are not yet extracted; the SVI path keeps its in-class code. Left open, so the task stays In Progress. + +### 2026-11-27 (second slice) + +Added `deepgp/functional/qx.py`: `qx_gradients` (used by `Layer` and `MRDView`), `aggregate_qx` and `disaggregate_qx_gradients` (MRD product-of-experts q(X) and its gradient back-propagation, previously inline in `MRDLayer`). Tested against finite differences. MRD `checkgrad` added: single MRD layer and MRD with a hidden layer pass. Back-constrained MRD fails `checkgrad`; this predates the extraction (see `backlog/bugs/2026-11-27_mrd-back-constraint-gradients.md`) and is recorded as an expected failure. + +Remaining: encoder layers (`EncoderLayer`) and the SVI path still hold their own gradient code; both move behind the same functions when those families are touched (encoders in Phase 3 with the MRD bug, SVI in Phase 4). The collapsed-family extraction that this task targets is done. diff --git a/backlog/features/2026-11-27_remove-mpi.md b/backlog/features/2026-11-27_remove-mpi.md new file mode 100644 index 0000000..27264b8 --- /dev/null +++ b/backlog/features/2026-11-27_remove-mpi.md @@ -0,0 +1,47 @@ +--- +id: "2026-11-27_remove-mpi" +title: "Remove MPI and SparseGP_MPI (CIP-0001 Phase 4, CIP-0002 Phase D)" +status: "In Progress" +priority: "High" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "features" +related_cips: ["0003", "0001", "0002"] +owner: "Neil Lawrence" +dependencies: [] +tags: +- backlog +- refactor +- mpi +--- + +# Task: Remove MPI and SparseGP_MPI + +## Description + +Phase 2, step 1 of CIP-0003. Execute CIP-0001 R17–R24 and CIP-0002 Phase D: delete `inference/vardtc_parallel.py` and `util/parallel.py`; rename `SparseGP_MPI` to `SparseGPLayer` (keep a deprecated alias); strip root-only branches and reductions from layers, `enclayer.py`, `mrd.py`, `model.py` and the inference modules. Keep accepting `mpi_comm=None` and `mpi_root=0`; raise `TypeError` if `mpi_comm` is not `None`. Single-machine scale comes from `psi_chunk_size` / `psi_threads`. + +## Acceptance Criteria + +- [x] No `mpi4py` import or `mpi_comm` branch remains in `deepgp/` +- [x] `DeepGP(..., mpi_comm=comm)` with non-`None` raises `TypeError` naming the chunked-psi alternative +- [x] `SparseGP_MPI` still importable, with a `FutureWarning`, pointing at `SparseGPLayer` +- [x] Reference-value tests (`dgp_*.h5`, `dgp_bc_*.h5`) unchanged and passing +- [x] MPI parity and policy tests replaced by a test of the new error +- [x] `.coveragerc` and README no longer mention MPI as supported + +## Implementation Notes + +Removal follows CIP-0001's deprecation text (the `FutureWarning` has been on `main` since the Phase 2 merge). No multi-machine users were identified in the Discussion; if one appears, CIP-0001 allows reducing MPI to a reducer hook instead. + +## Related + +- CIP: 0003 (Phase 2), 0001, 0002 + +## Progress Updates + +### 2026-11-27 + +Task created and started on branch `cip0003-remove-mpi`. + +Implementation complete on `cip0003-remove-mpi`: 56 tests pass (53 before, plus the new removal tests); reference tests unchanged. Awaiting review before status moves to Completed. diff --git a/backlog/features/2026-11-27_share-vardtc-with-gpy.md b/backlog/features/2026-11-27_share-vardtc-with-gpy.md new file mode 100644 index 0000000..6f202fd --- /dev/null +++ b/backlog/features/2026-11-27_share-vardtc-with-gpy.md @@ -0,0 +1,54 @@ +--- +id: "2026-11-27_share-vardtc-with-gpy" +title: "Replace local VarDTC with GPy's, including CIP-0013 sparse linalg modes" +status: "In Progress" +priority: "Medium" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "features" +related_cips: ["0003"] +owner: "Neil Lawrence" +dependencies: ["2026-11-27_remove-mpi"] +tags: +- backlog +- refactor +--- + +# Task: Replace local VarDTC with GPy's + +## Description + +Phase 2 of CIP-0003. After MPI is removed, `deepgp/inference/vardtc.py` differs from GPy's `VarDTC` mainly by the uncertain-input handling and chunking. Work out the real delta, upstream what belongs in GPy (or subclass thinly), and delete the rest. Pick up GPy CIP-0013's `stable` / `lq` linear algebra modes where the layer bound uses them. + +## Acceptance Criteria + +- [x] A written comparison of `deepgp.inference.vardtc.VarDTC` against `GPy...VarDTC` (what differs, and why) +- [x] Local code reduced to the documented delta +- [x] Reference-value tests unchanged +- [x] Choice of linalg mode exposed per layer, defaulting to current behaviour (`sparse_linalg=` on `SparseGPLayer`; settable later via `layer.inference_method.sparse_linalg`) + +## Related + +- CIP: 0003 (Phase 2) +- GPy CIP-0013 + +## Progress Updates + +### 2026-11-27 + +Task created from CIP-0003 (Accepted). Blocked on MPI removal. + +### 2026-11-27 (comparison and result) + +Compared on identical inputs (certain and uncertain X, Gaussian noise 0.1): log marginal, all gradients and the woodbury posterior agree with GPy's `VarDTC` to about 1e-11 once `const_jitter` is matched. The algebra was never the difference. The real delta: + +| Feature | GPy `VarDTC` | PyDeepGP (before) | Now | +|---|---|---|---| +| Uncertain outputs (`Y` is q(X) of layer below) | not supported | supported | local code, `_inference_uncertain_outputs` (the only retained algebra) | +| Chunked psi-statistics | no (psi arguments can be passed in) | yes | `psi_statistics`, passed to GPy via `psi0/psi1/psi2` | +| `Kuu_sigma` (hidden layers) | no (`Lm` can be passed in) | yes | factor built locally, passed as `Lm` | +| Jitter / noise floor | 1e-8 | 1e-6 | `const_jitter = 1e-6`, floor 1e-6 (reference tests depend on it) | +| Heteroscedastic noise, mean function, caching, `to_dict`, `sparse_linalg` | yes | no | inherited | +| `inferentia` option | n/a | imported a non-existent class | raises `NotImplementedError` | + +`vardtc.py` still carries the uncertain-outputs derivation. Moving it into GPy as an `uncertain_outputs` capability is the upstreaming candidate; it is left for a GPy CIP rather than done here. The linalg mode is exposed on `SparseGPLayer`; `DeepGP`-level pass-through is not yet wired. Tests: `deepgp/testing/test_vardtc_gpy.py` (63 pass overall, reference tests unchanged). diff --git a/backlog/features/2026-11-27_uncollapsed-whitened-core.md b/backlog/features/2026-11-27_uncollapsed-whitened-core.md new file mode 100644 index 0000000..5296afb --- /dev/null +++ b/backlog/features/2026-11-27_uncollapsed-whitened-core.md @@ -0,0 +1,117 @@ +--- +id: "2026-11-27_uncollapsed-whitened-core" +title: "Uncollapsed family: whitened marginals core and layer stack" +status: "In Progress" +priority: "High" +created: "2026-11-27" +last_updated: "2026-11-27" +category: "features" +related_cips: ["0003"] +owner: "Neil Lawrence" +dependencies: ["2026-11-27_pure-layer-functions"] +tags: +- backlog +- uncollapsed +--- + +# Task: Uncollapsed family: whitened marginals core and layer stack + +## Description + +Phase 4 of CIP-0003. GPy's SVGP cannot serve as a hidden layer (CIP-0003, Resolved Question 1), so PyDeepGP gets a small core of its own, as pure functions in `deepgp/functional/uncollapsed.py`: + +1. Whitened marginals `(mu, var)` at supplied inputs, with a backward pass that takes upstream gradients and returns gradients for `q(u)`, kernel, `Z` and the inputs. +2. Whitened KL and its gradients. +3. Reparameterised sampling with a caller-supplied `eps` (so gradients are testable and results reproducible). +4. A layer stack (doubly stochastic bound) built on 1 to 3, then a `DeepGP`-shaped shell, minibatching and natural gradients. + +## Acceptance Criteria + +- [x] Marginals agree with a dense unwhitened computation +- [x] Backward pass passes finite-difference checks for every output +- [x] Gradients flow through a two-layer stack with frozen `eps` +- [x] Doubly stochastic bound, with a likelihood at the top, passes finite-difference gradient checks (the `checkgrad`-style test on the `DeepGP` shell comes with the shell) +- [x] `DeepGP`-level shell with inference selectable by name; default unchanged +- [x] Minibatching with a seeded generator +- [x] Reproduce GPc CIP-0035 reference numbers on a shared small problem (Phase 5 overlap) + +## Related + +- CIP: 0003 (Phase 4) +- Salimbeni & Deisenroth (2017) + +## Progress Updates + +### 2026-11-27 + +Task created and started. Slice 1: items 1 to 3 of the description. + +Slice 1 done (`deepgp/functional/uncollapsed.py`, `deepgp/testing/test_uncollapsed.py`, 91 passed overall): +- `whitened_marginals` / `whitened_marginals_backward`, `whitened_kl`, `reparam_sample` / `reparam_sample_backward`, all array-in/array-out apart from the GPy kernel object. +- Marginals agree with a dense unwhitened computation; the backward pass matches finite differences for `q(u)`, kernel, `Z` and inputs (including a Cholesky backward pass for `Kmm`); gradients flow through a two-layer stack with frozen `eps`. +- Testing note: GPy kernels cache on array identity and parameter writes need the `Parameterized` API, so finite-difference checks pass copies and set kernel values with `kern[:] = ...`. + +Next slice: the doubly stochastic bound over a stack (likelihood at the top, KL per layer), with a `checkgrad`-style test. + +### 2026-11-27 (slice 2) + +`deepgp/functional/doubly_stochastic.py` (`doubly_stochastic_bound`), tests in `deepgp/testing/test_doubly_stochastic.py` (95 passed overall): +- Gaussian likelihood at the top, per-layer whitened KL, reparameterised samples through hidden layers with caller-supplied `eps`, `scale` for minibatches, optional residual (identity) mean on hidden layers. +- With one layer the bound equals GPy `SVGP`'s `log_likelihood` (to 1e-4 relative; the difference is jitter handling) once `q(u)` is mapped between whitened and unwhitened forms. +- Finite-difference checks pass for `q(u)`, kernels, `Z`, inputs and the noise variance on a three-layer stack, with and without residual means, two samples. + +Remaining: `DeepGP`-shaped shell with inference selectable by name, seeded minibatching, natural gradients, GPc cross-check. Non-Gaussian likelihoods at the top are not covered yet. + +### 2026-11-27 (slice 3) + +`deepgp/models/uncollapsed.py` (`DoublyStochasticDeepGP`, `WhitenedLayer`), tests in `deepgp/testing/test_doubly_stochastic_model.py` (104 passed overall): +- GPy `Model` holding kernels, `Z`, whitened `q(u)` (packed Cholesky as in GPy's SVGP) and the noise as parameters; `checkgrad` passes for stacks with and without residual means, with samples and on a minibatch. +- Randomness is explicit: frozen `eps` make the objective deterministic, so `optimize` and `checkgrad` work; `resample(seed)` and `set_batch` redraw. `fit_minibatch` runs Adam in GPy's unconstrained space with a seeded generator (identical trajectories for equal seeds; tested). `predict` is a Monte Carlo mixture over hidden layers. +- `DeepGP(..., inference_method='doubly_stochastic')` returns this model via `__new__`; the default path is unchanged (tested). It is a different model class, not a `DeepGP` instance. +- At initialisation `q(u)` equals the prior, so the top layer ignores its input and the bound does not depend on `eps` until `q(u)` moves; a test documents this. + +Limitations: supervised only (no `q(X)`), Gaussian likelihood only, no natural gradients, Adam is hand-rolled and untuned, no comparison on a real dataset yet. +Remaining: natural gradients, unsupervised (latent `X`), GPc CIP-0035 cross-check. + +### 2026-11-27 (slice 4: GPc cross-check) + +`deepgp/testing/gpc_reference_generate.py` builds GPc `DeepGP` models (1, 2, 3 layers; N=20, M=4, hidden width 2), overwrites the packed stochastic parameter vector with random values (layout read from `CSvgp::getStochasticParams`: log kernel parameters, `Z`, log beta, then per output the means and the lower Cholesky with log diagonal), reloads, and records GPc's ELBO and `layer_kl`. The golden file `gpc_reference.json` is committed; `test_gpc_reference.py` evaluates the same parameters in PyDeepGP, so CI does not need GPc. +- One layer: ELBO agrees to 1e-4, KL to 1e-6, predictive mean and variance to 1e-5 (GPc RBF is `variance * exp(-0.5 * inverseWidth * r^2)`, so `lengthscale = inverseWidth^-0.5`; GPc beta is a precision). +- Two and three layers (Monte Carlo, GPc's `elbo()` averaged over 4000 calls): agreement within four combined standard errors; per-layer KL agree. +Not done: the V8 composite-task reproduction (RMSE <= 0.26, NLL <= 0) needs training and the GPc task generator; it remains open for Phase 5. + +### 2026-11-27 (slice 5: natural gradients) + +`whitened_expectation_grads` and `whitened_natgrad_step` in `deepgp/functional/uncollapsed.py`; the bound now also returns `natgrad` (`g_m`, `g_S` for the top layer, data term only). `DoublyStochasticDeepGP.fit_minibatch(..., natgrad_gamma=g)` updates the top layer's `q(u)` by `theta <- (1-g) theta + g (theta_prior + grad_eta ELL)` and leaves everything else on Adam (the hybrid scheme of Salimbeni, Eleftheriadis and Hensman 2018, as in GPc's `natgrad_gamma`). Tests (`test_natgrad.py`): with `gamma = 1` on the full data and one layer the step reaches the analytic optimum `S = (I + B B^T / noise)^-1`, `m = S B y / noise` and the `q(u)` gradients vanish; small steps increase the bound; `g_S` is consistent with the Cholesky gradient; hybrid training is deterministic for equal seeds. +Hidden layers stay on Adam. Not compared with GPc's trained trajectories. + +### 2026-11-27 (slice 6: unsupervised) + +`doubly_stochastic_bound(..., x_var, eps_x)` treats `X` as the mean of `q(X) = N(X, diag(x_var))`: each sample draws `X + sqrt(x_var) eps_x`, and `scale * KL(q(X) || N(0, I))` is subtracted (scaled by N/B with the data term, so minibatches stay unbiased). `DoublyStochasticDeepGP(nDims, Y, None, ...)` holds `X_mean` and `X_var` (log-exp constrained) as parameters, initialised by standardised PCA of `Y`, with frozen `eps_x` alongside `eps`. Tests: finite-difference gradients for `X` and `x_var` through a residual two-layer stack, tiny-variance limit equals the deterministic bound minus the latent KL, `checkgrad` on the full model and on a minibatch, and a short training run that improves the bound and predicts. +Limitations: Gaussian likelihood only; no back-constraint (amortised `q(X)`) and no MRD views for this model; natural gradients still only for the top layer; no real dataset (oil, CMU walk) comparison against the collapsed model yet. + +### 2026-11-27 (slice 7: V8 and oil / CMU comparisons) + +Scripts (not run in CI): `examples/composite_v8.py`, `examples/compare_collapsed_vs_doubly_stochastic.py`. `DoublyStochasticDeepGP` now defaults `X=None`, so `DeepGP(nDims, Y, inference_method='doubly_stochastic')` selects the unsupervised model. + +**V8** (GPc composite task, RBF, M=64, hidden width 5, residual means, 3000 Adam steps, batch 256, lr 0.01, one seed, predictive NLL from the moment-matched Gaussian of 50 samples): + +| L | test RMSE | test NLL | ELBO/N | +|---|-----------|----------|--------| +| 1 | 0.772 | 1.151 | -1.228 | +| 2 | 0.204 | -0.193 | -0.156 | +| 3 | 0.207 | -0.188 | -0.229 | + +The gate (L=3: RMSE <= 0.26, NLL <= 0, beats one layer) is met. GPc's RBF numbers (3 seeds, same settings) are L=3 0.193 / -0.344 and L=2 0.249 / -0.171, so ours is within the RMSE range but the NLL is less sharp at L=3, and our L=2 is better than L=3 on this seed. One seed only; the ELBO at L=3 had not converged (it is below L=2). Initialisation (hidden-layer kernel variance, noise) is untuned and differs from GPc's `chi = 1/L` scheme. + +**Oil** (100 points, 12-D standardised, `[12, 5, 2]`, M=30; collapsed VarDTC 5000 iterations, doubly stochastic 3000 full-batch Adam steps): 1-NN leave-one-out class error in the 2-D latent / reconstruction RMSE: + +| model | seed 0 | seed 1 | +|-------|--------|--------| +| collapsed | 0.03 / 0.65 (500 iters) | 0.35 / 0.80 | +| doubly stochastic | 0.03 / 0.197 | 0.03 / 0.184 | +| + natgrad 0.1 | 0.03 / 0.178 | 0.03 / 0.172 | + +**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. diff --git a/cip/cip0003.md b/cip/cip0003.md new file mode 100644 index 0000000..39d8a73 --- /dev/null +++ b/cip/cip0003.md @@ -0,0 +1,274 @@ +--- +author: Neil Lawrence +created: "2026-11-27" +id: "0003" +last_updated: "2026-11-27" +status: In Progress +compressed: false +related_requirements: [] +related_cips: +- "0001" +- "0002" +related_gpy_cips: +- "000F" +- "0010" +- "0013" +- "000B" +related_gpc_cips: +- "0016" +- "0018" +- "0035" +- "003D" +tags: +- cip +- umbrella +- refactor +- deepgp +- uncollapsed +- interchange +title: Renovate and refactor PyDeepGP around pure layer functions and two inference families +--- + +# CIP-0003: Renovate and refactor PyDeepGP + +## Status + +- [x] Proposed - Initial idea documented (open for review) +- [x] Accepted - Approved 2026-11-27, with decisions below +- [x] In Progress - Phase 2 started 2026-11-27 +- [ ] Implemented - Work complete, awaiting verification +- [ ] Closed - Verified and complete +- [ ] Rejected - Will not be implemented +- [ ] Deferred - Postponed + +## Summary + +This is an umbrella CIP. It sets the target shape of PyDeepGP after +renovation and orders the work. CIP-0001 (Theano/MPI removal) and CIP-0002 +(MRD revival) are children of it; further children are created only when +this CIP is Accepted. + +The target, in one paragraph: layer mathematics become pure array-in / +array-out functions; `DeepGP(GPy.Model)` and the layer classes remain as a +thin GPy-native shell over them; two inference families — **collapsed** +(the 2013 psi-statistic bound) and **uncollapsed / doubly stochastic** +(after GPc CIP-0035) — sit behind one layer interface; MPI and Theano +disappear; the useful workflow of the Matlab `deepGP` is recovered as +small tested features; and correctness is checked against recorded golden +values and against GPc through the shared JSON interchange. + +## Motivation + +> **Correction (2026-11-27).** The evidence below was gathered from a local +> `main` that was behind `origin/main`. Upstream already contains CIP-0001 +> Phases 1–3 (NumPy encoder, MPI deprecation, chunked psi; PRs #37–#40) and +> CIP-0002 Phases A–C (MRD revival; PRs #42–#43), plus the Damianou 2013 +> examples (#41, #44). The default model builds, and 53 tests pass on the +> synced `main` (GPy 1.15, NumPy 2.5). The remaining problems described +> below — MPI as the base class of every layer, duplicated VarDTC, no +> pure-function layer core — still stand. Phases 1 and most of Phase 3 are +> therefore done; the plan below is updated accordingly. + +Three bodies of work now pull in different directions, and PyDeepGP is +the one that has not moved. + +**Matlab `deepGP`** (Damianou & Lawrence, AISTATS 2013; `hsvargplvm*`) +defines the capabilities users remember: a collapsed variational bound +with a Bayesian GP-LVM at each layer, MRD multi-view leaves, ARD scale +inspection and pruning, SNR control, priors on parameters and parent +layers, initialisation options, layer sampling and posterior propagation. + +**PyDeepGP today** (~3.2k lines) implements the same bound as GPy +`SparseGP` subclasses. + +- The default model does not build: `back_constraint=True` imports Theano, + which is not a declared dependency (CIP-0001). +- MPI is the base class of every layer (`SparseGP_MPI`) and fails on + NumPy ≥ 1.24. +- MRD is advertised but fails in `initialize_parameter` (CIP-0002). +- VarDTC is duplicated locally (`vardtc.py`, `vardtc_parallel.py`, + roughly 500 lines) rather than shared with GPy. + +**GPc** now has a doubly stochastic deep GP (`CDeepGp`, CIP-0035) with +minibatches, Adam, natural gradients, non-Gaussian final likelihoods and +several inducing families (points, ridge windows, Hermite windows — +CIP-0037, CIP-003D), together with `CBayesGplvm`, `CMrd` and a JSON model +interchange (CIP-0016). + +**GPy** is separating numerical functions from parameter objects +(CIP-000F), adding sparse linalg / LQ modes for VarDTC (CIP-0013), and +building a golden-value corpus and `to_dict` contract (CIP-0010). + +If PyDeepGP stays as is, it falls further behind both neighbours, and it +cannot use the improvements either of them offers. Renovating it is +largely a matter of aligning it with changes that already exist. + +### Tenets applied + +- **GPy-native stack:** layers stay GPy models; we reuse GPy's VarDTC, + SVGP and kernels rather than keeping local copies. +- **Layered composition:** depth is a stack of layers with a shared + interface; inference is per-layer and pluggable. +- **Maintained core first:** the serial sparse-variational path sets the + quality bar; MPI, Theano and prediction-layer clones do not. +- **Honest public surface:** anything advertised must run; otherwise it + fails clearly. +- **Test what you ship:** each phase below closes only when CI exercises + what it adds. + +## Detailed Description + +### Decisions taken (2026-11-27) + +| Question | Decision | +|---|---| +| Numerical backend | Stay on NumPy/SciPy and GPy. Track GPy's JAX evaluation (CIP-0010 Workstream G); do not lead it. | +| Uncollapsed inference | Prototyped and lived in PyDeepGP first, then transferred to GPy once the layer API is proven (see Phase 4). | +| Matlab parity | Reproduce the paper's experiments and the workflow that matters. We do not port the Matlab code or follow its structure. | + +### Target architecture + +1. **Pure layer functions** (`deepgp/functional/`, name provisional). + Bound, psi-statistic propagation and gradients as functions of arrays + and hyperparameters, following the CIP-000F Stage 2 conventions. No + `Param`, no observers, no communicator. +2. **GPy shell.** `DeepGP`, `ObservedLayer`, `HiddenLayer`, + `TopHiddenLayer`, `ObservedMRDLayer` keep their names and constructor + patterns. They hold parameters and call the functions. +3. **Inference families behind one interface.** + - *Collapsed:* the 2013 bound. This is the default and the reference + for Matlab comparison. + - *Uncollapsed:* whitened `q(u)` per layer, reparameterised samples + propagated through layers, minibatches and natural gradients. This + follows GPc CIP-0035 and starts from GPy's SVGP core where it + suffices. + The per-layer interface needs: forward marginals at supplied inputs, + accept upstream gradients, expose parameters. This is the same + boundary GPc CIP-0035 found necessary for hidden layers. +4. **Encoder.** NumPy MLP (CIP-0001). Back-constraints stay optional. +5. **No MPI, no Theano.** Single-machine scale comes from chunked psi + (CIP-0001) and minibatching (uncollapsed family). + +### Matlab capabilities to recover + +| Capability | Matlab | Priority | +|---|---|---| +| MRD multi-view layers | `demHighFive*` | High (CIP-0002) | +| ARD scale inspection and pruning | `ShowScales`, `PruneModel`, `RetainedScales` | High | +| Initialisation options for `X` | `InitXOptions` | High | +| Layer sampling, posterior propagation | `SampleLayer`, `PosteriorMeanVar` | Medium | +| SNR control | `ControlSNR`, `CheckSNR` | Medium | +| Priors on parameters / parent layers | `AddParamPrior`, `AddParentPrior` | Medium | +| Classification demo | `demHsvargplvmClassification` | Medium | +| Dynamics, mocap, skeleton display | `demSkelMult*`, `ShowSkel` | Deferred; visualisation falls to GPy CIP-000B | + +Acceptance demonstrations are the toy, USPS and high-five experiments of +Damianou & Lawrence (2013), already scaffolded under +`examples/damianou2013/`. + +### Verification + +- **Golden corpus.** Extend the stored `.h5` references into a corpus + with recorded tolerances, in the manner of GPy CIP-0010. +- **GPc cross-check.** Small identical models exchanged through the + CIP-0016 JSON interchange; objectives and gradients compared between + PyDeepGP and GPc. This is a stronger test than self-consistency. +- **Gradient checks** for every layer type and both inference families. + +## Implementation Plan + +Phases are ordered; each phase is a separate child CIP or PR set. No +backlog tasks are created until this CIP is Accepted. + +1. **Phase 1 — Make the default model build.** CIP-0001: NumPy encoder, + MPI deprecation, chunked psi, Theano-skipped tests running in CI. +2. **Phase 2 — Extract and unify.** + - Extract pure layer functions. + - Remove `SparseGP_MPI` as a base class. + - Replace the local VarDTC copies with GPy's, including CIP-0013 modes. + - Define the layer interface of the target architecture. +3. **Phase 3 — Recover multi-view and diagnostics.** CIP-0002 (MRD), + then ARD scale inspection and pruning, then initialisation options. +4. **Phase 4 — Uncollapsed family in PyDeepGP.** Implement on the Phase 2 + layer interface using GPy SVGP where possible; reproduce GPc + CIP-0035's reference numbers on shared small problems. Then open a + GPy CIP proposing transfer of the layer-ready SVGP pieces. +5. **Phase 5 — Verification corpus.** Golden corpus and GPc interchange + checks; wire into CI. +6. **Phase 6 — Remaining Matlab workflow.** Sampling, SNR control, priors, + classification demo. Revisit GPy2 compatibility using the CIP-0010 + inventory. + +## Backward Compatibility + +- Class names, constructor patterns (`nDims`, kernel lists, `add_layer`) + and the `predict` / `optimize` / `checkgrad` surface are kept. +- `mpi_comm` arguments follow the CIP-0001 deprecation window, then go. +- `gen_pred_model` / `gen_pred_layer` continue to raise + `NotImplementedError` until PredLayer replacements exist. +- Saved models: current `.h5` / pickle behaviour is kept through Phase 2; + a `to_dict` path arrives with Phase 5. + +## Testing Strategy + +Each phase closes only when CI covers what it adds (test-what-you-ship). +Coverage gating continues on the maintained path and widens as MRD and the +uncollapsed family enter it. Long optimisations stay in examples. + +## Related Requirements + +None yet. Candidate WHAT statements for a requirements pass: +"A default `DeepGP(...)` builds on current Python/NumPy"; "A saved deep GP +can be checked against another toolbox through a shared format." + +## Implementation Status + +- [x] Phase 1 (CIP-0001 Phases 1–3, merged upstream) +- [ ] Phase 2 (in progress; backlog tasks created 2026-11-27) +- [x] Phase 3 (MRD via CIP-0002 A–C; ARD scales, mask-style prune/restore and named initialisers in `deepgp/diagnostics.py`) +- [ ] Phase 4 +- [ ] Phase 5 +- [ ] Phase 6 + +## Resolved Questions (2026-11-27) + +1. **Does GPy's SVGP expose the hidden-layer boundary? No; Phase 4 needs a + small core of our own.** From reading `GPy/core/svgp.py` and + `inference/latent_function_inference/svgp.py`: + - `q(u)` is unwhitened, parameterised by `q_u_mean` and a Cholesky of + its covariance. The KL needs `Kmm⁻¹`, and there are no natural + gradients. GPc CIP-0035 found whitening necessary for stacking. + - The bound is hard-wired to `likelihood.variational_expectations`. A + hidden layer's "likelihood" is the rest of the network, so it must + accept upstream gradients `(dL/dμ, dL/dv)` instead. + - Inputs are fixed data. The marginals `(μ, v)` at supplied inputs are + computed inside `inference()` and not returned. Input gradients are + recoverable (`dL_dKmn` and `dL_dKdiag` are in `grad_dict`, and + `kern.gradients_X` / `gradients_X_diag` exist), but `SVGP` does not + assemble them. + - Minibatching uses `climin` with internal slicer state, not a seeded + generator we control. + What is reusable: GPy kernels, `Posterior`, `choleskies`, the mean + function hooks. The new core is a pure function computing whitened + marginals and KL, which is the thing worth proposing to GPy + (CIP-000F Stage 2 style) at transfer time. +2. **Pure-function package: public.** Decided 2026-11-27. It is still + marked provisional until Phase 4 settles its signatures. +3. **GPc interchange for deep models: not ready.** The gp-scuderia schema + is a flat single-GP document (`type`, `kernel`, `inducing_inputs`, + `likelihood`, `data`); `vi` is reserved but unimplemented, and + CIP-0001 there excludes multi-layer and latent-variable models from + 0.1. Raised as gp-scuderia CIP-0006 with four Proposed backlog tasks + (latent `q(X)` block, MRD, uncollapsed `deep_gp` with frozen `eps`, + collapsed bound). Phase 5 here depends on it. + +## References + +- Damianou & Lawrence (2013), *Deep Gaussian Processes*, AISTATS. +- Salimbeni & Deisenroth (2017), *Doubly Stochastic Variational Inference + for Deep Gaussian Processes*. +- PyDeepGP CIP-0001, CIP-0002. +- GPy CIP-000B, 000F, 0010, 0013. +- GPc CIP-0016, 0018, 0035, 0037, 003D. +- gp-scuderia CIP-0006 (latent-variable and deep GP models in the wire format). +- Matlab `deepGP` (`SheffieldML/deepGP-matlab`). diff --git a/deepgp/__init__.py b/deepgp/__init__.py index 5159051..46232ec 100644 --- a/deepgp/__init__.py +++ b/deepgp/__init__.py @@ -1,4 +1,5 @@ # Copyright (c) 2015-2016, the authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) -from .models import DeepGP \ No newline at end of file +from .models import DeepGP +from . import diagnostics diff --git a/deepgp/diagnostics.py b/deepgp/diagnostics.py new file mode 100644 index 0000000..993624c --- /dev/null +++ b/deepgp/diagnostics.py @@ -0,0 +1,126 @@ +# Licensed under the BSD 3-clause license (see LICENSE.txt) +"""ARD scale inspection, pruning and restore for a :class:`deepgp.DeepGP`. + +This recovers the capability of the Matlab ``hsvargplvmShowScales`` and +``PruneModel`` / ``RestorePrunedModel`` (CIP-0003, Phase 3), not their interface. + +Scales are the ARD input sensitivities of each layer kernel, ``variance / +lengthscale**2`` for stationary kernels. The entry for layer ``i`` describes the +latent dimensions that feed that layer, so a near-zero entry marks a dimension +the layer does not use. + +Pruning here *masks* irrelevant dimensions rather than resizing the model: the +kernel parameter that controls the dimension is driven to its "off" value +(very long lengthscale, or tiny variance for a linear kernel) and fixed, so the +optimiser cannot revive it. The latent array keeps its width. ``restore_model`` +returns the original values exactly. Structural removal of columns, with the +speed-up it would bring, is not implemented. +""" +from collections import OrderedDict + +import numpy as np + +_OFF_LENGTHSCALE = 1e8 +_OFF_VARIANCE = 1e-12 + + +def _layer_kernels(model): + """Ordered mapping from a label to the kernel of each layer (or MRD view).""" + out = OrderedDict() + for i, layer in enumerate(model.layers): + if hasattr(layer, 'views'): + for j, view in enumerate(layer.views): + out['layer_%d/view_%d' % (i, j)] = view.kern + else: + out['layer_%d' % i] = layer.kern + return out + + +def ard_scales(model, normalize=True): + """Per-layer ARD relevance of each input dimension. + + Returns an ordered dict ``label -> 1-d array``. With ``normalize`` each array + is divided by its maximum, so the most relevant dimension is 1. + """ + out = OrderedDict() + for label, kern in _layer_kernels(model).items(): + s = np.asarray(kern.input_sensitivity(summarize=True), dtype=float).copy() + if normalize and s.max() > 0: + s = s / s.max() + out[label] = s + return out + + +def show_scales(model, normalize=True, ax=None): + """Bar chart of ``ard_scales``; returns the matplotlib figure. Needs matplotlib.""" + import matplotlib.pyplot as plt + scales = ard_scales(model, normalize=normalize) + if ax is None: + fig, axes = plt.subplots(1, len(scales), squeeze=False, + figsize=(3.2 * len(scales), 2.8)) + axes = axes[0] + else: + axes = np.atleast_1d(ax) + fig = axes[0].figure + if len(axes) != len(scales): + raise ValueError('need %d axes, got %d' % (len(scales), len(axes))) + for a, (label, s) in zip(axes, scales.items()): + a.bar(np.arange(len(s)), s) + a.set_title(label) + a.set_xlabel('latent dimension') + axes[0].set_ylabel('relative ARD scale' if normalize else 'ARD scale') + fig.tight_layout() + return fig + + +def _controlling_param(kern): + """The ARD parameter whose value switches a dimension on or off, with its off value.""" + if hasattr(kern, 'lengthscale') and kern.lengthscale.size == kern.input_dim and kern.input_dim > 1: + return kern.lengthscale, _OFF_LENGTHSCALE + if hasattr(kern, 'variances') and kern.variances.size == kern.input_dim and kern.input_dim > 1: + return kern.variances, _OFF_VARIANCE + return None, None + + +def prune_model(model, threshold=1e-3): + """Switch off input dimensions whose normalised ARD scale is below ``threshold``. + + At least one dimension per kernel is always kept. Layers whose kernel is not + ARD (or has a single input) are skipped. Returns a dict ``label -> indices`` + of the pruned dimensions. Call ``restore_model`` to undo. + """ + if getattr(model, '_pruned', None): + raise RuntimeError('model is already pruned; call restore_model first') + record = [] + report = OrderedDict() + for label, kern in _layer_kernels(model).items(): + param, off = _controlling_param(kern) + if param is None: + report[label] = np.array([], dtype=int) + continue + s = np.asarray(kern.input_sensitivity(summarize=True), dtype=float) + rel = s / s.max() if s.max() > 0 else np.ones_like(s) + idx = np.where(rel < threshold)[0] + if len(idx) == len(rel): + idx = np.array([], dtype=int) + report[label] = idx + if len(idx) == 0: + continue + record.append((param, idx, param.values[idx].copy())) + param[idx] = off + for k in idx: + param[k:k + 1].fix(warning=False) + model._pruned = record + return report + + +def restore_model(model): + """Undo ``prune_model``, restoring the original parameter values exactly.""" + record = getattr(model, '_pruned', None) + if record is None: + raise RuntimeError('model has not been pruned') + for param, idx, values in record: + for k in idx: + param[k:k + 1].unfix() + param[idx] = values + model._pruned = None diff --git a/deepgp/encoder/mlp.py b/deepgp/encoder/mlp.py index 41ee31f..a74d692 100644 --- a/deepgp/encoder/mlp.py +++ b/deepgp/encoder/mlp.py @@ -147,6 +147,11 @@ def update_gradient(self, X, dL): if len(X.shape) == 1: X = X[None, :] dL = dL[None, :] + # Reset first: this call *sets* the parameter gradients. Without it, every + # repeated parameters_changed() between two predict() calls added another + # copy of the gradient (back-constrained MRD checkgrad was off by the + # number of repeats). + self.prepare() _, cache = self.layers[0].forward_all(X) X_grad = self.layers[0].backward_all(cache, dL) self.layers[0]._update_gradient() diff --git a/deepgp/functional/__init__.py b/deepgp/functional/__init__.py new file mode 100644 index 0000000..827bf55 --- /dev/null +++ b/deepgp/functional/__init__.py @@ -0,0 +1,45 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Pure (array-in / array-out) layer mathematics (CIP-0003 Phase 2). + +Public but provisional: names and signatures may change before 1.0. + +Layer interface +--------------- +A layer of a deep GP maps an input distribution q(X) (or fixed X) to marginals +over the layer output, and receives gradients from the layer above. In this +package a layer is split into + +* a *parameter shell* (``deepgp.layers``): GPy ``Parameterized`` objects holding + the kernel, inducing inputs, noise and q(X); +* *pure functions* (this package) that take arrays and return arrays. + +The collapsed (VarDTC) family is implemented by :func:`collapsed_bound` +(statistics -> bound, posterior and gradients w.r.t. the statistics) and +:func:`route_gradients` (gradients w.r.t. statistics -> gradients w.r.t. kernel +parameters and inducing inputs), :func:`qx_gradients` (-> q(X)), and, for MRD, +:func:`aggregate_qx` / :func:`disaggregate_qx_gradients`. The second function receives the GPy +kernel *object* as its single non-array argument, since GPy kernels are not yet +pure functions (GPy CIP-000F Stage 2). It never touches ``Param`` objects, +observers or communicators and returns plain arrays; the shell assigns them. + +The uncollapsed family (CIP-0003 Phase 4) implements the same two roles in +``uncollapsed.py``: :func:`whitened_marginals` (forward marginals at supplied +inputs) and :func:`whitened_marginals_backward` (upstream gradients to +parameters and to the inputs, so they continue to the layer below). +""" + +from .collapsed import collapsed_bound +from .gradients import route_gradients +from .uncollapsed import (whitened_marginals, whitened_marginals_backward, whitened_kl, + reparam_sample, reparam_sample_backward, + whitened_expectation_grads, whitened_natgrad_step) +from .doubly_stochastic import doubly_stochastic_bound +from .qx import qx_gradients, aggregate_qx, disaggregate_qx_gradients + +__all__ = ["collapsed_bound", "route_gradients", "qx_gradients", + "aggregate_qx", "disaggregate_qx_gradients", + "whitened_marginals", "whitened_marginals_backward", "whitened_kl", + "reparam_sample", "reparam_sample_backward", "doubly_stochastic_bound", + "whitened_expectation_grads", "whitened_natgrad_step"] diff --git a/deepgp/functional/collapsed.py b/deepgp/functional/collapsed.py new file mode 100644 index 0000000..ef88b27 --- /dev/null +++ b/deepgp/functional/collapsed.py @@ -0,0 +1,106 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Collapsed variational bound of a sparse GP layer, as a pure function.""" + +import numpy as np +from GPy.util.linalg import jitchol, backsub_both_sides, tdot, dtrtrs + +log_2_pi = np.log(2 * np.pi) + + +def collapsed_bound(Kmm, psi0, psi1, psi2, Y_mean, beta, Y_var=None): + """Collapsed bound with Gaussian noise, for certain or uncertain outputs. + + All arguments are arrays (``beta`` a positive float). Statistics are + *unscaled* by the precision. + + :param Kmm: M x M covariance of the inducing outputs, jitter included. + :param psi0: (N,) or scalar-sum of E[k(x, x)]. + :param psi1: N x M, E[k(x, Z)]. + :param psi2: M x M, sum_n E[k(Z, x_n) k(x_n, Z)]; ``None`` for deterministic + inputs, in which case it is ``psi1.T @ psi1``. + :param Y_mean: N x D output (mean when ``Y_var`` is given). + :param beta: noise precision. + :param Y_var: optional N x D output variances (uncertain outputs). + :returns: dict with ``logL`` (shape (1,)), ``dL_dKmm``, ``dL_dpsi0`` (N,), + ``dL_dpsi1``, ``dL_dpsi2`` (``None`` when ``psi2`` is ``None``, the + gradient having been folded into ``dL_dpsi1``), ``dL_dthetaL``, + ``woodbury_vector``, ``woodbury_inv``, ``cov``, ``Lm`` and, for uncertain + outputs, ``dL_dYmean`` (N x D) and ``dL_dYvar`` ((N,): the bound depends on + the variances only through their row sums). + """ + num_data, output_dim = Y_mean.shape + input_dim = Kmm.shape[0] + deterministic_inputs = psi2 is None + beta = float(beta) + + psi0_sum = np.sum(psi0) * beta + psi1b = psi1 * beta + psi2b = (psi1.T @ psi1 if deterministic_inputs else psi2) * beta + psi1Y = np.dot(Y_mean.T, psi1b) # D x M + if Y_var is not None: + Shalf = np.sqrt(Y_var.sum(axis=1)) + psi1S = Shalf[:, None] * psi1b + YRY = (np.square(Y_mean).sum() + Y_var.sum()) * beta + else: + Shalf = psi1S = None + YRY = np.sum(np.square(Y_mean)) * beta + + logL_R = -num_data * np.log(beta) + + Lm = jitchol(Kmm) + LmInvPsi2LmInvT = backsub_both_sides(Lm, psi2b, 'right') + Lambda = np.eye(input_dim) + LmInvPsi2LmInvT + LL = jitchol(Lambda) + LmLL = Lm.dot(LL) + + logdet_L = 2. * np.sum(np.log(np.diag(LL))) + b = dtrtrs(LmLL, psi1Y.T)[0].T + bbt = np.square(b).sum() + v = dtrtrs(LmLL, b.T, trans=1)[0].T + LLinvPsi1TYYTPsi1LLinvT = tdot(b.T) + + if psi1S is not None: + psi1SLLinv = dtrtrs(LmLL, psi1S.T)[0].T + bbt += np.square(psi1SLLinv).sum() + LLinvPsi1TYYTPsi1LLinvT += tdot(psi1SLLinv.T) + psi1SP = dtrtrs(LmLL, psi1SLLinv.T, trans=1)[0].T + tmp = -backsub_both_sides(LL, LLinvPsi1TYYTPsi1LLinvT + output_dim * np.eye(input_dim)) + dL_dpsi2R = backsub_both_sides(Lm, tmp + output_dim * np.eye(input_dim)) / 2 + + logL = -(output_dim * (num_data * log_2_pi + logL_R + psi0_sum - np.trace(LmInvPsi2LmInvT)) + + YRY - bbt) / 2. - output_dim * logdet_L / 2. + + dL_dKmm = dL_dpsi2R - output_dim * backsub_both_sides(Lm, LmInvPsi2LmInvT) / 2 + + LLInvLmT = dtrtrs(LL, Lm.T)[0] + cov = tdot(LLInvLmT.T) + wd_inv = backsub_both_sides( + Lm, np.eye(input_dim) - backsub_both_sides(LL, np.identity(input_dim), transpose='left'), + transpose='left') + + dL_dthetaL = ((YRY * beta + beta * output_dim * psi0_sum - num_data * output_dim * beta) / 2. + - beta * (dL_dpsi2R * psi2b).sum() + - beta * np.trace(LLinvPsi1TYYTPsi1LLinvT)) + + dL_dpsi0 = -output_dim * (beta * np.ones((num_data,))) / 2. + if Y_var is not None: + dL_dpsi1 = beta * (np.dot(Y_mean, v) + Shalf[:, None] * psi1SP) + else: + dL_dpsi1 = beta * np.dot(Y_mean, v) + if deterministic_inputs: + dL_dpsi1 += np.dot(psi1b, dL_dpsi2R) * 2. + dL_dpsi2 = None + else: + dL_dpsi2 = beta * dL_dpsi2R + + out = {'logL': np.asarray(logL).reshape(1), 'dL_dKmm': dL_dKmm, + 'dL_dpsi0': dL_dpsi0, 'dL_dpsi1': dL_dpsi1, 'dL_dpsi2': dL_dpsi2, + 'dL_dthetaL': dL_dthetaL, 'woodbury_vector': v.T, + 'woodbury_inv': wd_inv, 'cov': cov, 'Lm': Lm} + if Y_var is not None: + psi1LmiLLi = dtrtrs(LmLL, psi1b.T)[0].T + out['dL_dYmean'] = -Y_mean * beta + psi1LmiLLi.dot(b.T) + out['dL_dYvar'] = beta / -2. + np.square(psi1LmiLLi).sum(axis=1) / 2 + return out diff --git a/deepgp/functional/doubly_stochastic.py b/deepgp/functional/doubly_stochastic.py new file mode 100644 index 0000000..dbd158d --- /dev/null +++ b/deepgp/functional/doubly_stochastic.py @@ -0,0 +1,117 @@ +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Doubly stochastic variational bound for a stack of whitened sparse GPs (pure). + +Following Salimbeni & Deisenroth (2017). Inputs ``X`` are propagated through the +hidden layers by reparameterised samples (``f = mu + sqrt(var) * eps``); the top +layer supplies Gaussian marginals, for which the expected log likelihood is +analytic. The bound is the sample average of + + scale * sum_{n,p} E_q[log N(y_np | f_np, noise_var)] - kl_scale * sum_l KL_l, + +where ``scale = N / batch_size`` for minibatches. ``eps`` is supplied by the caller +so results are reproducible and gradients testable. + +A layer is a dict with keys ``kern``, ``Z``, ``q_mu``, ``q_chol`` and optionally +``residual`` (bool). With ``residual`` and equal input/output width the layer adds +its input to its mean (an identity mean function), which Salimbeni & Deisenroth +recommend for hidden layers. +""" + +import numpy as np + +from .uncollapsed import (whitened_marginals, whitened_marginals_backward, whitened_kl, + reparam_sample, reparam_sample_backward, + whitened_expectation_grads) + + +def _check_layers(layers, X): + width = X.shape[1] + for i, l in enumerate(layers): + if l.get('residual', False) and l['q_mu'].shape[1] != width: + raise ValueError("layer %d: residual needs output width %d = input width, got %d" + % (i, l['q_mu'].shape[1], width)) + width = l['q_mu'].shape[1] + return width + + +def doubly_stochastic_bound(layers, X, Y, noise_var, eps, jitter=1e-6, scale=1., kl_scale=1., + x_var=None, eps_x=None): + """Bound and gradients for a stack of layers. + + :param eps: list over samples; each entry a list with one ``(N, width)`` standard + normal array per hidden layer (``len(layers) - 1`` arrays; empty for one layer). + :param x_var: optional ``(N, Q)`` variances of a Gaussian ``q(X) = N(X, diag(x_var))`` over + the bottom inputs (the unsupervised case; ``X`` is then the mean). Each sample draws + ``X + sqrt(x_var) * eps_x[s]`` (``eps_x``: one ``(N, Q)`` array per sample) and the bound + subtracts ``scale * KL(q(X) || N(0, I))``. + :returns: ``(bound, grads)`` where ``grads`` has ``layers`` (list of dicts with + ``q_mu``, ``q_chol``, ``kern``, ``Z``), ``noise_var``, ``X``, ``x_var`` (``0.`` unless given) and ``natgrad`` (``g_m (M, P)`` and ``g_S (P, M, M)``: gradients of the + expected log likelihood, without the KL, with respect to the top layer's ``m`` and ``S``; + see :func:`whitened_natgrad_step`). + """ + L = len(layers) + out_width = _check_layers(layers, X) + if Y.shape[1] != out_width: + raise ValueError("Y has %d columns but the top layer has %d outputs" % (Y.shape[1], out_width)) + N = X.shape[0] + S = len(eps) + layer_grads = [dict(q_mu=0., q_chol=0., kern=0., Z=0.) for _ in range(L)] + gX, g_noise, ell, g_xvar = 0., 0., 0., 0. + if x_var is not None and (eps_x is None or len(eps_x) != len(eps)): + raise ValueError("x_var needs one eps_x array per sample") + nat_m, nat_S = 0., 0. + + for s_idx, sample in enumerate(eps): + if len(sample) != L - 1: + raise ValueError("each sample needs %d eps arrays, got %d" % (L - 1, len(sample))) + inputs, caches, variances = [], [], [] + h = X if x_var is None else reparam_sample(X, x_var, eps_x[s_idx]) + for l, layer in enumerate(layers): + inputs.append(h) + mu, var, cache = whitened_marginals(layer['kern'], layer['Z'].copy(), h.copy(), + layer['q_mu'], layer['q_chol'], jitter) + if layer.get('residual', False): + mu = mu + h + caches.append(cache); variances.append(var) + if l < L - 1: + h = reparam_sample(mu, var, sample[l]) + resid = Y - mu + ell += scale * np.sum(-0.5 * np.log(2 * np.pi * noise_var) - 0.5 * (resid ** 2 + var) / noise_var) + g_noise += scale * np.sum(-0.5 / noise_var + 0.5 * (resid ** 2 + var) / noise_var ** 2) + + g_mu = scale * resid / noise_var + g_var = -0.5 * scale / noise_var * np.ones_like(var) + for l in range(L - 1, -1, -1): + layer = layers[l] + g = whitened_marginals_backward(layer['kern'], layer['Z'].copy(), inputs[l].copy(), + caches[l], g_mu, g_var) + for k in ('q_mu', 'q_chol', 'kern', 'Z'): + layer_grads[l][k] = layer_grads[l][k] + g[k] / S + if l == L - 1: + gm, gS = whitened_expectation_grads(caches[l], g_mu, g_var) + nat_m = nat_m + gm / S + nat_S = nat_S + gS / S + g_in = g['X'] + (g_mu if layer.get('residual', False) else 0.) + if l > 0: + g_mu, g_var = reparam_sample_backward(variances[l - 1], sample[l - 1], g_in) + else: + gX = gX + g_in / S + if x_var is not None: + g_xvar = g_xvar + reparam_sample_backward(x_var, eps_x[s_idx], g_in)[1] / S + + kl = 0. + for l, layer in enumerate(layers): + k, dm, dL = whitened_kl(layer['q_mu'], layer['q_chol']) + kl += k + layer_grads[l]['q_mu'] = layer_grads[l]['q_mu'] - kl_scale * dm + layer_grads[l]['q_chol'] = layer_grads[l]['q_chol'] - kl_scale * dL + + bound = ell / S - kl_scale * kl + if x_var is not None: + kl_x = 0.5 * np.sum(X ** 2 + x_var - 1. - np.log(x_var)) + bound -= scale * kl_x + gX = gX - scale * X + g_xvar = g_xvar - scale * 0.5 * (1. - 1. / x_var) + return bound, dict(layers=layer_grads, noise_var=g_noise / S, X=gX, x_var=g_xvar, + natgrad=dict(g_m=nat_m, g_S=nat_S)) diff --git a/deepgp/functional/gradients.py b/deepgp/functional/gradients.py new file mode 100644 index 0000000..2cf4c8f --- /dev/null +++ b/deepgp/functional/gradients.py @@ -0,0 +1,40 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Route gradients with respect to statistics onto layer parameters (pure).""" + +import numpy as np + + +def route_gradients(kern, Z, X, dL_dKmm, dL_dpsi0=None, dL_dpsi1=None, + dL_dpsi2=None, dL_dKdiag=None, dL_dKnm=None): + """Gradients w.r.t. kernel parameters and inducing inputs. + + ``kern`` is the only non-array argument (a GPy kernel), used for its gradient + methods (which overwrite ``kern.gradient`` as scratch space; the caller + assigns the returned gradient). ``Z`` and ``X`` are arrays; ``X`` + may be a GPy ``VariationalPosterior`` (uncertain inputs), in which case the + ``dL_dpsi*`` arguments are used, otherwise ``dL_dKdiag`` and ``dL_dKnm``. + + :returns: ``(kern_gradient, Z_gradient)`` as arrays. + """ + from GPy.core.parameterization.variational import VariationalPosterior + if isinstance(X, VariationalPosterior): + kern.update_gradients_expectations(variational_posterior=X, Z=Z, + dL_dpsi0=dL_dpsi0, dL_dpsi1=dL_dpsi1, + dL_dpsi2=dL_dpsi2) + kerngrad = kern.gradient.copy() + kern.update_gradients_full(dL_dKmm, Z, None) + kerngrad += kern.gradient.copy() + Zgrad = kern.gradients_Z_expectations(dL_dpsi0, dL_dpsi1, dL_dpsi2, + Z=Z, variational_posterior=X) + Zgrad = Zgrad + kern.gradients_X(dL_dKmm, Z) + else: + kern.update_gradients_diag(dL_dKdiag, X) + kerngrad = kern.gradient.copy() + kern.update_gradients_full(dL_dKnm, X, Z) + kerngrad += kern.gradient + kern.update_gradients_full(dL_dKmm, Z, None) + kerngrad = kerngrad + kern.gradient + Zgrad = kern.gradients_X(dL_dKnm.T, Z, X) + kern.gradients_X(dL_dKmm, Z) + return np.asarray(kerngrad).copy(), np.asarray(Zgrad) diff --git a/deepgp/functional/qx.py b/deepgp/functional/qx.py new file mode 100644 index 0000000..a877601 --- /dev/null +++ b/deepgp/functional/qx.py @@ -0,0 +1,50 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Pure functions for the variational distribution q(X) of a layer's inputs.""" + +import numpy as np + + +def qx_gradients(kern, Z, X, dL_dpsi0, dL_dpsi1, dL_dpsi2): + """Gradients of the bound w.r.t. the mean and variance of q(X). + + :param kern: GPy kernel (the one non-array argument, see ``route_gradients``). + :param X: GPy ``VariationalPosterior`` supplying the values. + :returns: ``(dL_dmean, dL_dvar)`` arrays. + """ + return kern.gradients_qX_expectations(variational_posterior=X, Z=Z, + dL_dpsi0=dL_dpsi0, dL_dpsi1=dL_dpsi1, + dL_dpsi2=dL_dpsi2) + + +def aggregate_qx(view_means, view_variances): + """Product-of-experts combination of per-view Gaussians (MRD). + + Precisions add and the mean is the precision-weighted mean. + + :returns: ``(mean, variance, prec_denom)`` with ``prec_denom`` the summed precision. + """ + prec_denom = np.zeros_like(view_variances[0]) + mean = np.zeros_like(view_means[0]) + for m, v in zip(view_means, view_variances): + prec_denom = prec_denom + 1. / v + mean = mean + m / v + return mean / prec_denom, 1. / prec_denom, prec_denom + + +def disaggregate_qx_gradients(view_means, view_variances, prec_denom, + mean, dL_dmean, dL_dvar): + """Back-propagate gradients on the aggregate q(X) to each view's q(X). + + Inverse of :func:`aggregate_qx` in the chain-rule sense, as used by the MRD + layer for the per-view encoders. + + :returns: list of ``(dL_dmean_v, dL_dvar_v)``, one per view. + """ + out = [] + for m, v in zip(view_means, view_variances): + c = 1. / (prec_denom * v) + out.append((c * dL_dmean, + np.square(c) * dL_dvar + c * (mean - m) / v * dL_dmean)) + return out diff --git a/deepgp/functional/uncollapsed.py b/deepgp/functional/uncollapsed.py new file mode 100644 index 0000000..3cae808 --- /dev/null +++ b/deepgp/functional/uncollapsed.py @@ -0,0 +1,159 @@ +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Whitened sparse-GP layer marginals and gradients (pure; CIP-0003 Phase 4). + +A layer holds ``P`` independent outputs sharing one kernel and one set of +inducing inputs ``Z``. Each output ``p`` has a whitened variational posterior +``q(v_p) = N(m_p, S_p)`` with ``S_p = L_p L_p^T``, related to the inducing +values by ``u_p = Lm v_p`` where ``Kmm = Lm Lm^T``. At inputs ``X`` the marginals +of ``f_p`` are + + mu_p = B^T m_p + var_p = kdiag - colsum(B**2) + colsum((L_p^T B)**2), B = Lm^{-1} Kmn. + +This is the boundary a hidden layer needs (GPy's ``SVGP`` does not expose it): +:func:`whitened_marginals` returns marginals at supplied inputs, and +:func:`whitened_marginals_backward` takes the upstream gradients +``(dL/dmu, dL/dvar)`` and returns gradients for ``q(u)``, the kernel, ``Z`` and +the inputs, so the gradient can continue to the layer below. + +Arrays only, except that ``kern`` is a GPy kernel object (see +``deepgp.functional``). Shapes: ``Z (M, Q)``, ``X (N, Q)``, ``q_mu (M, P)``, +``q_chol (P, M, M)`` lower triangular; outputs ``(N, P)``. +""" + +import numpy as np +from scipy.linalg import solve_triangular + +from .gradients import route_gradients + + +def whitened_marginals(kern, Z, X, q_mu, q_chol, jitter=1e-6): + """Marginal mean and variance of each output at ``X``. + + :returns: ``(mu, var, cache)``; pass ``cache`` to the backward function. + """ + M = Z.shape[0] + Kmm = kern.K(Z) + jitter * np.eye(M) + Lm = np.linalg.cholesky(Kmm) + Knm = kern.K(X, Z) + B = solve_triangular(Lm, Knm.T, lower=True) + kdiag = kern.Kdiag(X) + C = np.einsum('pmk,mn->pkn', q_chol, B) + mu = B.T @ q_mu + var = kdiag[:, None] - np.sum(B ** 2, axis=0)[:, None] + np.sum(C ** 2, axis=1).T + cache = dict(Lm=Lm, B=B, C=C, q_mu=q_mu, q_chol=q_chol) + return mu, var, cache + + +def _cholesky_backward(Lm, dLm): + """Gradient w.r.t. the (symmetric) matrix whose Cholesky factor is ``Lm``.""" + P = np.tril(Lm.T @ dLm) + P[np.diag_indices_from(P)] *= 0.5 + inv = solve_triangular(Lm, np.eye(Lm.shape[0]), lower=True) # Lm^{-1} + dK = inv.T @ P @ inv + return 0.5 * (dK + dK.T) + + +def whitened_marginals_backward(kern, Z, X, cache, dL_dmu, dL_dvar): + """Gradients given upstream ``dL_dmu`` and ``dL_dvar`` (both ``(N, P)``). + + Returns a dict with ``q_mu``, ``q_chol`` (lower triangular), ``kern`` (array, + the caller assigns it), ``Z`` and ``X``. The ``X`` entry is the gradient to + pass to the layer below. + """ + Lm, B, C = cache['Lm'], cache['B'], cache['C'] + q_mu, q_chol = cache['q_mu'], cache['q_chol'] + g_total = dL_dvar.sum(axis=1) + + dq_mu = B @ dL_dmu + dB = q_mu @ dL_dmu.T - 2. * B * g_total[None, :] + dq_chol = np.empty_like(q_chol) + for p in range(q_chol.shape[0]): + dC = 2. * C[p] * dL_dvar[:, p][None, :] + dB += q_chol[p] @ dC + dq_chol[p] = np.tril(B @ dC.T) + + dKmn = solve_triangular(Lm, dB, lower=True, trans='T') # Lm^{-T} dB + dLm = -dKmn @ B.T + dKmm = _cholesky_backward(Lm, dLm) + dKnm = dKmn.T + + kerngrad, Zgrad = route_gradients(kern, Z, X, dKmm, dL_dKdiag=g_total, dL_dKnm=dKnm) + Xgrad = kern.gradients_X(dKnm, X, Z) + kern.gradients_X_diag(g_total, X) + return dict(q_mu=dq_mu, q_chol=dq_chol, kern=kerngrad, Z=Zgrad, X=Xgrad) + + +def whitened_kl(q_mu, q_chol): + """``sum_p KL(N(m_p, L_p L_p^T) || N(0, I))`` and its gradients. + + :returns: ``(kl, dq_mu, dq_chol)``. + """ + M = q_mu.shape[0] + diag = np.stack([np.diag(L) for L in q_chol]) + kl = 0.5 * (np.sum(q_chol ** 2) + np.sum(q_mu ** 2) - M * q_chol.shape[0] + - 2. * np.sum(np.log(np.abs(diag)))) + dq_chol = np.array(q_chol, dtype=float) + for p in range(q_chol.shape[0]): + dq_chol[p][np.diag_indices(M)] -= 1. / diag[p] + dq_chol[p] = np.tril(dq_chol[p]) + return kl, q_mu.copy(), dq_chol + + +def reparam_sample(mu, var, eps): + """``f = mu + sqrt(var) * eps`` with caller-supplied standard normal ``eps``.""" + return mu + np.sqrt(var) * eps + + +def reparam_sample_backward(var, eps, dL_df): + """Gradients ``(dL_dmu, dL_dvar)`` of :func:`reparam_sample`.""" + return dL_df, dL_df * eps / (2. * np.sqrt(var)) + + +def whitened_expectation_grads(cache, dL_dmu, dL_dvar): + """Gradients of the data term w.r.t. ``m_p`` and ``S_p`` (not ``L_p``). + + With ``mu_p = B^T m_p`` and ``var_p = ... + b^T S_p b`` these are + ``g_m = B dL_dmu`` and ``g_S[p] = B diag(dL_dvar[:, p]) B^T``, the quantities a + natural-gradient step needs. Excludes the KL. + + :returns: ``(g_m (M, P), g_S (P, M, M))``. + """ + B = cache['B'] + g_m = B @ dL_dmu + g_S = np.einsum('mn,np,kn->pmk', B, dL_dvar, B) + return g_m, g_S + + +def whitened_natgrad_step(q_mu, q_chol, g_m, g_S, gamma): + """One natural-gradient step on ``q(v_p) = N(m_p, S_p)`` for ``ELL - KL(q || N(0, I))``. + + In natural parameters ``theta1 = S^-1 m``, ``theta2 = -S^-1 / 2`` the natural gradient + equals the gradient in expectation parameters ``eta = (m, S + m m^T)``, and the KL + contributes ``theta_prior - theta`` with ``theta_prior = (0, -I/2)``. A step of size + ``gamma`` therefore moves + + theta <- (1 - gamma) theta + gamma (theta_prior + grad_eta ELL), + + with ``grad_eta1 ELL = g_m - 2 g_S m`` and ``grad_eta2 ELL = g_S``. For a Gaussian + likelihood ``gamma = 1`` on the full data reaches the optimum of ``q`` in one step. + ``g_S`` must be negative semi-definite so that the precision stays positive definite. + + :returns: ``(q_mu_new, q_chol_new)``. + """ + M, P = q_mu.shape + new_mu, new_chol = np.empty_like(q_mu), np.empty_like(q_chol) + for p in range(P): + L = q_chol[p] + S = L @ L.T + Lam = np.linalg.inv(S) + theta1 = Lam @ q_mu[:, p] + gS = 0.5 * (g_S[p] + g_S[p].T) + theta1 = (1. - gamma) * theta1 + gamma * (g_m[:, p] - 2. * gS @ q_mu[:, p]) + Lam_new = (1. - gamma) * Lam + gamma * (np.eye(M) - 2. * gS) + Lam_new = 0.5 * (Lam_new + Lam_new.T) + S_new = np.linalg.inv(Lam_new) + S_new = 0.5 * (S_new + S_new.T) + new_mu[:, p] = S_new @ theta1 + new_chol[p] = np.linalg.cholesky(S_new) + return new_mu, new_chol diff --git a/deepgp/inference/__init__.py b/deepgp/inference/__init__.py index 5d7e167..4d6463e 100644 --- a/deepgp/inference/__init__.py +++ b/deepgp/inference/__init__.py @@ -2,7 +2,6 @@ # Licensed under the BSD 3-clause license (see LICENSE.txt) from .vardtc import VarDTC -from .vardtc_parallel import VarDTC_parallel from .svi_vardtc import SVI_VarDTC from .svi_ratio import SVI_Ratio from .inferenceX import InferenceX diff --git a/deepgp/inference/svi_ratio.py b/deepgp/inference/svi_ratio.py index 9958c4b..3aa51d3 100644 --- a/deepgp/inference/svi_ratio.py +++ b/deepgp/inference/svi_ratio.py @@ -10,10 +10,7 @@ from GPy.inference.latent_function_inference.posterior import Posterior log_2_pi = np.log(2*np.pi) -try: - from mpi4py import MPI -except: - pass +from ..util.util import reject_mpi_comm class SVI_Ratio(LatentFunctionInference): """ @@ -22,7 +19,7 @@ class SVI_Ratio(LatentFunctionInference): const_jitter = 1e-6 def __init__(self, mpi_comm=None): - self.mpi_comm = mpi_comm + reject_mpi_comm(mpi_comm) def get_trYYT(self, Y): return np.sum(np.square(Y)) diff --git a/deepgp/inference/svi_vardtc.py b/deepgp/inference/svi_vardtc.py index bc92392..a1a2410 100644 --- a/deepgp/inference/svi_vardtc.py +++ b/deepgp/inference/svi_vardtc.py @@ -10,10 +10,7 @@ from GPy.inference.latent_function_inference.posterior import Posterior log_2_pi = np.log(2*np.pi) -try: - from mpi4py import MPI -except: - pass +from ..util.util import reject_mpi_comm class SVI_VarDTC(LatentFunctionInference): """ @@ -27,8 +24,7 @@ class SVI_VarDTC(LatentFunctionInference): """ const_jitter = 1e-6 def __init__(self, mpi_comm=None, mpi_root=0, psi_chunk_size=None, psi_threads=1): - self.mpi_comm = mpi_comm - self.mpi_root=mpi_root + reject_mpi_comm(mpi_comm) self.psi_chunk_size = psi_chunk_size self.psi_threads = 1 if psi_threads is None else int(psi_threads) @@ -88,9 +84,6 @@ def gatherPsiStat(self, kern, X, Z, Y, beta, uncertain_inputs): trYYT = self.get_trYYT(Y) YRY = trYYT*beta - if self.mpi_comm is not None: - from ..util.parallel import allReduceArrays - psi0, psi2, YRY, psi1Y = allReduceArrays([psi0, psi2, YRY, psi1Y], self.mpi_comm) return psi0, psi2, YRY, psi1, psi1Y def inference(self, kern, X, Z, likelihood, Y, qU_mean ,qU_var, Kuu_sigma=None): diff --git a/deepgp/inference/vardtc.py b/deepgp/inference/vardtc.py index 2005cd0..d7a050d 100644 --- a/deepgp/inference/vardtc.py +++ b/deepgp/inference/vardtc.py @@ -8,241 +8,125 @@ from GPy.util import diag from GPy.core.parameterization.variational import VariationalPosterior import numpy as np -from GPy.inference.latent_function_inference import LatentFunctionInference +from GPy.inference.latent_function_inference.var_dtc import VarDTC as GPyVarDTC from GPy.inference.latent_function_inference.posterior import Posterior log_2_pi = np.log(2*np.pi) -try: - from mpi4py import MPI -except: - pass +from ..util.util import reject_mpi_comm -class VarDTC(LatentFunctionInference): +class VarDTC(GPyVarDTC): """ - An object for inference when the likelihood is Gaussian, but we want to do sparse inference. + Sparse variational DTC inference for deep GP layers. - The function self.inference returns a Posterior object, which summarizes - the posterior. + Subclasses :class:`GPy.inference.latent_function_inference.var_dtc.VarDTC` + (CIP-0003 Phase 2). Compared with GPy's class this adds only: - For efficiency, we sometimes work with the cholesky of Y*Y.T. To save repeatedly recomputing this, we cache it. + * ``psi_chunk_size`` / ``psi_threads``: chunked psi-statistics (CIP-0001). + * ``Kuu_sigma``: per-inducing-point diagonal added to ``Kuu`` (hidden layers). + * uncertain outputs: ``Y`` may be a ``VariationalPosterior`` (the latent + variables of the layer below), which GPy's class does not support. + * ``const_jitter = 1e-6`` and a noise-variance floor of ``1e-6``, matching + the behaviour that the reference-value tests were generated with. + Everything else (algebra, gradients, posterior, ``sparse_linalg`` modes) + is GPy's. For deterministic ``Y`` the two classes agree to ~1e-11. """ const_jitter = 1e-6 - def __init__(self, mpi_comm=None, psi_chunk_size=None, psi_threads=1): - - self.mpi_comm = mpi_comm + _variance_floor = 1e-6 + + def __init__(self, mpi_comm=None, psi_chunk_size=None, psi_threads=1, + sparse_linalg="stable"): + reject_mpi_comm(mpi_comm) + try: + super(VarDTC, self).__init__(limit=1, sparse_linalg=sparse_linalg) + except TypeError: + # GPy releases without CIP-0013 have no ``sparse_linalg`` argument. + if sparse_linalg != "stable": + raise + super(VarDTC, self).__init__(limit=1) + # Newer GPy sets ``const_jitter`` per instance in ``__init__``, which would shadow the + # class attribute above; reassert our convention. + self.const_jitter = type(self).const_jitter self.psi_chunk_size = psi_chunk_size self.psi_threads = 1 if psi_threads is None else int(psi_threads) - self.Y_speedup = False # Replace Y with the cholesky factor of YY.T, but the computation of posterior object will be skipped. - - def get_trYYT(self, Y): - return np.sum(np.square(Y)) - - def get_YYTfactor(self, Y): - N, D = Y.shape - if (N>=D): - return Y.view(np.ndarray) - else: - return jitchol(tdot(Y)) - def gatherPsiStat(self, kern, X, Z, Y, beta, uncertain_inputs): - from ..util.psi_chunking import configure_kern_psicomp, row_slices + def __getstate__(self): + state = super(VarDTC, self).__getstate__() + return state, self.psi_chunk_size, self.psi_threads + + def __setstate__(self, state): + inner, self.psi_chunk_size, self.psi_threads = state + super(VarDTC, self).__setstate__(inner) - assert beta.size == 1 + def psi_statistics(self, kern, X, Z): + """Unscaled ``(psi0, psi1, psi2)`` for uncertain inputs, chunked if requested. + + ``psi0`` is per-point, ``psi1`` is N x M, ``psi2`` is M x M (summed over points). + """ + from ..util.psi_chunking import configure_kern_psicomp, row_slices # Prefer GPy R12 chunking/threading when the kernel supports it. psicomp_chunked = configure_kern_psicomp(kern, self.psi_chunk_size, self.psi_threads) N = X.shape[0] chunk = self.psi_chunk_size - use_serial_chunks = ( - uncertain_inputs - and chunk is not None - and int(chunk) > 0 - and int(chunk) < N - and not psicomp_chunked - ) - - if use_serial_chunks: + if chunk is not None and 0 < int(chunk) < N and not psicomp_chunked: # CIP-0001 R14: serial map-reduce over row chunks for any kernel. - psi1_parts = [] - psi2 = None - psi0 = 0.0 + psi0, psi1, psi2 = [], [], None for sl in row_slices(N, chunk): Xc = X[sl] - psi0 = psi0 + kern.psi0(Z, Xc).sum() - psi1_parts.append(kern.psi1(Z, Xc) * beta) - psi2_c = kern.psi2(Z, Xc) * beta + psi0.append(kern.psi0(Z, Xc)) + psi1.append(kern.psi1(Z, Xc)) + psi2_c = kern.psi2(Z, Xc) psi2 = psi2_c if psi2 is None else psi2 + psi2_c - psi1 = np.vstack(psi1_parts) - psi0 = psi0 * beta - elif uncertain_inputs: - psi0 = kern.psi0(Z, X) - psi1 = kern.psi1(Z, X)*beta - psi2 = kern.psi2(Z, X)*beta - psi0 = psi0.sum()*beta - else: - psi0 = kern.Kdiag(X) - psi1 = kern.K(X, Z) - psi2 = np.dot(psi1.T,psi1)*beta - psi1 = psi1*beta - psi0 = psi0.sum()*beta - - if isinstance(Y, VariationalPosterior): - m, s = Y.mean, Y.variance - - psi1Y = np.dot(m.T,psi1) # DxM - Shalf = np.sqrt(s.sum(axis=1)) - psi1S = Shalf[:,None]*psi1 - - YRY = (np.square(m).sum()+s.sum())*beta - else: - psi1Y = np.dot(Y.T,psi1) # DxM - - trYYT = self.get_trYYT(Y) - YRY = trYYT*beta - psi1S = None - Shalf = None - - return psi0, psi2, YRY, psi1, psi1Y, Shalf, psi1S - - def inference(self, kern, X, Z, likelihood, Y, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None): - """ - The first phase of inference: - Compute: log-likelihood, dL_dKmm + return np.hstack(psi0), np.vstack(psi1), psi2 + return kern.psi0(Z, X), kern.psi1(Z, X), kern.psi2(Z, X) - Cached intermediate results: Kmm, KmmInv, + def inference(self, kern, X, Z, likelihood, Y, Y_metadata=None, Lm=None, + dL_dKmm=None, Kuu_sigma=None, **kwargs): + if isinstance(Y, VariationalPosterior): + return self._inference_uncertain_outputs( + kern, X, Z, likelihood, Y, Y_metadata, Lm, dL_dKmm, Kuu_sigma) + if Kuu_sigma is not None and Lm is None: + Kmm = kern.K(Z).copy() + diag.add(Kmm, Kuu_sigma) + Lm = jitchol(Kmm) + if isinstance(X, VariationalPosterior): + psi0, psi1, psi2 = self.psi_statistics(kern, X, Z) + kwargs.update(psi0=psi0, psi1=psi1, psi2=psi2) + precision = 1. / np.fmax(likelihood.variance, self._variance_floor) + post, logL, grad_dict = super(VarDTC, self).inference( + kern, X, Z, likelihood, Y, Y_metadata=Y_metadata, Lm=Lm, + dL_dKmm=dL_dKmm, precision=np.asarray(precision).reshape(-1), **kwargs) + # Layers expect a length-1 vector (GPy returns a 1x1 matrix) and no dL_dm. + grad_dict.pop('dL_dm', None) + return post, np.asarray(logL).reshape(1), grad_dict + + def _inference_uncertain_outputs(self, kern, X, Z, likelihood, Y, Y_metadata=None, + Lm=None, dL_dKmm=None, Kuu_sigma=None): + """Uncertain outputs: Y is the q(X) of the layer below (not in GPy). + + Computes the statistics and delegates the algebra to the pure + :func:`deepgp.functional.collapsed_bound`. """ - - - num_data, output_dim = Y.shape - input_dim = Z.shape[0] - - uncertain_inputs = isinstance(X, VariationalPosterior) - uncertain_outputs = isinstance(Y, VariationalPosterior) - - # from ..models.sslvm import Gaussian_Gamma - # if isinstance(likelihood, Gaussian_Gamma): - # beta = likelihood.expectation_beta() - # logL_R = -num_data*likelihood.expectation_logbeta() - # else: - beta = 1./np.fmax(likelihood.variance, 1e-6) - logL_R = -num_data*np.log(beta) - - - psi0, psi2, YRY, psi1, psi1Y, Shalf, psi1S = self.gatherPsiStat(kern, X, Z, Y, beta, uncertain_inputs) - - #====================================================================== - # Compute Common Components - #====================================================================== - + from ..functional import collapsed_bound + beta = 1. / np.fmax(likelihood.variance, self._variance_floor) Kmm = kern.K(Z).copy() - if Kuu_sigma is not None: - diag.add(Kmm, Kuu_sigma) - else: - diag.add(Kmm, self.const_jitter) - Lm = jitchol(Kmm) - - #LmInv = dtrtri(Lm) - if uncertain_inputs: - LmInvPsi2LmInvT = backsub_both_sides(Lm, psi2, 'right') + diag.add(Kmm, Kuu_sigma if Kuu_sigma is not None else self.const_jitter) + if isinstance(X, VariationalPosterior): + psi0, psi1, psi2 = self.psi_statistics(kern, X, Z) else: - LmInvPsi2LmInvT = tdot(dtrtrs(Lm, psi1.T)[0])/beta #tdot(psi1.dot(LmInv.T).T) /beta - - Lambda = np.eye(Kmm.shape[0])+LmInvPsi2LmInvT - LL = jitchol(Lambda) - LmLL = Lm.dot(LL) -# LLInv = dtrtri(LL) - # LmLLInv = LLInv.dot(LmInv) - - logdet_L = 2.*np.sum(np.log(np.diag(LL))) - b = dtrtrs(LmLL, psi1Y.T)[0].T #psi1Y.dot(LmLLInv.T) - bbt = np.square(b).sum() - v = dtrtrs(LmLL, b.T, trans=1)[0].T #b.dot(LmLLInv) - LLinvPsi1TYYTPsi1LLinvT = tdot(b.T) - - if psi1S is not None: - psi1SLLinv = dtrtrs(LmLL, psi1S.T)[0].T #psi1S.dot(LmLLInv.T) - bbt += np.square(psi1SLLinv).sum() - LLinvPsi1TYYTPsi1LLinvT += tdot(psi1SLLinv.T) - psi1SP = dtrtrs(LmLL, psi1SLLinv.T, trans=1)[0].T #psi1SLLinv.dot(LmLLInv) - tmp = -backsub_both_sides(LL, LLinvPsi1TYYTPsi1LLinvT+output_dim*np.eye(input_dim)) - dL_dpsi2R = backsub_both_sides(Lm, tmp+output_dim*np.eye(input_dim))/2 - #tmp = -LLInv.T.dot(LLinvPsi1TYYTPsi1LLinvT+output_dim*np.eye(input_dim)).dot(LLInv) - #dL_dpsi2R = LmInv.T.dot(tmp+output_dim*np.eye(input_dim)).dot(LmInv)/2. - - #====================================================================== - # Compute log-likelihood - #====================================================================== - - logL = -(output_dim*(num_data*log_2_pi+logL_R+psi0-np.trace(LmInvPsi2LmInvT))+YRY- bbt)/2.-output_dim*logdet_L/2. - - #====================================================================== - # Compute dL_dKmm - #====================================================================== - - dL_dKmm = dL_dpsi2R - output_dim* backsub_both_sides(Lm, LmInvPsi2LmInvT)/2 #LmInv.T.dot(LmInvPsi2LmInvT).dot(LmInv)/2. - - #====================================================================== - # Compute the Posterior distribution of inducing points p(u|Y) - #====================================================================== - - LLInvLmT = dtrtrs(LL, Lm.T)[0] - cov = tdot(LLInvLmT.T) - - wd_inv = backsub_both_sides(Lm, np.eye(input_dim)- backsub_both_sides(LL, np.identity(input_dim), transpose='left'), transpose='left') - post = Posterior(woodbury_inv=wd_inv, woodbury_vector=v.T, K=Kmm, mean=None, cov=cov, K_chol=Lm) - - #====================================================================== - # Compute dL_dthetaL for uncertian input and non-heter noise - #====================================================================== - - # if isinstance(likelihood, Gaussian_Gamma): - # from scipy.special import polygamma - # dL_dthetaL = ((YRY + output_dim*psi0)/2. - (dL_dpsi2R*psi2).sum() - np.trace(LLinvPsi1TYYTPsi1LLinvT))/-beta - # likelihood.q_a.gradient = num_data*output_dim/2.*polygamma(1, likelihood.q_a) + dL_dthetaL/likelihood.q_b - # likelihood.q_b.gradient = num_data*output_dim/(-2.*likelihood.q_b) +dL_dthetaL*(-likelihood.q_a/(likelihood.q_b*likelihood.q_b)) - # else: - dL_dthetaL = (YRY*beta + beta*output_dim*psi0 - num_data*output_dim*beta)/2. - beta*(dL_dpsi2R*psi2).sum() - beta*np.trace(LLinvPsi1TYYTPsi1LLinvT) - - #====================================================================== - # Compute dL_dpsi - #====================================================================== - - dL_dpsi0 = -output_dim * (beta * np.ones((num_data,)))/2. - - if uncertain_outputs: - m,s = Y.mean, Y.variance - dL_dpsi1 = beta*(np.dot(m,v)+Shalf[:,None]*psi1SP) - else: - dL_dpsi1 = beta*np.dot(Y,v) - - if uncertain_inputs: - dL_dpsi2 = beta* dL_dpsi2R - else: - dL_dpsi1 += np.dot(psi1,dL_dpsi2R)*2. - dL_dpsi2 = None - - if uncertain_inputs: - grad_dict = {'dL_dKmm': dL_dKmm, - 'dL_dpsi0':dL_dpsi0, - 'dL_dpsi1':dL_dpsi1, - 'dL_dpsi2':dL_dpsi2, - 'dL_dthetaL':dL_dthetaL} - else: - grad_dict = {'dL_dKmm': dL_dKmm, - 'dL_dKdiag':dL_dpsi0, - 'dL_dKnm':dL_dpsi1, - 'dL_dthetaL':dL_dthetaL} - - if uncertain_outputs: - m,s = Y.mean, Y.variance - psi1LmiLLi = dtrtrs(LmLL, psi1.T)[0].T - LLiLmipsi1Y = b.T - grad_dict['dL_dYmean'] = -m*beta+ psi1LmiLLi.dot(LLiLmipsi1Y) - grad_dict['dL_dYvar'] = beta/-2.+ np.square(psi1LmiLLi).sum(axis=1)/2 - - return post, logL, grad_dict - - - + psi0, psi1, psi2 = kern.Kdiag(X), kern.K(X, Z), None + r = collapsed_bound(Kmm, psi0, psi1, psi2, Y.mean, float(beta[0]) if np.ndim(beta) else float(beta), + Y_var=Y.variance) + post = Posterior(woodbury_inv=r['woodbury_inv'], woodbury_vector=r['woodbury_vector'], + K=Kmm, mean=None, cov=r['cov'], K_chol=r['Lm']) + grad_dict = {'dL_dKmm': r['dL_dKmm'], 'dL_dpsi0': r['dL_dpsi0'], + 'dL_dpsi1': r['dL_dpsi1'], 'dL_dpsi2': r['dL_dpsi2'], + 'dL_dthetaL': r['dL_dthetaL'], + 'dL_dYmean': r['dL_dYmean'], 'dL_dYvar': r['dL_dYvar']} + if r['dL_dpsi2'] is None: + grad_dict = {'dL_dKmm': r['dL_dKmm'], 'dL_dKdiag': r['dL_dpsi0'], + 'dL_dKnm': r['dL_dpsi1'], 'dL_dthetaL': r['dL_dthetaL'], + 'dL_dYmean': r['dL_dYmean'], 'dL_dYvar': r['dL_dYvar']} + return post, r['logL'], grad_dict diff --git a/deepgp/inference/vardtc_parallel.py b/deepgp/inference/vardtc_parallel.py deleted file mode 100644 index c82fbce..0000000 --- a/deepgp/inference/vardtc_parallel.py +++ /dev/null @@ -1,291 +0,0 @@ -# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). -# Licensed under the BSD 3-clause license (see LICENSE.txt) - - - - -#from .posterior import Posterior -from GPy.util.linalg import jitchol, backsub_both_sides, tdot, dtrtrs, dtrtri,pdinv -from GPy.util import diag -from GPy.core.parameterization.variational import VariationalPosterior -import numpy as np -from GPy.inference.latent_function_inference import LatentFunctionInference -from GPy.inference.latent_function_inference.posterior import Posterior -from scipy.linalg import LinAlgError -log_2_pi = np.log(2*np.pi) - -try: - from mpi4py import MPI - from deepgp.util.parallel import allReduceArrays, broadcastArrays, reduceArrays -except: - pass - -class VarDTC_parallel(LatentFunctionInference): - """ - An object for inference when the likelihood is Gaussian, but we want to do sparse inference. - - The function self.inference returns a Posterior object, which summarizes - the posterior. - - For efficiency, we sometimes work with the cholesky of Y*Y.T. To save repeatedly recomputing this, we cache it. - - """ - const_jitter = 1e-8 - def __init__(self, mpi_comm=None, root=0): - - self.mpi_comm = mpi_comm - self.root = root - self.Y_speedup = False # Replace Y with the cholesky factor of YY.T, but the computation of posterior object will be skipped. - - def get_trYYT(self, Y): - return np.sum(np.square(Y)) - - def get_YYTfactor(self, Y): - N, D = Y.shape - if (N>=D): - return Y.view(np.ndarray) - else: - return jitchol(tdot(Y)) - - def gatherPsiStat(self, kern, X, Z, Y, beta, uncertain_inputs): - - assert beta.size == 1 - - if uncertain_inputs: - psi0 = kern.psi0(Z, X) - psi1 = kern.psi1(Z, X)*beta - psi2 = kern.psi2(Z, X)*beta - else: - psi0 = kern.Kdiag(X) - psi1 = kern.K(X, Z) - psi2 = np.dot(psi1.T,psi1)*beta - psi1 = psi1*beta - - psi0 = psi0.sum()*beta - - if isinstance(Y, VariationalPosterior): - m, s = Y.mean, Y.variance - - psi1Y = np.dot(m.T,psi1) # DxM - Shalf = np.sqrt(s.sum(axis=1)) - psi1S = Shalf[:,None]*psi1 - - YRY = (np.square(m).sum()+s.sum())*beta - else: - psi1Y = np.dot(Y.T,psi1) # DxM - - trYYT = self.get_trYYT(Y) - YRY = trYYT*beta - psi1S = None - Shalf = None - - psi0, psi2, YRY, psi1Y = allReduceArrays([psi0, psi2, YRY, psi1Y], self.mpi_comm) - return psi0, psi2, YRY, psi1, psi1Y, Shalf, psi1S - - def inference(self, kern, X, Z, likelihood, Y, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None): - if self.mpi_comm.rank==self.root: - return self.inference_root(kern, X, Z, likelihood, Y, Kuu_sigma, Y_metadata, Lm, dL_dKmm) - else: - return self.inference_nonroot(kern, X, Z, likelihood, Y, Y_metadata, Lm, dL_dKmm) - - - - def inference_root(self, kern, X, Z, likelihood, Y, Kuu_sigma=None, Y_metadata=None, Lm=None, dL_dKmm=None): - """ - The first phase of inference: - Compute: log-likelihood, dL_dKmm - - Cached intermediate results: Kmm, KmmInv, - """ - - num_data, output_dim = Y.shape - input_dim = Z.shape[0] - num_data_total = allReduceArrays([np.int32(num_data)], self.mpi_comm)[0] - - uncertain_inputs = isinstance(X, VariationalPosterior) - uncertain_outputs = isinstance(Y, VariationalPosterior) - - beta = 1./np.fmax(likelihood.variance, 1e-6) - - psi0, psi2, YRY, psi1, psi1Y, Shalf, psi1S = self.gatherPsiStat(kern, X, Z, Y, beta, uncertain_inputs) - - #====================================================================== - # Compute Common Components - #====================================================================== - - try: - Kmm = kern.K(Z).copy() - if Kuu_sigma is not None: - diag.add(Kmm, Kuu_sigma) - else: - diag.add(Kmm, self.const_jitter) - Lm = jitchol(Kmm) - - LmInv = dtrtri(Lm) - LmInvPsi2LmInvT = LmInv.dot(psi2.dot(LmInv.T)) - - Lambda = np.eye(Kmm.shape[0])+LmInvPsi2LmInvT - LL = jitchol(Lambda) - LLInv = dtrtri(LL) - flag = np.zeros((1,),dtype=np.int32) - self.mpi_comm.Bcast(flag,root=self.root) - except LinAlgError as e: - flag = np.ones((1,),dtype=np.int32) - self.mpi_comm.Bcast(flag,root=self.root) - raise e - - broadcastArrays([LmInv, LLInv],self.mpi_comm, self.root) - LmLLInv = LLInv.dot(LmInv) - - logdet_L = 2.*np.sum(np.log(np.diag(LL))) - b = psi1Y.dot(LmLLInv.T) - bbt = np.square(b).sum() - v = b.dot(LmLLInv) - LLinvPsi1TYYTPsi1LLinvT = tdot(b.T) - - if psi1S is not None: - psi1SLLinv = psi1S.dot(LmLLInv.T) - bbt_sum = np.square(psi1SLLinv).sum() - LLinvPsi1TYYTPsi1LLinvT_sum = tdot(psi1SLLinv.T) - bbt_sum, LLinvPsi1TYYTPsi1LLinvT_sum = reduceArrays([bbt_sum, LLinvPsi1TYYTPsi1LLinvT_sum], self.mpi_comm, self.root) - bbt += bbt_sum - LLinvPsi1TYYTPsi1LLinvT += LLinvPsi1TYYTPsi1LLinvT_sum - psi1SP = psi1SLLinv.dot(LmLLInv) - tmp = -LLInv.T.dot(LLinvPsi1TYYTPsi1LLinvT+output_dim*np.eye(input_dim)).dot(LLInv) - dL_dpsi2R = LmInv.T.dot(tmp+output_dim*np.eye(input_dim)).dot(LmInv)/2. - broadcastArrays([dL_dpsi2R], self.mpi_comm, self.root) - - #====================================================================== - # Compute log-likelihood - #====================================================================== - logL_R = -num_data_total*np.log(beta) - logL = -(output_dim*(num_data_total*log_2_pi+logL_R+psi0-np.trace(LmInvPsi2LmInvT))+YRY- bbt)/2.-output_dim*logdet_L/2. - - #====================================================================== - # Compute dL_dKmm - #====================================================================== - - dL_dKmm = dL_dpsi2R - output_dim* LmInv.T.dot(LmInvPsi2LmInvT).dot(LmInv)/2. - - #====================================================================== - # Compute the Posterior distribution of inducing points p(u|Y) - #====================================================================== - - wd_inv = backsub_both_sides(Lm, np.eye(input_dim)- backsub_both_sides(LL, np.identity(input_dim), transpose='left'), transpose='left') - post = Posterior(woodbury_inv=wd_inv, woodbury_vector=v.T, K=Kmm, mean=None, cov=None, K_chol=Lm) - - #====================================================================== - # Compute dL_dthetaL for uncertian input and non-heter noise - #====================================================================== - - dL_dthetaL = (YRY*beta + beta*output_dim*psi0 - num_data_total*output_dim*beta)/2. - beta*(dL_dpsi2R*psi2).sum() - beta*np.trace(LLinvPsi1TYYTPsi1LLinvT) - - #====================================================================== - # Compute dL_dpsi - #====================================================================== - - dL_dpsi0 = -output_dim * (beta * np.ones((num_data,)))/2. - - if uncertain_outputs: - m,s = Y.mean, Y.variance - dL_dpsi1 = beta*(np.dot(m,v)+Shalf[:,None]*psi1SP) - else: - dL_dpsi1 = beta*np.dot(Y,v) - - if uncertain_inputs: - dL_dpsi2 = beta* dL_dpsi2R - else: - dL_dpsi1 += np.dot(psi1,dL_dpsi2R)*2. - dL_dpsi2 = None - - if uncertain_inputs: - grad_dict = {'dL_dKmm': dL_dKmm, - 'dL_dpsi0':dL_dpsi0, - 'dL_dpsi1':dL_dpsi1, - 'dL_dpsi2':dL_dpsi2, - 'dL_dthetaL':dL_dthetaL} - else: - grad_dict = {'dL_dKmm': dL_dKmm, - 'dL_dKdiag':dL_dpsi0, - 'dL_dKnm':dL_dpsi1, - 'dL_dthetaL':dL_dthetaL} - - if uncertain_outputs: - m,s = Y.mean, Y.variance - psi1LmiLLi = psi1.dot(LmLLInv.T) - LLiLmipsi1Y = b.T - grad_dict['dL_dYmean'] = -m*beta+ psi1LmiLLi.dot(LLiLmipsi1Y) - grad_dict['dL_dYvar'] = beta/-2.+ np.square(psi1LmiLLi).sum(axis=1)/2 - - return post, logL, grad_dict - - def inference_nonroot(self, kern, X, Z, likelihood, Y,Y_metadata=None, Lm=None, dL_dKmm=None): - - num_data, output_dim = Y.shape - num_data_total = allReduceArrays([np.int32(num_data)], self.mpi_comm)[0] - - input_dim = Z.shape[0] - uncertain_inputs = isinstance(X, VariationalPosterior) - uncertain_outputs = isinstance(Y, VariationalPosterior) - beta = 1./np.fmax(likelihood.variance, 1e-6) - - psi0, psi2, YRY, psi1, psi1Y, Shalf, psi1S = self.gatherPsiStat(kern, X, Z, Y, beta, uncertain_inputs) - - flag = np.zeros((1,),dtype=np.int32) - self.mpi_comm.Bcast(flag,root=self.root) - if flag[0] == 1: raise LinAlgError('Linalg error!') - - LmInv, LLInv = np.empty((input_dim, input_dim)).T, np.empty((input_dim, input_dim)).T - broadcastArrays([LmInv, LLInv], self.mpi_comm, self.root) - LmLLInv = LLInv.dot(LmInv) - b = psi1Y.dot(LmLLInv.T) - v = b.dot(LmLLInv) - - if psi1S is not None: - psi1SLLinv = psi1S.dot(LmLLInv.T) - bbt_sum = np.square(psi1SLLinv).sum() - LLinvPsi1TYYTPsi1LLinvT_sum = tdot(psi1SLLinv.T) - reduceArrays([bbt_sum, LLinvPsi1TYYTPsi1LLinvT_sum], self.mpi_comm, self.root) - psi1SP = psi1SLLinv.dot(LmLLInv) - - dL_dpsi2R = np.empty((input_dim, input_dim)) - broadcastArrays([dL_dpsi2R], self.mpi_comm, self.root) - - dL_dpsi0 = -output_dim * (beta * np.ones((num_data,)))/2. - - if uncertain_outputs: - m,s = Y.mean, Y.variance - dL_dpsi1 = beta*(np.dot(m,v)+Shalf[:,None]*psi1SP) - else: - dL_dpsi1 = beta*np.dot(Y,v) - - if uncertain_inputs: - dL_dpsi2 = beta* dL_dpsi2R - else: - dL_dpsi1 += np.dot(psi1,dL_dpsi2R)*2. - dL_dpsi2 = None - - if uncertain_inputs: - grad_dict = {'dL_dKmm': None, - 'dL_dpsi0':dL_dpsi0, - 'dL_dpsi1':dL_dpsi1, - 'dL_dpsi2':dL_dpsi2, - 'dL_dthetaL':None} - else: - grad_dict = {'dL_dKmm': None, - 'dL_dKdiag':dL_dpsi0, - 'dL_dKnm':dL_dpsi1, - 'dL_dthetaL':None} - if uncertain_outputs: - m,s = Y.mean, Y.variance - psi1LmiLLi = psi1.dot(LmLLInv.T) - LLiLmipsi1Y = b.T - grad_dict['dL_dYmean'] = -m*beta+ psi1LmiLLi.dot(LLiLmipsi1Y) - grad_dict['dL_dYvar'] = beta/-2.+ np.square(psi1LmiLLi).sum(axis=1)/2 - - return None, 0, grad_dict - - - - - diff --git a/deepgp/layers/enclayer.py b/deepgp/layers/enclayer.py index 3e943a3..deb0a6a 100644 --- a/deepgp/layers/enclayer.py +++ b/deepgp/layers/enclayer.py @@ -6,6 +6,7 @@ from GPy import Param from GPy.core.parameterization.transformations import Logexp from GPy.core.parameterization.variational import VariationalPosterior +from deepgp.util.util import reject_mpi_comm class EncoderLayer(Parameterized): @@ -20,7 +21,7 @@ class EncoderLayer(Parameterized): def __init__(self, layer, direction='bottom_up', encoder='mlp', encoder_dims=None, mpi_comm=None, mpi_root=0, name='encoder'): super(EncoderLayer, self).__init__(name=name) - self.mpi_comm, self.mpi_root = mpi_comm, mpi_root + reject_mpi_comm(mpi_comm) self.layer = layer self.direction = direction if direction=='bottom_up': @@ -44,10 +45,6 @@ def __init__(self, layer, direction='bottom_up', encoder='mlp', encoder_dims=Non raise Exception('Unsupported encoder type: '+encoder) self.Y_var_common = Param('Y_var', self.Y.variance.values[1].copy(),Logexp()) - # Synchronize across MPI nodes - if self.mpi_comm is not None: - from ..util.parallel import broadcastArrays - broadcastArrays([self.encoder.param_array, self.Y_var_common], self.mpi_comm, self.mpi_root) self.link_parameters(self.encoder, self.Y_var_common) @property @@ -88,10 +85,3 @@ def update_gradients(self): """ if self.uncertain_input: self.X.mean.gradient += X_grad - - def _gather_gradients(self): - # mpi4py infers MPI datatypes from NumPy buffers (CIP-0001 R8). - enc_grad = self.encoder.gradient - self.mpi_comm.Reduce(enc_grad.copy(), enc_grad, root=self.mpi_root) - y_grad = self.Y_var.gradient - self.mpi_comm.Reduce(y_grad.copy(), y_grad, root=self.mpi_root) diff --git a/deepgp/layers/layers.py b/deepgp/layers/layers.py index 79e840f..49c742c 100644 --- a/deepgp/layers/layers.py +++ b/deepgp/layers/layers.py @@ -10,11 +10,19 @@ from GPy import kern from GPy.core.parameterization.variational import NormalPosterior, VariationalPosterior from deepgp.util.variational import NormalEntropy,NormalPrior -from deepgp.util.parallel import reduceArrays +from deepgp.util.util import reject_mpi_comm +from ..functional import route_gradients, qx_gradients from GPy.inference.latent_function_inference.posterior import Posterior -class SparseGP_MPI(SparseGP): - +class SparseGPLayer(SparseGP): + """Sparse GP that serves as the base of every DeepGP layer. + + ``mpi_comm`` and ``mpi_root`` are accepted for one further release so that + existing calls keep working; any non-``None`` communicator raises + ``TypeError`` (CIP-0001 R23, CIP-0003). Use ``psi_chunk_size`` and + ``psi_threads`` for single-machine scaling. + """ + def __init__(self, X, Y, Z, kernel, likelihood, mean_function=None, inference_method=None, name='sparse gp', Y_metadata=None, @@ -23,37 +31,34 @@ def __init__(self, X, Y, Z, kernel, likelihood, mpi_root=0, auto_update=True, psi_chunk_size=None, - psi_threads=1): - self.mpi_comm = mpi_comm - self.mpi_root = mpi_root + psi_threads=1, + sparse_linalg='stable'): + reject_mpi_comm(mpi_comm) self.psi_chunk_size = psi_chunk_size self.psi_threads = 1 if psi_threads is None else int(psi_threads) - self.psicov = False self.svi = False self.qU_ratio = 1. self.auto_update = auto_update if inference_method is None: - from ..inference import VarDTC_parallel, VarDTC - if mpi_comm is None: - inference_method = VarDTC(psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads) - else: - inference_method = VarDTC_parallel(mpi_comm, mpi_root) - elif inference_method=='inferentia' and mpi_comm is None: - from ..inference import VarDTC_Inferentia - inference_method = VarDTC_Inferentia() - self.psicov = True + from ..inference import VarDTC + inference_method = VarDTC(psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads, + sparse_linalg=sparse_linalg) + elif inference_method=='inferentia': + raise NotImplementedError( + "inference_method='inferentia' is not shipped in this repository; " + "use the default VarDTC (or 'svi').") elif inference_method=='svi': from ..inference import SVI_VarDTC inference_method = SVI_VarDTC(psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads) self.svi = True - super(SparseGP_MPI, self).__init__(X, Y, Z, kernel, - likelihood, - mean_function=mean_function, - inference_method=inference_method, - name=name, Y_metadata=Y_metadata, - normalizer=normalizer) + super(SparseGPLayer, self).__init__(X, Y, Z, kernel, + likelihood, + mean_function=mean_function, + inference_method=inference_method, + name=name, Y_metadata=Y_metadata, + normalizer=normalizer) from ..util.psi_chunking import apply_psi_chunking apply_psi_chunking(self, psi_chunk_size, self.psi_threads) @@ -79,98 +84,35 @@ def _inference_vardtc(self): self.qU_var = tdot(self.qU_W)+np.eye(self.Z.shape[0])*self.qU_a self.posterior, self._log_marginal_likelihood, self.grad_dict = self.inference_method.inference(self.kern, self.X, self.Z, self.likelihood, self.Y, self.qU_mean , self.qU_var, Kuu_sigma=self.Kuu_sigma) - if self.mpi_comm is None or (self.mpi_comm is not None and self.mpi_comm.rank==self.mpi_root): - KL, dKL_dqU_mean, dKL_dqU_var, dKL_dKuu = self.inference_method.comp_KL_qU(self.qU_mean ,self.qU_var) - self._log_marginal_likelihood += -KL*self.qU_ratio - self.grad_dict['dL_dqU_mean'] += -dKL_dqU_mean*self.qU_ratio - self.grad_dict['dL_dqU_var'] += -dKL_dqU_var*self.qU_ratio - self.grad_dict['dL_dKmm'] += -dKL_dKuu*self.qU_ratio + KL, dKL_dqU_mean, dKL_dqU_var, dKL_dKuu = self.inference_method.comp_KL_qU(self.qU_mean ,self.qU_var) + self._log_marginal_likelihood += -KL*self.qU_ratio + self.grad_dict['dL_dqU_mean'] += -dKL_dqU_mean*self.qU_ratio + self.grad_dict['dL_dqU_var'] += -dKL_dqU_var*self.qU_ratio + self.grad_dict['dL_dKmm'] += -dKL_dKuu*self.qU_ratio else: self.posterior, self._log_marginal_likelihood, self.grad_dict = self.inference_method.inference(self.kern, self.X, self.Z, self.likelihood, self.Y, self.Y_metadata, Kuu_sigma=self.Kuu_sigma if hasattr(self, 'Kuu_sigma') else None) self.likelihood.update_gradients(self.grad_dict['dL_dthetaL']) dL_dKmm = self.grad_dict['dL_dKmm'] - if (self.mpi_comm is None or (self.mpi_comm is not None and self.mpi_comm.rank==self.mpi_root)) and (hasattr(self, 'Kuu_sigma') and self.Kuu_sigma is not None): + if hasattr(self, 'Kuu_sigma') and self.Kuu_sigma is not None: self.Kuu_sigma.gradient = np.diag(dL_dKmm) - if isinstance(self.X, VariationalPosterior): - #gradients wrt kernel - - if self.psicov: - self.kern.update_gradients_expectations_psicov(variational_posterior=self.X, - Z=self.Z, - dL_dpsi0=self.grad_dict['dL_dpsi0'], - dL_dpsi1=self.grad_dict['dL_dpsi1'], - dL_dpsicov=self.grad_dict['dL_dpsicov']) - else: - self.kern.update_gradients_expectations(variational_posterior=self.X, - Z=self.Z, - dL_dpsi0=self.grad_dict['dL_dpsi0'], - dL_dpsi1=self.grad_dict['dL_dpsi1'], - dL_dpsi2=self.grad_dict['dL_dpsi2']) - kerngrad = self.kern.gradient.copy() - if self.mpi_comm is None: - self.kern.update_gradients_full(dL_dKmm, self.Z, None) - kerngrad += self.kern.gradient.copy() - self.kern.gradient = kerngrad - else: - kerngrad = reduceArrays([kerngrad], self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank==self.mpi_root: - self.kern.update_gradients_full(dL_dKmm, self.Z, None) - kerngrad += self.kern.gradient.copy() - self.kern.gradient = kerngrad - - #gradients wrt Z - if self.psicov: - self.Z.gradient = self.kern.gradients_Z_expectations_psicov( - self.grad_dict['dL_dpsi0'], - self.grad_dict['dL_dpsi1'], - self.grad_dict['dL_dpsicov'], - Z=self.Z, - variational_posterior=self.X) - else: - self.Z.gradient = self.kern.gradients_Z_expectations( - self.grad_dict['dL_dpsi0'], - self.grad_dict['dL_dpsi1'], - self.grad_dict['dL_dpsi2'], - Z=self.Z, - variational_posterior=self.X) - if self.mpi_comm is None: - self.Z.gradient += self.kern.gradients_X(dL_dKmm, self.Z) - else: - self.Z.gradient = reduceArrays([self.Z.gradient], self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank == self.mpi_root: - self.Z.gradient += self.kern.gradients_X(dL_dKmm, self.Z) - else: - #gradients wrt kernel - self.kern.update_gradients_diag(self.grad_dict['dL_dKdiag'], self.X) - kerngrad = self.kern.gradient.copy() - self.kern.update_gradients_full(self.grad_dict['dL_dKnm'], self.X, self.Z) - kerngrad += self.kern.gradient - if self.mpi_comm is None: - self.kern.update_gradients_full(dL_dKmm, self.Z, None) - self.kern.gradient += kerngrad - else: - kerngrad = reduceArrays([kerngrad], self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank==self.mpi_root: - self.kern.update_gradients_full(dL_dKmm, self.Z, None) - kerngrad += self.kern.gradient.copy() - self.kern.gradient = kerngrad - #gradients wrt Z - self.Z.gradient = self.kern.gradients_X(self.grad_dict['dL_dKnm'].T, self.Z, self.X) - if self.mpi_comm is None: - self.Z.gradient += self.kern.gradients_X(dL_dKmm, self.Z) - else: - self.Z.gradient = reduceArrays([self.Z.gradient], self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank == self.mpi_root: - self.Z.gradient += self.kern.gradients_X(dL_dKmm, self.Z) + kerngrad, Zgrad = route_gradients( + self.kern, self.Z, self.X, dL_dKmm, + dL_dpsi0=self.grad_dict.get('dL_dpsi0'), + dL_dpsi1=self.grad_dict.get('dL_dpsi1'), + dL_dpsi2=self.grad_dict.get('dL_dpsi2'), + dL_dKdiag=self.grad_dict.get('dL_dKdiag'), + dL_dKnm=self.grad_dict.get('dL_dKnm')) + self.kern.gradient = kerngrad + self.Z.gradient = Zgrad if self.svi: self.qU_mean.gradient = self.grad_dict['dL_dqU_mean'] self.qU_W.gradient = (self.grad_dict['dL_dqU_var']+self.grad_dict['dL_dqU_var'].T).dot(self.qU_W) self.qU_a.gradient = np.diag(self.grad_dict['dL_dqU_var']).sum() -class Layer(SparseGP_MPI): +class Layer(SparseGPLayer): def __init__(self, layer_lower, dim_down, dim_up, @@ -201,10 +143,6 @@ def __init__(self, layer_lower, Z = np.vstack([X.copy(),Z_more]) assert Z.shape[1] == X.shape[1] - if mpi_comm is not None: - from ..util.parallel import broadcastArrays - broadcastArrays([Z], mpi_comm, mpi_root) - if uncertain_inputs: X = NormalPosterior(X, X_variance) if kernel is None: kernel = kern.RBF(dim_up, ARD = True) assert kernel.input_dim==X.shape[1], "The dimensionality of input has to be equal to the input dimensionality of the kernel!" @@ -249,24 +187,10 @@ def Y_vals(self): return self.Y if self.layer_lower is None else self.layer_lower.X.mean def update_qX_gradients(self): - if self.psicov: - self.X.mean.gradient, self.X.variance.gradient = self.kern.gradients_qX_expectations_psicov( - variational_posterior=self.X, - Z=self.Z, - dL_dpsi0=self.grad_dict['dL_dpsi0'], - dL_dpsi1=self.grad_dict['dL_dpsi1'], - dL_dpsicov=self.grad_dict['dL_dpsicov']) - else: - self.X.mean.gradient, self.X.variance.gradient = self.kern.gradients_qX_expectations( - variational_posterior=self.X, - Z=self.Z, - dL_dpsi0=self.grad_dict['dL_dpsi0'], - dL_dpsi1=self.grad_dict['dL_dpsi1'], - dL_dpsi2=self.grad_dict['dL_dpsi2']) + self.X.mean.gradient, self.X.variance.gradient = qx_gradients( + self.kern, self.Z, self.X, self.grad_dict['dL_dpsi0'], + self.grad_dict['dL_dpsi1'], self.grad_dict['dL_dpsi2']) delta = -self.variationalterm.comp_value(self.X) - if self.mpi_comm is not None: - delta = reduceArrays([np.float64(delta)],self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank != self.mpi_root: delta = 0. self._log_marginal_likelihood += delta self.variationalterm.update_gradients(self.X) @@ -403,7 +327,6 @@ def from_TopHiddenLayer(layer, name='hiddenlayer'): inference_method=None, encoder=encoder, noise_var=noise_var, back_constraint=layer.back_constraint, - mpi_comm=layer.mpi_comm, mpi_root=layer.mpi_root, auto_update=layer.auto_update, name=name) class TopHiddenLayer(Layer): @@ -436,3 +359,14 @@ def update_layer(self): super(TopHiddenLayer,self).update_layer() self.Y.mean.gradient += self.grad_dict['dL_dYmean'] self.Y.variance.gradient += self.grad_dict['dL_dYvar'][:,None] + + +def __getattr__(name): + # Deprecated alias (CIP-0003): the MPI base class is gone. + if name == 'SparseGP_MPI': + import warnings + warnings.warn( + "SparseGP_MPI is deprecated and no longer supports MPI; " + "use SparseGPLayer.", FutureWarning, stacklevel=2) + return SparseGPLayer + raise AttributeError("module %r has no attribute %r" % (__name__, name)) diff --git a/deepgp/layers/mrd.py b/deepgp/layers/mrd.py index 8b9ea89..16a9562 100644 --- a/deepgp/layers/mrd.py +++ b/deepgp/layers/mrd.py @@ -1,7 +1,7 @@ import numpy as np -from .layers import SparseGP_MPI +from .layers import SparseGPLayer from GPy.core import Parameterized from GPy.core import SparseGP from GPy import likelihoods @@ -10,9 +10,10 @@ from GPy.util.initialization import initialize_latent from deepgp.util.variational import NormalEntropy,NormalPrior -from deepgp.util.parallel import reduceArrays +from deepgp.util.util import reject_mpi_comm +from ..functional import qx_gradients, aggregate_qx, disaggregate_qx_gradients -class MRDView(SparseGP_MPI): +class MRDView(SparseGPLayer): def __init__(self, Y, dim_down, dim_up, likelihood, MLP_dims=None, X=None, X_variance=None, init='rand', Z=None, num_inducing=10, kernel=None, inference_method=None, uncertain_inputs=True,mpi_comm=None, mpi_root=0, back_constraint=True, name='mrd-view'): @@ -74,12 +75,9 @@ def update_encoder_gradients(self): def update_qX_gradients(self): # Self.Xv is a placeholder for the gradient part... but we actually use the self.X for the value part (see the 'variational_posterior=' argument below) - self.Xv.mean.gradient, self.Xv.variance.gradient = self.kern.gradients_qX_expectations( - variational_posterior=self.X, - Z=self.Z, - dL_dpsi0=self.grad_dict['dL_dpsi0'], - dL_dpsi1=self.grad_dict['dL_dpsi1'], - dL_dpsi2=self.grad_dict['dL_dpsi2']) + self.Xv.mean.gradient, self.Xv.variance.gradient = qx_gradients( + self.kern, self.Z, self.X, self.grad_dict['dL_dpsi0'], + self.grad_dict['dL_dpsi1'], self.grad_dict['dL_dpsi2']) def update_gradients(self): super(MRDView, self).parameters_changed() @@ -120,7 +118,7 @@ def __init__(self, dim_down, dim_up, likelihood, MLP_dims=None, X=None, X_varian "hidden widths, or None for the default encoder width)." ) super(MRDLayer, self).__init__(name=name) - self.mpi_comm, self.mpi_root = mpi_comm, mpi_root + reject_mpi_comm(mpi_comm) self.back_constraint = True if back_constraint else False @@ -141,6 +139,10 @@ def __init__(self, dim_down, dim_up, likelihood, MLP_dims=None, X=None, X_varian self.link_parameters(*self.views) for v in self.views: v.X = self.X self.link_parameters(self.X) + if self.back_constraint: + # q(X) is derived from the view encoders on every update, so it is not free. + self.X.mean.fix(warning=False) + self.X.variance.fix(warning=False) def _aggregate_qX(self): @@ -151,12 +153,11 @@ def _aggregate_qX(self): self.X.mean[:] = 0 self.X.variance[:] = 0 - self.prec_denom = np.zeros_like(self.X.variance.values) - for v in self.views: - self.prec_denom += 1./v.Xv.variance.values - self.X.mean += v.Xv.mean.values/v.Xv.variance.values - self.X.mean /= self.prec_denom - self.X.variance[:] = 1./self.prec_denom + mean, var, self.prec_denom = aggregate_qx( + [v.Xv.mean.values for v in self.views], + [v.Xv.variance.values for v in self.views]) + self.X.mean[:] = mean + self.X.variance[:] = var else: for v in self.views: v.X = self.X @@ -182,19 +183,19 @@ def plot_latent(self, labels=None, which_indices=None, def update_qX_gradients(self): delta = -self.variationalterm.comp_value(self.X) - if self.mpi_comm is not None: - delta = reduceArrays([np.float64(delta)],self.mpi_comm, self.mpi_root)[0] - if self.mpi_comm.rank != self.mpi_root: delta = 0 self._log_marginal_likelihood += delta self.variationalterm.update_gradients(self.X) def update_encoder_gradients(self): if self.uncertain_inputs: - for v in self.views: - c = 1./(self.prec_denom*v.Xv.variance.values) - v.Xv.mean.gradient[:] = c*self.X.mean.gradient - v.Xv.variance.gradient[:] = np.square(c)*self.X.variance.gradient +\ - c*(self.X.mean.values-v.Xv.mean.values)/v.Xv.variance.values*self.X.mean.gradient + grads = disaggregate_qx_gradients( + [v.Xv.mean.values for v in self.views], + [v.Xv.variance.values for v in self.views], + self.prec_denom, self.X.mean.values, + self.X.mean.gradient, self.X.variance.gradient) + for v, (dm, dv) in zip(self.views, grads): + v.Xv.mean.gradient[:] = dm + v.Xv.variance.gradient[:] = dv v.update_encoder_gradients() def parameters_changed(self): diff --git a/deepgp/models/__init__.py b/deepgp/models/__init__.py index 3607766..5afe1fd 100644 --- a/deepgp/models/__init__.py +++ b/deepgp/models/__init__.py @@ -1,4 +1,5 @@ # Copyright (c) 2015-2016, the authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) -from .model import DeepGP \ No newline at end of file +from .model import DeepGP +from .uncollapsed import DoublyStochasticDeepGP diff --git a/deepgp/models/model.py b/deepgp/models/model.py index f631299..9519b13 100644 --- a/deepgp/models/model.py +++ b/deepgp/models/model.py @@ -9,10 +9,7 @@ from GPy import Model, likelihoods from GPy.core.parameterization.variational import VariationalPosterior, NormalPosterior from ..layers import ObservedLayer, ObservedMRDLayer, HiddenLayer, TopHiddenLayer - -_MPI_DEPRECATION = ( - "MPI support is deprecated; use chunked psi-statistics (see CIP-0001)." -) +from ..util.util import reject_mpi_comm class DeepGP(Model): """ @@ -25,6 +22,17 @@ class DeepGP(Model): m = deepgp.DeepGP(..., repeatX=True) """ + def __new__(cls, *args, **kwargs): + # inference_method='doubly_stochastic' selects the uncollapsed family (CIP-0003 + # Phase 4). It is a different parameterisation (whitened q(u) per layer), so it + # returns that model rather than a DeepGP; the default is unchanged. + if kwargs.get('inference_method') == 'doubly_stochastic': + from .uncollapsed import DoublyStochasticDeepGP + kwargs = dict(kwargs) + del kwargs['inference_method'] + return DoublyStochasticDeepGP(*args, **kwargs) + return super(DeepGP, cls).__new__(cls) + def __init__(self, nDims, Y, X=None, num_inducing=10, likelihood = None, inits='PCA', name='deepgp', kernels=None, obs_data='cont', back_constraint=True, @@ -32,24 +40,13 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, inference_method=None, psi_chunk_size=None, psi_threads=1, **kwargs): super(DeepGP, self).__init__(name=name) - self._IN_OPTIMIZATION_ = False # Back-forward compatibility with old interface if encoder_dims is None and 'MLP_dims' in kwargs: encoder_dims = kwargs['MLP_dims'] - # CIP-0001 Phase 2: deprecate MPI; refuse silently-wrong configurations. - if mpi_comm is not None: - warnings.warn(_MPI_DEPRECATION, FutureWarning, stacklevel=2) - if not back_constraint: - raise ValueError( - "mpi_comm is not supported with back_constraint=False: " - "per-data-point variational parameters are not synchronised " - "under the root-broadcast design, so results would be wrong. " - "Use back_constraint=True, or omit mpi_comm (see CIP-0001)." - ) - - self.mpi_comm, self.mpi_root = mpi_comm, mpi_root + # MPI was removed (CIP-0001, CIP-0003); the arguments are kept for compatibility. + reject_mpi_comm(mpi_comm) self.psi_chunk_size = psi_chunk_size self.psi_threads = 1 if psi_threads is None else int(psi_threads) self.obs_data = obs_data @@ -100,6 +97,8 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, # Parameters which exist differently per layer but specified as single componenents are here expanded to each layer if not isinstance(num_inducing, list or tuple): num_inducing = [num_inducing]*self.nLayers if not isinstance(inits, list or tuple): inits = [inits]*self.nLayers + from ..util.util import validate_init + for _init in inits: validate_init(_init, mrd=mrd_flag) # Initialize Layers self.layers = [] @@ -116,12 +115,9 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, init=inits[i], kernel=kernels[i] if kernels is not None else None, back_constraint=back_constraint, - MLP_dims=mrd_mlp_dims, - mpi_comm=mpi_comm, - mpi_root=mpi_root)) + MLP_dims=mrd_mlp_dims)) else: if self.X_observed and self.repeatX: - # self.layers.append(ObservedLayer(nDims[0],nDims[1], Y, X=Xs[i], likelihood=likelihood, num_inducing=num_inducing[i], init=inits[i], kernel=kernels[i] if kernels is not None else None, back_constraint=back_constraint, inference_method=inference_method, mpi_comm=mpi_comm, mpi_root=mpi_root)) self.layers.append(ObservedLayer(nDims[0], Xs[i].shape[1], Y, X=Xs[i], likelihood=likelihood, @@ -130,8 +126,6 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, kernel=kernels[i] if kernels is not None else None, back_constraint=back_constraint, inference_method=inference_method, - mpi_comm=mpi_comm, - mpi_root=mpi_root, auto_update=auto_update, repeatX=True, repeatXsplit=self.nDimsOrig[1], @@ -148,7 +142,6 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, kernel=kernels[i] if kernels is not None else None, back_constraint=back_constraint, inference_method=inference_method, - mpi_comm=mpi_comm, mpi_root=mpi_root, auto_update=auto_update, psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads)) @@ -167,7 +160,6 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, kernel=kernels[i] if kernels is not None else None, back_constraint=True if uncertain_inputs and back_constraint else False, inference_method=inference_method, - mpi_comm=mpi_comm, mpi_root=mpi_root, auto_update=auto_update, psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads)) @@ -179,7 +171,6 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, kernel=kernels[i] if kernels is not None else None, back_constraint=back_constraint, inference_method=inference_method, - mpi_comm=mpi_comm, mpi_root=mpi_root, auto_update=auto_update, psi_chunk_size=psi_chunk_size, psi_threads=self.psi_threads)) @@ -193,24 +184,18 @@ def __init__(self, nDims, Y, X=None, num_inducing=10, self.enclayers = [EncoderLayer(self.layers[i], direction=direction, encoder_dims=encoder_dims[i-1] if encoder_dims is not None else None, - mpi_comm = mpi_comm, - mpi_root=mpi_root, name='enclayer_'+str(i)) for i in range(self.nLayers-1,0,-1)] else: # For MRD, layer 0 owns per-view encoders inside ObservedMRDLayer; # EncoderLayer starts at layer 1 (CIP-0002 Phase C). enc_start = 1 if mrd_flag else 0 - self.enclayers = [ EncoderLayer(self.layers[i], direction=direction, encoder_dims=encoder_dims[i] if encoder_dims is not None else None, mpi_comm = mpi_comm, mpi_root=mpi_root, - name='enclayer_'+str(i)) for i in range(enc_start, self.nLayers)] + self.enclayers = [ EncoderLayer(self.layers[i], direction=direction, encoder_dims=encoder_dims[i] if encoder_dims is not None else None, name='enclayer_'+str(i)) for i in range(enc_start, self.nLayers)] self.link_parameters(*(self.enclayers+self.layers)) else: self.link_parameters(*self.layers) if self.X_observed and self.repeatX: self.ensure_repeatX_constraints() - if self.mpi_comm is not None: - from deepgp.util.parallel import broadcastArrays - broadcastArrays([self.param_array], self.mpi_comm, self.mpi_root) @property def Y(self): @@ -286,8 +271,6 @@ def parameters_changed(self): if self._mrd and hasattr(self.layers[0], 'update_encoder_gradients'): self.layers[0].update_encoder_gradients() [l.update_gradients() for l in self.enclayers[::-1]] - if self.mpi_comm is not None: - [l._gather_gradients() for l in self.enclayers] def add_layer(self, dim_up, X=None, X_variance=None, Z=None, @@ -313,8 +296,6 @@ def add_layer(self, dim_up, X=None, num_inducing=num_inducing, name='layer_'+str(self.nLayers), init=init, kernel=kernel, noise_var=noise_var, - mpi_comm=self.mpi_comm, - mpi_root=self.mpi_root, back_constraint=back_constraint, X=X, X_variance=X_variance, Z=Z, uncertain_inputs=uncertain_inputs, @@ -341,31 +322,10 @@ def gen_pred_model(self, Y=None, init_X='encoder', binObserved=False): ) def collect_all_XY(self, root=0): - if self.mpi_comm is None: - XY = [self.obslayer.Y.copy()] - for l in self.layers: XY.append(l.X.copy()) - return XY - else: - from mpi4py import MPI - from GPy.core.parameterization.variational import NormalPosterior - N,D = self.Y.shape - N_list = np.array(self.mpi_comm.allgather(N)) - N_all = np.sum(N_list) - Y_all = np.empty((N_all,D)) if self.mpi_comm.rank==root else None - self.mpi_comm.Gatherv([self.Y, MPI.DOUBLE], [Y_all, (N_list*D, None), MPI.DOUBLE], root=root) - if self.mpi_comm.rank==root: - XY = [Y_all] - for l in self.layers: - Q = l.X.shape[1] - X_mean_all = np.empty((N_all,Q)) if self.mpi_comm.rank==root else None - self.mpi_comm.Gatherv([l.X.mean.values, MPI.DOUBLE], [X_mean_all, (N_list*Q, None), MPI.DOUBLE], root=root) - X_var_all = np.empty((N_all,Q)) if self.mpi_comm.rank==root else None - self.mpi_comm.Gatherv([l.X.variance.values, MPI.DOUBLE], [X_var_all, (N_list*Q, None), MPI.DOUBLE], root=root) - if self.mpi_comm.rank==root: - XY.append(NormalPosterior(X_mean_all, X_var_all)) - if self.mpi_comm.rank==root: return XY - else: return None - + XY = [self.obslayer.Y.copy()] + for l in self.layers: XY.append(l.X.copy()) + return XY + def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None): """Make a prediction from the deep Gaussian process model for a given input""" from GPy.core.parameterization.variational import NormalPosterior @@ -389,38 +349,6 @@ def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None): x = NormalPosterior(mean, var) return self.layers[0].predict(x) - @Model.optimizer_array.setter - def optimizer_array(self, p): - if self.mpi_comm != None: - if self._IN_OPTIMIZATION_ and self.mpi_comm.rank==self.mpi_root: - self.mpi_comm.Bcast(np.int32(1),root=self.mpi_root) - self.mpi_comm.Bcast(p, root=self.mpi_root) - Model.optimizer_array.fset(self,p) - - def optimize(self, optimizer=None, start=None, **kwargs): - self._IN_OPTIMIZATION_ = True - if self.mpi_comm is None: - super(DeepGP, self).optimize(optimizer,start,**kwargs) - elif self.mpi_comm.rank==self.mpi_root: - super(DeepGP, self).optimize(optimizer,start,**kwargs) - self.mpi_comm.Bcast(np.int32(-1),root=self.mpi_root) - elif self.mpi_comm.rank!=self.mpi_root: - x = self.optimizer_array.copy() - flag = np.empty(1,dtype=np.int32) - while True: - self.mpi_comm.Bcast(flag,root=self.mpi_root) - if flag==1: - try: - self.optimizer_array = x - except (LinAlgError, ZeroDivisionError, ValueError): - pass - elif flag==-1: - break - else: - self._IN_OPTIMIZATION_ = False - raise Exception("Unrecognizable flag for synchronization!") - self._IN_OPTIMIZATION_ = False - def predict_withSamples(self, X, nSamples=100): y_mean, y_var = self.layers[-1].predict(X) diff --git a/deepgp/models/uncollapsed.py b/deepgp/models/uncollapsed.py new file mode 100644 index 0000000..c98ded4 --- /dev/null +++ b/deepgp/models/uncollapsed.py @@ -0,0 +1,240 @@ +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""Doubly stochastic (uncollapsed) deep GP as a GPy model (CIP-0003 Phase 4). + +A thin shell over :mod:`deepgp.functional.doubly_stochastic`: it holds the +parameters (kernels, inducing inputs, whitened ``q(u)``, noise) as GPy objects and +calls the pure functions. ``X=None`` gives the unsupervised model with latent ``q(X)``. + +``nDims`` follows ``DeepGP``: ``[D_y, ..., D_x]``, output first. ``kernels`` follows +the same order, so ``kernels[0]`` is the layer that produces ``Y``. + +Randomness is explicit. The model holds a frozen set of standard normal draws +``eps`` so that the objective is deterministic (``checkgrad`` and ``optimize`` +work). Call :meth:`resample` to draw new ones from the seeded generator, and +:meth:`fit_minibatch` to do so every step. +""" + +import numpy as np +import GPy +from GPy import Model +from GPy.core.parameterization import Param, Parameterized +from GPy.core.parameterization.transformations import Logexp +from GPy.util import choleskies +from GPy.util.pca import PCA + +from ..functional import (doubly_stochastic_bound, whitened_marginals, reparam_sample, + whitened_natgrad_step) + + +class WhitenedLayer(Parameterized): + """Parameters of one whitened sparse-GP layer.""" + + def __init__(self, kern, Z, q_mu, q_chol, residual=False, name='whitened_layer'): + super(WhitenedLayer, self).__init__(name=name) + self.kern = kern + self.Z = Param('Z', Z) + self.q_mu = Param('q_u_mean', q_mu) + self.q_chol_flat = Param('q_u_chol', choleskies.triang_to_flat(q_chol)) + self.residual = residual + self.link_parameters(self.kern, self.Z, self.q_mu, self.q_chol_flat) + + @property + def q_chol(self): + return choleskies.flat_to_triang(self.q_chol_flat.values) + + def as_dict(self): + return dict(kern=self.kern, Z=self.Z.values, q_mu=self.q_mu.values, + q_chol=self.q_chol, residual=self.residual) + + +class DoublyStochasticDeepGP(Model): + """Deep GP trained with doubly stochastic variational inference. + + With ``X=None`` the model is unsupervised: the bottom inputs are latent with + ``q(X) = N(X_mean, diag(X_var))``, initialised by PCA of ``Y`` (``nDims[-1]`` is the latent + width), sampled by reparameterisation, and regularised by ``KL(q(X) || N(0, I))``. + + :param nDims: ``[D_y, ..., D_x]``; hidden widths in between. + :param Y: ``(N, D_y)``; :param X: ``(N, D_x)``, or ``None`` for the unsupervised model. + :param kernels: optional list in ``nDims`` order (``kernels[0]`` produces ``Y``). + :param residual: identity mean function on hidden layers where widths allow. + :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. + """ + + 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'): + super(DoublyStochasticDeepGP, self).__init__(name=name) + dims = list(nDims)[::-1] # input side first + self.Y_all = np.asarray(Y, float) + self.unsupervised = X is None + if dims[-1] != self.Y_all.shape[1]: + raise ValueError("nDims %s does not match Y (%d)" % (list(nDims), self.Y_all.shape[1])) + if not self.unsupervised: + if dims[0] != X.shape[1]: + raise ValueError("nDims %s does not match X (%d)" % (list(nDims), X.shape[1])) + if X.shape[0] != Y.shape[0]: + raise ValueError("X and Y must have the same number of rows") + self.rng = np.random.RandomState(seed) + self.N = self.Y_all.shape[0] + if self.unsupervised: + if len(dims) < 2 or dims[0] > self.Y_all.shape[1]: + raise ValueError("latent width %d must be at most the number of outputs %d" + % (dims[0], self.Y_all.shape[1])) + x0 = PCA(self.Y_all).project(self.Y_all, dims[0]) + x0 = (x0 - x0.mean(0)) / (x0.std(0) + 1e-12) + self.X_all = x0 + else: + self.X_all = np.asarray(X, float) + self.n_samples, self.batch_size, self.jitter = n_samples, batch_size, jitter + self.idx = np.arange(self.N) + L = len(dims) - 1 + kernels = None if kernels is None else list(kernels)[::-1] + + # Hidden representations initialised by PCA of Y, as in DeepGP. + H = [self.X_all] + for w in dims[1:-1]: + p = PCA(self.Y_all) + h = p.project(self.Y_all, min(w, self.Y_all.shape[1])) + full = self.rng.randn(self.N, w) * 0.1 + full[:, :h.shape[1]] = h + H.append((full - full.mean(0)) / (full.std(0) + 1e-12)) + + self.layers = [] + for i in range(L): + Q, P = dims[i], dims[i + 1] + 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) + Z = H[i][self.rng.permutation(self.N)[:M]].copy() + hidden = i < L - 1 + s = q_sqrt_hidden if hidden else 1. + q_chol = np.stack([np.eye(M) * s for _ in range(P)]) + self.layers.append(WhitenedLayer(kern, Z, np.zeros((M, P)), q_chol, + residual=bool(residual and hidden and Q == P), + name='layer_%d' % i)) + self.noise_variance = Param('noise_variance', noise_var, Logexp()) + if self.unsupervised: + self.X_mean = Param('X_mean', self.X_all.copy()) + self.X_var = Param('X_var', np.full(self.X_all.shape, q_sqrt_x ** 2), Logexp()) + self.link_parameters(self.X_mean, self.X_var) + self.link_parameters(*(self.layers + [self.noise_variance])) + self.resample() + + # --- randomness ------------------------------------------------------- + def resample(self, seed=None): + """Draw a fresh frozen set of ``eps`` (optionally reseeding the generator).""" + if seed is not None: + self.rng = np.random.RandomState(seed) + n = len(self.idx) + widths = [l.q_mu.shape[1] for l in self.layers[:-1]] + self.eps = [[self.rng.randn(n, w) for w in widths] for _ in range(self.n_samples)] + if self.unsupervised: + self.eps_x = [self.rng.randn(n, self.X_all.shape[1]) for _ in range(self.n_samples)] + self.parameters_changed() + + def set_batch(self, idx=None): + """Use rows ``idx`` of the data (``None`` = all); draws new ``eps`` of the right size.""" + self.idx = np.arange(self.N) if idx is None else np.asarray(idx) + self.resample() + + # --- GPy model interface --------------------------------------------- + def parameters_changed(self): + if not hasattr(self, 'eps'): + return + Y = self.Y_all[self.idx] + layers = [l.as_dict() for l in self.layers] + extra = {} + if self.unsupervised: + X = self.X_mean.values[self.idx] + extra = dict(x_var=self.X_var.values[self.idx], eps_x=self.eps_x) + else: + X = self.X_all[self.idx] + bound, g = doubly_stochastic_bound(layers, X, Y, float(self.noise_variance.values[0]), self.eps, + jitter=self.jitter, scale=self.N / float(len(self.idx)), + **extra) + if self.unsupervised: + gm, gv = np.zeros_like(self.X_all), np.zeros_like(self.X_all) + gm[self.idx], gv[self.idx] = g['X'], g['x_var'] + self.X_mean.gradient, self.X_var.gradient = gm, gv + self._log_marginal_likelihood = bound + self._natgrad = g['natgrad'] + for layer, gl in zip(self.layers, g['layers']): + layer.kern.gradient = gl['kern'] + layer.Z.gradient = gl['Z'] + layer.q_mu.gradient = gl['q_mu'] + layer.q_chol_flat.gradient = choleskies.triang_to_flat(gl['q_chol']) + self.noise_variance.gradient = g['noise_var'] + + def log_likelihood(self): + return self._log_marginal_likelihood + + # --- training --------------------------------------------------------- + def fit_minibatch(self, steps=200, batch_size=None, lr=0.01, beta1=0.9, beta2=0.999, + seed=None, callback=None, natgrad_gamma=0.): + """Adam on minibatches; fresh batch and ``eps`` every step, from the model's generator. + + Parameters are updated in GPy's unconstrained space. At the end the full batch + is restored and ``eps`` redrawn. Returns the list of per-step bounds. + + With ``natgrad_gamma > 0`` the top layer's ``q(u)`` takes a natural-gradient step of + that size (see ``whitened_natgrad_step``) instead of an Adam step, and everything + else stays on Adam: the hybrid scheme of Salimbeni, Eleftheriadis and Hensman (2018). + """ + if seed is not None: + self.rng = np.random.RandomState(seed) + B = batch_size or self.batch_size or self.N + theta = self.optimizer_array.copy() + m, v, history = np.zeros_like(theta), np.zeros_like(theta), [] + for t in range(1, steps + 1): + self.idx = self.rng.permutation(self.N)[:B] + self.resample() + obj_grad = -self._log_likelihood_gradients() # gradient of minimised objective + if natgrad_gamma > 0.: + top = self.layers[-1] + new_mu, new_chol = whitened_natgrad_step( + 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) + 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) + self.optimizer_array = theta + if natgrad_gamma > 0.: + top.q_mu[:] = new_mu + top.q_chol_flat[:] = new_flat + theta = self.optimizer_array.copy() + history.append(self._log_marginal_likelihood) + if callback is not None: + callback(t, history[-1]) + self.set_batch(None) + return history + + # --- prediction -------------------------------------------------------- + def predict(self, Xnew, n_samples=None, seed=None): + """Mean and variance of ``y`` at ``Xnew`` from a Monte Carlo mixture over hidden layers. + + Variance includes the noise. Uses its own generator (``seed``) so the training + ``eps`` are not disturbed. + """ + S = n_samples or max(self.n_samples, 20) + rng = np.random.RandomState(0 if seed is None else seed) + means, vars_ = [], [] + for _ in range(S): + h = np.asarray(Xnew, float) + for l, layer in enumerate(self.layers): + d = layer.as_dict() + mu, var, _ = whitened_marginals(d['kern'], d['Z'].copy(), h.copy(), + d['q_mu'], d['q_chol'], self.jitter) + if d['residual']: + mu = mu + h + if l < len(self.layers) - 1: + h = reparam_sample(mu, var, rng.randn(*mu.shape)) + means.append(mu); vars_.append(var) + means, vars_ = np.array(means), np.array(vars_) + mean = means.mean(0) + var = (vars_ + means ** 2).mean(0) - mean ** 2 + float(self.noise_variance.values[0]) + return mean, var diff --git a/deepgp/testing/gpc_reference.json b/deepgp/testing/gpc_reference.json new file mode 100644 index 0000000..d81f2e9 --- /dev/null +++ b/deepgp/testing/gpc_reference.json @@ -0,0 +1,721 @@ +{ + "X": [ + [ + 1.764052345967664, + 0.4001572083672233 + ], + [ + 0.9787379841057392, + 2.240893199201458 + ], + [ + 1.8675579901499675, + -0.977277879876411 + ], + [ + 0.9500884175255894, + -0.1513572082976979 + ], + [ + -0.10321885179355784, + 0.41059850193837233 + ], + [ + 0.144043571160878, + 1.454273506962975 + ], + [ + 0.7610377251469934, + 0.12167501649282841 + ], + [ + 0.44386323274542566, + 0.33367432737426683 + ], + [ + 1.4940790731576061, + -0.20515826376580087 + ], + [ + 0.31306770165090136, + -0.8540957393017248 + ], + [ + -2.5529898158340787, + 0.6536185954403606 + ], + [ + 0.8644361988595055, + -0.7421650204064417 + ], + [ + 2.2697546239876076, + -1.4543656745987648 + ], + [ + 0.04575851730144607, + -0.1871838500258336 + ], + [ + 1.5327792143584575, + 1.469358769900285 + ], + [ + 0.1549474256969163, + 0.37816251960217356 + ], + [ + -0.8877857476301128, + -1.980796468223927 + ], + [ + -0.3479121493261526, + 0.15634896910398005 + ], + [ + 1.230290680727721, + 1.2023798487844115 + ], + [ + -0.3873268174079523, + -0.30230275057533557 + ] + ], + "Y": [ + [ + 0.8765288060807828 + ], + [ + 0.6877919442932962 + ], + [ + 0.7856614530864747 + ], + [ + 1.0085444721124308 + ], + [ + -0.15400088304643253 + ], + [ + 0.0997385416211737 + ], + [ + 0.5643937185857664 + ], + [ + 0.5071805797296628 + ], + [ + 0.8356688897726646 + ], + [ + 0.28670464368358417 + ], + [ + -0.6447461774401715 + ], + [ + 0.799419688434343 + ], + [ + 0.7144323417973313 + ], + [ + -0.07232066795594519 + ], + [ + 0.9964592137802104 + ], + [ + 0.1971613421131823 + ], + [ + -0.7690244443988521 + ], + [ + -0.31068860178871416 + ], + [ + 0.8791537092100554 + ], + [ + -0.41398872547411447 + ] + ], + "Xtest": [ + [ + -0.672460447775951, + -0.3595531615405413 + ], + [ + -0.813146282044454, + -1.7262826023316769 + ], + [ + 0.17742614225375283, + -0.4017809362082619 + ], + [ + -1.6301983469660446, + 0.4627822555257742 + ], + [ + -0.9072983643832422, + 0.05194539579613895 + ] + ], + "hidden": 2, + "num_inducing": 4, + "cases": [ + { + "name": "one_layer", + "num_layers": 1, + "layers": [ + { + "log_inverse_width": 0.48730360909897247, + "log_variance": -0.1835269240950226, + "Z": [ + [ + -0.5281717522634558, + -1.0729686221561705 + ], + [ + 0.8654076293246785, + -2.3015386968802827 + ], + [ + 1.74481176421648, + -0.7612069008951028 + ], + [ + 0.31903909605709857, + -0.2493703754774101 + ] + ], + "log_beta": 1.901859499843095, + "q_mu": [ + [ + -1.030070354748827 + ], + [ + -0.16120860200675374 + ], + [ + -0.19202717733420782 + ], + [ + 0.5668847211677187 + ] + ], + "q_chol": [ + [ + [ + 0.3408263972639845, + 0.0, + 0.0, + 0.0 + ], + [ + 0.08742228205737333, + 0.5385577833000291, + 0.0, + 0.0 + ], + [ + 0.07537415083528023, + 0.1351283923896617, + 0.4609292559238678, + 0.0 + ], + [ + -0.1403654151388603, + -0.04018321194390238, + 0.0795533200107279, + 0.47591488505287155 + ] + ] + ] + } + ], + "elbo": -66.52854952108257, + "layer_kl": [ + 2.3870960836541295 + ], + "pred_mean": [ + [ + -0.47529148963102513 + ], + [ + -0.7089839440701444 + ], + [ + -0.013377137222368003 + ], + [ + -0.04374360360085134 + ], + [ + -0.20077244052770407 + ] + ], + "pred_var": [ + [ + 0.6171953458205135 + ], + [ + 0.6525701098431124 + ], + [ + 0.33610755342294457 + ], + [ + 0.9792441934669596 + ], + [ + 0.8816141221979399 + ] + ] + }, + { + "name": "two_layer", + "num_layers": 2, + "layers": [ + { + "log_inverse_width": -0.12502735422164118, + "log_variance": -0.016880048167898842, + "Z": [ + [ + -2.136196095668454, + 1.6402708084049886 + ], + [ + -1.7934355851948631, + -0.841747365656204 + ], + [ + 0.5028814171580428, + -1.2452880866072316 + ], + [ + -1.057952218862339, + -0.9090076149268493 + ] + ], + "log_beta": 0.0, + "q_mu": [ + [ + 0.27572702227321216, + 1.1461040064074788 + ], + [ + 0.02076969649920173, + -0.5589627225567584 + ], + [ + 0.2695291602903944, + -0.2980798499032335 + ], + [ + -0.009565248260575738, + 0.5875006097501455 + ] + ], + "q_chol": [ + [ + [ + 0.6259105939383938, + 0.0, + 0.0, + 0.0 + ], + [ + 0.03848556780019435, + 0.5256843963478988, + 0.0, + 0.0 + ], + [ + -0.09564825187264518, + -0.17814184295779265, + 0.3355069954550752, + 0.0 + ], + [ + -0.04035854403240202, + 0.33470501833299066, + -0.3652151364781566, + 0.7271346797046443 + ] + ], + [ + [ + 0.5741546359199454, + 0.0, + 0.0, + 0.0 + ], + [ + -0.2802135981845645, + 0.7798210111181565, + 0.0, + 0.0 + ], + [ + 0.0917011169360576, + 0.007195588780228256, + 0.6737853100741651, + 0.0 + ], + [ + 0.15005488298260425, + -0.05716387762730249, + -0.05635041346184905, + 0.7800034795790548 + ] + ] + ] + }, + { + "log_inverse_width": 0.13004889902297126, + "log_variance": 0.38351376908156043, + "Z": [ + [ + -0.6346793051793623, + 0.5083962426834318 + ], + [ + 0.21611600626368202, + -1.8586123861234976 + ], + [ + -0.41931648215268885, + -0.13232889843674336 + ], + [ + -0.0395702396936057, + 0.3260034333869806 + ] + ], + "log_beta": 1.2013733026883573, + "q_mu": [ + [ + 0.023127761570848452 + ], + [ + -0.3388377886640207 + ], + [ + -0.719719513369309 + ], + [ + 0.2621482150051743 + ] + ], + "q_chol": [ + [ + [ + 0.8034445166542389, + 0.0, + 0.0, + 0.0 + ], + [ + 0.00997335137192173, + 0.5336335559652239, + 0.0, + 0.0 + ], + [ + -0.013717893433598721, + 0.10426794075704872, + 0.24612315812673918, + 0.0 + ], + [ + -0.011582799802943572, + 0.12370545081554726, + 0.18723193808955513, + 0.7039118303238736 + ] + ] + ] + } + ], + "elbo_mean": -67.9327414721272, + "elbo_stderr": 0.032112661546195014, + "layer_kl": [ + 2.9312578361084882, + 1.7249547420709048 + ] + }, + { + "name": "three_layer", + "num_layers": 3, + "layers": [ + { + "log_inverse_width": 0.5365885420290956, + "log_variance": 0.1309529551535968, + "Z": [ + [ + 0.09649746807200862, + -1.8634927033644908 + ], + [ + -0.27738820251439905, + -0.35475897926898675 + ], + [ + -0.08274148148245977, + -0.6270006768238473 + ], + [ + -0.04381816897592824, + -0.47721803035950267 + ] + ], + "log_beta": 0.0, + "q_mu": [ + [ + -0.6569323766813411, + 0.4423111902497923 + ], + [ + 0.4406590211037649, + 0.8547865318264742 + ], + [ + 0.025016821088430105, + -0.20233870730044543 + ], + [ + -0.2726799738097652, + -0.7732386577914842 + ] + ], + "q_chol": [ + [ + [ + 0.7693110900515986, + 0.0, + 0.0, + 0.0 + ], + [ + 0.22292225326118853, + 0.6761895146937875, + 0.0, + 0.0 + ], + [ + 0.09378674492442439, + -0.024077004478038587, + 0.4654452209274339, + 0.0 + ], + [ + 0.11175843996080562, + 0.2964166174689454, + -0.18661849934339056, + 0.4935752955893744 + ] + ], + [ + [ + 0.7806767310882987, + 0.0, + 0.0, + 0.0 + ], + [ + -0.05344061391701173, + 0.43896928587756145, + 0.0, + 0.0 + ], + [ + -0.1310823446643449, + 0.0044570723041524925, + 0.26471593405055455, + 0.0 + ], + [ + 0.15197751628297412, + 0.12791967614312238, + 0.1662281249902489, + 0.8397467592584962 + ] + ] + ] + }, + { + "log_inverse_width": -0.18086553120216547, + "log_variance": -0.5743416130217442, + "Z": [ + [ + 1.048147512246255, + 1.3337378194424865 + ], + [ + -0.1974146791582499, + 1.7746450314059348 + ], + [ + -0.6747275103117134, + 0.15061686536502228 + ], + [ + 0.15294570276248168, + -1.0641952739365244 + ] + ], + "log_beta": 0.0, + "q_mu": [ + [ + 0.21897330564004103, + 0.9694892302002471 + ], + [ + -0.5124654373040433, + 0.4496692229204071 + ], + [ + -0.07725342594964373, + 0.8848136516468713 + ], + [ + 0.24189417380026518, + 0.3381081999315311 + ] + ], + "q_chol": [ + [ + [ + 0.618561592855165, + 0.0, + 0.0, + 0.0 + ], + [ + -0.20560035188280246, + 0.803502435137013, + 0.0, + 0.0 + ], + [ + 0.02175948211552918, + 0.17518234294524626, + 0.6884373145590332, + 0.0 + ], + [ + -0.4373606627689068, + -0.1457760753858914, + -0.08866181077288134, + 0.4655370900731253 + ] + ], + [ + [ + 0.5160002822641421, + 0.0, + 0.0, + 0.0 + ], + [ + -0.0450309111779326, + 0.8431243607056229, + 0.0, + 0.0 + ], + [ + -0.011961140727835754, + 0.08467282774418955, + 0.9442565574911665, + 0.0 + ], + [ + -0.07958732165326567, + -0.10957899655399952, + 0.09675929774758636, + 0.6342207898524588 + ] + ] + ] + }, + { + "log_inverse_width": -0.20698820319415973, + "log_variance": 0.14592434258058454, + "Z": [ + [ + 0.851518950484708, + 0.48624932610831106 + ], + [ + -0.8342398506717849, + 1.344992456622238 + ], + [ + -0.6782126793411518, + 0.4264350744400753 + ], + [ + -0.7533347935974724, + -1.7441102506410942 + ] + ], + "log_beta": 1.6545879656832643, + "q_mu": [ + [ + 0.14351758234741221 + ], + [ + -0.03872048027996967 + ], + [ + 0.13803424862142158 + ], + [ + -0.3242054441532408 + ] + ], + "q_chol": [ + [ + [ + 0.678968279713096, + 0.0, + 0.0, + 0.0 + ], + [ + -0.07799876311463452, + 0.8091151729226274, + 0.0, + 0.0 + ], + [ + 0.12889260123970134, + -0.07878969677334503, + 0.3515829641898992, + 0.0 + ], + [ + 0.013262280930300891, + 0.019201173167415125, + 0.18624247772378094, + 0.6771544244603735 + ] + ] + ] + } + ], + "elbo_mean": -78.31087672205977, + "elbo_stderr": 0.042237188250983035, + "layer_kl": [ + 3.5160482406552322, + 2.5495954109408214, + 0.9882648431033565 + ] + } + ] +} \ No newline at end of file diff --git a/deepgp/testing/gpc_reference_generate.py b/deepgp/testing/gpc_reference_generate.py new file mode 100644 index 0000000..9041541 --- /dev/null +++ b/deepgp/testing/gpc_reference_generate.py @@ -0,0 +1,97 @@ +"""Generate ``gpc_reference.json``: GPc CIP-0035 reference values (not run in CI). + +Run with the GPc virtual environment (it provides the compiled ``gpc._gpc``):: + + cd /path/to/GPc/python + .venv/bin/python /path/to/PyDeepGP/deepgp/testing/gpc_reference_generate.py \ + /path/to/PyDeepGP/deepgp/testing/gpc_reference.json + +For each case we build a GPc ``DeepGP`` on fixed data, overwrite its packed +stochastic parameter vector with random values, reload it, and record the +parameters (in GPc's parameterisation) with GPc's ELBO. ``test_gpc_reference`` +then evaluates the same parameters with ``doubly_stochastic_bound``. + +Packed layout per layer (``CSvgp::getStochasticParams``): kernel log-parameters +(``inverseWidth``, ``variance``), inducing inputs ``Z`` (column major, M x Q), +log beta, then for each output the M posterior means followed by the lower +Cholesky factor of S in column-major order with the diagonal stored as logs. +GPc's RBF is ``k = variance * exp(-0.5 * inverseWidth * r^2)``. +""" +import json +import sys +import tempfile +import os + +import numpy as np +from gpc._gpc import DeepGP + + +def _build(X, Y, L, M, hidden, seed): + rng = np.random.RandomState(seed) + m = DeepGP(X, Y, layers=L, hidden=hidden, num_inducing=M) + path = os.path.join(tempfile.mkdtemp(), 'ref.model') + m.save(path) + t = open(path).read().split('\n') + idx = [k for k, l in enumerate(t) if l.startswith('numStochParams')] + widths = [X.shape[1]] + [hidden] * (L - 1) + [Y.shape[1]] + layers = [] + for l, i in enumerate(idx): + Q, P = widths[l], widths[l + 1] + K = int(t[i].split('=')[1]) + old = [float.fromhex(v) for v in t[i + 6].split()] + nq = P * (M + M * (M + 1) // 2) + nk = K - M * Q - 1 - nq + logk = rng.randn(nk) * 0.3 + Z = rng.randn(M, Q) + logbeta = (np.log(5.) + 0.2 * rng.randn()) if l == L - 1 \ + else old[nk + M * Q] + qm = 0.5 * rng.randn(M, P) + chol = np.stack([np.tril(0.15 * rng.randn(M, M)) + + np.diag(0.5 + 0.3 * rng.rand(M)) for _ in range(P)]) + v = list(logk) + list(Z.T.ravel()) + [logbeta] + for p in range(P): + v += list(qm[:, p]) + for c in range(M): + for r in range(c, M): + v.append(np.log(chol[p][r, c]) if r == c else chol[p][r, c]) + assert len(v) == K + t[i + 6] = ' '.join(float.hex(float(x)) for x in v) + ' ' + layers.append(dict(log_inverse_width=float(logk[0]), + log_variance=float(logk[1]), + Z=Z.tolist(), log_beta=float(logbeta), + q_mu=qm.tolist(), q_chol=chol.tolist())) + out = os.path.join(os.path.dirname(path), 'ref2.model') + open(out, 'w').write('\n'.join(t)) + return DeepGP.load(out), layers + + +def main(target, n_mc=4000): + rng = np.random.RandomState(0) + X = rng.randn(20, 2) + Y = np.sin(X[:, :1]) + 0.1 * rng.randn(20, 1) + Xt = rng.randn(5, 2) + cases = [] + for name, L, seed in (('one_layer', 1, 1), ('two_layer', 2, 2), + ('three_layer', 3, 3)): + g, layers = _build(X, Y, L, 4, 2, seed) + case = dict(name=name, num_layers=L, layers=layers) + if L == 1: + case['elbo'] = g.elbo() + case['layer_kl'] = [g.layer_kl(0)] + mu, var = g.predict(Xt) + case['pred_mean'] = np.asarray(mu).tolist() + case['pred_var'] = np.asarray(var).tolist() + else: + vals = np.array([g.elbo() for _ in range(n_mc)]) + case['elbo_mean'] = float(vals.mean()) + case['elbo_stderr'] = float(vals.std() / np.sqrt(n_mc)) + case['layer_kl'] = [g.layer_kl(i) for i in range(L)] + cases.append(case) + data = dict(X=X.tolist(), Y=Y.tolist(), Xtest=Xt.tolist(), hidden=2, + num_inducing=4, cases=cases) + with open(target, 'w') as f: + json.dump(data, f, indent=1) + + +if __name__ == '__main__': + main(sys.argv[1]) diff --git a/deepgp/testing/mpi_parity.py b/deepgp/testing/mpi_parity.py deleted file mode 100644 index f9e62d7..0000000 --- a/deepgp/testing/mpi_parity.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). -# Licensed under the BSD 3-clause license (see LICENSE.txt) - -""" -CIP-0001 R11: compare 2-rank MPI objective with a serial back-constrained model. - -Run under MPI:: - - mpiexec -n 2 python -m deepgp.testing.mpi_parity - -Builds a partitioned MPI model, copies its parameters onto a serial model with -the full dataset (so the comparison is not confounded by independent random -initialisation), then checks that log-likelihoods agree. -""" - -from __future__ import print_function - -import sys -import warnings - -import numpy as np -import GPy - -import deepgp - - -def _build_model(Y, X, mpi_comm=None): - kernels = [GPy.kern.RBF(3, ARD=True), GPy.kern.RBF(2, ARD=True)] - with warnings.catch_warnings(): - warnings.simplefilter('ignore', FutureWarning) - return deepgp.DeepGP( - [2, 3, 2], - Y, - X=X, - kernels=kernels, - num_inducing=4, - back_constraint=True, - mpi_comm=mpi_comm, - mpi_root=0, - ) - - -def main(): - from mpi4py import MPI - - comm = MPI.COMM_WORLD - rank = comm.rank - size = comm.size - if size < 2: - if rank == 0: - print('mpi_parity requires at least 2 ranks', file=sys.stderr) - return 2 - - rng = np.random.RandomState(42) - N, D, Q = 20, 2, 2 - Y_all = rng.randn(N, D) - X_all = rng.randn(N, Q) - - # Contiguous row partition across ranks (same total data as serial). - counts = [N // size + (1 if r < N % size else 0) for r in range(size)] - starts = np.cumsum([0] + counts[:-1]) - sl = slice(int(starts[rank]), int(starts[rank] + counts[rank])) - Y_local = np.ascontiguousarray(Y_all[sl]) - X_local = np.ascontiguousarray(X_all[sl]) - - # Independent seeds per rank; root values are broadcast inside DeepGP. - np.random.seed(1000 + rank) - m_mpi = _build_model(Y_local, X_local, mpi_comm=comm) - mpi_ll = float(m_mpi.log_likelihood()) if rank == 0 else None - - if rank == 0: - np.random.seed(7) - m_serial = _build_model(Y_all, X_all, mpi_comm=None) - # Same parameters as the MPI model (full data, serial inference). - m_serial.param_array[:] = m_mpi.param_array - m_serial.trigger_update() - serial_ll = float(m_serial.log_likelihood()) - - rel = abs(mpi_ll - serial_ll) / max(1.0, abs(serial_ll)) - print('serial_ll={:.10g} mpi_ll={:.10g} rel_diff={:.3e}'.format( - serial_ll, mpi_ll, rel)) - if not np.isfinite(mpi_ll) or not np.isfinite(serial_ll) or rel > 1e-5: - print('MPI parity check failed', file=sys.stderr) - return 1 - print('MPI parity check passed') - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/deepgp/testing/test_diagnostics.py b/deepgp/testing/test_diagnostics.py new file mode 100644 index 0000000..a37ee2c --- /dev/null +++ b/deepgp/testing/test_diagnostics.py @@ -0,0 +1,123 @@ +"""ARD scale inspection, prune/restore and initialiser names (CIP-0003 Phase 3).""" +import unittest + +import numpy as np +import GPy + +import deepgp +from deepgp.diagnostics import ard_scales, prune_model, restore_model, show_scales +from deepgp.util.util import validate_init + + +def _model(lengthscales=(1., 1e4), seed=3): + rng = np.random.RandomState(seed) + X = rng.randn(12, 1) + Y = np.hstack([np.sin(X), np.cos(X), X]) + 0.05 * rng.randn(12, 3) + np.random.seed(seed) + k = [GPy.kern.RBF(2, ARD=True, lengthscale=list(lengthscales))] + return deepgp.DeepGP([3, 2], Y, kernels=k, num_inducing=5, back_constraint=False) + + +class ScalesTest(unittest.TestCase): + def test_scales_identify_irrelevant_dimension(self): + s = ard_scales(_model()) + self.assertEqual(list(s), ['layer_0']) + self.assertAlmostEqual(s['layer_0'][0], 1.0) + self.assertLess(s['layer_0'][1], 1e-6) + + def test_unnormalised_scales(self): + s = ard_scales(_model(lengthscales=(2., 4.)), normalize=False)['layer_0'] + np.testing.assert_allclose(s, [0.25, 1. / 16]) + + def test_mrd_scales_per_view(self): + rng = np.random.RandomState(1) + X = rng.randn(10, 2) + Y1, Y2 = X @ rng.randn(2, 3), X @ rng.randn(2, 3) + m = deepgp.DeepGP([[3, 3], 2], [Y1, Y2], num_inducing=4, back_constraint=False, + kernels=[[GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(2, ARD=True)]]) + self.assertEqual(list(ard_scales(m)), ['layer_0/view_0', 'layer_0/view_1']) + + def test_plot_helper(self): + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig = show_scales(_model()) + self.assertEqual(len(fig.axes), 1) + plt.close(fig) + + +class PruneTest(unittest.TestCase): + def test_prune_restore_round_trip(self): + m = _model() + before, params = m.log_likelihood(), m.param_array.copy() + report = prune_model(m) + np.testing.assert_array_equal(report['layer_0'], [1]) + # An irrelevant dimension: the objective barely moves. + self.assertLess(abs(m.log_likelihood() - before), 1e-3 * (1 + abs(before))) + self.assertTrue(m.layers[0].kern.lengthscale[1:].is_fixed) + restore_model(m) + self.assertFalse(m.layers[0].kern.lengthscale[1:].is_fixed) + np.testing.assert_allclose(m.param_array, params) + self.assertAlmostEqual(m.log_likelihood(), before, places=10) + + def test_keeps_at_least_one_dimension(self): + m = _model(lengthscales=(1., 1.)) + prune_model(m, threshold=10.) # would remove everything + self.assertEqual(len(m.layers[0].kern.lengthscale.values), 2) + np.testing.assert_allclose(m.layers[0].kern.lengthscale.values, [1., 1.]) + + def test_double_prune_and_bare_restore_fail_clearly(self): + m = _model() + with self.assertRaises(RuntimeError): + restore_model(m) + prune_model(m) + with self.assertRaises(RuntimeError): + prune_model(m) + restore_model(m) + + +class InitTest(unittest.TestCase): + def test_names(self): + for name in ('PCA', 'rand', 'random', 'randomProjection', 'bgplvm'): + self.assertEqual(validate_init(name), name) + self.assertEqual(validate_init('PCA_single', mrd=True), 'PCA_single') + with self.assertRaises(ValueError): + validate_init('PCA_single') + with self.assertRaises(ValueError): + validate_init('pca-ish') + + def test_unknown_init_rejected_by_model(self): + Y = np.random.randn(8, 3) + with self.assertRaises(ValueError): + deepgp.DeepGP([3, 2], Y, inits='nonsense', num_inducing=4, back_constraint=False) + + def test_each_init_builds_and_default_is_pca(self): + np.random.seed(0) + Y = np.random.randn(10, 3) + for name in ('PCA', 'random', 'randomProjection'): + m = deepgp.DeepGP([3, 2], Y, inits=name, num_inducing=4, back_constraint=False) + self.assertTrue(np.isfinite(m.log_likelihood())) + import inspect + self.assertEqual(inspect.signature(deepgp.DeepGP.__init__).parameters['inits'].default, 'PCA') + + +class ToyExampleTest(unittest.TestCase): + def test_optimisation_reveals_relevant_dimension(self): + """Data generated from one latent signal, three latent dimensions offered.""" + rng = np.random.RandomState(0) + t = np.linspace(-2, 2, 30)[:, None] + Y = np.hstack([np.sin(2 * t), np.cos(t), t ** 2 / 2.]) + 0.02 * rng.randn(30, 3) + np.random.seed(0) + m = deepgp.DeepGP([3, 3], Y, num_inducing=8, back_constraint=False) + m.optimize(max_iters=300, messages=False) + s = ard_scales(m)['layer_0'] + order = np.sort(s)[::-1] + self.assertAlmostEqual(order[0], 1.0) + self.assertLess(order[-1], 0.5 * order[0]) + report = prune_model(m, threshold=0.5 * order[0] + 1e-9) + restore_model(m) + self.assertIn('layer_0', report) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_doubly_stochastic.py b/deepgp/testing/test_doubly_stochastic.py new file mode 100644 index 0000000..45db774 --- /dev/null +++ b/deepgp/testing/test_doubly_stochastic.py @@ -0,0 +1,121 @@ +"""Doubly stochastic bound: GPy SVGP agreement and finite-difference gradients.""" +import unittest + +import numpy as np +import GPy +from GPy.util import choleskies + +from deepgp.functional import doubly_stochastic_bound +from deepgp.testing.test_uncollapsed import _fd, _fd_kern + + +def _layer(rng, Q, P, M, residual=False, ls=1.): + kern = GPy.kern.RBF(Q, ARD=True, lengthscale=[ls] * Q, variance=1.2) + return dict(kern=kern, Z=rng.randn(M, Q), q_mu=0.5 * rng.randn(M, P), + q_chol=np.stack([np.tril(0.2 * rng.randn(M, M)) + np.eye(M) * (0.6 + rng.rand(M)) for _ in range(P)]), + residual=residual) + + +class SingleLayerVsGPyTest(unittest.TestCase): + def test_matches_gpy_svgp(self): + rng = np.random.RandomState(0) + N, Q, M, P = 12, 2, 5, 1 + X, Y = rng.randn(N, Q), rng.randn(N, P) + layer = _layer(rng, Q, P, M) + noise = 0.3 + bound, _ = doubly_stochastic_bound([layer], X, Y, noise, eps=[[]]) + + Lm = np.linalg.cholesky(layer['kern'].K(layer['Z']) + 1e-6 * np.eye(M)) + m = GPy.core.SVGP(X, Y, layer['Z'].copy(), layer['kern'].copy(), + GPy.likelihoods.Gaussian(variance=noise)) + m.q_u_mean[:] = Lm @ layer['q_mu'] + chol = np.stack([Lm @ layer['q_chol'][p] for p in range(P)]) # (P, M, M) + m.q_u_chol[:] = choleskies.triang_to_flat(chol) + self.assertAlmostEqual(bound, float(m.log_likelihood()), delta=1e-4 * (1 + abs(bound))) + + +class StackGradientTest(unittest.TestCase): + def _build(self, residual): + rng = np.random.RandomState(2) + N, Q = 6, 2 + X, Y = rng.randn(N, Q), rng.randn(N, 1) + layers = [_layer(rng, Q, 2, 4, residual=residual), _layer(rng, 2, 2, 3, residual=residual), + _layer(rng, 2, 1, 4)] + eps = [[rng.randn(N, 2), rng.randn(N, 2)] for _ in range(2)] + return layers, X, Y, eps + + def _check(self, residual): + layers, X, Y, eps = self._build(residual) + noise = [0.4] + F = lambda: doubly_stochastic_bound(layers, X.copy(), Y, noise[0], eps, scale=2.5, kl_scale=0.7)[0] + _, g = doubly_stochastic_bound(layers, X.copy(), Y, noise[0], eps, scale=2.5, kl_scale=0.7) + tol = dict(rtol=1e-5, atol=1e-6) + for l, layer in enumerate(layers): + P, M = layer['q_mu'].shape[1], layer['q_mu'].shape[0] + mask = np.broadcast_to(np.tril(np.ones((M, M), dtype=bool)), layer['q_chol'].shape) + np.testing.assert_allclose(g['layers'][l]['q_mu'], _fd(F, layer['q_mu']), **tol) + np.testing.assert_allclose(g['layers'][l]['q_chol'], _fd(F, layer['q_chol'], mask=mask), **tol) + np.testing.assert_allclose(g['layers'][l]['Z'], _fd(F, layer['Z']), **tol) + np.testing.assert_allclose(g['layers'][l]['kern'], _fd_kern(F, layer['kern']), **tol) + np.testing.assert_allclose(g['X'], _fd(F, X), **tol) + + def Fn(): + return doubly_stochastic_bound(layers, X.copy(), Y, noise[0], eps, scale=2.5, kl_scale=0.7)[0] + h = 1e-6 + v = noise[0] + noise[0] = v + h; fp = Fn() + noise[0] = v - h; fm = Fn() + self.assertAlmostEqual(g['noise_var'], (fp - fm) / (2 * h), places=4) + + def test_gradients_plain(self): + self._check(residual=False) + + def test_gradients_with_residual_mean(self): + self._check(residual=True) + + def test_validation(self): + layers, X, Y, eps = self._build(False) + with self.assertRaises(ValueError): + doubly_stochastic_bound(layers, X, Y, 0.4, [[eps[0][0]]]) # too few eps + with self.assertRaises(ValueError): + doubly_stochastic_bound(layers, X, np.hstack([Y, Y]), 0.4, eps) # wrong Y width + bad = [dict(layers[0], residual=True)] + layers[1:] # Q=2 -> P=2 fine + bad[0] = dict(bad[0], q_mu=bad[0]['q_mu'][:, :1], q_chol=bad[0]['q_chol'][:1]) + with self.assertRaises(ValueError): + doubly_stochastic_bound(bad, X, Y, 0.4, eps) + + +class LatentInputTest(unittest.TestCase): + def test_q_x_gradients(self): + rng = np.random.RandomState(4) + N, Q = 6, 2 + X, Y = rng.randn(N, Q), rng.randn(N, 3) + x_var = 0.2 + rng.rand(N, Q) + layers = [_layer(rng, Q, 2, 4, residual=True), _layer(rng, 2, 3, 4)] + eps = [[rng.randn(N, 2)] for _ in range(2)] + eps_x = [rng.randn(N, Q) for _ in range(2)] + kw = dict(scale=2., eps_x=eps_x) + F = lambda: doubly_stochastic_bound(layers, X.copy(), Y, 0.4, eps, x_var=x_var.copy(), **kw)[0] + _, g = doubly_stochastic_bound(layers, X.copy(), Y, 0.4, eps, x_var=x_var.copy(), **kw) + np.testing.assert_allclose(g['X'], _fd(F, X), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g['x_var'], _fd(F, x_var), rtol=1e-5, atol=1e-6) + + def test_zero_variance_reduces_to_deterministic_input(self): + rng = np.random.RandomState(5) + X, Y = rng.randn(5, 2), rng.randn(5, 1) + layers = [_layer(rng, 2, 1, 4)] + b0, _ = doubly_stochastic_bound(layers, X, Y, 0.3, [[]]) + v = np.full_like(X, 1e-14) + b1, _ = doubly_stochastic_bound(layers, X, Y, 0.3, [[]], x_var=v, eps_x=[rng.randn(5, 2)]) + kl_x = 0.5 * np.sum(X ** 2 + v - 1. - np.log(v)) + self.assertAlmostEqual(b1, b0 - kl_x, places=6) + + def test_requires_eps_x(self): + rng = np.random.RandomState(6) + X, Y = rng.randn(5, 2), rng.randn(5, 1) + with self.assertRaises(ValueError): + doubly_stochastic_bound([_layer(rng, 2, 1, 4)], X, Y, 0.3, [[]], x_var=np.ones_like(X)) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_doubly_stochastic_model.py b/deepgp/testing/test_doubly_stochastic_model.py new file mode 100644 index 0000000..af22dda --- /dev/null +++ b/deepgp/testing/test_doubly_stochastic_model.py @@ -0,0 +1,140 @@ +"""DoublyStochasticDeepGP: GPy model behaviour (checkgrad, determinism, minibatch, predict).""" +import unittest + +import numpy as np + +from deepgp.models.uncollapsed import DoublyStochasticDeepGP + + +def _data(N=40, seed=0): + rng = np.random.RandomState(seed) + X = rng.uniform(-2, 2, (N, 1)) + Y = np.sin(2 * X) + 0.1 * rng.randn(N, 1) + return X, Y + + +class ModelTest(unittest.TestCase): + def test_checkgrad_two_hidden_widths(self): + X, Y = _data(12) + m = DoublyStochasticDeepGP([1, 2, 1], Y, X, num_inducing=4, n_samples=2, seed=1) + self.assertEqual([l.q_mu.shape[1] for l in m.layers], [2, 1]) + self.assertTrue(m.checkgrad(tolerance=1e-3)) + + def test_checkgrad_residual_hidden(self): + X, Y = _data(10) + m = DoublyStochasticDeepGP([1, 1, 1], Y, X, num_inducing=4, seed=2) + self.assertTrue(m.layers[0].residual) + 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) + m.set_batch([0, 3, 5, 7, 9]) + self.assertTrue(m.checkgrad(tolerance=1e-3)) + + def test_objective_deterministic_until_resample(self): + X, Y = _data(10) + m = DoublyStochasticDeepGP([1, 2, 1], Y, X, num_inducing=4, seed=4) + # At initialisation q(u) is the prior, so the top layer ignores its input; move it off. + m.layers[-1].q_mu[:] = np.random.RandomState(0).randn(*m.layers[-1].q_mu.shape) + a = m.log_likelihood(); m.parameters_changed() + self.assertEqual(a, m.log_likelihood()) + m.resample() + self.assertNotEqual(a, m.log_likelihood()) + m.resample(seed=99); b = m.log_likelihood() + m.resample(seed=99); self.assertEqual(b, m.log_likelihood()) + + def test_validation(self): + X, Y = _data(10) + with self.assertRaises(ValueError): + DoublyStochasticDeepGP([1, 2, 3], Y, None) # latent wider than Y + with self.assertRaises(ValueError): + DoublyStochasticDeepGP([2, 1], Y, X) + + def test_optimize_improves_fixed_noise_objective(self): + X, Y = _data(25) + m = DoublyStochasticDeepGP([1, 1], Y, X, num_inducing=8, seed=5) + before = m.log_likelihood() + m.optimize(max_iters=60, messages=False) + self.assertGreater(m.log_likelihood(), before + 1.) + + def test_minibatch_fit_learns_and_is_reproducible(self): + X, Y = _data(60) + + def run(): + m = DoublyStochasticDeepGP([1, 1, 1], Y, X, num_inducing=10, seed=7, batch_size=20) + h = m.fit_minibatch(steps=150, lr=0.02, seed=11) + return m, h + m1, h1 = run() + m2, h2 = run() + np.testing.assert_allclose(h1, h2) # seeded: identical trajectories + self.assertGreater(np.mean(h1[-20:]), np.mean(h1[:20])) + mean, var = m1.predict(X, seed=0) + self.assertEqual(mean.shape, Y.shape) + self.assertTrue(np.all(var > 0)) + self.assertLess(np.mean((mean - Y) ** 2), np.var(Y)) # beats the constant predictor + + +if __name__ == '__main__': + unittest.main() + + +class SelectionByNameTest(unittest.TestCase): + def test_inference_method_selects_family(self): + import deepgp + X, Y = _data(10) + m = deepgp.DeepGP([1, 2, 1], Y, X, num_inducing=4, inference_method='doubly_stochastic', seed=1) + self.assertIsInstance(m, DoublyStochasticDeepGP) + self.assertTrue(np.isfinite(m.log_likelihood())) + + def test_default_unchanged(self): + import deepgp + X, Y = _data(10) + m = deepgp.DeepGP([1, 2], Y, num_inducing=4, back_constraint=False) + self.assertIsInstance(m, deepgp.DeepGP) + self.assertNotIsInstance(m, DoublyStochasticDeepGP) + + +class UnsupervisedTest(unittest.TestCase): + def _model(self, **kw): + rng = np.random.RandomState(0) + t = np.linspace(0, 6, 40)[:, None] + Y = np.hstack([np.sin(t), np.cos(t), np.sin(2 * t)]) + 0.05 * rng.randn(40, 3) + return Y, DoublyStochasticDeepGP([3, 2, 1], Y, None, num_inducing=8, noise_var=0.05, seed=0, **kw) + + def test_checkgrad(self): + _, m = self._model() + m.layers[-1].q_mu[:] = 0.3 * np.random.RandomState(1).randn(*m.layers[-1].q_mu.shape) + self.assertTrue(m.checkgrad()) + + def test_checkgrad_minibatch(self): + _, m = self._model() + m.layers[-1].q_mu[:] = 0.3 * np.random.RandomState(1).randn(*m.layers[-1].q_mu.shape) + m.set_batch(np.arange(0, 40, 3)) + self.assertTrue(m.checkgrad()) + + def test_latent_parameters_exist_and_pca_initialised(self): + Y, m = self._model() + self.assertEqual(m.X_mean.shape, (40, 1)) + self.assertEqual(m.X_var.shape, (40, 1)) + self.assertTrue(m.unsupervised) + + def test_training_improves_bound(self): + _, m = self._model() + m.set_batch(None) + start = m.log_likelihood() + m.fit_minibatch(steps=80, batch_size=20, lr=0.02, seed=3) + m.set_batch(None) + self.assertGreater(m.log_likelihood(), start) + mean, var = m.predict(m.X_mean.values[:5]) + self.assertEqual(mean.shape, (5, 3)) + self.assertTrue(np.all(var > 0)) + + +class SelectionUnsupervisedTest(unittest.TestCase): + def test_deepgp_without_x_selects_unsupervised_model(self): + import deepgp + Y = np.random.RandomState(0).randn(20, 4) + m = deepgp.DeepGP([4, 2], Y, num_inducing=5, inference_method='doubly_stochastic') + self.assertIsInstance(m, DoublyStochasticDeepGP) + self.assertTrue(m.unsupervised) diff --git a/deepgp/testing/test_functional.py b/deepgp/testing/test_functional.py new file mode 100644 index 0000000..654ee63 --- /dev/null +++ b/deepgp/testing/test_functional.py @@ -0,0 +1,171 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""CIP-0003 Phase 2: pure layer functions and layer checkgrad.""" + +import unittest + +import numpy as np +import GPy + +import deepgp +from deepgp.functional import collapsed_bound, route_gradients + + +def _stats(seed=0, N=12, D=2, M=4, Q=2, uncertain_inputs=True): + rng = np.random.RandomState(seed) + Z = rng.randn(M, Q) + k = GPy.kern.RBF(Q, ARD=True) + Kmm = k.K(Z) + 1e-6 * np.eye(M) + psi1 = rng.rand(N, M) + psi2 = psi1.T @ psi1 + 0.1 * np.eye(M) if uncertain_inputs else None + psi0 = np.ones(N) * 1.2 + return Kmm, psi0, psi1, psi2, rng.randn(N, D), rng.rand(N, D) * .1 + .02 + + +def _fd(f, x, eps=1e-6): + g = np.zeros_like(x) + for i in np.ndindex(*x.shape): + xp, xm = x.copy(), x.copy() + xp[i] += eps + xm[i] -= eps + g[i] = (f(xp) - f(xm)) / (2 * eps) + return g + + +class CollapsedBoundTest(unittest.TestCase): + def test_gradients_wrt_statistics_and_outputs(self): + Kmm, psi0, psi1, psi2, Ym, Yv = _stats() + beta = 5. + r = collapsed_bound(Kmm, psi0, psi1, psi2, Ym, beta, Y_var=Yv) + f = lambda **kw: float(collapsed_bound(**{**dict( + Kmm=Kmm, psi0=psi0, psi1=psi1, psi2=psi2, Y_mean=Ym, beta=beta, Y_var=Yv), **kw})['logL'][0]) + np.testing.assert_allclose(r['dL_dpsi1'], _fd(lambda x: f(psi1=x), psi1), atol=1e-5) + np.testing.assert_allclose(r['dL_dYmean'], _fd(lambda x: f(Y_mean=x), Ym), atol=1e-5) + # The bound sees only row sums of Y_var, so dL_dYvar is per row. + g = _fd(lambda x: f(Y_var=x), Yv) + np.testing.assert_allclose(g, np.repeat(r['dL_dYvar'][:, None], Yv.shape[1], 1), atol=1e-5) + # dL_dpsi0 is per point: shift one entry. + g0 = _fd(lambda x: f(psi0=x), psi0) + np.testing.assert_allclose(r['dL_dpsi0'], g0, atol=1e-5) + + def test_deterministic_inputs_fold_psi2_into_psi1(self): + Kmm, psi0, psi1, _, Ym, _ = _stats(uncertain_inputs=False) + r = collapsed_bound(Kmm, psi0, psi1, None, Ym, 4.) + self.assertIsNone(r['dL_dpsi2']) + g = _fd(lambda x: float(collapsed_bound(Kmm, psi0, x, None, Ym, 4.)['logL'][0]), psi1) + np.testing.assert_allclose(r['dL_dpsi1'], g, atol=1e-5) + + def test_matches_gpy_for_certain_outputs(self): + from GPy.inference.latent_function_inference.var_dtc import VarDTC as G + rng = np.random.RandomState(4) + Z, X, Y = rng.randn(5, 2), rng.randn(20, 2), rng.randn(20, 3) + k = GPy.kern.RBF(2, ARD=True) + lik = GPy.likelihoods.Gaussian(variance=.2) + g = G(); g.const_jitter = 1e-6 + _, lg, _ = g.inference(k, X, Z, lik, Y) + Kmm = k.K(Z) + 1e-6 * np.eye(5) + r = collapsed_bound(Kmm, k.Kdiag(X), k.K(X, Z), None, Y, 1. / .2) + np.testing.assert_allclose(r['logL'][0], np.squeeze(lg), rtol=1e-10) + + def test_route_gradients_returns_arrays(self): + rng = np.random.RandomState(5) + Z, X = rng.randn(4, 2), rng.randn(9, 2) + k = GPy.kern.RBF(2, ARD=True) + kg, zg = route_gradients(k, Z, X, np.eye(4), dL_dKdiag=np.ones(9), + dL_dKnm=rng.randn(9, 4)) + self.assertEqual(kg.shape, (k.size,)) + self.assertEqual(zg.shape, Z.shape) + self.assertIsInstance(kg, np.ndarray) + self.assertNotIsInstance(zg, GPy.core.Param) + + +class LayerCheckgradTest(unittest.TestCase): + def _data(self): + rng = np.random.RandomState(7) + return rng.randn(10, 3), rng.randn(10, 1) + + def test_unsupervised_stack(self): + Y, _ = self._data() + m = deepgp.DeepGP([3, 2, 2], Y, kernels=[GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(2, ARD=True)], + num_inducing=4, back_constraint=False) + self.assertTrue(m.checkgrad()) + + def test_supervised_stack(self): + Y, X = self._data() + m = deepgp.DeepGP([3, 2, 1], Y, X=X, kernels=[GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(1, ARD=True)], + num_inducing=4, back_constraint=False) + self.assertTrue(m.checkgrad()) + + def test_back_constrained_stack(self): + Y, _ = self._data() + m = deepgp.DeepGP([3, 2, 2], Y, kernels=[GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(2, ARD=True)], + num_inducing=4, back_constraint=True) + self.assertTrue(m.checkgrad()) + + +if __name__ == '__main__': + unittest.main() + + +class QXFunctionsTest(unittest.TestCase): + def test_aggregate_is_precision_weighted(self): + rng = np.random.RandomState(8) + ms = [rng.randn(5, 2) for _ in range(3)] + vs = [rng.rand(5, 2) + .1 for _ in range(3)] + from deepgp.functional import aggregate_qx + mean, var, prec = aggregate_qx(ms, vs) + np.testing.assert_allclose(prec, sum(1. / v for v in vs)) + np.testing.assert_allclose(var, 1. / prec) + np.testing.assert_allclose(mean, sum(m / v for m, v in zip(ms, vs)) / prec) + + def test_disaggregate_matches_finite_differences(self): + from deepgp.functional import aggregate_qx, disaggregate_qx_gradients + rng = np.random.RandomState(9) + ms = [rng.randn(4, 2) for _ in range(2)] + vs = [rng.rand(4, 2) + .2 for _ in range(2)] + wm, wv = rng.randn(4, 2), rng.randn(4, 2) + + def f(ms_, vs_): # scalar function of the aggregate + m, v, _ = aggregate_qx(ms_, vs_) + return float((wm * m).sum() + (wv * v).sum()) + + mean, var, prec = aggregate_qx(ms, vs) + grads = disaggregate_qx_gradients(ms, vs, prec, mean, wm, wv) + for i in range(2): + gm = _fd(lambda x: f([x if j == i else ms[j] for j in range(2)], vs), ms[i]) + gv = _fd(lambda x: f(ms, [x if j == i else vs[j] for j in range(2)]), vs[i]) + np.testing.assert_allclose(grads[i][0], gm, atol=1e-5) + np.testing.assert_allclose(grads[i][1], gv, atol=1e-5) + + +class MRDCheckgradTest(unittest.TestCase): + def _views(self): + rng = np.random.RandomState(10) + X = rng.randn(10, 2) + return X @ rng.randn(2, 3) + .05 * rng.randn(10, 3), X @ rng.randn(2, 3) + .05 * rng.randn(10, 3) + + def _kernels(self, q): + return [GPy.kern.RBF(q, ARD=True), GPy.kern.RBF(q, ARD=True)] + + def test_mrd_checkgrad(self): + Y1, Y2 = self._views() + m = deepgp.DeepGP([[3, 3], 2], [Y1, Y2], kernels=[self._kernels(2)], + num_inducing=4, back_constraint=False) + self.assertTrue(m.checkgrad()) + + def test_mrd_with_hidden_layer_checkgrad(self): + Y1, Y2 = self._views() + m = deepgp.DeepGP([[3, 3], 2, 2], [Y1, Y2], + kernels=[self._kernels(2), GPy.kern.RBF(2, ARD=True)], + num_inducing=4, back_constraint=False) + self.assertTrue(m.checkgrad()) + + # Known defect (backlog/bugs/2026-11-27_mrd-back-constraint-gradients.md): the + # encoder (MLP) gradients are a constant factor 5 from numerical, and the + # shared X_var gradient is lost. Present before the CIP-0003 extraction. + def test_mrd_back_constrained_checkgrad(self): + Y1, Y2 = self._views() + m = deepgp.DeepGP([[3, 3], 2], [Y1, Y2], kernels=[self._kernels(2)], + num_inducing=4, back_constraint=True) + self.assertTrue(m.checkgrad()) diff --git a/deepgp/testing/test_gpc_reference.py b/deepgp/testing/test_gpc_reference.py new file mode 100644 index 0000000..270bdd4 --- /dev/null +++ b/deepgp/testing/test_gpc_reference.py @@ -0,0 +1,107 @@ +"""Cross-check of the doubly stochastic bound against GPc CIP-0035 reference values. + +The golden file ``gpc_reference.json`` is produced by +``gpc_reference_generate.py`` with GPc's compiled ``DeepGP``; CI does not +depend on GPc. One layer is deterministic and must agree to rounding; deeper +models are Monte Carlo estimates and must agree within sampling error. +""" +import json +import os +import unittest + +import numpy as np +import GPy + +from deepgp.functional import doubly_stochastic_bound, whitened_kl, whitened_marginals + +_PATH = os.path.join(os.path.dirname(__file__), 'gpc_reference.json') + + +def _layers(case): + L = case['num_layers'] + out = [] + for l, d in enumerate(case['layers']): + Z = np.array(d['Z']) + kern = GPy.kern.RBF(Z.shape[1], + lengthscale=np.exp(-0.5 * d['log_inverse_width']), + variance=np.exp(d['log_variance'])) + out.append(dict(kern=kern, Z=Z, q_mu=np.array(d['q_mu']), + q_chol=np.array(d['q_chol']), residual=l < L - 1)) + return out, 1. / np.exp(case['layers'][-1]['log_beta']) + + +class TestGPcReference(unittest.TestCase): + @classmethod + def setUpClass(cls): + with open(_PATH) as f: + cls.data = json.load(f) + cls.X = np.array(cls.data['X']) + cls.Y = np.array(cls.data['Y']) + + def _case(self, name): + return next(c for c in self.data['cases'] if c['name'] == name) + + def _eps(self, L, S, seed=0): + rng = np.random.RandomState(seed) + N, Q = self.X.shape + return [[rng.randn(N, Q) for _ in range(L - 1)] for _ in range(S)] + + def test_one_layer_elbo_exact(self): + case = self._case('one_layer') + layers, noise = _layers(case) + bound, _ = doubly_stochastic_bound(layers, self.X, self.Y, noise, + self._eps(1, 1)) + self.assertAlmostEqual(bound, case['elbo'], places=4) + + def test_one_layer_kl_exact(self): + case = self._case('one_layer') + layers, _ = _layers(case) + kl = whitened_kl(layers[0]['q_mu'], layers[0]['q_chol'])[0] + self.assertAlmostEqual(kl, case['layer_kl'][0], places=6) + + def test_one_layer_prediction_exact(self): + case = self._case('one_layer') + layers, noise = _layers(case) + l = layers[0] + mu, var, _ = whitened_marginals(l['kern'], l['Z'], + np.array(self.data['Xtest']), + l['q_mu'], l['q_chol']) + np.testing.assert_allclose(mu, case['pred_mean'], atol=1e-5) + np.testing.assert_allclose(var[:, None] + noise if var.ndim == 1 + else var + noise, + case['pred_var'], atol=1e-5) + + def _check_stochastic(self, name, S=800): + case = self._case(name) + layers, noise = _layers(case) + # Our estimate has its own sampling error; compare with combined s.e. + vals = [] + for seed in range(4): + b, _ = doubly_stochastic_bound(layers, self.X, self.Y, noise, + self._eps(case['num_layers'], S // 4, + seed)) + vals.append(b) + ours = float(np.mean(vals)) + # per-seed estimates are means over S/4 samples; their spread gives s.e. + se_ours = float(np.std(vals, ddof=1) / np.sqrt(len(vals))) + se = np.hypot(se_ours, case['elbo_stderr']) + self.assertLess(abs(ours - case['elbo_mean']), 4 * se + 1e-3, + '%s: ours %.4f gpc %.4f (se %.4f)' + % (name, ours, case['elbo_mean'], se)) + + def test_two_layer_elbo_statistical(self): + self._check_stochastic('two_layer') + + def test_three_layer_elbo_statistical(self): + self._check_stochastic('three_layer') + + def test_layer_kl_all_cases(self): + for case in self.data['cases']: + layers, _ = _layers(case) + for l, ref in zip(layers, case['layer_kl']): + kl = whitened_kl(l['q_mu'], l['q_chol'])[0] + self.assertAlmostEqual(kl, ref, places=5) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_mpi_policy.py b/deepgp/testing/test_mpi_policy.py deleted file mode 100644 index 5de0fa2..0000000 --- a/deepgp/testing/test_mpi_policy.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). -# Licensed under the BSD 3-clause license (see LICENSE.txt) - -"""CIP-0001 Phase 2: MPI deprecation warning and unsupported configurations.""" - -import unittest -import warnings - -import numpy as np -import GPy - -import deepgp -from deepgp.models.model import _MPI_DEPRECATION - - -def _small_dims_and_data(): - rng = np.random.RandomState(0) - Y = rng.randn(8, 2) - X = rng.randn(8, 1) - kernels = [GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(1, ARD=True)] - return [2, 2, 1], Y, X, kernels - - -class MPIPolicyTest(unittest.TestCase): - def test_mpi_comm_without_back_constraint_raises(self): - nDims, Y, X, kernels = _small_dims_and_data() - with warnings.catch_warnings(): - warnings.simplefilter('ignore', FutureWarning) - with self.assertRaises(ValueError) as ctx: - deepgp.DeepGP( - nDims, Y, X=X, kernels=kernels, num_inducing=3, - back_constraint=False, mpi_comm=object(), - ) - self.assertIn('back_constraint=False', str(ctx.exception)) - - def test_mpi_comm_emits_future_warning(self): - nDims, Y, X, kernels = _small_dims_and_data() - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter('always') - try: - deepgp.DeepGP( - nDims, Y, X=X, kernels=kernels, num_inducing=3, - back_constraint=True, mpi_comm=object(), - ) - except Exception: - # Fake communicator is enough to exercise the policy check; - # construction may fail later when real MPI ops are needed. - pass - future = [w for w in caught if issubclass(w.category, FutureWarning)] - self.assertTrue(future, 'expected FutureWarning for mpi_comm') - self.assertIn(_MPI_DEPRECATION, str(future[0].message)) - - -if __name__ == '__main__': - unittest.main() diff --git a/deepgp/testing/test_mpi_removed.py b/deepgp/testing/test_mpi_removed.py new file mode 100644 index 0000000..784fbda --- /dev/null +++ b/deepgp/testing/test_mpi_removed.py @@ -0,0 +1,68 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""CIP-0003 Phase 2: MPI is removed; the arguments remain and fail clearly.""" + +import unittest +import warnings + +import numpy as np +import GPy + +import deepgp +from deepgp.util.util import MPI_REMOVED_MESSAGE + + +def _small_dims_and_data(): + rng = np.random.RandomState(0) + Y = rng.randn(8, 2) + X = rng.randn(8, 1) + kernels = [GPy.kern.RBF(2, ARD=True), GPy.kern.RBF(1, ARD=True)] + return [2, 2, 1], Y, X, kernels + + +class MPIRemovedTest(unittest.TestCase): + def test_mpi_comm_raises_type_error(self): + nDims, Y, X, kernels = _small_dims_and_data() + for back_constraint in (True, False): + with self.assertRaises(TypeError) as ctx: + deepgp.DeepGP( + nDims, Y, X=X, kernels=kernels, num_inducing=3, + back_constraint=back_constraint, mpi_comm=object(), + ) + self.assertIn('psi_chunk_size', str(ctx.exception)) + self.assertEqual(str(ctx.exception), MPI_REMOVED_MESSAGE) + + def test_mpi_comm_none_still_accepted(self): + nDims, Y, X, kernels = _small_dims_and_data() + m = deepgp.DeepGP(nDims, Y, X=X, kernels=kernels, num_inducing=3, + back_constraint=False, mpi_comm=None, mpi_root=0) + self.assertTrue(np.isfinite(m.log_likelihood())) + + def test_layer_and_inference_reject_communicator(self): + from deepgp.inference import VarDTC, SVI_VarDTC, SVI_Ratio + for cls in (VarDTC, SVI_VarDTC, SVI_Ratio): + with self.assertRaises(TypeError): + cls(mpi_comm=object()) + Y = np.random.RandomState(1).randn(6, 2) + with self.assertRaises(TypeError): + deepgp.layers.ObservedLayer(2, 1, Y, num_inducing=3, + back_constraint=False, mpi_comm=object()) + + def test_modules_removed(self): + with self.assertRaises(ImportError): + import deepgp.util.parallel # noqa: F401 + with self.assertRaises(ImportError): + from deepgp.inference import VarDTC_parallel # noqa: F401 + + def test_sparse_gp_mpi_alias_warns(self): + import deepgp.layers.layers as layers + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + cls = layers.SparseGP_MPI + self.assertIs(cls, layers.SparseGPLayer) + self.assertTrue(any(issubclass(w.category, FutureWarning) for w in caught)) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_natgrad.py b/deepgp/testing/test_natgrad.py new file mode 100644 index 0000000..c40af94 --- /dev/null +++ b/deepgp/testing/test_natgrad.py @@ -0,0 +1,83 @@ +"""Natural-gradient step for the top layer's whitened q(u).""" +import unittest + +import numpy as np +import GPy + +from deepgp.functional import (doubly_stochastic_bound, whitened_natgrad_step, + whitened_marginals, whitened_expectation_grads) +from deepgp.models import DoublyStochasticDeepGP + + +def _one_layer(seed=0, M=6, N=30): + rng = np.random.RandomState(seed) + X = rng.randn(N, 2) + Y = np.sin(X[:, :1]) + 0.1 * rng.randn(N, 1) + kern = GPy.kern.RBF(2, lengthscale=1.2, variance=0.8) + Z = rng.randn(M, 2) + q_mu = 0.3 * rng.randn(M, 1) + q_chol = np.tril(0.2 * rng.randn(1, M, M)) + np.eye(M)[None] * 0.7 + layer = dict(kern=kern, Z=Z, q_mu=q_mu, q_chol=q_chol, residual=False) + return X, Y, layer + + +class TestNatGrad(unittest.TestCase): + def test_gamma_one_reaches_optimum_gaussian(self): + X, Y, layer = _one_layer() + noise = 0.05 + _, g = doubly_stochastic_bound([layer], X, Y, noise, [[]]) + mu, chol = whitened_natgrad_step(layer['q_mu'], layer['q_chol'], + g['natgrad']['g_m'], g['natgrad']['g_S'], 1.) + layer2 = dict(layer, q_mu=mu, q_chol=chol) + b1, g1 = doubly_stochastic_bound([layer2], X, Y, noise, [[]]) + np.testing.assert_allclose(g1['layers'][0]['q_mu'], 0., atol=1e-6) + np.testing.assert_allclose(g1['layers'][0]['q_chol'], 0., atol=1e-6) + b0, _ = doubly_stochastic_bound([layer], X, Y, noise, [[]]) + self.assertGreater(b1, b0) + + def test_matches_analytic_optimum(self): + # The optimal Gaussian q(u) under the whitened prior has precision I + B B^T / noise. + X, Y, layer = _one_layer(seed=1) + noise = 0.1 + _, g = doubly_stochastic_bound([layer], X, Y, noise, [[]]) + mu, chol = whitened_natgrad_step(layer['q_mu'], layer['q_chol'], + g['natgrad']['g_m'], g['natgrad']['g_S'], 1.) + _, _, cache = whitened_marginals(layer['kern'], layer['Z'], X, layer['q_mu'], layer['q_chol']) + B = cache['B'] + S = np.linalg.inv(np.eye(B.shape[0]) + B @ B.T / noise) + np.testing.assert_allclose(chol[0] @ chol[0].T, S, atol=1e-6) + np.testing.assert_allclose(mu[:, 0], S @ B @ Y[:, 0] / noise, atol=1e-6) + + def test_small_step_increases_bound(self): + X, Y, layer = _one_layer(seed=2) + b0, g = doubly_stochastic_bound([layer], X, Y, 0.1, [[]]) + mu, chol = whitened_natgrad_step(layer['q_mu'], layer['q_chol'], + g['natgrad']['g_m'], g['natgrad']['g_S'], 0.1) + b1, _ = doubly_stochastic_bound([dict(layer, q_mu=mu, q_chol=chol)], X, Y, 0.1, [[]]) + self.assertGreater(b1, b0) + + def test_expectation_grads_consistent_with_chol_grad(self): + X, Y, layer = _one_layer(seed=3) + _, g = doubly_stochastic_bound([layer], X, Y, 0.1, [[]], kl_scale=0.) + gS = g['natgrad']['g_S'][0] + L = layer['q_chol'][0] + np.testing.assert_allclose(np.tril(2. * gS @ L), g['layers'][0]['q_chol'][0], atol=1e-8) + + def test_model_hybrid_training_beats_adam_start(self): + rng = np.random.RandomState(0) + X = rng.randn(60, 1) + Y = np.sin(2 * X) + 0.05 * rng.randn(60, 1) + m = DoublyStochasticDeepGP([1, 1, 1], Y, X, num_inducing=8, noise_var=0.05, seed=0) + start = m.log_likelihood() + hist = m.fit_minibatch(steps=60, batch_size=30, lr=0.02, seed=1, natgrad_gamma=0.2) + m.set_batch(None) + self.assertGreater(m.log_likelihood(), start) + # the natural-gradient path must keep q(u) valid + self.assertTrue(np.all(np.isfinite(m.layers[-1].q_chol))) + m2 = DoublyStochasticDeepGP([1, 1, 1], Y, X, num_inducing=8, noise_var=0.05, seed=0) + m2.fit_minibatch(steps=60, batch_size=30, lr=0.02, seed=1, natgrad_gamma=0.2) + np.testing.assert_allclose(m2.optimizer_array, m.optimizer_array) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_uncollapsed.py b/deepgp/testing/test_uncollapsed.py new file mode 100644 index 0000000..0fb55c7 --- /dev/null +++ b/deepgp/testing/test_uncollapsed.py @@ -0,0 +1,131 @@ +"""Whitened marginals core: agreement with dense algebra and finite differences.""" +import unittest + +import numpy as np +import GPy + +from deepgp.functional import (whitened_marginals, whitened_marginals_backward, whitened_kl, + reparam_sample, reparam_sample_backward) + + +def _setup(seed=0, N=7, M=4, Q=2, P=3): + rng = np.random.RandomState(seed) + kern = GPy.kern.RBF(Q, ARD=True, lengthscale=[0.8, 1.3], variance=1.4) + Z, X = rng.randn(M, Q), rng.randn(N, Q) + q_mu = rng.randn(M, P) + q_chol = np.stack([np.tril(0.3 * rng.randn(M, M)) + np.eye(M) * (0.5 + rng.rand(M)) for _ in range(P)]) + return kern, Z, X, q_mu, q_chol, rng + + +def _fd(f, x, eps=1e-6, mask=None): + g = np.zeros_like(x) + it = np.nditer(x, flags=['multi_index']) + for _ in it: + i = it.multi_index + if mask is not None and not mask[i]: + continue + old = x[i] + x[i] = old + eps; fp = f() + x[i] = old - eps; fm = f() + x[i] = old + g[i] = (fp - fm) / (2 * eps) + return g + + +def _fd_kern(f, kern, eps=1e-6): + """Finite differences over kernel parameter values (set via the Parameterized API).""" + base = kern.param_array.copy() + g = np.zeros_like(base) + for i in range(base.size): + for sign in (1, -1): + v = base.copy(); v[i] += sign * eps + kern[:] = v + g[i] += sign * f() + kern[:] = base + return g / (2 * eps) + + +class WhitenedMarginalsTest(unittest.TestCase): + def test_matches_dense_unwhitened_algebra(self): + kern, Z, X, m, L, _ = _setup() + jit = 1e-6 + mu, var, _ = whitened_marginals(kern, Z, X, m, L, jitter=jit) + Kmm = kern.K(Z) + jit * np.eye(len(Z)) + Lm = np.linalg.cholesky(Kmm) + Knm, Kinv = kern.K(X, Z), np.linalg.inv(Kmm) + for p in range(m.shape[1]): + mu_u, S_u = Lm @ m[:, p], Lm @ L[p] @ L[p].T @ Lm.T # unwhitened q(u) + np.testing.assert_allclose(mu[:, p], Knm @ Kinv @ mu_u, rtol=1e-8, atol=1e-8) + cov = kern.K(X) - Knm @ Kinv @ Knm.T + Knm @ Kinv @ S_u @ Kinv @ Knm.T + np.testing.assert_allclose(var[:, p], np.diag(cov), rtol=1e-6, atol=1e-8) + + def test_zero_variance_posterior_is_prior_mean_free(self): + kern, Z, X, m, L, _ = _setup() + mu, var, _ = whitened_marginals(kern, Z, X, np.zeros_like(m), np.stack([np.eye(4)] * 3)) + np.testing.assert_allclose(mu, 0.) + np.testing.assert_allclose(var, kern.Kdiag(X)[:, None] * np.ones((1, 3)), rtol=1e-6) + + def test_backward_matches_finite_differences(self): + kern, Z, X, m, L, rng = _setup() + a, b = rng.randn(*(X.shape[0], m.shape[1])), rng.randn(X.shape[0], m.shape[1]) + + def F(): + mu, var, _ = whitened_marginals(kern, Z.copy(), X.copy(), m, L) # copies: GPy caches on array identity + return np.sum(a * mu + b * var) + + _, _, cache = whitened_marginals(kern, Z, X, m, L) + g = whitened_marginals_backward(kern, Z, X, cache, a, b) + np.testing.assert_allclose(g['q_mu'], _fd(F, m), rtol=1e-5, atol=1e-6) + low = np.tril(np.ones((4, 4), dtype=bool)) + mask = np.broadcast_to(low, L.shape) + np.testing.assert_allclose(g['q_chol'], _fd(F, L, mask=mask), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g['Z'], _fd(F, Z), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g['X'], _fd(F, X), rtol=1e-5, atol=1e-6) + kg = _fd_kern(F, kern) + np.testing.assert_allclose(g['kern'], kg, rtol=1e-5, atol=1e-6) + + def test_kl_matches_dense_and_finite_differences(self): + _, _, _, m, L, _ = _setup() + kl, dm, dL = whitened_kl(m, L) + dense = 0. + for p in range(m.shape[1]): + S = L[p] @ L[p].T + dense += 0.5 * (np.trace(S) + m[:, p] @ m[:, p] - len(m) - np.linalg.slogdet(S)[1]) + self.assertAlmostEqual(kl, dense, places=10) + np.testing.assert_allclose(dm, _fd(lambda: whitened_kl(m, L)[0], m), rtol=1e-6, atol=1e-7) + mask = np.broadcast_to(np.tril(np.ones((4, 4), dtype=bool)), L.shape) + np.testing.assert_allclose(dL, _fd(lambda: whitened_kl(m, L)[0], L, mask=mask), rtol=1e-5, atol=1e-6) + + +class TwoLayerStackTest(unittest.TestCase): + """Upstream gradients flow through a reparameterised sample into the layer below.""" + + def test_gradient_through_two_layers_with_frozen_eps(self): + k1, Z1, X, m1, L1, rng = _setup(seed=1, P=2) # layer 1: 2 outputs + k2 = GPy.kern.RBF(2, ARD=True, lengthscale=[1., 1.5]) + Z2 = rng.randn(4, 2) + m2 = rng.randn(4, 1) + L2 = np.stack([np.tril(0.2 * rng.randn(4, 4)) + np.eye(4)]) + eps = rng.randn(X.shape[0], 2) + a, b = rng.randn(X.shape[0], 1), rng.randn(X.shape[0], 1) + + def forward(): + mu1, v1, c1 = whitened_marginals(k1, Z1.copy(), X.copy(), m1, L1) + f1 = reparam_sample(mu1, v1, eps) + mu2, v2, c2 = whitened_marginals(k2, Z2.copy(), f1, m2, L2) + return np.sum(a * mu2 + b * v2), (v1, c1, c2, f1) + + F = lambda: forward()[0] + _, (v1, c1, c2, f1) = forward() + g2 = whitened_marginals_backward(k2, Z2, f1, c2, a, b) + dmu1, dv1 = reparam_sample_backward(v1, eps, g2['X']) + g1 = whitened_marginals_backward(k1, Z1, X, c1, dmu1, dv1) + np.testing.assert_allclose(g1['X'], _fd(F, X), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g1['q_mu'], _fd(F, m1), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g1['Z'], _fd(F, Z1), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g1['kern'], _fd_kern(F, k1), rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(g2['kern'], _fd_kern(F, k2), rtol=1e-5, atol=1e-6) + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/testing/test_vardtc_gpy.py b/deepgp/testing/test_vardtc_gpy.py new file mode 100644 index 0000000..d8a27b4 --- /dev/null +++ b/deepgp/testing/test_vardtc_gpy.py @@ -0,0 +1,102 @@ +# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). +# Licensed under the BSD 3-clause license (see LICENSE.txt) + +"""CIP-0003 Phase 2: deepgp VarDTC is GPy's VarDTC plus a documented delta.""" + +import unittest + +import numpy as np +import GPy +from GPy.core.parameterization.variational import NormalPosterior +from GPy.inference.latent_function_inference.var_dtc import VarDTC as GPyVarDTC + +from deepgp.inference import VarDTC + + +def _problem(uncertain, seed=0, N=30, D=3, Q=2, M=6): + rng = np.random.RandomState(seed) + Y = rng.randn(N, D) + Z = rng.randn(M, Q) + X = (NormalPosterior(rng.randn(N, Q), rng.rand(N, Q) * .1 + .05) + if uncertain else rng.randn(N, Q)) + return Y, X, Z + + +class VarDTCDeltaTest(unittest.TestCase): + def setUp(self): + self.lik = GPy.likelihoods.Gaussian(variance=.1) + self.kern = GPy.kern.RBF(2, ARD=True) + + def _gpy(self): + g = GPyVarDTC() + g.const_jitter = 1e-6 + return g + + def test_agrees_with_gpy_for_deterministic_outputs(self): + for uncertain in (False, True): + Y, X, Z = _problem(uncertain) + pg, lg, gg = self._gpy().inference(self.kern, X, Z, self.lik, Y) + pl, ll, gl = VarDTC().inference(self.kern, X, Z, self.lik, Y) + np.testing.assert_allclose(np.squeeze(ll), np.squeeze(lg), rtol=1e-10) + for k, v in gl.items(): + np.testing.assert_allclose(v, np.reshape(gg[k], np.shape(v)), atol=1e-8) + np.testing.assert_allclose(pl.woodbury_vector, pg.woodbury_vector, atol=1e-9) + + def test_chunked_psi_matches_unchunked(self): + Y, X, Z = _problem(True) + _, l0, g0 = VarDTC().inference(self.kern, X, Z, self.lik, Y) + _, l1, g1 = VarDTC(psi_chunk_size=7).inference(self.kern, X, Z, self.lik, Y) + np.testing.assert_allclose(l1, l0, rtol=1e-10) + for k in g0: + np.testing.assert_allclose(g1[k], g0[k], atol=1e-8) + + def test_kuu_sigma_changes_bound_consistently(self): + Y, X, Z = _problem(True) + sig = np.full(Z.shape[0], 1e-3) + _, l0, _ = VarDTC().inference(self.kern, X, Z, self.lik, Y) + _, l1, _ = VarDTC().inference(self.kern, X, Z, self.lik, Y, Kuu_sigma=sig) + self.assertTrue(np.isfinite(l1).all()) + self.assertGreater(abs(float(l1[0] - l0[0])), 0.0) + + def test_uncertain_outputs_supported(self): + Y, X, Z = _problem(True) + Yq = NormalPosterior(Y, np.full(Y.shape, .05)) + _, ll, gl = VarDTC().inference(self.kern, X, Z, self.lik, Yq) + self.assertTrue(np.isfinite(ll).all()) + self.assertIn('dL_dYmean', gl) + # With vanishing output variance, the bound approaches the deterministic one. + Yq0 = NormalPosterior(Y, np.full(Y.shape, 1e-12)) + _, l0, _ = VarDTC().inference(self.kern, X, Z, self.lik, Yq0) + _, lD, _ = VarDTC().inference(self.kern, X, Z, self.lik, Y) + np.testing.assert_allclose(l0, lD, rtol=1e-6) + + def test_sparse_linalg_modes_agree(self): + Y, X, Z = _problem(False) + ref = VarDTC().inference(self.kern, X, Z, self.lik, Y)[1] + try: + lq = VarDTC(sparse_linalg='lq').inference(self.kern, X, Z, self.lik, Y)[1] + except TypeError: + self.skipTest('GPy without CIP-0013 sparse_linalg') + np.testing.assert_allclose(lq, ref, rtol=1e-6) + + def test_layer_exposes_sparse_linalg(self): + import deepgp + Y = np.random.RandomState(2).randn(10, 2) + try: + layer = deepgp.layers.ObservedLayer(2, 1, Y, num_inducing=3, + back_constraint=False) + layer.inference_method.sparse_linalg = 'lq' + except (TypeError, AttributeError): + self.skipTest('GPy without CIP-0013 sparse_linalg') + self.assertEqual(layer.inference_method.sparse_linalg, 'lq') + + def test_inferentia_fails_clearly(self): + import deepgp + Y = np.random.RandomState(3).randn(10, 2) + with self.assertRaises(NotImplementedError): + deepgp.layers.ObservedLayer(2, 1, Y, num_inducing=3, back_constraint=False, + inference_method='inferentia') + + +if __name__ == '__main__': + unittest.main() diff --git a/deepgp/util/parallel.py b/deepgp/util/parallel.py deleted file mode 100644 index bd60062..0000000 --- a/deepgp/util/parallel.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) 2015-2016, the authors (see AUTHORS.txt). -# Licensed under the BSD 3-clause license (see LICENSE.txt) - - -import numpy as np - - -def get_id_within_node(comm=None): - from mpi4py import MPI - if comm is None: - comm = MPI.COMM_WORLD - rank = comm.rank - nodename = MPI.Get_processor_name() - nodelist = comm.allgather(nodename) - return len([i for i in nodelist[:rank] if i == nodename]) - - -def allReduceArrays(arrL, comm): - """Allreduce a list of NumPy scalars/arrays. mpi4py infers MPI datatypes.""" - res = [] - for arr in arrL: - if np.isscalar(arr): - send = np.asarray(arr).reshape(1) - arr_out = np.empty_like(send) - comm.Allreduce(send, arr_out) - res.append(arr_out.reshape(())) - else: - arr_out = np.empty_like(arr) - comm.Allreduce(arr, arr_out) - res.append(arr_out) - return res - - -def reduceArrays(arrL, comm, root=0): - """Reduce a list of NumPy scalars/arrays to ``root``. Non-root entries are None.""" - res = [] - for arr in arrL: - if np.isscalar(arr): - send = np.asarray(arr).reshape(1) - arr_out = np.empty_like(send) if comm.rank == root else None - comm.Reduce(send, arr_out, root=root) - res.append(arr_out.reshape(()) if comm.rank == root else None) - else: - arr_out = np.empty_like(arr) if comm.rank == root else None - comm.Reduce(arr, arr_out, root=root) - res.append(arr_out if comm.rank == root else None) - return res - - -def broadcastArrays(arrL, comm, root=0): - """Broadcast a list of NumPy arrays from ``root`` (in-place).""" - for arr in arrL: - comm.Bcast(arr, root=root) diff --git a/deepgp/util/util.py b/deepgp/util/util.py index 25f61df..991f2fe 100644 --- a/deepgp/util/util.py +++ b/deepgp/util/util.py @@ -8,6 +8,34 @@ from GPy.core.parameterization.variational import VariationalPosterior, NormalPosterior import sys + +MPI_REMOVED_MESSAGE = ( + "MPI support has been removed from PyDeepGP (CIP-0001, CIP-0003). " + "Use psi_chunk_size and psi_threads for single-machine scaling; " + "mpi_comm must be None." +) + + +def reject_mpi_comm(mpi_comm): + """Raise TypeError if a communicator is passed (the argument is kept for compatibility).""" + if mpi_comm is not None: + raise TypeError(MPI_REMOVED_MESSAGE) + +#: Named initialisers for the latent space X. 'PCA' is the default. +#: 'rand' and 'random' are synonyms. 'PCA_concat' and 'PCA_single' apply to MRD +#: layers only (PCA of concatenated views, or one block of dimensions per view). +INITIALISERS = ('PCA', 'bgplvm', 'randomProjection', 'rand', 'random') +MRD_INITIALISERS = ('PCA_concat', 'PCA_single') + + +def validate_init(init, mrd=False): + """Return ``init`` if it is a known initialiser name, else raise ValueError.""" + allowed = INITIALISERS + (MRD_INITIALISERS if mrd else ()) + if init not in allowed: + raise ValueError("Unknown initialiser %r; choose from %s" % (init, ', '.join(allowed))) + return init + + def initialize_latent(init, datanum, input_dim, Y): Xr = np.random.randn(datanum, input_dim) if init == 'PCA': diff --git a/examples/compare_collapsed_vs_doubly_stochastic.py b/examples/compare_collapsed_vs_doubly_stochastic.py new file mode 100644 index 0000000..6f59cab --- /dev/null +++ b/examples/compare_collapsed_vs_doubly_stochastic.py @@ -0,0 +1,110 @@ +"""Collapsed (VarDTC / Bayesian GP-LVM) versus doubly stochastic deep GPs on oil and CMU mocap. + +Not run in CI (needs ``pods`` and downloads data). + +Oil (100 points, 12-D, 3 classes): unsupervised ``[12, 5, 2]`` stacks. We report the +leave-one-out 1-nearest-neighbour class error in the 2-D top latent space and the +training reconstruction RMSE. + +CMU subject 35, walk (62-D joint angles): train on every other frame of one walk, hold out the +frames in between. The held-out latent is the mean of the neighbouring training latents, pushed +through the model; we report held-out RMSE. This tests how smooth and informative the +learned top latent is, not dynamics. + + python examples/compare_collapsed_vs_doubly_stochastic.py [oil|cmu] [seed] +""" +import sys +import time + +import numpy as np + +import deepgp + + +def standardise(Y): + mu, sd = Y.mean(0), Y.std(0) + sd[sd < 1e-8] = 1. + return (Y - mu) / sd, mu, sd + + +def loo_1nn_error(X, labels): + D = ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1) + np.fill_diagonal(D, np.inf) + return float(np.mean(labels[D.argmin(1)] != labels)) + + +def collapsed(Y, nDims, M, iters, seed): + 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 + t0 = time.time() + m.optimize(max_iters=iters, messages=False) + return m, time.time() - t0 + + +def doubly_stochastic(Y, nDims, M, iters, seed, natgrad_gamma=0.): + m = deepgp.DeepGP(nDims, Y, num_inducing=M, inference_method='doubly_stochastic', + seed=seed, noise_var=0.05, n_samples=1) + 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 + + +def top_latent(m): + return m.X_mean.values if hasattr(m, 'X_mean') else np.asarray(m.layers[-1].X.mean) + + +def oil(seed=0, iters=(5000, 3000)): + import pods + d = pods.datasets.oil_100() + Y, _, _ = standardise(d['X']) + labels = d['Y'].argmax(1) + 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), + 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) + mean, _ = md.predict(top_latent(md), n_samples=20, seed=0) + rows.append(('doubly stochastic' + (' + natgrad' if gamma else ''), + loo_1nn_error(top_latent(md), labels), + float(np.sqrt(np.mean((mean - Y) ** 2))), td)) + return rows + + +def cmu(seed=0, iters=(5000, 3000)): + import pods + d = pods.datasets.cmu_mocap('35', ['01'], [], sample_every=1) + Y, _, _ = standardise(d['Y']) + Y = Y[:(len(Y) // 2) * 2] + train, test = Y[0::2], Y[1::2] + nDims, M = [Y.shape[1], 5, 3], 25 + rows = [] + + def held_out(model, X, predict): + Xmid = 0.5 * (X[:-1] + X[1:]) # between consecutive training frames + mean = predict(Xmid) + return float(np.sqrt(np.mean((mean - test[:-1]) ** 2))) + + 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) + Xd = top_latent(md) + rows.append(('doubly stochastic' + (' + natgrad' if gamma else ''), + 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 + + +if __name__ == '__main__': + which = sys.argv[1] if len(sys.argv) > 1 else 'oil' + seed = int(sys.argv[2]) if len(sys.argv) > 2 else 0 + for row in (oil if which == 'oil' else cmu)(seed): + print(row, flush=True) diff --git a/examples/composite_v8.py b/examples/composite_v8.py new file mode 100644 index 0000000..52070ca --- /dev/null +++ b/examples/composite_v8.py @@ -0,0 +1,58 @@ +"""GPc CIP-0035 verification oracle V8: the composite task (not run in CI). + +A 10-D input is projected to two dimensions and passed through a nonlinearity +of the projection, so depth should help. The task generator is the one used by +GPc's JAX prototype and ``validation/gpc_vs_mlp.py`` (N=2000 train, 1000 test). +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] +""" +import sys +import time + +import numpy as np +import GPy + +import deepgp + + +def task(seed=0): + r = np.random.default_rng(seed) + Bm = np.linalg.qr(r.normal(size=(10, 2)))[0] + X = r.normal(size=(2000, 10)) + Xt = r.normal(size=(1000, 10)) + f = lambda x: np.sin(2 * (x @ Bm)[:, 0] + (x @ Bm)[:, 1] ** 2) + n = 0.1 + y = f(X) + n * r.normal(size=len(X)) + yt = f(Xt) + n * r.normal(size=len(Xt)) + mu, sd = y.mean(), y.std() + return X, ((y - mu) / sd)[:, None], Xt, ((yt - mu) / sd)[:, None] + + +def evaluate(model, Xt, yt, n_samples=50): + mean, var = model.predict(Xt, n_samples=n_samples, seed=123) + rmse = float(np.sqrt(np.mean((mean - yt) ** 2))) + nll = float(-np.mean(-0.5 * np.log(2 * np.pi * var) - 0.5 * (yt - mean) ** 2 / var)) + return rmse, nll + + +def run(L, M=64, hidden=5, iters=3000, seed=0, natgrad_gamma=0., batch=256): + 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) + 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) + + +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): + for s in range(seeds): + print(run(L, iters=iters, seed=s), flush=True) diff --git a/setup.py b/setup.py index 5023a07..87f9fc9 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,7 @@ def read(fname): "deepgp.models", "deepgp.testing"], package_dir={'deepgp': 'deepgp'}, - package_data={'deepgp.testing': ['*.txt', '*.h5']}, + package_data={'deepgp.testing': ['*.txt', '*.h5', '*.json']}, include_package_data=True, py_modules = ['deepgp.__init__'], long_description=read('README.md'),