Skip to content

Commit 6dbef8a

Browse files
Jammy2211claude
andcommitted
fix: pad empty halo slots with benign params so substructure jax.grad is finite
galaxies_to_halo_arrays padded empty slots with zeros, so a padded NFWTruncatedSph slot had scale_radius = 0 and jax.grad through the multi-plane deflections was NaN whenever planes held different halo counts. Empty slots now hold the profile's `vmapped_padding_params` row (ones when it has none) behind a zero centre. Adds the witness test: 2 + 5 halos at max_n=8 give the same finite gradient as no padding, to 1e-10. Closes #871 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent aa02375 commit 6dbef8a

2 files changed

Lines changed: 137 additions & 2 deletions

File tree

‎autolens/lens/substructure_util.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,24 @@ def extract(prof):
7878
raise ValueError(f"Unsupported halo profile class: {profile_cls}")
7979

8080

81+
def _padding_params_from(profile_cls, n_params):
82+
"""
83+
The parameter row put into an empty halo slot: a zero centre followed by the profile's
84+
``vmapped_padding_params`` (ones when it has none).
85+
86+
The mask zeroes an empty slot's deflection, but zero padding would put a zero scale
87+
radius into the profile, whose infinite partial derivatives turn every ``jax.grad``
88+
through the plane into NaN (zero cotangent times infinity). A row inside the profile's
89+
domain keeps the gradients finite. ``vmapped_deflections_from`` swaps in the same row
90+
itself; padding here as well keeps the gradients finite with an autogalaxy whose hook
91+
predates that swap.
92+
"""
93+
radial = getattr(profile_cls, "vmapped_padding_params", None)
94+
if radial is None:
95+
radial = np.ones(n_params - 2)
96+
return np.concatenate([np.zeros(2), np.asarray(radial, dtype=float)])
97+
98+
8199
def precompute_scaling_matrix(plane_redshifts, cosmology=None):
82100
import jax.numpy as jnp
83101

@@ -168,7 +186,8 @@ def galaxies_to_halo_arrays(galaxies, plane_redshifts, max_n, profile_cls):
168186
Returns
169187
-------
170188
The halo parameters ``(n_planes, max_n, n_params)``, the slot mask ``(n_planes, max_n)``
171-
and the sheet convergence of each plane ``(n_planes,)``.
189+
and the sheet convergence of each plane ``(n_planes,)``. Slots the mask leaves empty hold
190+
the profile's benign padding parameters (see ``_padding_params_from``), not zeros.
172191
"""
173192
import jax.numpy as jnp
174193

@@ -183,7 +202,10 @@ def galaxies_to_halo_arrays(galaxies, plane_redshifts, max_n, profile_cls):
183202
else:
184203
_check_max_n(counts=counts, plane_redshifts=plane_redshifts, max_n=max_n)
185204

186-
params = np.zeros((n_planes, max_n, n_params))
205+
params = np.tile(
206+
_padding_params_from(profile_cls=profile_cls, n_params=n_params),
207+
(n_planes, max_n, 1),
208+
)
187209
mask = np.zeros((n_planes, max_n), dtype=bool)
188210
sheet_kappas = np.zeros(n_planes)
189211

‎test_autolens/lens/test_substructure_util.py‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,116 @@ def test__los_realizations_to_arrays__overflow_names_the_realisation():
237237
max_n=3,
238238
profile_cls=al.mp.NFWTruncatedSph,
239239
)
240+
241+
242+
def _multi_plane_summed_deflections(grid, plane_params, plane_masks, scaling_matrix):
243+
"""
244+
Trace ``grid`` through the halo planes one at a time and return the sum of every plane's
245+
deflections, each plane taking its own (possibly unpadded) parameter array.
246+
"""
247+
import jax.numpy as jnp
248+
249+
deflections = []
250+
total = 0.0
251+
for i, (params, mask) in enumerate(zip(plane_params, plane_masks)):
252+
traced = grid
253+
for j in range(i):
254+
traced = traced - scaling_matrix[i, j] * deflections[j]
255+
plane_deflections = al.mp.NFWTruncatedSph.vmapped_deflections_from(
256+
traced, params, mask
257+
)
258+
deflections.append(plane_deflections)
259+
total = total + jnp.sum(plane_deflections)
260+
return total
261+
262+
263+
def _nfw_truncated_halos_scattered(redshift, total, seed):
264+
rng = np.random.default_rng(seed)
265+
return [
266+
al.Galaxy(
267+
redshift=redshift,
268+
mass=al.mp.NFWTruncatedSph(
269+
centre=tuple(rng.uniform(-1.0, 1.0, size=2)),
270+
kappa_s=float(rng.uniform(0.01, 0.05)),
271+
scale_radius=float(rng.uniform(0.5, 1.5)),
272+
truncation_radius=float(rng.uniform(2.0, 4.0)),
273+
),
274+
)
275+
for _ in range(total)
276+
]
277+
278+
279+
@requires_jax
280+
def test__galaxies_to_halo_arrays__padded_slots_keep_multi_plane_gradients_finite():
281+
import jax
282+
import jax.numpy as jnp
283+
284+
plane_redshifts = [0.3, 0.6]
285+
counts = [2, 5]
286+
galaxies = _nfw_truncated_halos_scattered(
287+
redshift=0.3, total=2, seed=1
288+
) + _nfw_truncated_halos_scattered(redshift=0.6, total=5, seed=2)
289+
290+
with jax.enable_x64(True):
291+
grid = jnp.array(np.random.default_rng(3).uniform(-2.0, 2.0, size=(30, 2)))
292+
scaling_matrix = substructure_util.precompute_scaling_matrix(plane_redshifts)
293+
294+
padded_params, padded_mask, _ = substructure_util.galaxies_to_halo_arrays(
295+
galaxies=galaxies,
296+
plane_redshifts=plane_redshifts,
297+
max_n=8,
298+
profile_cls=al.mp.NFWTruncatedSph,
299+
)
300+
assert not bool(padded_mask.all())
301+
302+
unpadded = [
303+
substructure_util.galaxies_to_halo_arrays(
304+
galaxies=[g for g in galaxies if g.redshift == z],
305+
plane_redshifts=[z],
306+
max_n=count,
307+
profile_cls=al.mp.NFWTruncatedSph,
308+
)
309+
for z, count in zip(plane_redshifts, counts)
310+
]
311+
unpadded_params = [params[0] for params, _, _ in unpadded]
312+
unpadded_masks = [mask[0] for _, mask, _ in unpadded]
313+
assert all(bool(mask.all()) for mask in unpadded_masks)
314+
315+
def padded(grid, params):
316+
return _multi_plane_summed_deflections(
317+
grid, list(params), list(padded_mask), scaling_matrix
318+
)
319+
320+
def no_padding(grid, params):
321+
return _multi_plane_summed_deflections(
322+
grid, params, unpadded_masks, scaling_matrix
323+
)
324+
325+
d_grid, d_params = jax.grad(padded, argnums=(0, 1))(grid, padded_params)
326+
d_grid_ref, d_params_ref = jax.grad(no_padding, argnums=(0, 1))(
327+
grid, unpadded_params
328+
)
329+
330+
assert np.isfinite(np.asarray(d_grid)).all()
331+
assert np.isfinite(np.asarray(d_params)).all()
332+
np.testing.assert_allclose(d_grid, d_grid_ref, rtol=0.0, atol=1e-10)
333+
for plane, count in enumerate(counts):
334+
np.testing.assert_allclose(
335+
d_params[plane, :count], d_params_ref[plane], rtol=0.0, atol=1e-10
336+
)
337+
assert np.all(np.asarray(d_params[plane, count:]) == 0.0)
338+
339+
340+
@requires_jax
341+
def test__galaxies_to_halo_arrays__empty_slots_hold_benign_padding():
342+
params, mask, _ = substructure_util.galaxies_to_halo_arrays(
343+
galaxies=_nfw_truncated_halos_on_plane(redshift=0.7, total=1),
344+
plane_redshifts=[0.7],
345+
max_n=3,
346+
profile_cls=al.mp.NFWTruncatedSph,
347+
)
348+
349+
assert mask.tolist() == [[True, False, False]]
350+
np.testing.assert_allclose(np.asarray(params[0, 0]), [0.0, 0.0, 0.01, 1.0, 2.0])
351+
radial_padding = np.asarray(params[0, 1:, 2:])
352+
assert np.all(radial_padding[:, 1] > 0.0)

0 commit comments

Comments
 (0)