Batched CMB power spectra

Batched CMB power spectra#

This notebook computes and times the TT, TE, EE and lensing potential spectra of 128 flat \(\Lambda\)CDM cosmologies, then lenses them.

One jax.jit-ed function builds the batch and solves the Einstein-Boltzmann system for every (cosmology, \(k\)) pair in one GPU launch with solve_eb. We keep only the line-of-sight sources, project them with transfer_functions and integrate the spectra with cmb_power_spectrum. solve_cmb(cosmologies, grid=grid) runs the same three steps in one call. The results below were run on an NVIDIA 4070 SUPER desktop GPU.

import jax
import matplotlib.pyplot as plt
import numpy as np
from discoeb import LCDM, solve_eb

from discocmb import (
    Grid,
    LineOfSightSources,
    cmb_power_spectrum,
    error_weights,
    lensed_spectra,
    transfer_functions,
)

N_COSMOLOGIES = 128

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.

def planck_like(omega_b, omega_c, h) -> LCDM:
    """A flat LCDM cosmology at the Planck 2018 best fit but for ``omega_b``, ``omega_c`` and ``h``."""

    return LCDM.from_density_parameters(
        Omega_m=(omega_b + omega_c) / h**2,
        Omega_b=omega_b / h**2,
        H_0=100.0 * h,
        A_s=2.100549e-9,
        n_s=0.9660499,
        T_cmb=2.7255,
        Y_He=0.2454006,
        N_eff=3.046,  # three massless neutrino flavours
        z_re=7.67,  # the reionization redshift
    )


def draw_batch(key: jax.Array) -> list[LCDM]:
    """``N_COSMOLOGIES`` cosmologies about the Planck 2018 best fit.

    The batch draws ``omega_b``, ``omega_c`` and ``h`` independently and
    uniformly within a fraction of a per cent of the best fit. 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])
    return [planck_like(omega_b[i], omega_c[i], h[i]) for i in range(N_COSMOLOGIES)]

Grid.from_fiducial sets up the grid of wave modes, save times and quadrature points we will integrate over. These are chosen to capture the times and wave modes over which the sources vary.

%time grid = Grid.from_fiducial(planck_like(0.02238280, 0.1201075, 0.6732117))
CPU times: user 1min 59s, sys: 1.57 s, total: 2min 1s
Wall time: 12.2 s

Then to run the solve and compute the CMB power spectra:

@jax.jit
def solve_cmb_power_spectrum(grid: Grid, key: jax.Array):
    """``C_l`` of a batch about Planck 2018: TT, TE, EE and the lensing potential, each ``(N_COSMOLOGIES, lmax + 1)``."""

    cosmologies = draw_batch(key)
    values = solve_eb(  # (cosmology, quantity, k, save)
        cosmologies,
        grid.k_values,
        grid.a_save,
        extra=[LineOfSightSources],
        keep=[LineOfSightSources.keep],
        # the photon quadrupole and E_2 weighted at low k, without which the
        # low multipoles of EE and TE come out 10 to 40 per cent low
        error_weights=error_weights(LCDM),
    )
    transfers = transfer_functions(
        values, grid
    )  # Theta_l(k), E_l(k) and the lensing potential's
    cl, _ = cmb_power_spectrum(transfers, cosmologies)
    return cl

LineOfSightSources adds the sources to the model, so they compile into the solver’s kernel, and to save memory we keep only the source terms at every save instead of the full state.

The first call traces the function and loads the GPU kernel. modax compiles the kernel once and caches it on disk:

warm_up_key, key = jax.random.split(jax.random.key(0))
%time cl = jax.block_until_ready(solve_cmb_power_spectrum(grid, warm_up_key))
CPU times: user 1min 58s, sys: 1.23 s, total: 2min
Wall time: 9.24 s

The second call runs on a batch it has not seen before, as in an inference loop:

%time cl = jax.block_until_ready(solve_cmb_power_spectrum(grid, key))
CPU times: user 1.96 ms, sys: 0 ns, total: 1.96 ms
Wall time: 61.1 ms

lensed_spectra lenses the spectra with the lensing potential they carry. The plots show \(D_\ell = \ell(\ell+1) C_\ell / 2\pi\) of the lensed spectra of the batch, and the unlensed spectra of its first cosmology dashed.

lensed = lensed_spectra(cl, grid)

ell = np.arange(2, 2501)
to_dl = ell * (ell + 1.0) / (2.0 * np.pi) * (2.7255e6) ** 2  # muK^2
fig, axes = plt.subplots(1, 4, figsize=(15, 3.6))
for ax, name in zip(axes, ("tt", "te", "ee", "bb")):
    ax.plot(
        ell,
        to_dl[:, None] * np.asarray(getattr(lensed, name))[:, ell].T,
        color="C0",
        lw=0.3,
        alpha=0.4,
    )
    if name != "bb":
        ax.plot(
            ell,
            to_dl * np.asarray(getattr(cl, name))[0, ell],
            color="k",
            ls="--",
            lw=0.8,
        )
    ax.set_xscale("log")
    ax.set_xlabel(r"$\ell$")
    ax.set_title(f"lensed {name.upper()}")
axes[0].set_ylabel(r"$D_\ell$ [$\mu$K$^2$]")
fig.tight_layout()
plt.show()
../_images/b2ff3cb178fd2e74e2532eb75c6cdfe66e61dd6d228b562b69ce454d1962b602.png