Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
282 changes: 202 additions & 80 deletions autoarray/inversion/inversion/imaging/inversion_imaging_util.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from functools import partial
from functools import lru_cache, partial
import numpy as np
from typing import Optional, List, Tuple

Expand Down Expand Up @@ -534,6 +534,40 @@ def apply_operator(self, Fbatch_flat):

return back.reshape((B, M)).T # (M, B)

def _kernel_operands(self):
"""
The array operands of the jitted curvature kernels, unwrapped to raw arrays.

`inverse_variances_native` can be an autoarray structure (e.g. `Array2D`) in the NumPy
path, which is not a valid JAX argument, so `.array` is taken where present.
"""
import jax.numpy as jnp

return tuple(
jnp.asarray(getattr(a, "array", a))
for a in (
self.inverse_variances_native,
self.Khat_r,
self.Khat_flip_r,
self.col_offsets,
)
)

def _kernel_statics(self):
"""
The static (compile-time) sizes of the jitted curvature kernels. Calls sharing these
and the array shapes reuse one compiled kernel.
"""
return dict(
B=int(self.batch_size),
y_shape=int(self.y_shape),
x_shape=int(self.x_shape),
Ky=int(self.Ky),
Kx=int(self.Kx),
Fy=int(self.fft_shape[0]),
Fx=int(self.fft_shape[1]),
)

def curvature_matrix_diag_from(self, rows, cols, vals, *, S: int):
"""
Compute the diagonal (mapper–mapper) curvature matrix block F = Aᵀ W A.
Expand Down Expand Up @@ -578,45 +612,15 @@ def curvature_matrix_diag_from(self, rows, cols, vals, *, S: int):
even when S is not a multiple of batch_size.
"""
import jax.numpy as jnp
from jax import lax
from jax.ops import segment_sum

rows = jnp.asarray(rows, dtype=jnp.int32)
cols = jnp.asarray(cols, dtype=jnp.int32)
vals = jnp.asarray(vals, dtype=jnp.float64)

y_shape, x_shape = self.y_shape, self.x_shape
M = y_shape * x_shape
B = self.batch_size

n_blocks = (S + B - 1) // B
S_pad = n_blocks * B

C0 = jnp.zeros((S, S_pad), dtype=jnp.float64)

def body(block_i, C):
start = block_i * B

in_block = (cols >= start) & (cols < (start + B))
bc = jnp.where(in_block, cols - start, 0).astype(jnp.int32)
v = jnp.where(in_block, vals, 0.0)

F = jnp.zeros((M, B), dtype=jnp.float64)
F = F.at[rows, bc].add(v)

G = self.apply_operator(F) # (M, B)

contrib = vals[:, None] * G[rows, :]
Cblock = segment_sum(contrib, cols, num_segments=S) # (S, B)

width = jnp.minimum(B, jnp.maximum(0, S - start))
Cblock = Cblock * (self.col_offsets < width)[None, :]

return lax.dynamic_update_slice(C, Cblock, (0, start))

C_pad = lax.fori_loop(0, n_blocks, body, C0)
C = C_pad[:, :S]
return 0.5 * (C + C.T)
return _curvature_matrix_diag_kernel()(
jnp.asarray(rows, dtype=jnp.int32),
jnp.asarray(cols, dtype=jnp.int32),
jnp.asarray(vals, dtype=jnp.float64),
*self._kernel_operands(),
S=int(S),
**self._kernel_statics(),
)

def curvature_matrix_off_diag_from(
self, rows0, cols0, vals0, rows1, cols1, vals1, *, S0: int, S1: int
Expand Down Expand Up @@ -662,48 +666,19 @@ def curvature_matrix_off_diag_from(
- Padding to `S1_pad = ceil(S1/B)*B` ensures `dynamic_update_slice` is always legal.
"""
import jax.numpy as jnp
from jax import lax
from jax.ops import segment_sum

rows0 = jnp.asarray(rows0, dtype=jnp.int32)
cols0 = jnp.asarray(cols0, dtype=jnp.int32)
vals0 = jnp.asarray(vals0, dtype=jnp.float64)

rows1 = jnp.asarray(rows1, dtype=jnp.int32)
cols1 = jnp.asarray(cols1, dtype=jnp.int32)
vals1 = jnp.asarray(vals1, dtype=jnp.float64)

y_shape, x_shape = self.y_shape, self.x_shape
M = y_shape * x_shape
B = self.batch_size

n_blocks = (S1 + B - 1) // B
S1_pad = n_blocks * B

F01_0 = jnp.zeros((S0, S1_pad), dtype=jnp.float64)

def body(block_i, F01):
start = block_i * B

in_block = (cols1 >= start) & (cols1 < (start + B))
bc = jnp.where(in_block, cols1 - start, 0).astype(jnp.int32)
v = jnp.where(in_block, vals1, 0.0)

F = jnp.zeros((M, B), dtype=jnp.float64)
F = F.at[rows1, bc].add(v)

G = self.apply_operator(F) # (M, B)

contrib = vals0[:, None] * G[rows0, :]
block = segment_sum(contrib, cols0, num_segments=S0)

width = jnp.minimum(B, jnp.maximum(0, S1 - start))
block = block * (self.col_offsets < width)[None, :]

return lax.dynamic_update_slice(F01, block, (0, start))

F01_pad = lax.fori_loop(0, n_blocks, body, F01_0)
return F01_pad[:, :S1]
return _curvature_matrix_off_diag_kernel()(
jnp.asarray(rows0, dtype=jnp.int32),
jnp.asarray(cols0, dtype=jnp.int32),
jnp.asarray(vals0, dtype=jnp.float64),
jnp.asarray(rows1, dtype=jnp.int32),
jnp.asarray(cols1, dtype=jnp.int32),
jnp.asarray(vals1, dtype=jnp.float64),
*self._kernel_operands(),
S0=int(S0),
S1=int(S1),
**self._kernel_statics(),
)

def curvature_matrix_off_diag_func_list_from(
self,
Expand Down Expand Up @@ -807,3 +782,150 @@ def curvature_matrix_off_diag_func_list_from(
# 4) accumulate to source pixels
contrib = vals[:, None] * back_at_rows
return segment_sum(contrib, cols, num_segments=S) # (S, n_funcs)


# ---------------------------------------------------------------------------
# Jitted curvature kernels for `ImagingSparseOperator`.
#
# The block loops used to be eager `lax.fori_loop` calls closing over a fresh
# `body` function on every call, so JAX retraced and recompiled on every call
# (HowToLens chapter_3 tutorial_6: 132 backend compiles over 118 calls). Here
# each kernel is a single module-level `jax.jit` function with its sizes
# static, so calls with the same sizes and array shapes (e.g. a regularization
# scan over a fixed mesh) reuse one compile. Inside an outer `jax.jit` the
# kernel is simply inlined.
#
# The kernels are built lazily behind `lru_cache` so importing autoarray never
# imports JAX. Numerics are identical to the previous closures: same blocking,
# same masking of the padded tail, same symmetrisation.
# ---------------------------------------------------------------------------

_KERNEL_STATICS = ("B", "y_shape", "x_shape", "Ky", "Kx", "Fy", "Fx")


def _apply_operator_kernel(
Fbatch_flat, inv_var, Khat_r, Khat_flip_r, *, y_shape, x_shape, Ky, Kx, Fy, Fx
):
"""
Pure-function form of `ImagingSparseOperator.apply_operator` (W = Hᵀ N⁻¹ H applied to a
batch), used inside the jitted curvature kernels.
"""
import jax.numpy as jnp

M = y_shape * x_shape
B = Fbatch_flat.shape[1]
Fimg = Fbatch_flat.T.reshape((B, y_shape, x_shape))

Fpad = jnp.pad(Fimg, ((0, 0), (0, Fy - y_shape), (0, Fx - x_shape)))
Fhat = jnp.fft.rfft2(Fpad, s=(Fy, Fx))
blurred_pad = jnp.fft.irfft2(Fhat * Khat_r[None, :, :], s=(Fy, Fx))

cy, cx = Ky // 2, Kx // 2
blurred = blurred_pad[:, cy : cy + y_shape, cx : cx + x_shape]

weighted = blurred * inv_var[None, :, :]

Wpad = jnp.pad(weighted, ((0, 0), (0, Fy - y_shape), (0, Fx - x_shape)))
What = jnp.fft.rfft2(Wpad, s=(Fy, Fx))
back_pad = jnp.fft.irfft2(What * Khat_flip_r[None, :, :], s=(Fy, Fx))
back = back_pad[:, cy : cy + y_shape, cx : cx + x_shape]

return back.reshape((B, M)).T


@lru_cache(maxsize=None)
def _curvature_matrix_diag_kernel():
"""The jitted F = Aᵀ W A kernel behind `ImagingSparseOperator.curvature_matrix_diag_from`."""
import jax
import jax.numpy as jnp
from jax import lax
from jax.ops import segment_sum

@partial(jax.jit, static_argnames=("S",) + _KERNEL_STATICS)
def kernel(
rows, cols, vals, inv_var, Khat_r, Khat_flip_r, col_offsets,
*, S, B, y_shape, x_shape, Ky, Kx, Fy, Fx,
):
M = y_shape * x_shape
n_blocks = (S + B - 1) // B
S_pad = n_blocks * B

C0 = jnp.zeros((S, S_pad), dtype=jnp.float64)

def body(block_i, C):
start = block_i * B

in_block = (cols >= start) & (cols < (start + B))
bc = jnp.where(in_block, cols - start, 0).astype(jnp.int32)
v = jnp.where(in_block, vals, 0.0)

F = jnp.zeros((M, B), dtype=jnp.float64)
F = F.at[rows, bc].add(v)

G = _apply_operator_kernel(
F, inv_var, Khat_r, Khat_flip_r,
y_shape=y_shape, x_shape=x_shape, Ky=Ky, Kx=Kx, Fy=Fy, Fx=Fx,
) # (M, B)

contrib = vals[:, None] * G[rows, :]
Cblock = segment_sum(contrib, cols, num_segments=S) # (S, B)

width = jnp.minimum(B, jnp.maximum(0, S - start))
Cblock = Cblock * (col_offsets < width)[None, :]

return lax.dynamic_update_slice(C, Cblock, (0, start))

C_pad = lax.fori_loop(0, n_blocks, body, C0)
C = C_pad[:, :S]
return 0.5 * (C + C.T)

return kernel


@lru_cache(maxsize=None)
def _curvature_matrix_off_diag_kernel():
"""The jitted F01 = A0ᵀ W A1 kernel behind `ImagingSparseOperator.curvature_matrix_off_diag_from`."""
import jax
import jax.numpy as jnp
from jax import lax
from jax.ops import segment_sum

@partial(jax.jit, static_argnames=("S0", "S1") + _KERNEL_STATICS)
def kernel(
rows0, cols0, vals0, rows1, cols1, vals1,
inv_var, Khat_r, Khat_flip_r, col_offsets,
*, S0, S1, B, y_shape, x_shape, Ky, Kx, Fy, Fx,
):
M = y_shape * x_shape
n_blocks = (S1 + B - 1) // B
S1_pad = n_blocks * B

F01_0 = jnp.zeros((S0, S1_pad), dtype=jnp.float64)

def body(block_i, F01):
start = block_i * B

in_block = (cols1 >= start) & (cols1 < (start + B))
bc = jnp.where(in_block, cols1 - start, 0).astype(jnp.int32)
v = jnp.where(in_block, vals1, 0.0)

F = jnp.zeros((M, B), dtype=jnp.float64)
F = F.at[rows1, bc].add(v)

G = _apply_operator_kernel(
F, inv_var, Khat_r, Khat_flip_r,
y_shape=y_shape, x_shape=x_shape, Ky=Ky, Kx=Kx, Fy=Fy, Fx=Fx,
) # (M, B)

contrib = vals0[:, None] * G[rows0, :]
block = segment_sum(contrib, cols0, num_segments=S0)

width = jnp.minimum(B, jnp.maximum(0, S1 - start))
block = block * (col_offsets < width)[None, :]

return lax.dynamic_update_slice(F01, block, (0, start))

F01_pad = lax.fori_loop(0, n_blocks, body, F01_0)
return F01_pad[:, :S1]

return kernel
Original file line number Diff line number Diff line change
Expand Up @@ -1017,3 +1017,81 @@ def test__curvature_matrix_via_sparse_operator_from__dispatches_on_the_two_stage
**kwargs
),
)


@pytest.fixture
def _sparse_operator_and_triplets(masked_imaging_7x7):
pytest.importorskip("jax")

operator = masked_imaging_7x7.apply_sparse_operator(batch_size=4).sparse_operator

rng = np.random.default_rng(1)
M = operator.y_shape * operator.x_shape

def triplets(S, nnz):
rows = rng.integers(0, M, size=nnz)
cols = rng.integers(0, S, size=nnz)
vals = rng.random(nnz)
return rows, cols, vals

return operator, triplets


def _dense_from(rows, cols, vals, M, S):
A = np.zeros((M, S))
np.add.at(A, (rows, cols), vals)
return A


def test__imaging_sparse_operator__curvature_blocks_match_dense_reference(
_sparse_operator_and_triplets,
):
operator, triplets = _sparse_operator_and_triplets
M = operator.y_shape * operator.x_shape

# S deliberately not a multiple of the batch size, so the padded tail is exercised.
rows0, cols0, vals0 = triplets(S=7, nnz=40)
rows1, cols1, vals1 = triplets(S=5, nnz=30)
A0 = _dense_from(rows0, cols0, vals0, M, 7)
A1 = _dense_from(rows1, cols1, vals1, M, 5)

WA0 = np.asarray(operator.apply_operator(A0))
WA1 = np.asarray(operator.apply_operator(A1))

diag = np.asarray(operator.curvature_matrix_diag_from(rows0, cols0, vals0, S=7))
off = np.asarray(
operator.curvature_matrix_off_diag_from(
rows0, cols0, vals0, rows1, cols1, vals1, S0=7, S1=5
)
)

ref = A0.T @ WA0
assert diag == pytest.approx(0.5 * (ref + ref.T), rel=1e-10, abs=1e-12)
assert off == pytest.approx(A0.T @ WA1, rel=1e-10, abs=1e-12)


def test__imaging_sparse_operator__repeated_same_shape_calls_reuse_one_compile(
_sparse_operator_and_triplets,
):
"""
A regularization scan over a fixed mesh calls the curvature kernels repeatedly with the
same sizes and shapes. They must reuse one compile, not retrace per call as the former
per-call `fori_loop` closures did.
"""
from autoarray.inversion.inversion.imaging import inversion_imaging_util as util

operator, triplets = _sparse_operator_and_triplets
kernel = util._curvature_matrix_diag_kernel()

rows, cols, vals = triplets(S=6, nnz=33)
first = np.asarray(operator.curvature_matrix_diag_from(rows, cols, vals, S=6))
compiled = kernel._cache_size()
assert compiled >= 1 # the kernel really was compiled, so the check below is not vacuous

for _ in range(3):
again = np.asarray(
operator.curvature_matrix_diag_from(rows, cols, vals * 1.0, S=6)
)

assert kernel._cache_size() == compiled
assert again == pytest.approx(first, rel=0, abs=0)
Loading