File size: 3,327 Bytes
5a42b66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""The batched sampler must reproduce propagating each sample alone.

All J BALLAST samples share one fused scan over time (a ~20x win, since the
per-sample scans are latency-bound). Key derivation is arranged to match the
per-sample loop exactly, so this is a refactor, not a change of method -- and
that is checked here rather than assumed.

Agreement is to ~1e-14 rather than bit-exact: the batched step contracts
L_space @ Z @ L_Q as one einsum, so XLA associates the products differently from
the per-sample `L_space @ Z @ L_Q.T`. Trajectories are chaotic (a drifter's path
is an Euler integration through a sampled field), so this tolerance is asserted
on the *positions*, where it stays at 1e-14 over the horizon tested; the
validity masks must match exactly.
"""

import jax
import jax.numpy as jnp
import numpy as np

jax.config.update("jax_enable_x64", True)

from ballast.experiment import SYNTH_PARAMS as P
from ballast.gp import posterior_ext_state, sample_ext_state
from ballast.policies import sample_and_project
from ballast.spde import make_ops, propagate
from ballast.trajectory import Grid, advect

DT, OBS_EVERY, J = 0.01, 5, 3


def _setup():
    grid = Grid(jnp.linspace(-2, 2, 7), jnp.linspace(-2, 2, 7))
    ops = make_ops(grid.R, P, DT)
    k = jax.random.PRNGKey(0)
    S = jax.random.uniform(k, (9, 2), minval=-2, maxval=2)
    t = jax.random.uniform(jax.random.fold_in(k, 1), (9,), minval=0, maxval=1.0)
    y = jax.random.normal(jax.random.fold_in(k, 2), (9, 2))
    mean, chol = posterior_ext_state(S, t, y, grid.R, 1.0, P, 0.1)
    exist = jnp.array([[0.3, -0.2], [-1.0, 0.7]])
    return grid, ops, mean, chol, exist


def test_batched_matches_per_sample_loop():
    grid, ops, mean, chol, exist = _setup()
    n_steps, t_m = 60, 1.0
    key = jax.random.PRNGKey(7)

    cpos, cval, epos, eval_, t_traj, raw = sample_and_project(
        key, ops, mean, chol, exist, t_m, grid=grid, n_steps=n_steps,
        obs_every=OBS_EVERY, n_samples=J, dt=DT,
    )

    # reference: the original one-sample-at-a-time route
    keys = jax.random.split(key, J)
    for j in range(J):
        ka, kb = jax.random.split(keys[j])
        X0 = sample_ext_state(ka, mean, chol, grid.n)
        fields = propagate(X0, kb, ops, n_steps)
        s0 = jnp.concatenate([grid.R, exist], axis=0)
        pos_r, val_r, tidx_r = advect(
            grid, fields, s0, jnp.ones(s0.shape[0], dtype=bool), DT, OBS_EVERY
        )
        np.testing.assert_allclose(raw[:, j], pos_r, rtol=1e-12, atol=1e-12)
        np.testing.assert_array_equal(
            np.concatenate([cval[:, j], eval_[:, j]], axis=1), val_r
        )
        np.testing.assert_allclose(t_traj, t_m + tidx_r * DT, rtol=1e-12)
        snapped = grid.snap(pos_r)
        np.testing.assert_allclose(cpos[:, j], snapped[:, : grid.n], rtol=0, atol=0)  # snapped -> exact
        np.testing.assert_allclose(epos[:, j], snapped[:, grid.n :], rtol=0, atol=0)  # snapped -> exact


def test_grid_is_hashable_by_value():
    """Static jit args must hash by value, or every campaign recompiles."""
    a = Grid(jnp.linspace(-2, 2, 5), jnp.linspace(-2, 2, 5))
    b = Grid(jnp.linspace(-2, 2, 5), jnp.linspace(-2, 2, 5))
    c = Grid(jnp.linspace(-2, 2, 6), jnp.linspace(-2, 2, 5))
    assert hash(a) == hash(b) and a == b
    assert hash(a) != hash(c) and a != c