Batched matter power spectra#
This notebook computes and times the linear matter power spectrum \(P(k)\) of 128 flat \(\Lambda\)CDM cosmologies.
One jax.jit-ed function builds the batch, solves the Einstein-Boltzmann system for every (cosmology, \(k\)) pair in one GPU launch with solve_eb, and computes \(P(k)\) with matter_power_spectrum. The results below were run on an NVIDIA 4070 SUPER desktop GPU.
import time
import jax
import jax.numpy as jnp
import numpy as np
from discoeb import LCDM, matter_power_spectrum, solve_eb
N_COSMOLOGIES = 128
K = np.geomspace(1.0e-4, 1.0, 128) # wave numbers, 1/Mpc
The parameters are specified as physical densities, \(\omega = \Omega h^2\), or density parameters using the LCDM.from_density_parameters method. We draw a batch of cosmologies by sampling \(\omega_b\), \(\omega_c\) and \(h\) uniformly within a fraction of a per cent of the Planck 2018 best fit. Every parameter is traced, so a new batch will reuse the compiled function.
@jax.jit
def solve_matter_power_spectrum(key: jax.Array) -> jax.Array:
"""``P(k)`` in Mpc^3 today, ``(N_COSMOLOGIES, len(K))``, of a batch about Planck 2018.
The batch draws ``omega_b``, ``omega_c`` and ``h`` independently and
uniformly within a fraction of a per cent of the Planck 2018 best fit
(flat, three massless neutrino flavours). Each ``key`` gives a different batch.
"""
u = jax.random.uniform(key, (3, N_COSMOLOGIES), minval=-1.0, maxval=1.0)
omega_b = 0.02238280 * (1.0 + 0.006 * u[0])
omega_c = 0.1201075 * (1.0 + 0.008 * u[1])
h = 0.6732117 * (1.0 + 0.004 * u[2])
A_s, n_s, k_p = 2.100549e-9, 0.9660499, 0.05 # k_p: pivot scale of A_s, 1/Mpc
cosmologies = [
LCDM.from_density_parameters(
Omega_m=(omega_b[i] + omega_c[i]) / h[i] ** 2,
Omega_b=omega_b[i] / h[i] ** 2,
H_0=100.0 * h[i],
A_s=A_s,
n_s=n_s,
k_p=k_p,
T_cmb=2.7255,
Y_He=0.2454006,
N_eff=3.046,
)
for i in range(N_COSMOLOGIES)
]
values = solve_eb( # (cosmology, name, k, a)
cosmologies,
K,
[1.0], # the scale factor today
keep=("delta_c", "delta_b"),
# recombination ten times looser than the hierarchy. This moves P(k)
# by under 6e-4 and takes 150 steps per trajectory instead of 225.
thermo_weight=0.1,
)
delta_c, delta_b = jnp.unstack(values[..., -1], axis=1) # each (cosmology, k)
# one cosmology's P(k), mapped over the batch with K held fixed
return jax.vmap(matter_power_spectrum, in_axes=(None,))(
K,
delta_c=delta_c,
delta_b=delta_b,
omega_c=omega_c,
omega_b=omega_b,
A_s=jnp.full(N_COSMOLOGIES, A_s),
n_s=jnp.full(N_COSMOLOGIES, n_s),
k_p=jnp.full(N_COSMOLOGIES, k_p),
)
The first call traces the function and loads the GPU kernel. modax compiles the kernel once, in about ~30s, and caches it on disk. The second call runs on a batch it has not seen before, as in an inference loop.
def timed(key: jax.Array) -> tuple[np.ndarray, float]:
start = time.perf_counter()
pk = jax.block_until_ready(solve_matter_power_spectrum(key))
return np.asarray(pk), time.perf_counter() - start
warm_up_key, key = jax.random.split(jax.random.key(0))
_, first = timed(warm_up_key)
pk, elapsed = timed(key) # a batch not seen before
print(f"first call, with tracing and the kernel's compile or load: {first:.1f} s")
print(f"P(k) of {pk.shape[0]} new cosmologies x {pk.shape[1]} modes: {elapsed:.3f} s")
print()
print("the first cosmology of the batch:")
print(f"{'k [1/Mpc]':>12} {'P(k) [Mpc^3]':>14}")
first_pk = pk[0]
for kv, pv in zip(K[::8], first_pk[::8]):
print(f"{kv:12.4e} {pv:14.6e}")
print(f"P(k) peaks at k = {K[np.argmax(first_pk)]:.4g} 1/Mpc")
first call, with tracing and the kernel's compile or load: 3.1 s
P(k) of 128 new cosmologies x 128 modes: 0.219 s
the first cosmology of the batch:
k [1/Mpc] P(k) [Mpc^3]
1.0000e-04 2.017577e+03
1.7864e-04 3.529696e+03
3.1911e-04 6.160562e+03
5.7004e-04 1.068531e+04
1.0183e-03 1.827247e+04
1.8190e-03 3.034637e+04
3.2495e-03 4.766197e+04
5.8047e-03 6.779910e+04
1.0369e-02 8.092354e+04
1.8523e-02 6.972089e+04
3.3089e-02 4.182552e+04
5.9109e-02 2.346785e+04
1.0559e-01 9.555337e+03
1.8862e-01 3.453462e+03
3.3695e-01 1.062766e+03
6.0190e-01 2.966120e+02
P(k) peaks at k = 0.01115 1/Mpc