diff --git a/README.md b/README.md index 2c8654053..a9775b2f2 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,8 @@ Results are framed by **astronomy instrument** (HST, Euclid, JWST, …) rather t | Cell | Instrument | Platform | Inversion path | Step-sum total | PyAutoLens version | |------|------------|----------|----------------|----------------|--------------------| -| `cluster/image_plane` | — | local_cpu_fp64 | dense (mapping) | 4.99 s | v2026.7.6.649 | -| `cluster/source_plane` | — | local_cpu_fp64 | dense (mapping) | 3.1 ms | v2026.7.6.649 | +| `cluster/image_plane` | — | local_cpu_fp64 | dense (mapping) | 10.25 s | v2026.7.23.1 | +| `cluster/source_plane` | — | local_cpu_fp64 | dense (mapping) | 4.5 ms | v2026.7.23.1 | | `datacube/delaunay` | alma_high | hpc_a100_fp64 | dense (mapping) | — | v2026.7.6.649 | | `datacube/delaunay` | alma_high | hpc_a100_mp | dense (mapping) | — | v2026.7.6.649 | | `datacube/inversion` | alma_high | hpc_a100_fp64 | dense (mapping) | — | v2026.7.6.649 | diff --git a/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.json b/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.json new file mode 100644 index 000000000..ded70266e --- /dev/null +++ b/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.json @@ -0,0 +1,42 @@ +{ + "autolens_version": "2026.7.23.1", + "device": { + "backend": "cpu", + "device": "cpu:0", + "xla_flags": "--xla_disable_hlo_passes=constant_folding --xla_gpu_autotune_level=0", + "omp_num_threads": "1", + "cpu_count": 8 + }, + "configuration": { + "n_systems": 2, + "n_images_total": 6, + "n_planes": 3, + "n_mass_profiles": 13, + "likelihood": "image_plane (FitPositionsImagePairRepeat)", + "solver_grid": "200x200 @ 0.7 arcsec", + "solver_pixel_scale_precision": 0.01 + }, + "steps": { + "1 source centres (back-trace)": 0.012421499995980412, + "2.point_0 PointSolver solve (z=1.0)": 0.583530866667085, + "2.point_1 PointSolver solve (z=2.0)": 0.3362739999987146, + "3.point_0 FitPositionsImagePairRepeat (fit total)": 4.335666899998614, + "3.point_1 FitPositionsImagePairRepeat (fit total)": 4.9793703999966965, + "4.point_0 FitPositionsImagePairRepeatSolved (fit total, analytic \u03b2*)": 4.929903699994611, + "4.point_1 FitPositionsImagePairRepeatSolved (fit total, analytic \u03b2*)": 4.697616299999936 + }, + "total_step_by_step": 10.24726366665709, + "log_likelihood": -51694194.57333637, + "solved": { + "fit_positions_cls": "FitPositionsImagePairRepeatSolved", + "log_likelihood": -11022861.386487413, + "total_step_solved_extra": 9.627519999994547, + "delta_per_system_s": { + "point_0": 0.594236799995997, + "point_1": -0.2817540999967605 + }, + "delta_total_s": 0.3124826999992365, + "free_centre_params_removed_per_point_source": 2, + "free_centre_params_removed_total": 4 + } +} \ No newline at end of file diff --git a/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.png b/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.png new file mode 100644 index 000000000..2df294e7f Binary files /dev/null and b/results/breakdown/cluster/image_plane_breakdown_v2026.7.23.1.png differ diff --git a/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.json b/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.json new file mode 100644 index 000000000..97a615549 --- /dev/null +++ b/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.json @@ -0,0 +1,44 @@ +{ + "autolens_version": "2026.7.23.1", + "device": { + "backend": "cpu", + "device": "cpu:0", + "xla_flags": "--xla_disable_hlo_passes=constant_folding --xla_gpu_autotune_level=0", + "omp_num_threads": "1", + "cpu_count": 8 + }, + "configuration": { + "n_systems": 2, + "n_images_total": 6, + "n_planes": 3, + "n_mass_profiles": 13, + "likelihood": "source_plane (FitPositionsSource)" + }, + "steps": { + "1.0 ray-trace point_0 (3 img)": 0.0010556900000665338, + "1.1 ray-trace point_1 (3 img)": 0.0008053600002313032, + "2.0 magnification (hessian) point_0": 0.0017030000002705493, + "2.1 magnification (hessian) point_1": 0.0008346700000402052, + "3.0 weighted chi2 point_0": 3.963000053772703e-05, + "3.1 weighted chi2 point_1": 3.6700000055134294e-05, + "4 log-likelihood assembly": 6.836999964434653e-05, + "5.point_0 FitPositionsSource (fit total)": 0.06679779999831226, + "5.point_1 FitPositionsSource (fit total)": 0.047178799999528565, + "6.point_0 FitPositionsSourceSolved (fit total, analytic \u03b2*)": 0.07292849999794271, + "6.point_1 FitPositionsSourceSolved (fit total, analytic \u03b2*)": 0.061136500000429805 + }, + "total_step_by_step": 0.004543420000845799, + "reference_log_likelihood": -40135921.91112596, + "solved": { + "fit_positions_cls": "FitPositionsSourceSolved", + "log_likelihood": -4230422.577412412, + "total_step_solved_extra": 0.24804159999621334, + "delta_per_system_s": { + "point_0": 0.006130699999630451, + "point_1": 0.01395770000090124 + }, + "delta_total_s": 0.020088400000531692, + "free_centre_params_removed_per_point_source": 2, + "free_centre_params_removed_total": 4 + } +} \ No newline at end of file diff --git a/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.png b/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.png new file mode 100644 index 000000000..4f216c28a Binary files /dev/null and b/results/breakdown/cluster/source_plane_breakdown_v2026.7.23.1.png differ diff --git a/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.json b/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.json new file mode 100644 index 000000000..0ccfc8201 --- /dev/null +++ b/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.json @@ -0,0 +1,30 @@ +{ + "autolens_version": "2026.7.23.1", + "dataset": "simple", + "fit_positions_cls": "FitPositionsImagePairAllSolved", + "configuration": { + "observed_image_positions": 4, + "positions_noise_sigma": 0.05, + "free_parameters": 5, + "free_parameters_image_plane_plain": 8, + "free_parameters_delta": -3, + "point_source_profile": "PointSolved" + }, + "eager_per_call": 0.27352910000045083, + "eager_log_likelihood": 7.743201200876817, + "full_pipeline_single_jit": 0.03859548000036739, + "full_pipeline_log_likelihood": 7.743201200876806, + "repeat_fit_class_steady_state": { + "fit_positions_cls": "FitPositionsImagePairRepeatSolved", + "per_call": 0.047158170000329847, + "log_likelihood": 4.981203683959095 + }, + "vmap": { + "batch_size": 3, + "batch_time": 0.084402240000054, + "per_call": 0.028134080000018002, + "speedup_vs_single_jit": 1.4 + }, + "pinned_expected": 7.743201200876817, + "pinned_drift": [] +} \ No newline at end of file diff --git a/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.png b/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.png new file mode 100644 index 000000000..2ec5ca81a Binary files /dev/null and b/results/runtime/point_source/image_plane_solved/image_plane_solved_summary_v2026.7.23.1.png differ diff --git a/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.json b/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.json new file mode 100644 index 000000000..c19202888 --- /dev/null +++ b/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.json @@ -0,0 +1,26 @@ +{ + "autolens_version": "2026.7.23.1", + "dataset": "simple", + "fit_positions_cls": "FitPositionsSourceSolved", + "configuration": { + "observed_image_positions": 4, + "positions_noise_sigma": 0.05, + "free_parameters": 5, + "free_parameters_source_plane_plain": 8, + "free_parameters_delta": -3, + "point_source_profile": "PointSolved" + }, + "eager_per_call": 0.010933216999983415, + "eager_log_likelihood": 0.5986504297427313, + "full_pipeline_jits": true, + "full_pipeline_single_jit": 0.0003383600000233855, + "full_pipeline_log_likelihood": 0.5986504555530896, + "vmap": { + "batch_size": 3, + "batch_time": 0.00035438000049907713, + "per_call": 0.00011812666683302571, + "speedup_vs_single_jit": 2.9 + }, + "pinned_expected": 0.5986504555530896, + "pinned_drift": [] +} \ No newline at end of file diff --git a/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.png b/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.png new file mode 100644 index 000000000..98838e014 Binary files /dev/null and b/results/runtime/point_source/source_plane_solved/source_plane_solved_summary_v2026.7.23.1.png differ diff --git a/results/simulators/cluster_summary_v2026.7.23.1.json b/results/simulators/cluster_summary_v2026.7.23.1.json new file mode 100644 index 000000000..59eedf28a --- /dev/null +++ b/results/simulators/cluster_summary_v2026.7.23.1.json @@ -0,0 +1,59 @@ +{ + "autolens_version": "2026.7.23.1", + "type": "cluster", + "configuration": { + "imaging_grid_shape": [ + 1000, + 1000 + ], + "solver_grid_shape": [ + 800, + 800 + ], + "pixel_scales": 0.1, + "n_sources": 2, + "source_redshifts": [ + 1.0, + 2.0 + ], + "n_lens_galaxies": 2, + "host_halo_mass_at_200": 1995262314968882.8, + "over_sample_sub_sizes": [ + 32, + 8, + 2 + ] + }, + "phases": { + "setup_imaging_grid": 0.19407199999841396, + "setup_galaxies": 0.0070218999971984886, + "setup_tracer": 1.0099996870849282e-05, + "register_pytrees": 0.4693944999962696, + "solver_build": 0.04854239999986021, + "jitted_solve_src0_lower": 17.030921099998523, + "jitted_solve_src0_compile": 1.4590461999978288, + "jitted_solve_src0_first_call": 6.7645153000048595, + "jitted_solve_src0_steady_x3": 23.18231260000175, + "jitted_solve_src1_lower": 1.540487199999916, + "jitted_solve_src1_compile": 1.6291495000041323, + "jitted_solve_src1_first_call": 7.864882399997441, + "jitted_solve_src1_steady_x3": 18.281628900003852, + "setup_psf_simulator": 0.000654800001939293, + "via_tracer_from": 141.9311338999978, + "output_fits": 0.11429460000363179, + "output_scaling_galaxies_csv": 0.0002865999995265156, + "output_point_datasets": 0.00159939999866765, + "output_json": 0.017929999994521495 + }, + "diagnostic": { + "solver_compile_total_s": 3.088195700001961, + "solver_lower_total_s": 18.57140829999844, + "solver_steady_total_s": 41.4639415000056, + "via_tracer_from_s": 141.9311338999978, + "compile_vs_via_tracer_ratio": 0.02 + }, + "positions_found": { + "src0": 3, + "src1": 3 + } +} \ No newline at end of file diff --git a/results/simulators/cluster_summary_v2026.7.23.1.png b/results/simulators/cluster_summary_v2026.7.23.1.png new file mode 100644 index 000000000..30ad114fa Binary files /dev/null and b/results/simulators/cluster_summary_v2026.7.23.1.png differ diff --git a/scripts/cluster/likelihood_breakdown/image_plane.py b/scripts/cluster/likelihood_breakdown/image_plane.py index af8e8bacf..af9388fd6 100644 --- a/scripts/cluster/likelihood_breakdown/image_plane.py +++ b/scripts/cluster/likelihood_breakdown/image_plane.py @@ -30,6 +30,24 @@ one-off compile stays at minutes; production precision (0.001") multiplies the triangle fan-out, not the structure of the breakdown. +Solved-variant addendum (issue #657 phase 3) +---------------------------------------------- + +Alongside the plain ``FitPositionsImagePairRepeat`` steps above, step 4 +times ``FitPositionsImagePairRepeatSolved`` per system against a second +tracer (``tracer_solved``) built with zero-parameter ``al.ps.PointSolved`` +profiles in place of ``al.ps.Point`` — the analytic β* extension in the +image plane. This is a glafic-style extension, **not** a result from +Lombardi 2024 (arXiv:2406.15280); see ``autolens/point/fit/solved.py``'s +module docstring for the attribution split. Step 2's forward-solve is +unaffected by (and shared with) the solved variant: ``solver.solve()`` only +consumes an explicit ``source_plane_coordinate`` + the tracer's mass +profiles, never the point-source profile type, so only step 3's non-solved +fit and step 4's solved fit differ. A printed summary reports the +per-system fit-total runtime delta (step 4 − step 3), to be weighed against +the 2 fewer free centre parameters per point source (4 total for this +cluster's 2 systems) a full model-fit would otherwise sample. + Output ------ @@ -215,6 +233,17 @@ def jit_profile(func, label, *args, n_repeats=10): n_mass_profiles = len(main_lens_galaxies) + len(scaling_galaxies) + 1 print(f"Tracer: {len(tracer.planes)} planes, {n_mass_profiles} mass components.") +# Solved-variant tracer: `al.ps.PointSolved` (0 params) in place of `al.ps.Point` +# (2 centre params) per source, name-paired the same way. Used only by step 4 +# below — step 1/2's back-trace + forward-solve don't read the point-source +# profile type at all, so they're shared as-is with the plain-path tracer. +source_galaxies_solved = [ + al.Galaxy(redshift=float(d.redshift), **{d.name: al.ps.PointSolved()}) for d in dataset_list +] +tracer_solved = al.Tracer( + galaxies=main_lens_galaxies + scaling_galaxies + [host_halo_galaxy] + source_galaxies_solved +) + positions_list = [np.atleast_2d(np.asarray(d.positions)) for d in dataset_list] plane_indices = [ tracer.plane_index_via_redshift_from(redshift=float(d.redshift)) for d in dataset_list @@ -308,6 +337,7 @@ def solve(source_plane_coordinate, _z=float(dataset.redshift)): # pairing overhead is the difference from step 2). # --------------------------------------------------------------------------- fit_log_likelihoods = [] +fit_total_times = [] for dataset in dataset_list: with timer.section(f"step3_fit_total_{dataset.name}"): fit = al.FitPositionsImagePairRepeat( @@ -318,6 +348,7 @@ def solve(source_plane_coordinate, _z=float(dataset.redshift)): solver=solver, ) fit_log_likelihoods.append(float(fit.log_likelihood)) + fit_total_times.append(timer.records[-1][1]) likelihood_steps.append( (f"3.{dataset.name} FitPositionsImagePairRepeat (fit total)", timer.records[-1][1]) ) @@ -325,6 +356,56 @@ def solve(source_plane_coordinate, _z=float(dataset.redshift)): log_likelihood_total = sum(fit_log_likelihoods) print(f"\n image-plane log likelihood (sum over systems): {log_likelihood_total:.6e}") +# --------------------------------------------------------------------------- +# Step 4 — FitPositionsImagePairRepeatSolved per system: same forward-solve +# machinery as steps 2/3, but the source-plane centre driving the +# PointSolver is analytically solved (β*, tensor-weighted precision) rather +# than read from a centre-bearing profile. `tracer_solved` carries +# `PointSolved` in place of `Point` so the *Solved fit class's name-pairing +# finds a parameter-free profile — pairing a centre-bearing profile with a +# *Solved fit class raises `PointProfileMismatchException`. Eager-timed, +# matching step 3's pattern (the fit re-runs the forward-solve internally). +# --------------------------------------------------------------------------- +_n_plain_steps = len(likelihood_steps) + +fit_solved_log_likelihoods = [] +fit_solved_total_times = [] +for dataset in dataset_list: + with timer.section(f"step4_fit_total_solved_{dataset.name}"): + fit_solved = al.FitPositionsImagePairRepeatSolved( + name=dataset.name, + data=dataset.positions, + noise_map=dataset.positions_noise_map, + tracer=tracer_solved, + solver=solver, + ) + fit_solved_log_likelihoods.append(float(fit_solved.log_likelihood)) + fit_solved_total_times.append(timer.records[-1][1]) + likelihood_steps.append( + ( + f"4.{dataset.name} FitPositionsImagePairRepeatSolved (fit total, analytic β*)", + timer.records[-1][1], + ) + ) + +log_likelihood_total_solved = sum(fit_solved_log_likelihoods) +print( + f"\n image-plane log likelihood, solved (sum over systems): {log_likelihood_total_solved:.6e}" +) + +print("\n--- Solved vs plain: per-system fit-total runtime delta ---") +delta_per_system = {} +for dataset, plain_t, solved_t in zip(dataset_list, fit_total_times, fit_solved_total_times): + delta = solved_t - plain_t + pct = 100.0 * delta / plain_t if plain_t else float("nan") + delta_per_system[dataset.name] = delta + print( + f" {dataset.name}: plain={plain_t:.6f}s solved={solved_t:.6f}s " + f"delta={delta:+.6f}s ({pct:+.1f}%) -- vs -2 free centre params/source if sampled" + ) +delta_total = sum(delta_per_system.values()) +print(f" TOTAL delta across {len(dataset_list)} systems: {delta_total:+.6f}s") + # =================================================================== # PART B — Summary + artifacts @@ -344,12 +425,23 @@ def solve(source_plane_coordinate, _z=float(dataset.redshift)): print(f"PER-STEP BREAKDOWN SUMMARY — CLUSTER IMAGE-PLANE — v{al_version}") print("=" * 70) max_label = max(len(label) for label, _ in likelihood_steps) +# `step_total` stays scoped to the original (plain-path) decomposition — +# steps 1-3 — so it keeps meaning "sum of the decomposed likelihood steps" +# for the README auto-table / XLA-fusion-caveat comparison against +# full_pipeline_single_jit. Step 4 (solved) is an additive extra +# measurement, not part of that decomposition; its cost is reported +# separately as `total_step_solved_extra`. step_total = 0.0 +step_total_solved_extra = 0.0 for i, (label, per_call) in enumerate(likelihood_steps, 1): print(f" {i:>2}. {label:<{max_label}} {per_call:>12.6f} s") - step_total += per_call + if i <= _n_plain_steps: + step_total += per_call + else: + step_total_solved_extra += per_call print("-" * 70) -print(f" {'TOTAL (step-by-step)':<{max_label}} {step_total:>12.6f} s") +print(f" {'TOTAL (step-by-step, plain)':<{max_label}} {step_total:>12.6f} s") +print(f" {'TOTAL (solved, extra)':<{max_label}} {step_total_solved_extra:>12.6f} s") print("=" * 70) breakdown_summary = { @@ -367,6 +459,15 @@ def solve(source_plane_coordinate, _z=float(dataset.redshift)): "steps": {label: per_call for label, per_call in likelihood_steps}, "total_step_by_step": step_total, "log_likelihood": log_likelihood_total, + "solved": { + "fit_positions_cls": "FitPositionsImagePairRepeatSolved", + "log_likelihood": log_likelihood_total_solved, + "total_step_solved_extra": step_total_solved_extra, + "delta_per_system_s": delta_per_system, + "delta_total_s": delta_total, + "free_centre_params_removed_per_point_source": 2, + "free_centre_params_removed_total": 2 * len(dataset_list), + }, } dict_path, chart_path = resolve_output_paths( diff --git a/scripts/cluster/likelihood_breakdown/source_plane.py b/scripts/cluster/likelihood_breakdown/source_plane.py index e27d82d45..f629a2e90 100644 --- a/scripts/cluster/likelihood_breakdown/source_plane.py +++ b/scripts/cluster/likelihood_breakdown/source_plane.py @@ -49,6 +49,27 @@ is marked JIT-blocked); the per-step decomposition below sidesteps that by compiling the numerical core of each step in isolation. +Solved-variant addendum (issue #657 phase 3) +---------------------------------------------- + +Steps 5-6 add a plain-vs-solved fit-total comparison: step 5 times the +production ``al.FitPositionsSource`` per system (eager, atomic — the same +call PART C already asserts in summed form, just split per system here so +it is comparable to step 6), and step 6 times +``al.FitPositionsSourceSolved`` per system against a second tracer +(``tracer_solved``) built with zero-parameter ``al.ps.PointSolved`` +profiles in place of ``al.ps.Point``. This IS the paper's result (Lombardi +2024, arXiv:2406.15280 §5.1) — unlike the image-plane solved extension, the +source-plane analytic β* solve is exactly what the paper derives. The +analytic solve itself (``autolens/point/fit/solved.py``: ``SolvedCentre``) +is profiled as a single atomic fit-total here, not further decomposed into +its own jacobian/precision-tensor sub-steps, mirroring how PART C already +treats the plain ``FitPositionsSource`` as one atomic reference alongside +the fully decomposed steps 1-4. A printed summary reports the per-system +fit-total runtime delta (step 6 − step 5), to be weighed against the 2 +fewer free centre parameters per point source (4 total for this cluster's +2 systems) a full model-fit would otherwise sample. + Output ------ @@ -253,6 +274,16 @@ def jit_profile(func, label, *args, n_repeats=10): f"(2 main dPIE + {len(scaling_galaxies)} scaling dPIE + 1 NFW host)." ) +# Solved-variant tracer: `al.ps.PointSolved` (0 params) in place of +# `al.ps.Point(centre=...)` (2 centre params) per source, name-paired the +# same way. Used only by step 6 below. +source_galaxies_solved = [ + al.Galaxy(redshift=float(d.redshift), **{d.name: al.ps.PointSolved()}) for d in dataset_list +] +tracer_solved = al.Tracer( + galaxies=main_lens_galaxies + scaling_galaxies + [host_halo_galaxy] + source_galaxies_solved +) + positions_list = [np.atleast_2d(np.asarray(d.positions)) for d in dataset_list] noise_list = [np.asarray(d.positions_noise_map) for d in dataset_list] plane_indices = [ @@ -370,6 +401,80 @@ def log_likelihood_total(chi_squareds, noise_norms): ) likelihood_steps.append(("4 log-likelihood assembly", timer.records[-1][1] / 10)) +_n_plain_steps = len(likelihood_steps) + +# --------------------------------------------------------------------------- +# Step 5 — FitPositionsSource per system, fit-total (eager). Steps 1-4 above +# decompose the internals of this same call; this atomic per-system timing +# exists purely so the solved-vs-plain runtime delta below (step 6 - step 5) +# is apples-to-apples — steps 1-4's individually-JIT-profiled sub-steps +# aren't directly comparable to step 6's single eager +# FitPositionsSourceSolved timing. PART C's `reference_fit_positions_source` +# assertion further below is unaffected — this is an additive per-system +# timing, not a replacement. +# --------------------------------------------------------------------------- +fit_plain_log_likelihoods = [] +fit_plain_total_times = [] +for dataset in dataset_list: + with timer.section(f"step5_fit_total_plain_{dataset.name}"): + fit_plain = al.FitPositionsSource( + name=dataset.name, + data=dataset.positions, + noise_map=dataset.positions_noise_map, + tracer=tracer, + solver=None, + ) + fit_plain_log_likelihoods.append(float(fit_plain.log_likelihood)) + fit_plain_total_times.append(timer.records[-1][1]) + likelihood_steps.append( + (f"5.{dataset.name} FitPositionsSource (fit total)", timer.records[-1][1]) + ) + +# --------------------------------------------------------------------------- +# Step 6 — FitPositionsSourceSolved per system, fit-total (eager, analytic +# β*). `tracer_solved` carries `PointSolved` in place of `Point` so the +# *Solved fit class's name-pairing finds a parameter-free profile — pairing +# a centre-bearing profile with a *Solved fit class raises +# PointProfileMismatchException. Defaults to xp=numpy (no JAX needed). +# --------------------------------------------------------------------------- +fit_solved_log_likelihoods = [] +fit_solved_total_times = [] +for dataset in dataset_list: + with timer.section(f"step6_fit_total_solved_{dataset.name}"): + fit_solved = al.FitPositionsSourceSolved( + name=dataset.name, + data=dataset.positions, + noise_map=dataset.positions_noise_map, + tracer=tracer_solved, + solver=None, + ) + fit_solved_log_likelihoods.append(float(fit_solved.log_likelihood)) + fit_solved_total_times.append(timer.records[-1][1]) + likelihood_steps.append( + ( + f"6.{dataset.name} FitPositionsSourceSolved (fit total, analytic β*)", + timer.records[-1][1], + ) + ) + +log_likelihood_total_solved = sum(fit_solved_log_likelihoods) +print( + f"\n source-plane log likelihood, solved (sum over systems): {log_likelihood_total_solved:.6e}" +) + +print("\n--- Solved vs plain: per-system fit-total runtime delta ---") +delta_per_system = {} +for dataset, plain_t, solved_t in zip(dataset_list, fit_plain_total_times, fit_solved_total_times): + delta = solved_t - plain_t + pct = 100.0 * delta / plain_t if plain_t else float("nan") + delta_per_system[dataset.name] = delta + print( + f" {dataset.name}: plain={plain_t:.6f}s solved={solved_t:.6f}s " + f"delta={delta:+.6f}s ({pct:+.1f}%) -- vs -2 free centre params/source if sampled" + ) +delta_total = sum(delta_per_system.values()) +print(f" TOTAL delta across {len(dataset_list)} systems: {delta_total:+.6f}s") + # =================================================================== # PART C — Eager reference check (FitPositionsSource, production path) @@ -414,12 +519,22 @@ def log_likelihood_total(chi_squareds, noise_norms): print(f"PER-STEP BREAKDOWN SUMMARY — CLUSTER SOURCE-PLANE — v{al_version}") print("=" * 70) max_label = max(len(label) for label, _ in likelihood_steps) +# `step_total` stays scoped to the original (plain-path) decomposition — +# steps 1-4 — so it keeps meaning "sum of the decomposed likelihood steps" +# for the README auto-table / XLA-fusion-caveat comparison. Steps 5-6 +# (plain-vs-solved fit-total comparison) are additive extra measurements, +# not part of that decomposition; their cost is reported separately. step_total = 0.0 +step_total_solved_extra = 0.0 for i, (label, per_call) in enumerate(likelihood_steps, 1): print(f" {i:>2}. {label:<{max_label}} {per_call:>12.6f} s") - step_total += per_call + if i <= _n_plain_steps: + step_total += per_call + else: + step_total_solved_extra += per_call print("-" * 70) -print(f" {'TOTAL (step-by-step)':<{max_label}} {step_total:>12.6f} s") +print(f" {'TOTAL (step-by-step, plain)':<{max_label}} {step_total:>12.6f} s") +print(f" {'TOTAL (steps 5-6, extra)':<{max_label}} {step_total_solved_extra:>12.6f} s") print("=" * 70) breakdown_summary = { @@ -435,6 +550,15 @@ def log_likelihood_total(chi_squareds, noise_norms): "steps": {label: per_call for label, per_call in likelihood_steps}, "total_step_by_step": step_total, "reference_log_likelihood": reference_log_likelihood, + "solved": { + "fit_positions_cls": "FitPositionsSourceSolved", + "log_likelihood": log_likelihood_total_solved, + "total_step_solved_extra": step_total_solved_extra, + "delta_per_system_s": delta_per_system, + "delta_total_s": delta_total, + "free_centre_params_removed_per_point_source": 2, + "free_centre_params_removed_total": 2 * len(dataset_list), + }, } dict_path, chart_path = resolve_output_paths( diff --git a/scripts/misc/likelihood_breakdown/README.md b/scripts/misc/likelihood_breakdown/README.md index 9d51f7c9d..ab5edd188 100644 --- a/scripts/misc/likelihood_breakdown/README.md +++ b/scripts/misc/likelihood_breakdown/README.md @@ -13,8 +13,8 @@ For *how long the likelihood actually takes* on production hardware — i.e. a s | Cell | Instrument | Platform | Inversion path | Step-sum total | PyAutoLens version | |------|------------|----------|----------------|----------------|--------------------| -| `cluster/image_plane` | — | local_cpu_fp64 | dense (mapping) | 4.99 s | v2026.7.6.649 | -| `cluster/source_plane` | — | local_cpu_fp64 | dense (mapping) | 3.1 ms | v2026.7.6.649 | +| `cluster/image_plane` | — | local_cpu_fp64 | dense (mapping) | 10.25 s | v2026.7.23.1 | +| `cluster/source_plane` | — | local_cpu_fp64 | dense (mapping) | 4.5 ms | v2026.7.23.1 | | `datacube/delaunay` | alma_high | hpc_a100_fp64 | dense (mapping) | — | v2026.7.6.649 | | `datacube/delaunay` | alma_high | hpc_a100_mp | dense (mapping) | — | v2026.7.6.649 | | `datacube/inversion` | alma_high | hpc_a100_fp64 | dense (mapping) | — | v2026.7.6.649 | diff --git a/scripts/misc/likelihood_runtime/README.md b/scripts/misc/likelihood_runtime/README.md index ffe89088b..8d8fa0d38 100644 --- a/scripts/misc/likelihood_runtime/README.md +++ b/scripts/misc/likelihood_runtime/README.md @@ -85,6 +85,8 @@ Empirical effect: mp on CPU consistently helps 7 – 23 %. On GPU it's more vari | `datacube/delaunay.py` | Datacube (34-channel cube) | DelaunayBrightnessImage per channel, shared lens model | | `point_source/image_plane.py` | Point source | Image-plane χ² via `PointSolver` | | `point_source/source_plane.py` | Point source | Source-plane χ² (cheaper proxy) | +| `point_source/image_plane_solved.py` | Point source | Image-plane χ² via `PointSolver`, analytically-solved centre (`PointSolved` + `FitPositionsImagePairAllSolved`; also times `FitPositionsImagePairRepeatSolved` as a second steady-state entry) | +| `point_source/source_plane_solved.py` | Point source | Source-plane χ² (analytically-solved centre, `PointSolved` + `FitPositionsSourceSolved`) — full pipeline JITs cleanly (phase-2 xp-propagation fix, unlike the plain source-plane path) | ## Driving the matrix — `sweep.py` and `aggregate.py` diff --git a/scripts/misc/simulators/README.md b/scripts/misc/simulators/README.md index e1e13ffed..6d5ee183e 100644 --- a/scripts/misc/simulators/README.md +++ b/scripts/misc/simulators/README.md @@ -45,7 +45,7 @@ Auto-generated by `scripts/build_readme.py` from the latest `*_summary_v | Script | Total wall time | PyAutoLens version | |--------|-----------------|--------------------| -| `cluster.py` | 234.99 s | v2026.7.6.649 | +| `cluster.py` | 220.54 s | v2026.7.23.1 | | `group.py` | 38.11 s | v2026.5.14.2 | | `group4_mge_hst.py` | 4.28 s | v2026.7.9.1 | | `imaging.py` | 3.12 s | v2026.5.14.2 | diff --git a/scripts/point_source/likelihood_runtime/image_plane_solved.py b/scripts/point_source/likelihood_runtime/image_plane_solved.py new file mode 100644 index 000000000..f485d65ac --- /dev/null +++ b/scripts/point_source/likelihood_runtime/image_plane_solved.py @@ -0,0 +1,645 @@ +""" +JAX Profiling: Point-Source Likelihood — Image-Plane Chi-Squared (Solved) +=========================================================================== + +Profiles ``AnalysisPoint.log_likelihood_function`` for a lensed point-source +``PointDataset`` using the **analytically-solved image-plane** chi-squared +(``al.FitPositionsImagePairAllSolved``), the sibling of ``image_plane.py`` +introduced in issue #657 phase 3. + +Instead of sampling the source's centre as 2 free model parameters, this +variant pairs a zero-parameter ``al.ps.PointSolved`` profile with a +``*Solved`` fit class, which analytically solves for the source-plane centre +β* (tensor-weighted precision, Lombardi 2024 arXiv:2406.15280 §5.1) from the +current tracer before handing that centre to the same ``PointSolver`` +forward-solve used by the non-solved image-plane path. The image-plane +pairing chi-squared itself is unchanged from ``image_plane.py`` — only the +source of the centre driving the solve differs, and using a centre-free +extension in the image plane at all is **not** from the paper: it mirrors +glafic's source-position optimization convention, so attribute it as an +extension, not a paper result (see ``autolens/point/fit/solved.py`` module +docstring, which makes this attribution split explicit). + +Parameter-count delta +---------------------- + +Swapping ``al.ps.PointFlux`` (used by ``image_plane.py``: 2 centre + 1 flux += 3 params) for ``al.ps.PointSolved`` (0 params) drops the model from 8 to 5 +free parameters here — a delta of 3, not the 2 you would expect from the +paper's centre-only framing. 2 of those 3 are the analytically-solved +source-plane centre; the third is the flux parameter, which this +positions-only harness (``point_dataset_positions_only.json``, no flux +data fitted) never actually used regardless of PointFlux vs PointSolved — +dropping it is a side effect of PointSolved having no flux attribute at +all, not part of the phase-3 analytic-solve story. + +Second steady-state entry +-------------------------- + +In addition to the primary ``FitPositionsImagePairAllSolved`` full-pipeline +JIT/vmap timings (mirroring ``image_plane.py`` exactly), this script also +times ``al.FitPositionsImagePairRepeatSolved`` at the same compiled-input +shape (identical ``params_tree`` / dataset / solver) as a second +steady-state entry — a modest addition since only ``fit_positions_cls`` +differs between the two ``AnalysisPoint`` instances. This second entry is +timing-only: it is not part of the vmap / memory / regression-pin machinery +below, which stays scoped to the primary AllSolved fit class. + +Pytree-native parameter inputs +------------------------------ + +As in ``image_plane.py``, this script uses ``af.ModelInstance`` as the JIT +input via PyAutoFit's opt-in pytree registration +(``autofit.jax.register_model``, PRs #1220 / #1221 / #1222). + +Three-tier numerical assertions +------------------------------- + +1. **eager ≡ JIT**: numpy-path log-likelihood matches single-JIT result. +2. **JIT ≡ vmap**: every entry of the batched vmap output matches the + single-JIT result. +3. **regression constant**: hardcoded + ``EXPECTED_LOG_LIKELIHOOD_IMAGE_PLANE_SOLVED`` guards against silent + drift in the underlying solver / chi-squared / analytic-solve stack. + Captured during authoring against the dataset already committed in this + worktree (``noise_seed=1`` in ``simulators/point_source.py``); refresh it + the same way ``image_plane.py`` documents if the dataset or priors + change. +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) + + +import json + +# AUTOLENS_PROFILING_SMOKE=1 short-circuit (Phase 5 / CI lint smoke). +# Verifies the import graph + module-level setup succeeded without running +# the full profiling pipeline. Skipped entirely when the env var is unset. +import os as _smoke_os +import subprocess +import sys +import sys as _smoke_sys +import time +from contextlib import contextmanager +from pathlib import Path + +import jax +import jax.numpy as jnp +import matplotlib +import numpy as np + +if _smoke_os.environ.get("AUTOLENS_PROFILING_SMOKE") == "1": + print(f"[smoke] {__file__}: imports + module setup OK; exiting.") + _smoke_sys.exit(0) + +# Sweep-driver CLI args (--config-name / --output-dir / --use-mixed-precision). +# Tolerates extra/unknown args via parse_known_args inside the helper. +sys.path.insert(0, str(_profiling_root())) +from simulators.point_source import INSTRUMENTS # noqa: E402 +from vram import ( # noqa: E402 + probe_vmap_memory, + recommend_batch_size, + resolve_vmap_batch, + write_probe_json, +) + +from _profile_cli import ( + auto_simulate_if_missing, + check_pinned, + device_info_dict, + parse_profile_cli, + record_pinned_check, # noqa: E402 + resolve_output_paths, +) + +_cli = parse_profile_cli() + +matplotlib.use("Agg") +import autofit as af +import autolens as al +import matplotlib.pyplot as plt +from autofit.jax import register_model as _register_model_pytrees + +# --------------------------------------------------------------------------- +# Profiling helpers (mirrors imaging/mge.py and image_plane.py) +# --------------------------------------------------------------------------- + + +class Timer: + def __init__(self): + self.records: list[tuple[str, float]] = [] + + @contextmanager + def section(self, label: str): + start = time.perf_counter() + yield + elapsed = time.perf_counter() - start + self.records.append((label, elapsed)) + print(f" [{label}] {elapsed:.4f} s") + + def summary(self): + print("\n" + "=" * 70) + print("PROFILING SUMMARY") + print("=" * 70) + max_label = max(len(r[0]) for r in self.records) + total = 0.0 + for label, elapsed in self.records: + print(f" {label:<{max_label}} {elapsed:>10.4f} s") + total += elapsed + print("-" * 70) + print(f" {'TOTAL':<{max_label}} {total:>10.4f} s") + print("=" * 70) + + +def block(x): + if hasattr(x, "block_until_ready"): + x.block_until_ready() + return x + + +def jit_profile(func, label, *args, n_repeats=10): + jitted = jax.jit(func) + + with timer.section(f"{label}_lower"): + lowered = jitted.lower(*args) + + with timer.section(f"{label}_compile"): + compiled = lowered.compile() + + with timer.section(f"{label}_first_call"): + result = compiled(*args) + block(result) + + with timer.section(f"{label}_steady_x{n_repeats}"): + for _ in range(n_repeats): + result = compiled(*args) + block(result) + + per_call = timer.records[-1][1] / n_repeats + print(f" -> per-call avg: {per_call:.6f} s") + return compiled, result + + +timer = Timer() +instrument = "simple" + + +# =================================================================== +# PART A — Setup +# =================================================================== + +print(f"\n--- Dataset loading [{instrument}] ---") + +_script_dir = Path(__file__).resolve().parent +_workspace_root = _profiling_root() +dataset_path = Path("dataset") / "point_source" / instrument + +auto_simulate_if_missing( + dataset_path, + dataset_type="point_source", + instrument=instrument, + workspace_root=_workspace_root, +) + +with timer.section("dataset_load"): + dataset = al.from_json( + file_path=dataset_path / "point_dataset_positions_only.json", + ) + +n_observed_positions = dataset.positions.shape[0] +positions_noise_sigma = float(dataset.positions_noise_map[0]) + +print("\n--- Point solver ---") + +with timer.section("solver_build"): + grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.2) + solver = al.PointSolver.for_grid( + grid=grid, + pixel_scale_precision=0.001, + magnification_threshold=0.1, + ) + +print("\n--- Model construction (PointSolved — 0 source params) ---") + +with timer.section("model_build"): + # GaussianPrior(mean=truth, sigma=small) centres prior-median at the + # simulator truth while keeping params free so gradient diagnostics + # have dimensionality. Prior means MUST match the simulator's truth + # values exactly, otherwise the PointSolver finds fewer image-plane + # positions than the dataset contains and chi² explodes. + # + # Simulator truth (see autolens_workspace_developer/jax_profiling/ + # dataset_setup/point_source.py): + # Isothermal at centre=(0, 0), einstein_radius=1.6, + # ell_comps = al.convert.ell_comps_from(axis_ratio=0.9, angle=45°) + # ≈ (0.0526316, 0.0) + # source point_0.centre = (0.07, 0.07) — NOT used here: `PointSolved` + # has no `centre` at all, so there is nothing to prior-align on the + # source side. The analytic solve (see module docstring) recovers the + # source-plane centre from the tracer + observed positions instead. + mass = af.Model(al.mp.Isothermal) + mass.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.005) + mass.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.005) + mass.einstein_radius = af.GaussianPrior(mean=1.6, sigma=0.05) + mass.ell_comps.ell_comps_0 = af.GaussianPrior(mean=0.05263158, sigma=0.01) + mass.ell_comps.ell_comps_1 = af.GaussianPrior(mean=0.0, sigma=0.01) + lens = af.Model(al.Galaxy, redshift=0.5, mass=mass) + + # `PointSolved` has no `centre` / `flux` attributes, so no priors to set + # here — that is the whole point of the analytic solve. + point_0 = af.Model(al.ps.PointSolved) + source = af.Model(al.Galaxy, redshift=1.0, point_0=point_0) + + model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) + +print(f" Total free parameters: {model.total_free_parameters}") +print( + " (was 8 with al.ps.PointFlux in image_plane.py: 5 mass + 2 centre + 1 flux; " + f"PointSolved drops all 3 source params -> {model.total_free_parameters} mass-only. " + "2 of the 3 are the analytically-solved source centre (paper Sec 5.1 beta*); the " + "3rd is the flux param this positions-only dataset never fits either way.)" +) + +print("\n--- Instantiate concrete model ---") + +with timer.section("instance_from_vector"): + param_vector = model.physical_values_from_prior_medians + instance = model.instance_from_vector(vector=param_vector) + +with timer.section("register_pytrees"): + _register_model_pytrees(model) + +params_tree = jax.tree_util.tree_map(jnp.asarray, instance) + + +# --------------------------------------------------------------------------- +# Eager baseline — full FitPointDataset (image-plane chi-squared, solved) +# --------------------------------------------------------------------------- + +print("\n--- Eager FitPointDataset (image-plane, solved) ---") + +analysis_eager = al.AnalysisPoint( + dataset=dataset, + solver=solver, + fit_positions_cls=al.FitPositionsImagePairAllSolved, + use_jax=False, +) + +with timer.section("fit_eager"): + fit_eager = analysis_eager.fit_from(instance=instance) + log_likelihood_ref = float(fit_eager.log_likelihood) + figure_of_merit_ref = float(fit_eager.figure_of_merit) + +n_eager_repeats = 10 +with timer.section(f"eager_log_likelihood_x{n_eager_repeats}"): + for _ in range(n_eager_repeats): + analysis_eager.log_likelihood_function(instance=instance) +eager_per_call = timer.records[-1][1] / n_eager_repeats + +print(f" log_likelihood = {log_likelihood_ref}") +print(f" figure_of_merit = {figure_of_merit_ref}") +print(f" eager per-call = {eager_per_call:.6f} s") + + +# =================================================================== +# PART B — Full-pipeline JIT (FitPositionsImagePairAllSolved) +# =================================================================== + +print("\n" + "=" * 70) +print("FULL-PIPELINE JIT (image-plane, solved)") +print("=" * 70) + +analysis_jax = al.AnalysisPoint( + dataset=dataset, + solver=solver, + fit_positions_cls=al.FitPositionsImagePairAllSolved, + use_jax=True, +) + + +def full_pipeline_from_params(params_tree): + return analysis_jax.log_likelihood_function(instance=params_tree) + + +_, full_result = jit_profile(full_pipeline_from_params, "full_pipeline", params_tree) +full_pipeline_per_call = timer.records[-1][1] / 10 +print(f" full log_likelihood = {full_result}") + + +# =================================================================== +# PART B.2 — Second steady-state entry: FitPositionsImagePairRepeatSolved +# =================================================================== +# +# Same compiled-input shape as PART B (identical params_tree / dataset / +# solver, only fit_positions_cls differs) — a modest addition on top of the +# AllSolved profiling above, since the phase-3 economics question also cares +# about the nearest-pair-with-repeats scheme, not just the all-pairs one. + +print("\n" + "=" * 70) +print("SECOND STEADY-STATE (image-plane, solved): FitPositionsImagePairRepeatSolved") +print("=" * 70) + +analysis_jax_repeat = al.AnalysisPoint( + dataset=dataset, + solver=solver, + fit_positions_cls=al.FitPositionsImagePairRepeatSolved, + use_jax=True, +) + + +def repeat_pipeline_from_params(params_tree): + return analysis_jax_repeat.log_likelihood_function(instance=params_tree) + + +_, repeat_result = jit_profile(repeat_pipeline_from_params, "repeat_fit_class", params_tree) +repeat_fit_class_per_call = timer.records[-1][1] / 10 +print(f" FitPositionsImagePairRepeatSolved log_likelihood = {repeat_result}") + + +# =================================================================== +# PART B.5 — vmap-probe mode (early exit) +# =================================================================== +# +# When ``--vmap-probe`` is set the script JIT-vmaps the pipeline at the +# configured batch sizes, reads ``compiled.memory_analysis()``, writes a +# ``vmap_probe.json`` with the recommended A100 batch_size, and exits +# before the full vmap timing loop. See ``vram/README.md`` for methodology. +# Scoped to the primary AllSolved fit class only — the repeat-class timing +# above is a bonus entry, not part of this machinery. + +if _cli.vmap_probe: + probe = probe_vmap_memory( + full_pipeline_from_params, + params_tree, + batch_sizes=(1, 4, 16), + dataset="point_source", + model="image_plane_solved", + instrument=instrument, + ) + recommended = recommend_batch_size(probe) + probe_path = ( + _cli.output_dir + or (_workspace_root / "results" / "runtime" / "point_source" / "image_plane_solved") + ) / ( + "vmap_probe_image_plane_solved_sparse.json" + if _cli.use_sparse_operator + else "vmap_probe_image_plane_solved.json" + ) + write_probe_json(probe, recommended, probe_path) + print(f"\n vmap_probe samples: {probe.samples}") + print(f" per_replica: {probe.per_replica_mb:.1f} MB / replica") + print(f" recommended batch: {recommended}") + print(f" written to: {probe_path}") + sys.exit(0) + +# =================================================================== +# PART C — vmap over the full pipeline +# =================================================================== + +print("\n--- vmap batched evaluation ---") + +_batch_resolved, _batch_source = resolve_vmap_batch( + "point_source", + "image_plane_solved", + instrument, + output_dir=_cli.output_dir + or (_workspace_root / "results" / "runtime" / "point_source" / "image_plane_solved"), + path="sparse" if _cli.use_sparse_operator else "dense", + backend=jax.default_backend(), +) +print(f" vmap batch_size: {_batch_resolved} (source: {_batch_source})") +batch_size = _batch_resolved or 3 + +batched_params = jax.tree_util.tree_map( + lambda leaf: jnp.broadcast_to(leaf, (batch_size, *leaf.shape)), + params_tree, +) + +vmapped_full = jax.jit(jax.vmap(full_pipeline_from_params)) + +with timer.section("vmap_first_call"): + result_vmap = vmapped_full(batched_params) + block(result_vmap) + +n_vmap_repeats = 10 +with timer.section(f"vmap_steady_x{n_vmap_repeats}"): + for _ in range(n_vmap_repeats): + result_vmap = vmapped_full(batched_params) + block(result_vmap) + +vmap_batch_time = timer.records[-1][1] / n_vmap_repeats +vmap_per_call = vmap_batch_time / batch_size +vmap_speedup = full_pipeline_per_call / vmap_per_call + +print(f" batch results = {result_vmap}") +print(f" vmap batch of {batch_size}: {vmap_batch_time:.6f} s") +print(f" vmap per call: {vmap_per_call:.6f} s") +print(f" single JIT per call: {full_pipeline_per_call:.6f} s") +print(f" vmap speedup: {vmap_speedup:.1f}x faster per likelihood") + + +# =================================================================== +# PART D — Three-tier numerical assertions +# =================================================================== +# +# Tier 1: eager (NumPy path) ≡ single JIT +# Tier 2: single JIT ≡ every entry of vmap output +# Tier 3: hardcoded regression constant (deterministic via seeded simulator) + +np.testing.assert_allclose( + log_likelihood_ref, + float(full_result), + rtol=1e-4, + err_msg=( + f"point_source/image_plane_solved: eager vs JIT mismatch — " + f"eager={log_likelihood_ref} vs JIT={float(full_result)}" + ), +) + +np.testing.assert_allclose( + np.array(result_vmap), + float(full_result), + rtol=1e-4, + err_msg="point_source/image_plane_solved: JIT vs vmap mismatch", +) + + +# =================================================================== +# PART E — Static memory analysis +# =================================================================== + +print("\n--- Static memory analysis ---") + +lowered_batched = vmapped_full.lower(batched_params) +compiled_batched = lowered_batched.compile() +mem = compiled_batched.memory_analysis() +print(f" Output size: {mem.output_size_in_bytes / 1024**2:.3f} MB") +print(f" Temp size: {mem.temp_size_in_bytes / 1024**2:.3f} MB") +print(f" Total: {(mem.output_size_in_bytes + mem.temp_size_in_bytes) / 1024**2:.3f} MB") + + +# =================================================================== +# Summary + outputs +# =================================================================== + +al_version = al.__version__ + +print("\n" + "=" * 70) +print(f"JAX LIKELIHOOD SUMMARY — POINT SOURCE IMAGE-PLANE SOLVED — v{al_version}") +print("=" * 70) +print(f" Dataset: {instrument}") +print(f" Observed image positions: {n_observed_positions}") +print(f" Position noise sigma: {positions_noise_sigma}") +print( + f" Free parameters: {model.total_free_parameters} " + "(image_plane.py: 8; delta=-3 -> -2 solved centre, -1 unused flux)" +) +print( + " fit_positions_cls: FitPositionsImagePairAllSolved (image-plane chi-squared, solved centre)" +) +print("-" * 70) +print(f" Eager full likelihood: {eager_per_call:.6f} s/call ({log_likelihood_ref:.6f})") +print(f" Full pipeline (JIT): {full_pipeline_per_call:.6f} s/call") +print( + f" Repeat fit class (JIT): {repeat_fit_class_per_call:.6f} s/call " + f"(FitPositionsImagePairRepeatSolved, {float(repeat_result):.6f})" +) +print(f" vmap per-call (batch={batch_size}): {vmap_per_call:.6f} s") +print(f" vmap speedup vs single JIT: {vmap_speedup:.1f}x") +print("=" * 70) + +likelihood_summary = { + "autolens_version": al_version, + "dataset": instrument, + "fit_positions_cls": "FitPositionsImagePairAllSolved", + "configuration": { + "observed_image_positions": int(n_observed_positions), + "positions_noise_sigma": positions_noise_sigma, + "free_parameters": int(model.total_free_parameters), + "free_parameters_image_plane_plain": 8, + "free_parameters_delta": int(model.total_free_parameters) - 8, + "point_source_profile": "PointSolved", + }, + "eager_per_call": eager_per_call, + "eager_log_likelihood": log_likelihood_ref, + "full_pipeline_single_jit": full_pipeline_per_call, + "full_pipeline_log_likelihood": float(full_result), + "repeat_fit_class_steady_state": { + "fit_positions_cls": "FitPositionsImagePairRepeatSolved", + "per_call": repeat_fit_class_per_call, + "log_likelihood": float(repeat_result), + }, + "vmap": { + "batch_size": batch_size, + "batch_time": vmap_batch_time, + "per_call": vmap_per_call, + "speedup_vs_single_jit": round(vmap_speedup, 1), + }, +} + +results_dir = _workspace_root / "results" / "runtime" / "point_source" / "image_plane_solved" +results_dir.mkdir(parents=True, exist_ok=True) + +dict_path = results_dir / f"image_plane_solved_summary_v{al_version}.json" +dict_path.write_text(json.dumps(likelihood_summary, indent=2)) +print(f"\n Results dict saved to: {dict_path}") + +# --- Bar chart --- + +labels = [ + "Eager full likelihood", + "Full pipeline (JIT, AllSolved)", + "Repeat fit class (JIT, RepeatSolved)", + f"vmap per-call (batch={batch_size})", +] +times = [eager_per_call, full_pipeline_per_call, repeat_fit_class_per_call, vmap_per_call] +colors = ["#8172B3", "#C44E52", "#DD8452", "#55A868"] + +fig, ax = plt.subplots(figsize=(10, 4.5)) +y_pos = range(len(labels)) +bars = ax.barh(y_pos, times, color=colors, edgecolor="white", height=0.6) + +for bar, t in zip(bars, times): + ax.text( + bar.get_width() + max(times) * 0.01, + bar.get_y() + bar.get_height() / 2, + f"{t:.6f} s", + va="center", + fontsize=9, + ) + +ax.set_yticks(y_pos) +ax.set_yticklabels(labels, fontsize=10) +ax.invert_yaxis() +ax.set_xlabel("Time per call (s)", fontsize=11) +fig.suptitle( + "Point-Source Likelihood — Image-Plane Chi-Squared (Solved)", + fontsize=12, + fontweight="bold", +) +ax.set_title( + f"AutoLens v{al_version} | {n_observed_positions} positions | " + f"{model.total_free_parameters} free params (was 8) | " + f"vmap speedup: {vmap_speedup:.1f}x", + fontsize=9, +) +ax.margins(x=0.20) +fig.tight_layout() + +chart_path = results_dir / f"image_plane_solved_summary_v{al_version}.png" +fig.savefig(chart_path, dpi=150) +plt.close(fig) +print(f" Bar chart saved to: {chart_path}") + + +# =================================================================== +# Tier 3: regression assertion — deterministic via seeded simulator +# =================================================================== +# +# Simulator truth parameters + seeded noise (noise_seed=1 in +# simulators/point_source.py) make the image-plane log-likelihood +# deterministic; PointSolved's analytic centre solve is itself a +# deterministic function of the tracer + observed positions, so eager, JIT, +# and vmap all agree to float64. Constant captured 2026-07-30 during +# authoring of this script (issue #657 phase 3) against the dataset already +# committed in this worktree (v2026.7.23.1); refresh it the same way +# image_plane.py documents if the dataset or mass priors change. +_pinned_drift: list = [] +_pinned_expected = None + +EXPECTED_LOG_LIKELIHOOD_IMAGE_PLANE_SOLVED = 7.743201200876817 +_pinned_expected = EXPECTED_LOG_LIKELIHOOD_IMAGE_PLANE_SOLVED + +_rec = check_pinned(log_likelihood_ref, _pinned_expected, label="eager", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) +_rec = check_pinned(float(full_result), _pinned_expected, label="JIT", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) +_rec = check_pinned(np.array(result_vmap), _pinned_expected, label="vmap", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) + +timer.summary() + + +# Pinned-value outcome -> result JSON: profiling records and flags drift, +# never adjudicates library correctness (autolens_workspace_test's remit; +# boundary rule in results/notes/design_lock_in.md). PyAutoHeart's vitals +# scan reads the pinned_drift field. +record_pinned_check(dict_path, _pinned_expected, _pinned_drift) +if _pinned_expected is not None and not _pinned_drift: + print(" Pinned-value check PASSED (recorded in result JSON).") diff --git a/scripts/point_source/likelihood_runtime/source_plane_solved.py b/scripts/point_source/likelihood_runtime/source_plane_solved.py new file mode 100644 index 000000000..5b2b43a3e --- /dev/null +++ b/scripts/point_source/likelihood_runtime/source_plane_solved.py @@ -0,0 +1,600 @@ +""" +JAX Profiling: Point-Source Likelihood — Source-Plane Chi-Squared (Solved) +============================================================================= + +Profiles ``AnalysisPoint.log_likelihood_function`` for a lensed point-source +``PointDataset`` using the **analytically-solved source-plane** chi-squared +(``al.FitPositionsSourceSolved``), the sibling of ``source_plane.py`` +introduced in issue #657 phase 3. + +This is the paper's actual result (Lombardi 2024, arXiv:2406.15280 §5.1): +rather than sampling the source-plane centre as 2 free parameters on a +``al.ps.Point`` / ``al.ps.PointFlux`` profile, a zero-parameter +``al.ps.PointSolved`` profile is paired with ``FitPositionsSourceSolved``, +which analytically solves for the tensor-weighted-precision centre β* from +the observed positions' back-traced source-plane locations, then computes +the same magnification-weighted chi-squared ``source_plane.py`` profiles. + +Full pipeline now JITs cleanly (phase-2 fix) +--------------------------------------------- + +``source_plane.py``'s full-pipeline JIT is blocked because +``Grid2DIrregular.grid_2d_via_deflection_grid_from`` does not propagate +``xp``, so its ``model_data`` ends up holding JAX tracers under a NumPy +``_xp`` and ``squared_distances_to_coordinate_from`` calls ``np.square`` on +a tracer. That was fixed upstream in phase 2 (PyAutoArray#414), and +``FitPositionsSourceSolved``'s analytic β* solve +(``autolens/point/fit/solved.py``: ``SolvedCentre``) exercises the same +ray-trace path cleanly under JAX — verified during authoring: +``jax.jit(analysis_jax.log_likelihood_function)(params_tree)`` succeeds +end-to-end and matches the eager NumPy value at ``rtol=1e-4``. This script +therefore profiles the **full pipeline** directly (structurally mirroring +``image_plane.py``, not ``source_plane.py``'s try/except + JIT-able-prefix +fallback) — there is no blocked path here to work around. + +Parameter-count delta +---------------------- + +Swapping ``al.ps.PointFlux`` (used by ``source_plane.py``: 2 centre + 1 +flux = 3 params) for ``al.ps.PointSolved`` (0 params) drops the model from +8 to 5 free parameters — a delta of 3. 2 of those are the analytically- +solved source-plane centre (the paper's β*); the third is the flux +parameter, which this positions-only harness never fits regardless of +PointFlux vs PointSolved. + +Pytree-native parameter inputs +------------------------------ + +As in ``source_plane.py``, this script uses ``af.ModelInstance`` as the JIT +input via PyAutoFit's opt-in pytree registration +(``autofit.jax.register_model``, PR #1220 / #1221 / #1222). + +Three-tier numerical assertions +------------------------------- + +1. **eager ≡ JIT**: numpy-path log-likelihood matches single-JIT result. +2. **JIT ≡ vmap**: every entry of the batched vmap output matches the + single-JIT result. +3. **regression constant**: hardcoded + ``EXPECTED_LOG_LIKELIHOOD_SOURCE_PLANE_SOLVED`` guards against silent + drift. Captured during authoring against the dataset already committed + in this worktree; refresh it the same way ``source_plane.py`` documents + if the dataset or priors change. +""" + +import sys as _sys +from pathlib import Path as _Path + + +def _profiling_root() -> _Path: + for _p in _Path(__file__).resolve().parents: + if (_p / "ruff.toml").exists(): + return _p + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +_misc_dir = str(_profiling_root() / "scripts" / "misc") +if _misc_dir not in _sys.path: + _sys.path.insert(0, _misc_dir) + + +import json + +# AUTOLENS_PROFILING_SMOKE=1 short-circuit (Phase 5 / CI lint smoke). +# Verifies the import graph + module-level setup succeeded without running +# the full profiling pipeline. Skipped entirely when the env var is unset. +import os as _smoke_os +import subprocess +import sys +import sys as _smoke_sys +import time +from contextlib import contextmanager +from pathlib import Path + +import jax +import jax.numpy as jnp +import matplotlib +import numpy as np + +if _smoke_os.environ.get("AUTOLENS_PROFILING_SMOKE") == "1": + print(f"[smoke] {__file__}: imports + module setup OK; exiting.") + _smoke_sys.exit(0) + +# Sweep-driver CLI args (--config-name / --output-dir / --use-mixed-precision). +# Tolerates extra/unknown args via parse_known_args inside the helper. +sys.path.insert(0, str(_profiling_root())) +from simulators.point_source import INSTRUMENTS # noqa: E402 +from vram import ( # noqa: E402 + probe_vmap_memory, + recommend_batch_size, + resolve_vmap_batch, + write_probe_json, +) + +from _profile_cli import ( + auto_simulate_if_missing, + check_pinned, + device_info_dict, + parse_profile_cli, + record_pinned_check, # noqa: E402 + resolve_output_paths, +) + +_cli = parse_profile_cli() + +matplotlib.use("Agg") +import autofit as af +import autolens as al +import matplotlib.pyplot as plt +from autofit.jax import register_model as _register_model_pytrees + +# --------------------------------------------------------------------------- +# Profiling helpers (mirrors imaging/mge.py and image_plane.py) +# --------------------------------------------------------------------------- + + +class Timer: + def __init__(self): + self.records: list[tuple[str, float]] = [] + + @contextmanager + def section(self, label: str): + start = time.perf_counter() + yield + elapsed = time.perf_counter() - start + self.records.append((label, elapsed)) + print(f" [{label}] {elapsed:.4f} s") + + def summary(self): + print("\n" + "=" * 70) + print("PROFILING SUMMARY") + print("=" * 70) + max_label = max(len(r[0]) for r in self.records) + total = 0.0 + for label, elapsed in self.records: + print(f" {label:<{max_label}} {elapsed:>10.4f} s") + total += elapsed + print("-" * 70) + print(f" {'TOTAL':<{max_label}} {total:>10.4f} s") + print("=" * 70) + + +def block(x): + if hasattr(x, "block_until_ready"): + x.block_until_ready() + return x + + +def jit_profile(func, label, *args, n_repeats=10): + jitted = jax.jit(func) + + with timer.section(f"{label}_lower"): + lowered = jitted.lower(*args) + + with timer.section(f"{label}_compile"): + compiled = lowered.compile() + + with timer.section(f"{label}_first_call"): + result = compiled(*args) + block(result) + + with timer.section(f"{label}_steady_x{n_repeats}"): + for _ in range(n_repeats): + result = compiled(*args) + block(result) + + per_call = timer.records[-1][1] / n_repeats + print(f" -> per-call avg: {per_call:.6f} s") + return compiled, result + + +timer = Timer() +instrument = "simple" + + +# =================================================================== +# PART A — Setup +# =================================================================== + +print(f"\n--- Dataset loading [{instrument}] ---") + +_script_dir = Path(__file__).resolve().parent +_workspace_root = _profiling_root() +dataset_path = Path("dataset") / "point_source" / instrument + +auto_simulate_if_missing( + dataset_path, + dataset_type="point_source", + instrument=instrument, + workspace_root=_workspace_root, +) + +with timer.section("dataset_load"): + dataset = al.from_json( + file_path=dataset_path / "point_dataset_positions_only.json", + ) + +n_observed_positions = dataset.positions.shape[0] +positions_noise_sigma = float(dataset.positions_noise_map[0]) + +print("\n--- Point solver ---") + +with timer.section("solver_build"): + grid = al.Grid2D.uniform(shape_native=(100, 100), pixel_scales=0.2) + solver = al.PointSolver.for_grid( + grid=grid, + pixel_scale_precision=0.001, + magnification_threshold=0.1, + ) + +print("\n--- Model construction (PointSolved — 0 source params) ---") + +with timer.section("model_build"): + # GaussianPrior(mean=truth, sigma=small) centres prior-median at the + # simulator truth while keeping params free so gradient vectors and + # finite-difference diagnostics have dimensionality. Prior means MUST + # match the simulator's truth values exactly, otherwise the ray-traced + # source-plane positions cluster around the wrong centre and chi² + # explodes. + # + # Simulator truth (see autolens_workspace_developer/jax_profiling/ + # dataset_setup/point_source.py): + # Isothermal at centre=(0, 0), einstein_radius=1.6, + # ell_comps = al.convert.ell_comps_from(axis_ratio=0.9, angle=45°) + # ≈ (0.0526316, 0.0) + # source point_0.centre = (0.07, 0.07) — NOT used here: `PointSolved` + # has no `centre`, so nothing to prior-align on the source side. + mass = af.Model(al.mp.Isothermal) + mass.centre.centre_0 = af.GaussianPrior(mean=0.0, sigma=0.005) + mass.centre.centre_1 = af.GaussianPrior(mean=0.0, sigma=0.005) + mass.einstein_radius = af.GaussianPrior(mean=1.6, sigma=0.05) + mass.ell_comps.ell_comps_0 = af.GaussianPrior(mean=0.05263158, sigma=0.005) + mass.ell_comps.ell_comps_1 = af.GaussianPrior(mean=0.0, sigma=0.005) + lens = af.Model(al.Galaxy, redshift=0.5, mass=mass) + + # `PointSolved` has no `centre` / `flux` attributes, so no priors here. + point_0 = af.Model(al.ps.PointSolved) + source = af.Model(al.Galaxy, redshift=1.0, point_0=point_0) + + model = af.Collection(galaxies=af.Collection(lens=lens, source=source)) + +print(f" Total free parameters: {model.total_free_parameters}") +print( + " (was 8 with al.ps.PointFlux in source_plane.py: 5 mass + 2 centre + 1 flux; " + f"PointSolved drops all 3 source params -> {model.total_free_parameters} mass-only. " + "2 of the 3 are the analytically-solved source centre (paper Sec 5.1 beta*); the " + "3rd is the flux param this positions-only dataset never fits either way.)" +) + +print("\n--- Instantiate concrete model ---") + +with timer.section("instance_from_vector"): + param_vector = model.physical_values_from_prior_medians + instance = model.instance_from_vector(vector=param_vector) + +with timer.section("register_pytrees"): + _register_model_pytrees(model) + +params_tree = jax.tree_util.tree_map(jnp.asarray, instance) + + +# --------------------------------------------------------------------------- +# Eager baseline — full FitPointDataset (source-plane chi-squared, solved) +# --------------------------------------------------------------------------- + +print("\n--- Eager FitPointDataset (source-plane, solved) ---") + +analysis_eager = al.AnalysisPoint( + dataset=dataset, + solver=solver, + fit_positions_cls=al.FitPositionsSourceSolved, + use_jax=False, +) + +with timer.section("fit_eager"): + fit_eager = analysis_eager.fit_from(instance=instance) + log_likelihood_ref = float(fit_eager.log_likelihood) + figure_of_merit_ref = float(fit_eager.figure_of_merit) + +n_eager_repeats = 100 +with timer.section(f"eager_log_likelihood_x{n_eager_repeats}"): + for _ in range(n_eager_repeats): + analysis_eager.log_likelihood_function(instance=instance) +eager_per_call = timer.records[-1][1] / n_eager_repeats + +print(f" log_likelihood = {log_likelihood_ref}") +print(f" figure_of_merit = {figure_of_merit_ref}") +print(f" eager per-call = {eager_per_call:.6f} s") + + +# =================================================================== +# PART B — Full-pipeline JIT (FitPositionsSourceSolved — JITs cleanly) +# =================================================================== +# +# Unlike source_plane.py's plain FitPositionsSource, the analytic β* solve +# in FitPositionsSourceSolved does not hit the xp-propagation blocker (fixed +# upstream in phase 2, PyAutoArray#414) — see module docstring. No +# try/except, no JIT-able-prefix fallback needed: this IS the full pipeline. + +print("\n" + "=" * 70) +print("FULL-PIPELINE JIT (source-plane, solved)") +print("=" * 70) + +analysis_jax = al.AnalysisPoint( + dataset=dataset, + solver=solver, + fit_positions_cls=al.FitPositionsSourceSolved, + use_jax=True, +) + + +def full_pipeline_from_params(params_tree): + return analysis_jax.log_likelihood_function(instance=params_tree) + + +_, full_result = jit_profile(full_pipeline_from_params, "full_pipeline", params_tree) +full_pipeline_per_call = timer.records[-1][1] / 10 +print(f" full log_likelihood = {full_result}") + +# =================================================================== +# PART B.5 — vmap-probe mode (early exit) +# =================================================================== +# +# When ``--vmap-probe`` is set the script JIT-vmaps the pipeline at the +# configured batch sizes, reads ``compiled.memory_analysis()``, writes a +# ``vmap_probe.json`` with the recommended A100 batch_size, and exits +# before the full vmap timing loop. See ``vram/README.md`` for methodology. + +if _cli.vmap_probe: + probe = probe_vmap_memory( + full_pipeline_from_params, + params_tree, + batch_sizes=(1, 4, 16), + dataset="point_source", + model="source_plane_solved", + instrument=instrument, + ) + recommended = recommend_batch_size(probe) + probe_path = ( + _cli.output_dir + or (_workspace_root / "results" / "runtime" / "point_source" / "source_plane_solved") + ) / ( + "vmap_probe_source_plane_solved_sparse.json" + if _cli.use_sparse_operator + else "vmap_probe_source_plane_solved.json" + ) + write_probe_json(probe, recommended, probe_path) + print(f"\n vmap_probe samples: {probe.samples}") + print(f" per_replica: {probe.per_replica_mb:.1f} MB / replica") + print(f" recommended batch: {recommended}") + print(f" written to: {probe_path}") + sys.exit(0) + +# =================================================================== +# PART C — vmap over the full pipeline +# =================================================================== + +print("\n--- vmap batched evaluation ---") + +_batch_resolved, _batch_source = resolve_vmap_batch( + "point_source", + "source_plane_solved", + instrument, + output_dir=_cli.output_dir + or (_workspace_root / "results" / "runtime" / "point_source" / "source_plane_solved"), + path="sparse" if _cli.use_sparse_operator else "dense", + backend=jax.default_backend(), +) +print(f" vmap batch_size: {_batch_resolved} (source: {_batch_source})") +batch_size = _batch_resolved or 3 + +batched_params = jax.tree_util.tree_map( + lambda leaf: jnp.broadcast_to(leaf, (batch_size, *leaf.shape)), + params_tree, +) + +vmapped_full = jax.jit(jax.vmap(full_pipeline_from_params)) + +with timer.section("vmap_first_call"): + result_vmap = vmapped_full(batched_params) + block(result_vmap) + +n_vmap_repeats = 10 +with timer.section(f"vmap_steady_x{n_vmap_repeats}"): + for _ in range(n_vmap_repeats): + result_vmap = vmapped_full(batched_params) + block(result_vmap) + +vmap_batch_time = timer.records[-1][1] / n_vmap_repeats +vmap_per_call = vmap_batch_time / batch_size +vmap_speedup = full_pipeline_per_call / vmap_per_call + +print(f" batch results = {result_vmap}") +print(f" vmap batch of {batch_size}: {vmap_batch_time:.6f} s") +print(f" vmap per call: {vmap_per_call:.6f} s") +print(f" single JIT per call: {full_pipeline_per_call:.6f} s") +print(f" vmap speedup: {vmap_speedup:.1f}x faster per likelihood") + + +# =================================================================== +# PART D — Three-tier numerical assertions +# =================================================================== +# +# Tier 1: eager (NumPy path) ≡ single JIT +# Tier 2: single JIT ≡ every entry of vmap output +# Tier 3: hardcoded regression constant (deterministic via seeded simulator) + +np.testing.assert_allclose( + log_likelihood_ref, + float(full_result), + rtol=1e-4, + err_msg=( + f"point_source/source_plane_solved: eager vs JIT mismatch — " + f"eager={log_likelihood_ref} vs JIT={float(full_result)}" + ), +) + +np.testing.assert_allclose( + np.array(result_vmap), + float(full_result), + rtol=1e-4, + err_msg="point_source/source_plane_solved: JIT vs vmap mismatch", +) + + +# =================================================================== +# PART E — Static memory analysis +# =================================================================== + +print("\n--- Static memory analysis ---") + +lowered_batched = vmapped_full.lower(batched_params) +compiled_batched = lowered_batched.compile() +mem = compiled_batched.memory_analysis() +print(f" Output size: {mem.output_size_in_bytes / 1024**2:.3f} MB") +print(f" Temp size: {mem.temp_size_in_bytes / 1024**2:.3f} MB") +print(f" Total: {(mem.output_size_in_bytes + mem.temp_size_in_bytes) / 1024**2:.3f} MB") + + +# =================================================================== +# Summary + outputs +# =================================================================== + +al_version = al.__version__ + +print("\n" + "=" * 70) +print(f"JAX LIKELIHOOD SUMMARY — POINT SOURCE SOURCE-PLANE SOLVED — v{al_version}") +print("=" * 70) +print(f" Dataset: {instrument}") +print(f" Observed image positions: {n_observed_positions}") +print(f" Position noise sigma: {positions_noise_sigma}") +print( + f" Free parameters: {model.total_free_parameters} " + "(source_plane.py: 8; delta=-3 -> -2 solved centre, -1 unused flux)" +) +print( + " fit_positions_cls: FitPositionsSourceSolved (source-plane chi-squared, solved centre)" +) +print("-" * 70) +print(f" Eager full likelihood: {eager_per_call:.6f} s/call ({log_likelihood_ref:.6f})") +print(f" Full pipeline (JIT): {full_pipeline_per_call:.6f} s/call") +print(f" vmap per-call (batch={batch_size}): {vmap_per_call:.6f} s") +print(f" vmap speedup vs single JIT: {vmap_speedup:.1f}x") +print("=" * 70) + +likelihood_summary = { + "autolens_version": al_version, + "dataset": instrument, + "fit_positions_cls": "FitPositionsSourceSolved", + "configuration": { + "observed_image_positions": int(n_observed_positions), + "positions_noise_sigma": positions_noise_sigma, + "free_parameters": int(model.total_free_parameters), + "free_parameters_source_plane_plain": 8, + "free_parameters_delta": int(model.total_free_parameters) - 8, + "point_source_profile": "PointSolved", + }, + "eager_per_call": eager_per_call, + "eager_log_likelihood": log_likelihood_ref, + "full_pipeline_jits": True, + "full_pipeline_single_jit": full_pipeline_per_call, + "full_pipeline_log_likelihood": float(full_result), + "vmap": { + "batch_size": batch_size, + "batch_time": vmap_batch_time, + "per_call": vmap_per_call, + "speedup_vs_single_jit": round(vmap_speedup, 1), + }, +} + +results_dir = _workspace_root / "results" / "runtime" / "point_source" / "source_plane_solved" +results_dir.mkdir(parents=True, exist_ok=True) + +dict_path = results_dir / f"source_plane_solved_summary_v{al_version}.json" +dict_path.write_text(json.dumps(likelihood_summary, indent=2)) +print(f"\n Results dict saved to: {dict_path}") + +# --- Bar chart --- + +labels = [ + "Eager full likelihood", + "Full pipeline (JIT)", + f"vmap per-call (batch={batch_size})", +] +times = [eager_per_call, full_pipeline_per_call, vmap_per_call] +colors = ["#8172B3", "#C44E52", "#55A868"] + +fig, ax = plt.subplots(figsize=(10, 4.0)) +y_pos = range(len(labels)) +bars = ax.barh(y_pos, times, color=colors, edgecolor="white", height=0.6) + +for bar, t in zip(bars, times): + ax.text( + bar.get_width() + max(times) * 0.01, + bar.get_y() + bar.get_height() / 2, + f"{t:.6f} s", + va="center", + fontsize=9, + ) + +ax.set_yticks(y_pos) +ax.set_yticklabels(labels, fontsize=10) +ax.invert_yaxis() +ax.set_xlabel("Time per call (s)", fontsize=11) +fig.suptitle( + "Point-Source Likelihood — Source-Plane Chi-Squared (Solved)", + fontsize=12, + fontweight="bold", +) +ax.set_title( + f"AutoLens v{al_version} | {n_observed_positions} positions | " + f"{model.total_free_parameters} free params (was 8) | " + f"vmap speedup: {vmap_speedup:.1f}x", + fontsize=9, +) +ax.margins(x=0.20) +fig.tight_layout() + +chart_path = results_dir / f"source_plane_solved_summary_v{al_version}.png" +fig.savefig(chart_path, dpi=150) +plt.close(fig) +print(f" Bar chart saved to: {chart_path}") + + +# =================================================================== +# Regression assertion — deterministic via seeded simulator +# =================================================================== +# +# Simulator truth parameters + seeded noise (noise_seed=1 in +# simulators/point_source.py) make the log-likelihood deterministic; the +# analytic β* solve is itself a deterministic function of the tracer and +# observed positions. Constant captured 2026-07-30 during authoring of this +# script (issue #657 phase 3) against the dataset already committed in this +# worktree (v2026.7.23.1); refresh it the same way source_plane.py +# documents if the dataset or mass priors change. +_pinned_drift: list = [] +_pinned_expected = None + +EXPECTED_LOG_LIKELIHOOD_SOURCE_PLANE_SOLVED = 0.5986504555530896 +_pinned_expected = EXPECTED_LOG_LIKELIHOOD_SOURCE_PLANE_SOLVED + +_rec = check_pinned(log_likelihood_ref, _pinned_expected, label="eager", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) +_rec = check_pinned(float(full_result), _pinned_expected, label="JIT", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) +_rec = check_pinned(np.array(result_vmap), _pinned_expected, label="vmap", rtol=1e-4) +if _rec is not None: + _pinned_drift.append(_rec) + +timer.summary() + + +# Pinned-value outcome -> result JSON: profiling records and flags drift, +# never adjudicates library correctness (autolens_workspace_test's remit; +# boundary rule in results/notes/design_lock_in.md). PyAutoHeart's vitals +# scan reads the pinned_drift field. +record_pinned_check(dict_path, _pinned_expected, _pinned_drift) +if _pinned_expected is not None and not _pinned_drift: + print(" Pinned-value check PASSED (recorded in result JSON).")