nrptorch 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nrptorch-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vladimir Starostin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.4
2
+ Name: nrptorch
3
+ Version: 0.1.0
4
+ Summary: GPU-native nonreversible parallel tempering in PyTorch
5
+ Author: Vladimir Starostin
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/StarostinV/nrptorch
8
+ Project-URL: Source, https://github.com/StarostinV/nrptorch
9
+ Project-URL: Issues, https://github.com/StarostinV/nrptorch/issues
10
+ Keywords: parallel tempering,MCMC,Bayesian inference,multimodal sampling,pytorch,GPU
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
17
+ Classifier: Topic :: Scientific/Engineering :: Physics
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: torch>=2.1
22
+ Requires-Dist: numpy
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: pytest-timeout; extra == "dev"
26
+ Requires-Dist: scipy; extra == "dev"
27
+ Requires-Dist: arviz; extra == "dev"
28
+ Provides-Extra: docs
29
+ Requires-Dist: mkdocs-material; extra == "docs"
30
+ Requires-Dist: mkdocstrings[python]; extra == "docs"
31
+ Dynamic: license-file
32
+
33
+ # nrptorch
34
+
35
+ GPU-native **nonreversible parallel tempering** (NRPT) in PyTorch for continuous,
36
+ unnormalized densities: many independent tempering ladders, all temperatures and
37
+ all local moves batched on the device, deterministic even/odd swaps, exact
38
+ reference refreshes, adaptive temperature schedules, and diagnostics that say when
39
+ a run should not be trusted.
40
+
41
+ ![Nonreversible vs reversible parallel tempering on a 2-D Gaussian mixture](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/nrpt_gmm2d.gif)
42
+
43
+ *Nonreversible and reversible parallel tempering differ only in the swap schedule
44
+ (alternating even/odd pairs vs a random parity each sweep): same 32 temperatures,
45
+ same tuning (a separate pilot run), same local moves, same budget. The animation shows
46
+ the whole run: at sweep 0 every chain sits in one mode of a four-mode mixture. Bars:
47
+ estimated weights (outlines: true weights). Right: error of the weights over sweeps;
48
+ "no tempering" is 256 random-walk chains with the same density evaluations. Over 4
49
+ seeds the error after 1,200 sweeps is 0.09 [0.057, 0.108] for NRPT and 0.34
50
+ [0.31, 0.38] for reversible PT (script:
51
+ [`docs/figures/make_animation.py`](https://github.com/StarostinV/nrptorch/blob/main/docs/figures/make_animation.py)).*
52
+
53
+ Documentation: <https://starostinv.github.io/nrptorch/>. License: MIT.
54
+
55
+ ## Installation
56
+
57
+ ```
58
+ pip install nrptorch
59
+ ```
60
+
61
+ Requires Python >= 3.10 and PyTorch >= 2.1 (install the CUDA build of PyTorch first
62
+ for GPU runs). From source: `pip install -e ".[dev]"`.
63
+
64
+ ## Example
65
+
66
+ ```python
67
+ import torch
68
+ from nrptorch import NRPT, GeometricPath, RandomWalkMH, DiagNormalReference
69
+ from nrptorch import diagnostics as dg
70
+
71
+ D = 2
72
+ prior = DiagNormalReference(torch.zeros(D), 3.0 * torch.ones(D)) # N(0, 3^2 I)
73
+ centers = torch.tensor([[-2.0, 0.0], [2.0, 0.0]])
74
+
75
+
76
+ def log_likelihood(x): # (N, D) -> (N,)
77
+ d2 = ((x[:, None, :] - centers.to(x)) ** 2).sum(-1)
78
+ return torch.logsumexp(-0.5 * d2 / 0.3**2, dim=1)
79
+
80
+
81
+ path = GeometricPath(prior.log_prob, prior.sample, log_likelihood=log_likelihood)
82
+ sampler = NRPT(path, RandomWalkMH(step_size=0.3), n_temperatures=16, n_ladders=8,
83
+ device="cpu", dtype=torch.float32, seed=0) # device="cuda" for the GPU
84
+ state = sampler.initialize()
85
+ state, info = sampler.warmup(state, n_sweeps=1024, adapt_schedule=True, adapt_local=True)
86
+ result = sampler.sample(state, n_sweeps=2048, thin=2)
87
+
88
+ result.samples # (S, B, D): cold-temperature draws of B independent ladders
89
+ result.diagnostics # swap rejection per edge, barrier estimate, round-trip rate, ...
90
+ dg.rhat(result.samples[..., 0]) # rank-normalized split R-hat across ladders
91
+ dg.ess_bulk(result.samples[..., 0]) # bulk ESS
92
+ torch.save(sampler.checkpoint(result.state), "ckpt.pt") # exact resume, incl. RNG state
93
+ ```
94
+
95
+ Warmup adapts the temperature ladder (equal estimated swap rejection per
96
+ neighbouring pair), per-temperature step sizes and a diagonal preconditioner,
97
+ then freezes them. `n_groups` samples many independent posteriors in one run,
98
+ and `exchange="reversible"` gives the classical randomized-parity baseline. The
99
+ documentation covers these, the gradient-based explorers (MALA, HMC) and the
100
+ diagnostics.
101
+
102
+ ## Benchmarks
103
+
104
+ Unless stated otherwise: RTX 3060, float32, same number of target-density evaluations per sweep
105
+ for every method (NRPT and reversible PT: B ladders × K temperatures; untempered RWM:
106
+ B·K chains), 4096 warmup + 8192 production sweeps, 3 seeds. Every target has an exact
107
+ or analytic ground truth. Code: [`benchmarks/`](https://github.com/StarostinV/nrptorch/tree/main/benchmarks); raw records:
108
+ [`docs/results/`](https://github.com/StarostinV/nrptorch/tree/main/docs/results); figures: `python docs/figures/make_benchmark_figures.py`.
109
+
110
+ ![Round-trip rate vs number of temperatures](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_lambda.png)
111
+
112
+ **Why nonreversible swaps.** A round trip is a replica travelling from the reference
113
+ to the target and back, the unit in which tempering moves information between modes.
114
+ With the deterministic even/odd scheme the round-trip rate rises with the number of
115
+ temperatures K and levels off at 1/(2 + 2Λ), where Λ is the global communication
116
+ barrier of the path (Syed et al. 2022); with random swap parity it peaks and then
117
+ falls towards zero, because each replica's temperature index performs a random walk.
118
+ Left: with exact draws at every temperature (the idealised local exploration the
119
+ theory assumes), measurements (dots, 3 seeds × 16 ladders) sit on the theoretical
120
+ curves (dashed). Right: with the library's random-walk moves, reversible PT still
121
+ follows its curve, while NRPT approaches its limit more slowly because consecutive
122
+ energies are correlated; at K = 257 it reaches 0.090 of the 0.101 limit, against 0.002
123
+ for reversible PT (CPU, float64, 4096 adaptive warmup sweeps, then burn-in until every
124
+ replica has visited the reference). Script: [`benchmarks/lambda_convergence.py`](https://github.com/StarostinV/nrptorch/blob/main/benchmarks/lambda_convergence.py);
125
+ figure: `python docs/figures/make_lambda_figure.py`.
126
+
127
+ ![Mode-weight error](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_mode_weights.png)
128
+
129
+ **Mode weights.** Error = total variation between the estimated and the true
130
+ mode/component weights (exact for Gaussian mixtures via `E_p[r_m(X)] = w_m`).
131
+ Up to D = 8, NRPT is the most accurate method on every target, from both starts.
132
+ The largest gains over reversible PT are on Gaussian mixtures with random rotated
133
+ covariances when all chains start in one mode: at D = 8 the error is 0.04–0.07 for NRPT,
134
+ 0.28–0.37 for reversible PT and 0.39–0.47 for untempered RWM. Reversible PT completes
135
+ essentially no round trips at K = 128 (a random-walk index needs ~K² sweeps per trip).
136
+ At D = 16 and D = 32 every method fails (error 0.2–0.8) and NRPT's advantage
137
+ disappears: round trips drop to ~0.002 per sweep (D = 16) and 0 (D = 32).
138
+
139
+ **Unimodal targets.** On a single Gaussian, untempered RWM with B·K chains wins
140
+ by 20–40× in ESS per second: NRPT spends most evaluations away from the target.
141
+ Tempering pays only when there are modes to cross.
142
+
143
+ **Diagnostics can lie.** Untempered RWM started in one mode reports R-hat 1.00 and
144
+ very high ESS while missing most of the mass (weight error 0.47–0.75). The
145
+ benchmark therefore always reports accuracy against the truth, not only ESS/R-hat.
146
+
147
+ ![GPU throughput](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_throughput.png)
148
+
149
+ **Throughput.** On the GPU the time per sweep is nearly constant (1.7–2 ms) from
150
+ 8 to 16,384 states for a cheap density, i.e. extra temperatures and ladders are
151
+ almost free until the density saturates the device. For such a cheap density the CPU
152
+ is still faster at the sizes measured (0.7–1.3 ms up to 2,048 states); the GPU pays off
153
+ for expensive densities: with a 3.2M-parameter MLP it stays flat up to ~2,048 states,
154
+ where it is ~17× faster than the CPU. In a one-seed screen, ESS per
155
+ second kept rising up to K = 256 temperatures — far beyond the CPU rule of thumb
156
+ K ≈ 2Λ. Current overhead: eager PyTorch kernel launches (NRPT sweep 2.0 ms vs
157
+ 0.67 ms for plain RWM at 512 states); compilation is planned.
158
+
159
+ **Where it fails.** A mixture with a narrow and a wide mode (entropic barrier),
160
+ Neal's funnel and the Gaussian mixtures at D ≥ 16 defeat every method here (weight
161
+ error 0.2–0.8; funnel mean error ≈ 0.7). Random-walk local moves cannot explore these
162
+ geometries at the intermediate temperatures, and the swap scheme cannot compensate.
@@ -0,0 +1,130 @@
1
+ # nrptorch
2
+
3
+ GPU-native **nonreversible parallel tempering** (NRPT) in PyTorch for continuous,
4
+ unnormalized densities: many independent tempering ladders, all temperatures and
5
+ all local moves batched on the device, deterministic even/odd swaps, exact
6
+ reference refreshes, adaptive temperature schedules, and diagnostics that say when
7
+ a run should not be trusted.
8
+
9
+ ![Nonreversible vs reversible parallel tempering on a 2-D Gaussian mixture](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/nrpt_gmm2d.gif)
10
+
11
+ *Nonreversible and reversible parallel tempering differ only in the swap schedule
12
+ (alternating even/odd pairs vs a random parity each sweep): same 32 temperatures,
13
+ same tuning (a separate pilot run), same local moves, same budget. The animation shows
14
+ the whole run: at sweep 0 every chain sits in one mode of a four-mode mixture. Bars:
15
+ estimated weights (outlines: true weights). Right: error of the weights over sweeps;
16
+ "no tempering" is 256 random-walk chains with the same density evaluations. Over 4
17
+ seeds the error after 1,200 sweeps is 0.09 [0.057, 0.108] for NRPT and 0.34
18
+ [0.31, 0.38] for reversible PT (script:
19
+ [`docs/figures/make_animation.py`](https://github.com/StarostinV/nrptorch/blob/main/docs/figures/make_animation.py)).*
20
+
21
+ Documentation: <https://starostinv.github.io/nrptorch/>. License: MIT.
22
+
23
+ ## Installation
24
+
25
+ ```
26
+ pip install nrptorch
27
+ ```
28
+
29
+ Requires Python >= 3.10 and PyTorch >= 2.1 (install the CUDA build of PyTorch first
30
+ for GPU runs). From source: `pip install -e ".[dev]"`.
31
+
32
+ ## Example
33
+
34
+ ```python
35
+ import torch
36
+ from nrptorch import NRPT, GeometricPath, RandomWalkMH, DiagNormalReference
37
+ from nrptorch import diagnostics as dg
38
+
39
+ D = 2
40
+ prior = DiagNormalReference(torch.zeros(D), 3.0 * torch.ones(D)) # N(0, 3^2 I)
41
+ centers = torch.tensor([[-2.0, 0.0], [2.0, 0.0]])
42
+
43
+
44
+ def log_likelihood(x): # (N, D) -> (N,)
45
+ d2 = ((x[:, None, :] - centers.to(x)) ** 2).sum(-1)
46
+ return torch.logsumexp(-0.5 * d2 / 0.3**2, dim=1)
47
+
48
+
49
+ path = GeometricPath(prior.log_prob, prior.sample, log_likelihood=log_likelihood)
50
+ sampler = NRPT(path, RandomWalkMH(step_size=0.3), n_temperatures=16, n_ladders=8,
51
+ device="cpu", dtype=torch.float32, seed=0) # device="cuda" for the GPU
52
+ state = sampler.initialize()
53
+ state, info = sampler.warmup(state, n_sweeps=1024, adapt_schedule=True, adapt_local=True)
54
+ result = sampler.sample(state, n_sweeps=2048, thin=2)
55
+
56
+ result.samples # (S, B, D): cold-temperature draws of B independent ladders
57
+ result.diagnostics # swap rejection per edge, barrier estimate, round-trip rate, ...
58
+ dg.rhat(result.samples[..., 0]) # rank-normalized split R-hat across ladders
59
+ dg.ess_bulk(result.samples[..., 0]) # bulk ESS
60
+ torch.save(sampler.checkpoint(result.state), "ckpt.pt") # exact resume, incl. RNG state
61
+ ```
62
+
63
+ Warmup adapts the temperature ladder (equal estimated swap rejection per
64
+ neighbouring pair), per-temperature step sizes and a diagonal preconditioner,
65
+ then freezes them. `n_groups` samples many independent posteriors in one run,
66
+ and `exchange="reversible"` gives the classical randomized-parity baseline. The
67
+ documentation covers these, the gradient-based explorers (MALA, HMC) and the
68
+ diagnostics.
69
+
70
+ ## Benchmarks
71
+
72
+ Unless stated otherwise: RTX 3060, float32, same number of target-density evaluations per sweep
73
+ for every method (NRPT and reversible PT: B ladders × K temperatures; untempered RWM:
74
+ B·K chains), 4096 warmup + 8192 production sweeps, 3 seeds. Every target has an exact
75
+ or analytic ground truth. Code: [`benchmarks/`](https://github.com/StarostinV/nrptorch/tree/main/benchmarks); raw records:
76
+ [`docs/results/`](https://github.com/StarostinV/nrptorch/tree/main/docs/results); figures: `python docs/figures/make_benchmark_figures.py`.
77
+
78
+ ![Round-trip rate vs number of temperatures](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_lambda.png)
79
+
80
+ **Why nonreversible swaps.** A round trip is a replica travelling from the reference
81
+ to the target and back, the unit in which tempering moves information between modes.
82
+ With the deterministic even/odd scheme the round-trip rate rises with the number of
83
+ temperatures K and levels off at 1/(2 + 2Λ), where Λ is the global communication
84
+ barrier of the path (Syed et al. 2022); with random swap parity it peaks and then
85
+ falls towards zero, because each replica's temperature index performs a random walk.
86
+ Left: with exact draws at every temperature (the idealised local exploration the
87
+ theory assumes), measurements (dots, 3 seeds × 16 ladders) sit on the theoretical
88
+ curves (dashed). Right: with the library's random-walk moves, reversible PT still
89
+ follows its curve, while NRPT approaches its limit more slowly because consecutive
90
+ energies are correlated; at K = 257 it reaches 0.090 of the 0.101 limit, against 0.002
91
+ for reversible PT (CPU, float64, 4096 adaptive warmup sweeps, then burn-in until every
92
+ replica has visited the reference). Script: [`benchmarks/lambda_convergence.py`](https://github.com/StarostinV/nrptorch/blob/main/benchmarks/lambda_convergence.py);
93
+ figure: `python docs/figures/make_lambda_figure.py`.
94
+
95
+ ![Mode-weight error](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_mode_weights.png)
96
+
97
+ **Mode weights.** Error = total variation between the estimated and the true
98
+ mode/component weights (exact for Gaussian mixtures via `E_p[r_m(X)] = w_m`).
99
+ Up to D = 8, NRPT is the most accurate method on every target, from both starts.
100
+ The largest gains over reversible PT are on Gaussian mixtures with random rotated
101
+ covariances when all chains start in one mode: at D = 8 the error is 0.04–0.07 for NRPT,
102
+ 0.28–0.37 for reversible PT and 0.39–0.47 for untempered RWM. Reversible PT completes
103
+ essentially no round trips at K = 128 (a random-walk index needs ~K² sweeps per trip).
104
+ At D = 16 and D = 32 every method fails (error 0.2–0.8) and NRPT's advantage
105
+ disappears: round trips drop to ~0.002 per sweep (D = 16) and 0 (D = 32).
106
+
107
+ **Unimodal targets.** On a single Gaussian, untempered RWM with B·K chains wins
108
+ by 20–40× in ESS per second: NRPT spends most evaluations away from the target.
109
+ Tempering pays only when there are modes to cross.
110
+
111
+ **Diagnostics can lie.** Untempered RWM started in one mode reports R-hat 1.00 and
112
+ very high ESS while missing most of the mass (weight error 0.47–0.75). The
113
+ benchmark therefore always reports accuracy against the truth, not only ESS/R-hat.
114
+
115
+ ![GPU throughput](https://raw.githubusercontent.com/StarostinV/nrptorch/main/docs/figures/fig_throughput.png)
116
+
117
+ **Throughput.** On the GPU the time per sweep is nearly constant (1.7–2 ms) from
118
+ 8 to 16,384 states for a cheap density, i.e. extra temperatures and ladders are
119
+ almost free until the density saturates the device. For such a cheap density the CPU
120
+ is still faster at the sizes measured (0.7–1.3 ms up to 2,048 states); the GPU pays off
121
+ for expensive densities: with a 3.2M-parameter MLP it stays flat up to ~2,048 states,
122
+ where it is ~17× faster than the CPU. In a one-seed screen, ESS per
123
+ second kept rising up to K = 256 temperatures — far beyond the CPU rule of thumb
124
+ K ≈ 2Λ. Current overhead: eager PyTorch kernel launches (NRPT sweep 2.0 ms vs
125
+ 0.67 ms for plain RWM at 512 states); compilation is planned.
126
+
127
+ **Where it fails.** A mixture with a narrow and a wide mode (entropic barrier),
128
+ Neal's funnel and the Gaussian mixtures at D ≥ 16 defeat every method here (weight
129
+ error 0.2–0.8; funnel mean error ≈ 0.7). Random-walk local moves cannot explore these
130
+ geometries at the intermediate temperatures, and the swap scheme cannot compensate.
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "nrptorch"
3
+ dynamic = ["version"]
4
+ description = "GPU-native nonreversible parallel tempering in PyTorch"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Vladimir Starostin" }]
9
+ requires-python = ">=3.10"
10
+ dependencies = ["torch>=2.1", "numpy"]
11
+ keywords = ["parallel tempering", "MCMC", "Bayesian inference", "multimodal sampling", "pytorch", "GPU"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Science/Research",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Topic :: Scientific/Engineering :: Mathematics",
19
+ "Topic :: Scientific/Engineering :: Physics",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/StarostinV/nrptorch"
24
+ Source = "https://github.com/StarostinV/nrptorch"
25
+ Issues = "https://github.com/StarostinV/nrptorch/issues"
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest", "pytest-timeout", "scipy", "arviz"]
29
+ docs = ["mkdocs-material", "mkdocstrings[python]"]
30
+
31
+ [build-system]
32
+ requires = ["setuptools>=77"]
33
+ build-backend = "setuptools.build_meta"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.dynamic]
39
+ version = { attr = "nrptorch.__version__" }
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ markers = ["slow: statistical end-to-end tests", "gpu: needs CUDA"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,17 @@
1
+ """PyTorch-native nonreversible parallel tempering."""
2
+
3
+ from .exchange import deo_kernel, pair_lower_indices, permute_slots, update_round_trips
4
+ from .explorers import HMC, MALA, RandomWalkMH, hmc_kernel, mala_kernel, rwm_kernel
5
+ from .paths import DiagNormalReference, GeometricPath, ShapeError
6
+ from .sampler import NRPT, NonFiniteError, SampleResult, SweepRandomness, sweep_kernel
7
+ from .state import Diagnostics, NRPTState
8
+
9
+ __all__ = [
10
+ "NRPT", "GeometricPath", "RandomWalkMH", "DiagNormalReference", "NRPTState", "Diagnostics",
11
+ "SampleResult", "SweepRandomness", "ShapeError", "NonFiniteError", "sweep_kernel",
12
+ "MALA", "HMC", "mala_kernel", "hmc_kernel", "deo_kernel", "pair_lower_indices", "permute_slots", "update_round_trips", "rwm_kernel",
13
+ ]
14
+ __version__ = "0.1.0"
15
+
16
+ from .adaptation import AdaptationConfig, ScheduleError, schedule_from_barrier # noqa: E402
17
+ __all__ += ["AdaptationConfig", "ScheduleError", "schedule_from_barrier"]
@@ -0,0 +1,234 @@
1
+ """Warmup-only adaptation: annealing schedule, RWM step sizes, diagonal preconditioner.
2
+
3
+ Round structure: warmup is split into rounds of geometrically
4
+ growing length (first_round, 2*first_round, ...); the remainder of the budget
5
+ is folded into the last round. In each round the first ``discard_frac`` of
6
+ sweeps re-equilibrate after the previous round's parameter change and are
7
+ excluded from the round's statistics.
8
+
9
+ At the end of every round except the last:
10
+ * schedule: mean edge rejection r_i = mean(1 - alpha_i) over attempts gives a
11
+ piecewise-linear cumulative barrier Lambda(beta_i) = sum_{j<i} max(r_j, floor);
12
+ new betas invert it at equally spaced quantiles (small-gap approximation
13
+ r_i ~ lambda(beta_i) * dbeta_i);
14
+ * preconditioner: per-slot coordinate variances of the round's draws,
15
+ shrunk toward ``precond_floor``; step sizes reset to the explorer's default_step(D)
16
+ (RWM 2.38 / sqrt(D), MALA 1.65 / D^(1/6), HMC 1 / (L D^(1/4))).
17
+ The last round never changes the schedule or preconditioner, so step sizes
18
+ are tuned on the frozen production ladder.
19
+
20
+ Step sizes adapt every sweep (all rounds) by Robbins-Monro on the log scale,
21
+ log eps_k += gamma_t * (acc_k - target), gamma_t = scale / (t + 1)^kappa with
22
+ t restarting each round; acc_k is that sweep's acceptance fraction at slot k
23
+ over ladders and local steps. Bounded to [min_step, max_step].
24
+
25
+ All parameters are frozen once warmup returns; nothing here runs in sample().
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ from dataclasses import dataclass, replace
32
+
33
+ import torch
34
+ from torch import Tensor
35
+
36
+ from .state import Diagnostics, NRPTState, accum_dtype
37
+
38
+
39
+ class ScheduleError(ValueError):
40
+ pass
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class AdaptationConfig:
45
+ adapt_schedule: bool = True
46
+ adapt_step_size: bool = True
47
+ adapt_precond: bool = True
48
+ first_round: int = 128
49
+ discard_frac: float = 0.25
50
+ target_accept: float | None = None # None: the explorer's own (RWM 0.234, MALA 0.574, HMC 0.8)
51
+ rm_scale: float = 1.0
52
+ rm_kappa: float = 0.6
53
+ min_step: float = 1e-6
54
+ max_step: float = 1e3
55
+ barrier_floor: float = 1e-8 # per-edge floor for strict invertibility
56
+ min_spacing: float = 1e-6 # minimum beta gap
57
+ damping: float = 0.0 # new = (1-d) * proposed + d * old
58
+ precond_floor: float = 1e-3
59
+ precond_prior_n: float = 5.0 # Stan-style shrinkage weight toward precond_floor
60
+
61
+ def __post_init__(self):
62
+ checks = [
63
+ (self.first_round >= 1, "first_round >= 1"),
64
+ (0 <= self.discard_frac < 1, "0 <= discard_frac < 1"),
65
+ (self.target_accept is None or 0 < self.target_accept < 1, "0 < target_accept < 1"),
66
+ (self.rm_scale > 0 and 0.5 < self.rm_kappa <= 1, "rm_scale > 0, 0.5 < rm_kappa <= 1"),
67
+ (0 < self.min_step < self.max_step, "0 < min_step < max_step"),
68
+ (self.barrier_floor >= 0 and self.min_spacing > 0, "barrier_floor >= 0, min_spacing > 0"),
69
+ (0 <= self.damping < 1, "0 <= damping < 1"),
70
+ (self.precond_floor > 0 and self.precond_prior_n >= 0, "precond_floor > 0, prior_n >= 0"),
71
+ ]
72
+ for ok, msg in checks:
73
+ if not ok:
74
+ raise ValueError(f"AdaptationConfig: need {msg}")
75
+
76
+ def round_lengths(self, n_sweeps: int) -> list[int]:
77
+ if n_sweeps <= 0:
78
+ return []
79
+ lens, n = [], self.first_round
80
+ while sum(lens) + n <= n_sweeps:
81
+ lens.append(n)
82
+ n *= 2
83
+ rem = n_sweeps - sum(lens)
84
+ if not lens:
85
+ return [n_sweeps]
86
+ lens[-1] += rem
87
+ return lens
88
+
89
+
90
+ def cumulative_barrier(betas: Tensor, rejection: Tensor, floor: float) -> Tensor:
91
+ """Lambda at each grid point, (K,), Lambda[0] = 0."""
92
+ inc = rejection.clamp(min=floor)
93
+ return torch.cat([torch.zeros(1, dtype=inc.dtype), inc.cumsum(0)])
94
+
95
+
96
+ def schedule_from_barrier(betas: Tensor, rejection: Tensor, floor: float = 1e-8,
97
+ min_spacing: float = 1e-6, damping: float = 0.0) -> Tensor:
98
+ """Equal-barrier ladder of the same size from per-edge rejection estimates.
99
+
100
+ betas (K,) float64 on CPU, rejection (K-1,). Keeps the grid when the total
101
+ barrier is zero or the estimates are not finite.
102
+ """
103
+ betas = betas.detach().double().cpu()
104
+ rejection = rejection.detach().double().cpu()
105
+ K = betas.numel()
106
+ if rejection.shape != (K - 1,):
107
+ raise ValueError("rejection must have shape (K-1,)")
108
+ if not torch.isfinite(rejection).all() or float(rejection.sum()) <= 0:
109
+ return betas.clone()
110
+ lam = cumulative_barrier(betas, rejection, floor)
111
+ targets = torch.linspace(0, float(lam[-1]), K, dtype=torch.float64)
112
+ idx = torch.searchsorted(lam, targets, right=True).clamp(1, K - 1) - 1
113
+ frac = (targets - lam[idx]) / (lam[idx + 1] - lam[idx])
114
+ new = betas[idx] + frac.clamp(0, 1) * (betas[idx + 1] - betas[idx])
115
+ new[0], new[-1] = 0.0, 1.0
116
+ if damping > 0:
117
+ new = (1 - damping) * new + damping * betas
118
+ # enforce minimum spacing by a forward pass anchored at both ends
119
+ if min_spacing * (K - 1) >= 1:
120
+ raise ScheduleError(f"min_spacing {min_spacing} infeasible for K={K}")
121
+ for i in range(1, K - 1):
122
+ new[i] = max(float(new[i]), float(new[i - 1]) + min_spacing)
123
+ for i in range(K - 2, 0, -1):
124
+ new[i] = min(float(new[i]), float(new[i + 1]) - min_spacing)
125
+ if new[1] - new[0] < min_spacing * (1 - 1e-9) or not (new.diff() > 0).all():
126
+ raise ScheduleError("cannot satisfy strict monotone spacing")
127
+ return new
128
+
129
+
130
+ @dataclass
131
+ class _RoundStats:
132
+ rej_sum: Tensor
133
+ attempts: Tensor
134
+ x_sum: Tensor
135
+ x_sq: Tensor
136
+ n: int = 0
137
+
138
+
139
+ def adaptive_warmup(sampler, state: NRPTState, n_sweeps: int, cfg: AdaptationConfig):
140
+ """Run adaptive warmup; returns (state with frozen params and reset diagnostics, info).
141
+
142
+ With slot-parameter groups (state.betas of shape (G,K)) every group is adapted
143
+ from its own B/G ladders only; ungrouped state is handled as G = 1.
144
+ """
145
+ B, K, D = state.shape
146
+ G = state.n_groups
147
+ Bg = B // G
148
+ grouped = state.grouped
149
+ dev = state.x.device
150
+ fd = accum_dtype(dev)
151
+
152
+ def to_g(t): # slot parameter -> leading group axis
153
+ return t if grouped else t.unsqueeze(0)
154
+
155
+ def from_g(t):
156
+ return t if grouped else t[0]
157
+
158
+ target = cfg.target_accept if cfg.target_accept is not None else getattr(
159
+ sampler.explorer, "target_accept", 0.234)
160
+ reset_step = (sampler.explorer.default_step(D) if hasattr(sampler.explorer, "default_step")
161
+ else 2.38 / math.sqrt(D))
162
+ history = []
163
+ lens = cfg.round_lengths(n_sweeps)
164
+ for r, n_round in enumerate(lens):
165
+ last = r == len(lens) - 1
166
+ n_discard = int(cfg.discard_frac * n_round)
167
+ st = _RoundStats(torch.zeros(G, K - 1, dtype=fd, device=dev),
168
+ torch.zeros(G, K - 1, dtype=torch.int64, device=dev),
169
+ torch.zeros(G, K, D, dtype=fd, device=dev),
170
+ torch.zeros(G, K, D, dtype=fd, device=dev))
171
+ round_start = state.diagnostics
172
+ log_step = to_g(state.step_size).log() # (G,K)
173
+ for t in range(n_round):
174
+ before = state.diagnostics
175
+ state = sampler.sweep(state)
176
+ after = state.diagnostics
177
+ if cfg.adapt_step_size and sampler.L > 0:
178
+ acc = ((after.group_local_accepts - before.group_local_accepts)[:, 1:].to(state.x.dtype)
179
+ / (Bg * sampler.L)) # (G,K-1)
180
+ gamma = cfg.rm_scale / (t + 1) ** cfg.rm_kappa
181
+ log_step = torch.cat([log_step[:, :1], log_step[:, 1:] + gamma * (acc - target)], 1)
182
+ log_step = log_step.clamp(math.log(cfg.min_step), math.log(cfg.max_step))
183
+ state = replace(state, step_size=from_g(log_step.exp()))
184
+ if t >= n_discard:
185
+ st.rej_sum += after.group_edge_rejection_sum - before.group_edge_rejection_sum
186
+ st.attempts += after.group_edge_attempts - before.group_edge_attempts
187
+ xs = state.x.to(fd).view(G, Bg, K, D)
188
+ st.x_sum += xs.sum(1)
189
+ st.x_sq += (xs * xs).sum(1)
190
+ st.n += Bg
191
+ # ---- end of round: host-side decisions (one sync per round)
192
+ rej = (st.rej_sum / st.attempts.clamp(min=1)).double().cpu() # (G,K-1)
193
+ rej = torch.where(st.attempts.cpu() > 0, rej, torch.full_like(rej, float("nan")))
194
+ barrier = torch.nansum(rej, 1) # (G,)
195
+ rec = dict(round=r, n_sweeps=n_round, betas=state.betas.double().cpu().clone(),
196
+ edge_rejection=from_g(rej), barrier=float(barrier.mean()),
197
+ step_size=state.step_size.double().cpu().clone(),
198
+ local_accept_rate=_round_local_accept(round_start, state.diagnostics),
199
+ round_trip_rate=float((state.diagnostics.round_trips - round_start.round_trips).sum())
200
+ / (n_round * B))
201
+ if grouped:
202
+ rec["group_barrier"] = barrier
203
+ if not last:
204
+ if cfg.adapt_schedule:
205
+ old = to_g(state.betas)
206
+ new = torch.stack([schedule_from_barrier(old[g], rej[g], cfg.barrier_floor,
207
+ cfg.min_spacing, cfg.damping) for g in range(G)])
208
+ new_t = new.to(device=dev, dtype=state.betas.dtype)
209
+ # spacing survives the cast up to rounding (half of min_spacing)
210
+ if (not (new_t.diff(dim=1) >= 0.5 * cfg.min_spacing).all() or (new_t[:, 0] != 0).any()
211
+ or (new_t[:, -1] != 1).any()):
212
+ raise ScheduleError(f"adapted ladder violates min_spacing in {new_t.dtype}")
213
+ state = replace(state, betas=from_g(new_t))
214
+ sampler.betas = state.betas
215
+ if cfg.adapt_precond and st.n > 1:
216
+ mean = st.x_sum / st.n
217
+ var = (st.x_sq / st.n - mean * mean).clamp(min=0) * st.n / (st.n - 1)
218
+ w = st.n / (st.n + cfg.precond_prior_n)
219
+ pre = (w * var + (1 - w) * cfg.precond_floor).clamp(min=cfg.precond_floor) # (G,K,D)
220
+ pre = torch.cat([to_g(state.precond_diag)[:, :1], pre[:, 1:].to(state.x.dtype)], 1)
221
+ step = torch.full_like(state.step_size, reset_step)
222
+ state = replace(state, precond_diag=from_g(pre), step_size=step)
223
+ rec["new_betas"] = state.betas.double().cpu().clone()
224
+ history.append(rec)
225
+ sampler._check_nonfinite(state)
226
+ final = state.diagnostics.summary(sampler.exchange)
227
+ state = replace(state, diagnostics=Diagnostics.zeros(B, K, dev, G))
228
+ return state, dict(rounds=history, final_round=history[-1] if history else None, cumulative=final)
229
+
230
+
231
+ def _round_local_accept(before: Diagnostics, after: Diagnostics) -> Tensor:
232
+ att = (after.local_attempts - before.local_attempts).double().cpu()
233
+ acc = (after.local_accepts - before.local_accepts).double().cpu()
234
+ return torch.where(att > 0, acc / att.clamp(min=1), torch.full_like(att, float("nan")))