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,701 @@
1
+ """psyphy.model.likelihood
2
+
3
+ Task likelihoods for psychophysical experiments.
4
+
5
+ This module defines task-specific mappings from a model (e.g., WPPM) and stimuli
6
+ to response likelihoods.
7
+
8
+ Current direction
9
+ -----------------
10
+ `OddityTask`: the log-likelihood is computed via Monte Carlo observer
11
+ simulation of the full 3-stimulus oddity decision rule (two identical references,
12
+ one comparison).
13
+
14
+ The public API is:
15
+
16
+ - ``TaskLikelihood.predict(params, stimuli, model, noise)``
17
+ Optional fast predictor for p(correct). For MC-only tasks this may be
18
+ unimplemented.
19
+
20
+ - ``TaskLikelihood.loglik(params, data, model, noise, **kwargs)``
21
+ Compute log-likelihood of observed responses under this task.
22
+
23
+ Connections
24
+ -----------
25
+ - WPPM delegates to the task to compute likelihood.
26
+ - Noise models are passed through so likelihoods can simulate observer responses.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from abc import ABC, abstractmethod
32
+ from dataclasses import dataclass
33
+ from typing import Any
34
+
35
+ import jax
36
+ import jax.numpy as jnp
37
+ import jax.random as jr
38
+
39
+ Stimulus = tuple[jnp.ndarray, jnp.ndarray]
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class OddityTaskConfig:
44
+ """Configuration for :class:`OddityTask`.
45
+
46
+ This is the single source of truth for MC likelihood controls.
47
+
48
+ Attributes
49
+ ----------
50
+ num_samples : int
51
+ Number of Monte Carlo samples per trial.
52
+ bandwidth : float
53
+ Logistic CDF smoothing bandwidth.
54
+ default_key_seed : int
55
+ Seed used when no key is provided (keeps behavior deterministic by
56
+ default while allowing reproducibility control upstream).
57
+ """
58
+
59
+ num_samples: int = 1000
60
+ bandwidth: float = 1e-2
61
+ default_key_seed: int = 0
62
+
63
+ def __post_init__(self) -> None:
64
+ if int(self.num_samples) <= 0:
65
+ raise ValueError(f"num_samples must be > 0, got {self.num_samples}")
66
+ if float(self.bandwidth) <= 0:
67
+ raise ValueError(f"bandwidth must be > 0, got {self.bandwidth}")
68
+
69
+
70
+ class TaskLikelihood(ABC):
71
+ """
72
+ Abstract base class for task likelihoods
73
+ """
74
+
75
+ @abstractmethod
76
+ def predict(
77
+ self, params: Any, stimuli: Stimulus, model: Any, noise: Any
78
+ ) -> jnp.ndarray:
79
+ """Predict probability of correct response for a stimulus."""
80
+ ...
81
+
82
+ @abstractmethod
83
+ def loglik(
84
+ self, params: Any, data: Any, model: Any, noise: Any, **kwargs: Any
85
+ ) -> jnp.ndarray:
86
+ """Compute log-likelihood of observed responses under this task.
87
+
88
+ Why ``**kwargs``?
89
+ - Different tasks may need different optional runtime controls.
90
+ - MC-based tasks may need parameters such as a PRNG ``key``.
91
+ In particular, :class:`OddityTask` takes Monte Carlo controls
92
+ (``num_samples`` and ``bandwidth``) exclusively from
93
+ :class:`OddityTaskConfig` to avoid silent mismatch bugs.
94
+
95
+ Notes
96
+ -----
97
+ - Task implementations should document which kwargs they accept.
98
+ - Callers should not assume arbitrary kwargs are supported.
99
+ """
100
+ ...
101
+
102
+
103
+ class OddityTask(TaskLikelihood):
104
+ """
105
+ Three-alternative forced-choice oddity task (MC-based only).
106
+
107
+ Implements the full 3-stimulus oddity task using Monte Carlo simulation:
108
+ - Samples three internal representations per trial (z0, z1, z2)
109
+ - Uses proper oddity decision rule with three pairwise distances
110
+ - Suitable for complex covariance structures
111
+
112
+ Notes
113
+ -----
114
+ MC simulation in loglik() (full 3-stimulus oddity):
115
+ 1. Sample three internal representations: z_ref, z_refprime ~ N(ref, Σ_ref), z_comparison ~ N(comparison, Σ_comparison)
116
+ 2. Compute average covariance: Σ_avg = (2/3) Σ_ref + (1/3) Σ_comparison
117
+ 3. Compute three pairwise Mahalanobis distances:
118
+ - d^2(z_ref, z_refprime) = distance between two reference samples
119
+ - d^2(z_ref, z_comparison) = distance from ref to comparison
120
+ - d^2(z_refprime, z_comparison) = distance from reference_prime to comparison
121
+ 4. Apply oddity decision rule: delta = min(d^2(z_ref,z_comparison), d^2(z_refprime,z_comparison)) - d^2(z_ref,z_refprime)
122
+ 5. Logistic smoothing: P(correct) \approx logistic.cdf(delta / bandwidth)
123
+ 6. Average over samples
124
+
125
+ Examples
126
+ --------
127
+ >>> from psyphy.model.likelihood import OddityTask
128
+ >>> from psyphy.model.likelihood import OddityTaskConfig
129
+ >>> from psyphy.model import WPPM, Prior
130
+ >>> from psyphy.model.noise import GaussianNoise
131
+ >>> import jax.numpy as jnp
132
+ >>> import jax.random as jr
133
+ >>>
134
+ >>> # Create task and model (task-owned MC controls)
135
+ >>> likelihood = OddityTask(
136
+ ... config=OddityTaskConfig(num_samples=1000, bandwidth=1e-2)
137
+ ... )
138
+ >>> model = WPPM(
139
+ ... input_dim=2,
140
+ ... prior=Prior(input_dim=2),
141
+ ... likelihood=task,
142
+ ... noise=GaussianNoise(),
143
+ ... )
144
+ >>> params = model.init_params(jr.PRNGKey(0))
145
+
146
+ >>> # MC simulation
147
+ >>> from psyphy.data.dataset import ResponseData
148
+ >>> data = ResponseData()
149
+ >>> data.add_trial(ref, comparison, resp=1)
150
+ >>> ll_mc = likelihood.loglik(params, data, model, model.noise, key=jr.PRNGKey(42))
151
+ >>> print(f"Log-likelihood (MC): {ll_mc:.4f}")
152
+ """
153
+
154
+ def __init__(self, config: OddityTaskConfig | None = None) -> None:
155
+ # No analytical parameters in MC-only mode.
156
+ self.config = config or OddityTaskConfig()
157
+
158
+ def predict(
159
+ self, params: Any, stimuli: Stimulus, model: Any, noise: Any
160
+ ) -> jnp.ndarray:
161
+ """Predict p(correct) for a single (ref, comparison) stimulus.
162
+
163
+ Even though OddityTask is *MC-only*, we still implement ``predict``.
164
+ Reason: large parts of the library (posterior predictive, acquisition
165
+ functions, diagnostics, etc.) need a forward model that returns
166
+ p(correct) at candidate stimuli. Historically this used an analytical
167
+ approximation, but in MC-only mode we compute it via simulation.
168
+
169
+ Notes
170
+ -----
171
+ - This method is intentionally lightweight: it performs the same
172
+ single-trial Monte Carlo simulation used by ``loglik``.
173
+ - If you need to control MC fidelity/smoothing, set
174
+ ``OddityTaskConfig(num_samples=..., bandwidth=...)`` when you
175
+ construct the task.
176
+ - If you need reproducible randomness, pass ``key=...`` to ``loglik``.
177
+ """
178
+
179
+ num_samples = int(self.config.num_samples)
180
+ bandwidth = float(self.config.bandwidth)
181
+ key = jr.PRNGKey(int(self.config.default_key_seed))
182
+
183
+ ref, comparison = stimuli
184
+ return self._simulate_trial_mc(
185
+ params=params,
186
+ ref=ref,
187
+ comparison=comparison,
188
+ model=model,
189
+ noise=noise,
190
+ num_samples=num_samples,
191
+ bandwidth=bandwidth,
192
+ key=key,
193
+ )
194
+
195
+ # Intentionally no `predict_with_kwargs`: we want a single source of truth.
196
+
197
+ def loglik(
198
+ self, params: Any, data: Any, model: Any, noise: Any, **kwargs: Any
199
+ ) -> jnp.ndarray:
200
+ """
201
+ Compute log-likelihood via Monte Carlo observer simulation.
202
+
203
+ This method implements the FULL 3-stimulus oddity task. Instead of using
204
+ an analytical approximation, we:
205
+ 1. Sample three internal noisy representations per trial:
206
+ - z_ref, z_refprime ~ N(ref, Σ_ref) [two samples from reference]
207
+ - z_comparison ~ N(comparison, Σ_comparison) [one sample from comparison]
208
+ 2. Compute three pairwise Mahalanobis distances
209
+ 3. Apply oddity decision rule: comparison is odd if it's farther from BOTH ref and reference_prime
210
+ 4. Apply logistic smoothing to approximate P(correct)
211
+ 5. Average over MC samples
212
+
213
+ Parameters
214
+ ----------
215
+ params : Any
216
+ Model parameters as expected by ``model._compute_sqrt``.
217
+ data : ResponseData
218
+ Trial data with refs, comparisons, and responses
219
+ model : WPPM
220
+ Model instance providing ``_compute_sqrt`` for covariance computation.
221
+ noise : NoiseModel
222
+ Observer noise model (provides ``sample_standard``).
223
+ key : jax.random.PRNGKey, optional
224
+ Random key for reproducible sampling.
225
+ If None, uses ``OddityTaskConfig.default_key_seed``.
226
+
227
+ Returns
228
+ -------
229
+ jnp.ndarray
230
+ Scalar sum of log-likelihoods over all trials.
231
+ Same shape and interpretation as ``loglik``.
232
+
233
+ Raises
234
+ ------
235
+ TypeError
236
+ If ``num_samples`` or ``bandwidth`` are provided as kwargs.
237
+ ValueError
238
+ If the task configuration is invalid (e.g. ``num_samples <= 0``).
239
+
240
+ Notes
241
+ -----
242
+ Monte Carlo controls (``num_samples``, ``bandwidth``) are owned by the
243
+ task configuration:
244
+
245
+ - Create the task with ``OddityTask(config=OddityTaskConfig(...))``.
246
+ - Pass only the PRNG ``key`` at call time when you want to control
247
+ randomness.
248
+
249
+ Notes
250
+ -----
251
+ **Full 3-stimulus oddity task algorithm:**
252
+
253
+ For each trial (ref, comparison, response):
254
+ 1. Compute covariances:
255
+ - Σ_ref = U_ref @ U_ref.T + σ^2 I
256
+ - Σ_comparison = U_comparison @ U_comparison.T + σ^2 I
257
+ - Σ_avg = (2/3) Σ_ref + (1/3) Σ_comparison [weighted by stimulus frequency]
258
+
259
+ 2. Sample three internal representations:
260
+ - z_ref, z_refprime ~ N(ref, Σ_ref) [2 samples from reference, num_samples times each]
261
+ - z_comparison ~ N(comparison, Σ_comparison) [1 sample from comparison, num_samples times]
262
+
263
+ 3. Compute three pairwise Mahalanobis distances:
264
+ - d^2(z_ref, z_refprime) = (z_ref - z_refprime).T @ Σ_avg^{-1} @ (z_ref - z_refprime) [ref vs reference_prime]
265
+ - d^2(z_ref, z_comparison) = (z_ref - z_comparison).T @ Σ_avg^{-1} @ (z_ref - z_comparison) [ref vs comparison]
266
+ - d^2(z_refprime, z_comparison) = (z_refprime - z_comparison).T @ Σ_avg^{-1} @ (z_refprime - z_comparison) [reference_prime vs comparison]
267
+
268
+ 4. Apply oddity decision rule:
269
+ - delta = min(d^2(z_ref,z_comparison), d^2(z_refprime,z_comparison)) - d^2(z_ref,z_refprime)
270
+ - delta > 0 means comparison is farther from BOTH ref and reference_prime -> correct identification
271
+
272
+ 5. Apply logistic smoothing:
273
+ - P(correct) \approx mean(logistic.cdf(delta / bandwidth))
274
+
275
+ 6. Bernoulli log-likelihood:
276
+ - LL = Σ [y * log(p) + (1-y) * log(1-p)]
277
+
278
+ Performance:
279
+ - Memory: O(num_samples * input_dim) per trial
280
+ - Vectorized across trials using jax.vmap for GPU acceleration
281
+ - Can be JIT-compiled for additional speed (future optimization)
282
+
283
+ Examples
284
+ --------
285
+ >>> import jax.numpy as jnp
286
+ >>> import jax.random as jr
287
+ >>> from psyphy.model import WPPM, Prior
288
+ >>> from psyphy.model.likelihood import OddityTask
289
+ >>> from psyphy.model.noise import GaussianNoise
290
+ >>> from psyphy.data.dataset import ResponseData
291
+ >>>
292
+ >>> # Setup
293
+ >>> model = WPPM(
294
+ ... input_dim=2,
295
+ ... prior=Prior(input_dim=2, basis_degree=3),
296
+ ... likelihood=OddityTask(),
297
+ ... noise=GaussianNoise(sigma=0.03),
298
+ ... )
299
+ >>> params = model.init_params(jr.PRNGKey(0))
300
+ >>>
301
+ >>> # Create trial data
302
+ >>> data = ResponseData()
303
+ >>> data.add_trial(
304
+ ... ref=jnp.array([0.0, 0.0]), comparison=jnp.array([0.3, 0.2]), resp=1
305
+ ... )
306
+ >>>
307
+ >>> loglik = model.likelihood.loglik(
308
+ ... params,
309
+ ... data,
310
+ ... model,
311
+ ... model.noise,
312
+ ... num_samples=5000,
313
+ ... bandwidth=1e-3,
314
+ ... key=jr.PRNGKey(42),
315
+ ... )
316
+ >>> print(f"MC (N=5000): {loglik:.4f}")
317
+
318
+
319
+ """
320
+ # Task is the single source of truth for MC controls.
321
+ num_samples = int(self.config.num_samples)
322
+ bandwidth = float(self.config.bandwidth)
323
+
324
+ # Only PRNG key is accepted dynamically.
325
+ key = kwargs.pop("key", None)
326
+ if "num_samples" in kwargs or "bandwidth" in kwargs:
327
+ raise TypeError(
328
+ "OddityTask.loglik does not accept 'num_samples'/'bandwidth' overrides. "
329
+ "Configure them via OddityTaskConfig when constructing the task."
330
+ )
331
+ if kwargs:
332
+ unexpected = ", ".join(sorted(kwargs.keys()))
333
+ raise TypeError(
334
+ f"Unexpected keyword arguments for OddityTask.loglik: {unexpected}"
335
+ )
336
+
337
+ if num_samples <= 0:
338
+ raise ValueError(f"num_samples must be > 0, got {num_samples}")
339
+ if bandwidth <= 0:
340
+ raise ValueError(f"bandwidth must be > 0, got {bandwidth}")
341
+
342
+ if key is None:
343
+ key = jr.PRNGKey(int(self.config.default_key_seed))
344
+
345
+ # Unpack trial data.
346
+ #
347
+ # Compute-efficient contract: `data` should be a batch of arrays.
348
+ # We accept either a TrialData dataclass or any object with
349
+ # `.refs/.comparisons/.responses` array attributes.
350
+ refs = jnp.asarray(data.refs)
351
+ comparisons = jnp.asarray(data.comparisons)
352
+ responses = jnp.asarray(data.responses)
353
+ n_trials = int(refs.shape[0])
354
+
355
+ # Split keys for each trial (ensures independent sampling)
356
+ trial_keys = jr.split(key, n_trials)
357
+
358
+ # Vectorized computation of P(correct) for all trials
359
+ # This processes all trials in parallel using jax.vmap
360
+ # Note: probabilities are already clipped in _simulate_trial_mc()
361
+ probs = self._simulate_trials_mc_vectorized(
362
+ params=params,
363
+ refs=refs,
364
+ comparisons=comparisons,
365
+ model=model,
366
+ noise=noise,
367
+ num_samples=num_samples,
368
+ bandwidth=bandwidth,
369
+ trial_keys=trial_keys,
370
+ )
371
+
372
+ # Bernoulli log-likelihood: LL = Σ [y log(p) + (1-y) log(1-p)]
373
+ # Probabilities are already clipped to [eps, 1-eps] so log is safe
374
+ log_likelihoods = jnp.where(
375
+ responses == 1,
376
+ jnp.log(probs), # Correct response
377
+ jnp.log(1.0 - probs), # Incorrect response
378
+ )
379
+
380
+ return jnp.sum(log_likelihoods)
381
+
382
+ def _simulate_trials_mc_vectorized(
383
+ self,
384
+ params: Any,
385
+ refs: jnp.ndarray,
386
+ comparisons: jnp.ndarray,
387
+ model: Any,
388
+ noise: Any,
389
+ num_samples: int,
390
+ bandwidth: float,
391
+ trial_keys: jnp.ndarray,
392
+ ) -> jnp.ndarray:
393
+ """
394
+ Vectorized Monte Carlo simulation across all trials.
395
+
396
+ This method processes multiple trials in parallel using JAX's vmap,
397
+ which is much faster than a Python loop (especially on GPU/TPU).
398
+
399
+ Parameters
400
+ ----------
401
+ params : Any
402
+ Model parameters as expected by ``model._compute_sqrt``.
403
+ refs : jnp.ndarray, shape (n_trials, input_dim)
404
+ Reference stimuli for all trials
405
+ comparisons : jnp.ndarray, shape (n_trials, input_dim)
406
+ Probe stimuli for all trials
407
+ model : WPPM
408
+ Model instance
409
+ noise : NoiseModel
410
+ Observer noise model
411
+ num_samples : int
412
+ Number of Monte Carlo samples per trial
413
+ bandwidth : float
414
+ Logistic smoothing bandwidth
415
+ trial_keys : jnp.ndarray, shape (n_trials, 2)
416
+ Random keys for each trial
417
+
418
+ Returns
419
+ -------
420
+ probs : jnp.ndarray, shape (n_trials,)
421
+ Estimated P(correct) for each trial
422
+ """
423
+
424
+ # Create a vectorized version of the single-trial simulation
425
+ # vmap automatically batches over the first axis of each input
426
+ def simulate_single(ref, comparison, key):
427
+ return self._simulate_trial_mc(
428
+ params, ref, comparison, model, noise, num_samples, bandwidth, key
429
+ )
430
+
431
+ # Apply to all trials in parallel
432
+ probs = jax.vmap(simulate_single)(refs, comparisons, trial_keys)
433
+
434
+ return probs
435
+
436
+ def _simulate_trial_mc(
437
+ self,
438
+ params: Any,
439
+ ref: jnp.ndarray,
440
+ comparison: jnp.ndarray,
441
+ model: Any,
442
+ noise: Any,
443
+ num_samples: int,
444
+ bandwidth: float,
445
+ key: Any,
446
+ ) -> jnp.ndarray:
447
+ """
448
+ Simulate a single 3-stimulus oddity trial via Monte Carlo.
449
+
450
+ This implements the FULL oddity task where the observer sees three stimuli:
451
+ two identical references and one comparison. The task is to identify which
452
+ stimulus is the "odd one out" (the comparison).
453
+
454
+ Parameters
455
+ ----------
456
+ params : Any
457
+ Model parameters as expected by ``model._compute_sqrt``.
458
+ ref : jnp.ndarray, shape (input_dim,)
459
+ Reference stimulus (2 samples represented)
460
+ comparison : jnp.ndarray, shape (input_dim,)
461
+ Probe stimulus (1 sample represented, the "odd one out")
462
+ model : WPPM
463
+ Model instance providing covariance structure
464
+ noise : NoiseModel
465
+ Observer noise (currently unused, noise in covariance?)
466
+ num_samples : int
467
+ Number of Monte Carlo samples for estimating P(correct)
468
+ bandwidth : float
469
+ Logistic smoothing parameter (controls decision sharpness)
470
+ key : PRNGKey
471
+ JAX random key for sampling
472
+
473
+ Returns
474
+ -------
475
+ float
476
+ Estimated P(correct) for this trial, in range [0, 1]
477
+
478
+ Notes
479
+ -----
480
+ **Full 3-stimulus oddity task algorithm:**
481
+
482
+ 1. Sample three internal representations:
483
+ - z_ref, z_refprime ~ N(ref, Σ_ref) [two samples from reference]
484
+ - z_comparison ~ N(comparison, Σ_comparison) [one sample from comparison]
485
+
486
+ 2. Compute covariance for distance metric:
487
+ - Σ_avg = (2/3) * Σ_ref + (1/3) * Σ_comparison
488
+ - Weighted by stimulus frequency (2 refs, 1 comparison)
489
+
490
+ 3. Compute three pairwise Mahalanobis distances:
491
+ - d^2(z_ref, z_refprime) = (z_ref - z_refprime).T @ Σ_avg^{-1} @ (z_ref - z_refprime) [ref vs reference_prime]
492
+ - d^2(z_ref, z_comparison) = (z_ref - z_comparison).T @ Σ_avg^{-1} @ (z_ref - z_comparison) [ref vs comparison]
493
+ - d^2(z_refprime, z_comparison) = (z_refprime - z_comparison).T @ Σ_avg^{-1} @ (z_refprime - z_comparison) [reference_prime vs comparison]
494
+
495
+ 4. Decision rule (correct response):
496
+ - The comparison (z_comparison) is the odd one if it's farther from BOTH ref and reference_prime
497
+ than ref and reference_prime are from each other
498
+ - delta = min(d^2(z_ref,z_comparison), d^2(z_refprime,z_comparison)) - d^2(z_ref,z_refprime)
499
+ - delta > 0 indicates correct identification of comparison as odd
500
+
501
+ 5. Smooth decision with logistic CDF:
502
+ - P(correct | sample) \approx sigmoid(delta / bandwidth)
503
+ - Approximates noisy threshold decision
504
+
505
+ 6. Monte Carlo average:
506
+ - P(correct) \approx mean over num_samples
507
+
508
+ """
509
+ # Get input dimension and require Wishart mode.
510
+ # OddityTask is intentionally MC-only and currently only supports the
511
+ # WPPM/Wishart covariance parameterization.
512
+ input_dim = ref.shape[0]
513
+ if model.basis_degree is None:
514
+ raise ValueError(
515
+ "(Expected a basis degree, got None. model.basis_degree must not be None)."
516
+ )
517
+
518
+ # ========================================================================
519
+ # STEP 1: Compute covariance structures at ref and comparison locations
520
+ # ========================================================================
521
+
522
+ # Wishart mode: Spatially-varying covariance
523
+ # Compute U matrices that define covariances at each location
524
+ # These U matrices define the two distributions:
525
+
526
+ # U_ref defines DISTRIBUTION 1 covariance: Σ_ref = U_ref @ U_ref.T + diag_term * I
527
+ U_ref = model._compute_sqrt(params, ref) # (input_dim, embedding_dim)
528
+
529
+ # U_comparison defines DISTRIBUTION 2 covariance: Σ_comparison = U_comparison @ U_comparison.T + diag_term * I
530
+ U_comparison = model._compute_sqrt(
531
+ params, comparison
532
+ ) # (input_dim, embedding_dim)
533
+
534
+ # Diagonal noise term (small regularization, same for both distributions)
535
+ diag_term = model.diag_term
536
+ sqrt_diag = jnp.sqrt(diag_term)
537
+
538
+ # ========================================================================
539
+ # STEP 2: Sample internal representations (3 samples from 2 distributions)
540
+ # ========================================================================
541
+ # Split random key: 3 for embedding samples + 3 for diagonal noise
542
+ keys = jr.split(key, 6)
543
+
544
+ # manual sampling using reparameterization trick
545
+ # Covariance structure: Σ = U @ U.T + diag_term * I
546
+ # Reparameterization: z = n_embed @ U.T + mean + sqrt(diag_term) * n_diag
547
+
548
+ embed_dim = U_ref.shape[1] # type: ignore
549
+
550
+ # Samples from standard normal (will be transformed to our target distributions 1 and 2)
551
+ n_ref_embed = noise.sample_standard(keys[0], (num_samples, embed_dim))
552
+ n_refprime_embed = noise.sample_standard(keys[1], (num_samples, embed_dim))
553
+ n_comparison_embed = noise.sample_standard(keys[2], (num_samples, embed_dim))
554
+
555
+ # Sample diagonal noise (independent across dimensions)
556
+ n_ref_diag = noise.sample_standard(keys[3], (num_samples, input_dim))
557
+ n_refprime_diag = noise.sample_standard(keys[4], (num_samples, input_dim))
558
+ n_comparison_diag = noise.sample_standard(keys[5], (num_samples, input_dim))
559
+
560
+ # =================================================================
561
+ # SAMPLING: Transform standard normals to samples from our 2 distributions
562
+ # =================================================================
563
+
564
+ # SAMPLE 1 & 2: From DISTRIBUTION 1 (Reference), z_ref ~ N(ref, Σ_ref)
565
+ # Both z_ref and z_refprime sampled from N(ref, Σ_ref)
566
+ # where Σ_ref = U_ref @ U_ref.T + diag_term * I
567
+ z_ref = n_ref_embed @ U_ref.T + ref[None, :] + sqrt_diag * n_ref_diag # type: ignore
568
+ # ^^^^^^ ^^^^^ ^^^^^^^
569
+ # | | |
570
+ # | | +--- MEAN: ref (same for z_ref and z_refprime)
571
+ # | +--- COVARIANCE: Uses U_ref (defines Σ_ref)
572
+ # +--- Independent noise (different from z_refprime, but same distribution)
573
+
574
+ # z_refprime ~ N(ref, Σ_ref)
575
+ z_refprime = (
576
+ n_refprime_embed @ U_ref.T + ref[None, :] + sqrt_diag * n_refprime_diag
577
+ ) # type: ignore
578
+ # ^^^^^ ^^^^ ^^^^^^^^^^
579
+ # | | |
580
+ # | | +--- MEAN: ref (SAME as z_ref!)
581
+ # | +--- COVARIANCE: Uses U_ref (SAME as z_ref!)
582
+ # +--- Independent noise (different from z_ref)
583
+
584
+ # SAMPLE 3: From DISTRIBUTION 2 (Probe), z_comparison ~ N(comparison, Σ_comparison)
585
+ # z_comparison sampled from N(comparison, Σ_comparison)
586
+ # where Σ_comparison = U_comparison @ U_comparison.T + diag_term * I
587
+ z_comparison = (
588
+ n_comparison_embed @ U_comparison.T
589
+ + comparison[None, :]
590
+ + sqrt_diag * n_comparison_diag
591
+ ) # type: ignore
592
+ # ^^^^^^^^ ^^^^^^ ^^^^^^^^^^
593
+ # | | |
594
+ # | | +--- MEAN: comparison (DIFFERENT from ref!)
595
+ # | +--- COVARIANCE: Uses U_comparison (DIFFERENT from U_ref!)
596
+ # +--- independent noise (different distribution from z_ref and z_refprime)
597
+
598
+ # ========================================================================
599
+ # STEP 3: Compute average covariance for Mahalanobis distance
600
+ # ========================================================================
601
+ # we need a single covariance matrix for computing Mahalanobis distances
602
+ # Weight by frequency: we sampled 2 times from N(ref, Σ_ref) and 1 time from N(comparison, Σ_comparison)
603
+ # -> so we use weights (2/3) for reference distribution and (1/3) for comparison distribution
604
+
605
+ # For Wishart mode, explicitly construct full covariances from U matrices
606
+ # Σ_ref = U_ref @ U_ref.T + diag_term * I (covariance of DISTRIBUTION 1)
607
+ Sigma_ref_full = U_ref @ U_ref.T + diag_term * jnp.eye(input_dim) # type: ignore
608
+
609
+ # Σ_comparison = U_comparison @ U_comparison.T + diag_term * I (covariance of DISTRIBUTION 2)
610
+ Sigma_comparison_full = U_comparison @ U_comparison.T + diag_term * jnp.eye(
611
+ input_dim
612
+ ) # type: ignore
613
+
614
+ # Weighted average: (2/3) * Σ_ref + (1/3) * Σ_comparison
615
+ Sigma_avg = (2.0 / 3.0) * Sigma_ref_full + (1.0 / 3.0) * Sigma_comparison_full
616
+ # ^^^^^^^ ^^^^^^^
617
+ # 2 samples from ref 1 sample from comparison
618
+
619
+ # ========================================================================
620
+ # STEP 4: Compute three pairwise Mahalanobis distances
621
+ # ========================================================================
622
+ # difference vectors for all sample pairs, all of shape (num_samples, input_dim)
623
+ diff_ref_refprime = z_ref - z_refprime # distance ref to reference_prime
624
+ diff_ref_comparison = z_ref - z_comparison # distance ref to comparison
625
+ diff_refprime_comparison = (
626
+ z_refprime - z_comparison
627
+ ) # distance reference_prime to comparison
628
+
629
+ # Mahalanobis distance formula: d^2(x) = x^T @ Σ^{-1} @ x, where x is the difference vector, e.g., (z_ref - z_refprime)
630
+ # We compute this efficiently without explicit matrix inversion.
631
+
632
+ # Mathematical trick:
633
+ # 1. Let y = Σ^{-1} @ x
634
+ # 2. Then Σ @ y = x (linear system)
635
+ # 3. We find y using jnp.linalg.solve(Σ, x), which is O(D^3) but numerically stable.
636
+ # 4. then, d^2 = x^T @ y = dot(x, y)
637
+
638
+ # Stack differences for batch processing: (3, num_samples, input_dim)
639
+ diffs_stacked = jnp.stack(
640
+ [diff_ref_refprime, diff_ref_comparison, diff_refprime_comparison], axis=0
641
+ )
642
+
643
+ # Vectorized Solve via vmap:
644
+ # We apply solve(Sigma_avg, d.T) to each of the 3 difference sets.
645
+ # - Input d: (num_samples, input_dim)
646
+ # - d.T: (input_dim, num_samples) -> acts as a batch of column vectors
647
+ # - solve(Sigma, d.T): Solves Σ y_i = x_i for all i simultaneously.
648
+ # - Result 'solved': (3, input_dim, num_samples) containing the vectors Σ^{-1} x
649
+ solved = jax.vmap(lambda d: jnp.linalg.solve(Sigma_avg, d.T))(diffs_stacked)
650
+
651
+ # Compute Dot Products: x^T @ y
652
+ # We perform element-wise multiplication and sum over dimensions.
653
+ # - diff_ref_refprime: x (num_samples, input_dim)
654
+ # - solved[0].T: y (num_samples, input_dim)
655
+ # - sum(x * y, axis=1): equivalent to dot product for each sample
656
+ d_sq_ref_reference_prime = jnp.sum(
657
+ diff_ref_refprime * solved[0].T, axis=1
658
+ ) # (num_samples,)
659
+ d_sq_ref_comparison = jnp.sum(
660
+ diff_ref_comparison * solved[1].T, axis=1
661
+ ) # (num_samples,)
662
+ d_sq_refprime_comparison = jnp.sum(
663
+ diff_refprime_comparison * solved[2].T, axis=1
664
+ ) # (num_samples,)
665
+
666
+ # ========================================================================
667
+ # STEP 5: apply oddity decision rule
668
+ # ========================================================================
669
+ # Correct response: comparison (z_comparison) is farther from BOTH ref and reference_prime than they are from each other
670
+ # delta > 0 means: min[d(z_ref,z_comparison), d(z_refprime,z_comparison)] > d(z_ref,z_refprime)
671
+ # -> z_comparison is the outlier
672
+
673
+ #
674
+ delta = (
675
+ jnp.minimum(d_sq_ref_comparison, d_sq_refprime_comparison)
676
+ - d_sq_ref_reference_prime
677
+ ) # (num_samples,)
678
+
679
+ # ========================================================================
680
+ # STEP 6: Smooth decision with logistic CDF
681
+ # ========================================================================
682
+ # Logistic CDF approximates a noisy threshold decision
683
+ # bandwidth controls decision noise:
684
+ # - small bandwidth (~1e-3): sharp threshold (nearly deterministic)
685
+ # - large bandwidth (~5e-2): smooth, gradual transition
686
+ # P(correct | delta) \approx sigmoid(delta / bandwidth)
687
+
688
+ prob_correct_per_sample = jax.scipy.stats.logistic.cdf(delta / bandwidth)
689
+
690
+ # ========================================================================
691
+ # STEP 7: Monte Carlo average
692
+ # ========================================================================
693
+ # by law of large numbers: mean(samples) -> E[P(correct)]
694
+ prob = jnp.mean(prob_correct_per_sample)
695
+
696
+ # Clip probability to avoid numerical issues with log(0) or log(1)
697
+ # - Use eps=1e-6 for safety (or smaller epsilon and increase precison from float32 to float64)
698
+ # - Clipping here (before return) ensures gradients stay finite
699
+ # - Without this, prob=1.0 -> log(1.0)=0.0 -> grad through clip at boundary -> NaN
700
+ eps = 1e-6
701
+ return jnp.clip(prob, eps, 1.0 - eps)