psyphy 0.0.2__py3-none-any.whl

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.
@@ -0,0 +1,89 @@
1
+ """
2
+ langevin.py
3
+ -----------
4
+
5
+ Langevin samplers for posterior inference.
6
+
7
+ Will lkely implement:
8
+ - Overdamped (unadjusted) Langevin Algorithm (ULA) (exists in BlackJax)
9
+ - Underdamped Langevin (with BAOAB splitting scheme?)
10
+
11
+ Used for posterior-aware trial placement (InfoGain).
12
+
13
+
14
+ MVP implementation:
15
+ - Stub that returns an initial Posterior.
16
+ - Future: implement underdamped Langevin dynamics (e.g. BAOAB integrator).
17
+ """
18
+
19
+ from psyphy.inference.base import InferenceEngine
20
+ from psyphy.posterior.posterior import MAPPosterior
21
+
22
+
23
+ class LangevinSampler(InferenceEngine):
24
+ """
25
+ Langevin sampler (stub).
26
+
27
+ Parameters
28
+ ----------
29
+ steps : int, default=1000
30
+ Number of Langevin steps.
31
+ step_size : float, default=1e-3
32
+ Integration step size.
33
+ temperature : float, default=1.0
34
+ Noise scale (temperature).
35
+ """
36
+
37
+ def __init__(
38
+ self, steps: int = 1000, step_size: float = 1e-3, temperature: float = 1.0
39
+ ):
40
+ self.steps = steps
41
+ self.step_size = step_size
42
+ self.temperature = temperature
43
+
44
+ def fit(self, model, data) -> MAPPosterior:
45
+ """
46
+ Fit model parameters with Langevin dynamics (stub).
47
+
48
+ Parameters
49
+ ----------
50
+ model : WPPM
51
+ Model instance.
52
+ data : ResponseData
53
+ Observed trials.
54
+
55
+ """
56
+
57
+ raise NotImplementedError("Langevin Sampler not implemented yet.")
58
+
59
+
60
+ class NumpyroSampler(InferenceEngine):
61
+ """
62
+ Numpyro-based sampler (stub).
63
+
64
+ Parameters
65
+ ----------
66
+ steps : int, default=1000
67
+ Number of sampling steps.
68
+ """
69
+
70
+ def __init__(self, steps: int = 1000):
71
+ self.steps = steps
72
+
73
+ def fit(self, model, data) -> MAPPosterior:
74
+ """
75
+ Fit model parameters using Numpyro (stub).
76
+
77
+ Parameters
78
+ ----------
79
+ model : WPPM
80
+ Model instance.
81
+ data : ResponseData
82
+ Observed trials.
83
+
84
+ Returns
85
+ -------
86
+ MAPPosterior
87
+ Posterior distribution containing sample history.
88
+ """
89
+ raise NotImplementedError("NumpyroSampler.fit not implemented yet.")
@@ -0,0 +1,56 @@
1
+ """
2
+ laplace.py
3
+ ----------
4
+
5
+ Laplace approximation to posterior.
6
+
7
+
8
+ Approximates posterior with a Gaussian:
9
+ N(mean = MAP, covariance = H^-1 at MAP)
10
+
11
+ Provides posterior.sample() cheaply.
12
+ Useful for InfoGainPlacement when only MAP fit is available.
13
+
14
+
15
+ MVP implementation:
16
+ - Stub that just returns the MAP posterior.
17
+ - Future: compute covariance from Hessian at MAP params.
18
+ """
19
+
20
+ # import jax.scipy.linalg as jl
21
+ # from optax import GradientTransformation
22
+
23
+ from psyphy.inference.base import InferenceEngine
24
+ from psyphy.posterior.posterior import MAPPosterior
25
+
26
+
27
+ class LaplaceApproximation(InferenceEngine):
28
+ """
29
+ Laplace approximation around MAP estimate.
30
+
31
+ Methods
32
+ -------
33
+ from_map(map_posterior) -> Posterior
34
+ Construct a Gaussian approximation centered at MAP.
35
+ """
36
+
37
+ def from_map(self, map_posterior: MAPPosterior) -> MAPPosterior:
38
+ """
39
+ Return posterior approximation from MAP.
40
+
41
+ Parameters
42
+ ----------
43
+ map_posterior : Posterior
44
+ Posterior object from MAP optimization.
45
+
46
+ Returns
47
+ -------
48
+ MAPPosterior
49
+ Posterior distribution containing Laplace approximation.
50
+ """
51
+ # 1. First find MAP estimate
52
+ # 2. Compute Hessian at MAP
53
+ # 3. Invert Hessian to get covariance
54
+ # 4. Return Gaussian posterior with MAP mean and covariance
55
+
56
+ return map_posterior
@@ -0,0 +1,245 @@
1
+ """
2
+ map_optimizer.py
3
+ ----------------
4
+
5
+ MAP (Maximum A Posteriori) optimizer using Optax.
6
+
7
+ MVP implementation:
8
+ - Uses gradient ascent on log posterior.
9
+ - Defaults to SGD with momentum, but any Optax optimizer can be passed in.
10
+
11
+ Connections
12
+ -----------
13
+ - Calls WPPM.log_posterior_from_data(params, data) as the objective.
14
+ - Returns a Posterior object wrapping the MAP estimate.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import contextlib
20
+
21
+ import jax
22
+ import optax
23
+
24
+ from psyphy.inference.base import InferenceEngine
25
+ from psyphy.posterior.posterior import MAPPosterior
26
+
27
+
28
+ class MAPOptimizer(InferenceEngine):
29
+ """
30
+ MAP (Maximum A Posteriori) optimizer.
31
+
32
+ Parameters
33
+ ----------
34
+ steps : int, default=500
35
+ Number of optimization steps.
36
+ optimizer : optax.GradientTransformation, optional
37
+ Optax optimizer to use. Default: SGD with momentum.
38
+
39
+ Notes
40
+ -----
41
+ - Loss function = negative log posterior.
42
+ - Gradients computed with jax.grad.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ steps: int = 500,
48
+ learning_rate: float = 5e-5,
49
+ momentum: float = 0.9,
50
+ optimizer: optax.GradientTransformation | None = None,
51
+ *,
52
+ track_history: bool = True,
53
+ log_every: int = 1,
54
+ progress_every: int = 10,
55
+ show_progress: bool = False,
56
+ max_grad_norm: float | None = 1.0,
57
+ ):
58
+ """Create a MAP optimizer.
59
+
60
+ Parameters
61
+ ----------
62
+ steps : int
63
+ Number of optimization steps.
64
+ optimizer : optax.GradientTransformation | None
65
+ Optax optimizer to use.
66
+ learning_rate : float, optional
67
+ Learning rate for the default optimizer (SGD with momentum).
68
+ momentum : float, optional
69
+ Momentum for the default optimizer (SGD with momentum).
70
+ track_history : bool, optional
71
+ When True, record loss history during fitting for plotting.
72
+ log_every : int, optional
73
+ Record every N steps (also records the last step).
74
+ progress_every : int, optional
75
+ Update the progress-bar loss display every N steps (and the last step)
76
+ when show_progress=True.
77
+ This is kept separate from log_every so you can record loss at high
78
+ frequency for plotting (e.g. log_every=1) without forcing a device->host
79
+ sync for the progress UI every step.
80
+ show_progress : bool, optional
81
+ When True, display a tqdm progress bar during fitting.
82
+ This is a UI feature: if tqdm is not installed,
83
+ fitting proceeds without a progress bar.
84
+ max_grad_norm : float | None, optional
85
+ If set, clip gradients by global norm to this value before applying
86
+ optimizer updates. This stabilizes optimization when gradients blow up.
87
+ """
88
+ self.steps = steps
89
+ base_optimizer = optimizer or optax.sgd(
90
+ learning_rate=learning_rate, momentum=momentum
91
+ )
92
+ if max_grad_norm is None:
93
+ self.optimizer = base_optimizer
94
+ else:
95
+ self.optimizer = optax.chain(
96
+ optax.clip_by_global_norm(float(max_grad_norm)),
97
+ base_optimizer,
98
+ )
99
+
100
+ self.track_history = track_history
101
+ self.log_every = max(1, int(log_every))
102
+ self.progress_every = max(1, int(progress_every))
103
+ self.show_progress = bool(show_progress)
104
+ self.max_grad_norm = max_grad_norm
105
+ # Exposed after fit() when tracking is enabled
106
+ self.loss_steps: list[int] = []
107
+ self.loss_history: list[float] = []
108
+
109
+ def fit(
110
+ self,
111
+ model,
112
+ data,
113
+ init_params: dict | None = None,
114
+ seed: int | None = None,
115
+ ) -> MAPPosterior:
116
+ """
117
+ Fit model parameters with MAP optimization.
118
+
119
+ Parameters
120
+ ----------
121
+ model : WPPM
122
+ Model instance.
123
+ data : ResponseData
124
+ Observed trials.
125
+ init_params : dict | None, optional
126
+ Initial parameter PyTree to start optimization from. If provided,
127
+ this takes precedence over the seed.
128
+ seed : int | None, optional
129
+ PRNG seed used to draw initial parameters from the model's prior
130
+ when init_params is not provided, and as the base key for the MC
131
+ likelihood random stream during optimization. If None, defaults to 0.
132
+
133
+ Returns
134
+ -------
135
+ MAPPosterior
136
+ Posterior wrapper around MAP params and model.
137
+ """
138
+
139
+ rng_seed = 0 if seed is None else int(seed)
140
+ # Master key: split into init key and optimization key stream.
141
+ master_key = jax.random.PRNGKey(rng_seed)
142
+ init_key, opt_key = jax.random.split(master_key)
143
+
144
+ # Initialize parameters
145
+ params = init_params if init_params is not None else model.init_params(init_key)
146
+ opt_state = self.optimizer.init(params)
147
+
148
+ # key is now an explicit argument so each JIT-compiled call receives a
149
+ # distinct random key — a fresh MC noise realization per gradient step.
150
+ @jax.jit
151
+ def step(params, opt_state, key):
152
+ loss, grads = jax.value_and_grad(
153
+ lambda p: -model.log_posterior_from_data(p, data, key=key)
154
+ )(params)
155
+ updates, opt_state = self.optimizer.update(grads, opt_state, params)
156
+ params = optax.apply_updates(params, updates)
157
+ return params, opt_state, loss
158
+
159
+ # clear any previous history
160
+ if self.track_history:
161
+ self.loss_steps.clear()
162
+ self.loss_history.clear()
163
+
164
+ # Optional progress bar.
165
+ #
166
+ # Why we *manually* advance the bar:
167
+ # - When JAX runs on GPU, the first `step(...)` call can spend a long time in
168
+ # compilation, and tqdm may not visibly advance if the underlying iterator
169
+ # doesn't get a chance to redraw.
170
+ # - By keeping a normal `range(self.steps)` loop and calling `pbar.update(1)`
171
+ # ourselves, we ensure the bar advances exactly once per iteration.
172
+ #
173
+ # Performance note: *displaying the loss* requires transferring `loss` from
174
+ # device -> host, which can add sync overhead. We therefore only attach a
175
+ # loss postfix every `progress_every` steps.
176
+ pbar = None
177
+ if self.show_progress:
178
+ try:
179
+ from tqdm.auto import tqdm
180
+
181
+ pbar = tqdm(total=self.steps, desc="MAP fit", leave=False)
182
+ except Exception:
183
+ # Soft dependency: tqdm not available (or terminal unsuitable).
184
+ pbar = None
185
+
186
+ for i in range(self.steps):
187
+ # Split a fresh subkey for each step so the MC likelihood sees a
188
+ # different noise realization on every gradient evaluation.
189
+ opt_key, subkey = jax.random.split(opt_key)
190
+ params, opt_state, loss = step(params, opt_state, subkey)
191
+
192
+ # Non-finite guard: if loss becomes NaN/Inf, optimization has diverged.
193
+ # Stop early so downstream plots don’t look “truncated” due to NaNs.
194
+ if not bool(jax.numpy.isfinite(loss)):
195
+ if self.track_history:
196
+ try:
197
+ self.loss_steps.append(i)
198
+ self.loss_history.append(float(loss))
199
+ except Exception:
200
+ pass
201
+ print(
202
+ f"[MAPOptimizer] Non-finite loss at step {i}: {loss}. "
203
+ "Stopping early."
204
+ )
205
+ if pbar is not None:
206
+ with contextlib.suppress(Exception):
207
+ pbar.update(1)
208
+ break
209
+
210
+ if self.track_history and (
211
+ (i % self.log_every == 0) or (i == self.steps - 1)
212
+ ):
213
+ # Pull scalar to host and record
214
+ try:
215
+ self.loss_steps.append(i)
216
+ self.loss_history.append(float(loss))
217
+ except Exception:
218
+ # do not break fitting if logging fails
219
+ pass
220
+
221
+ # progress bar loss display (avoid host sync every step)
222
+ if pbar is not None and (
223
+ (i % self.progress_every == 0) or (i == self.steps - 1)
224
+ ):
225
+ with contextlib.suppress(Exception):
226
+ pbar.set_postfix(loss=float(loss))
227
+
228
+ if pbar is not None:
229
+ with contextlib.suppress(Exception):
230
+ pbar.update(1)
231
+ # Encourage a redraw occasionally in environments with buffered/stale
232
+ # TTY updates.
233
+ if (i % self.progress_every == 0) or (i == self.steps - 1):
234
+ pbar.refresh()
235
+
236
+ if pbar is not None:
237
+ with contextlib.suppress(Exception):
238
+ pbar.close()
239
+
240
+ return MAPPosterior(params=params, model=model)
241
+
242
+ # Optional helper
243
+ def get_history(self) -> tuple[list[int], list[float]]:
244
+ """Return (steps, losses) recorded during the last fit when tracking was enabled."""
245
+ return self.loss_steps, self.loss_history
@@ -0,0 +1,46 @@
1
+ """
2
+ psyphy.model
3
+ ============
4
+
5
+ Model-layer API: everything model-related in one place.
6
+
7
+ Includes
8
+ --------
9
+ - WPPM (core model)
10
+ - Priors (Prior)
11
+ - Tasks (TaskLikelihood base, OddityTask)
12
+ - Noise models (GaussianNoise, StudentTNoise)
13
+
14
+ All functions/classes use JAX arrays (jax.numpy as jnp) for autodiff
15
+ and optimization with Optax.
16
+
17
+ Typical usage
18
+ -------------
19
+ from psyphy.model import WPPM, Prior, OddityTask, GaussianNoise
20
+ """
21
+
22
+ from .base import Model
23
+ from .covariance_field import CovarianceField, WPPMCovarianceField
24
+ from .likelihood import OddityTask, OddityTaskConfig, TaskLikelihood
25
+ from .noise import GaussianNoise, StudentTNoise
26
+ from .prior import Prior
27
+ from .wppm import WPPM
28
+
29
+ __all__ = [
30
+ # Base
31
+ "Model",
32
+ # Covariance fields
33
+ "CovarianceField",
34
+ "WPPMCovarianceField",
35
+ # Models
36
+ "WPPM",
37
+ # Priors
38
+ "Prior",
39
+ # Tasks
40
+ "TaskLikelihood",
41
+ "OddityTask",
42
+ "OddityTaskConfig",
43
+ # Noise models
44
+ "GaussianNoise",
45
+ "StudentTNoise",
46
+ ]
psyphy/model/base.py ADDED
@@ -0,0 +1,77 @@
1
+ """
2
+ base.py
3
+ -------
4
+
5
+ Base class for psychophysical models.
6
+
7
+ Design
8
+ ------
9
+ Models in PsyPhy are **stateless configuration objects**.
10
+ They consist of a:
11
+ 1. Prior (init_params) and a
12
+ 2. Likelihood (log_likelihood)
13
+
14
+ They do NOT hold data or fitted parameters.
15
+ Inference is handled by external engines (e.g. MAPOptimizer) which
16
+ return a Posterior object containing the results.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from abc import ABC, abstractmethod
22
+ from typing import TYPE_CHECKING, Any
23
+
24
+ import jax.numpy as jnp
25
+
26
+ if TYPE_CHECKING:
27
+ from psyphy.data import ResponseData
28
+
29
+
30
+ class Model(ABC):
31
+ """
32
+ Abstract base class for psychophysical models.
33
+
34
+ Subclasses must implement:
35
+ - init_params(key) --> sample initial parameters (Prior)
36
+ - log_likelihood_from_data(params, data) --> compute likelihood
37
+ """
38
+
39
+ # ------------------------------------------------------------------
40
+ # Abstract methods (must be implemented by subclasses)
41
+ # ------------------------------------------------------------------
42
+
43
+ @abstractmethod
44
+ def init_params(self, key: Any) -> dict: # jax.random.KeyArray
45
+ """
46
+ Sample initial parameters from prior.
47
+
48
+ Parameters
49
+ ----------
50
+ key : jax.random.KeyArray
51
+ PRNG key
52
+
53
+ Returns
54
+ -------
55
+ dict
56
+ Parameter PyTree
57
+ """
58
+ ...
59
+
60
+ @abstractmethod
61
+ def log_likelihood_from_data(self, params: dict, data: ResponseData) -> jnp.ndarray:
62
+ """
63
+ Compute log p(data | params).
64
+
65
+ Parameters
66
+ ----------
67
+ params : dict
68
+ Model parameters
69
+ data : ResponseData
70
+ Observed trials
71
+
72
+ Returns
73
+ -------
74
+ jnp.ndarray
75
+ Log-likelihood (scalar)
76
+ """
77
+ ...