Repository navigation
Description
Overview
The numerical audit (#603) found a block-tail indexing defect in the shared KNN neighbor search. With 130 nodes and the default 128-node block, queries at the last two nodes select earlier nodes instead of themselves. This affects KNearestNeighbor and KNNBarycentric.
Plan
- Preserve the audit's regression and reproduce the tail-node failure.
- Align final-block coordinates, validity masks and emitted point indices.
- Compare neighbor selection with a brute-force oracle across block boundaries and JAX modes.
- Remove the strict expected-failure marker only once the repair passes.
Detailed implementation plan
Affected repositories: PyAutoArray (primary), autolens_workspace_test. Suggested branch: feature/knn-partial-point-block.
- Fix
autoarray/inversion/mesh/interpolator/knn.py:get_interpolation_weights. A finallax.dynamic_slicestart is clamped backward but the mask/indices assume the requested start. Prefer static padding to a whole number of blocks plus a true global-index validity mask, or a consistent clamped-start scheme with no duplicate candidate corruption. Preserve bounded memory and existing full-block outputs. - Use deterministic unique-distance datasets at N below/equal/above B, including129/130/257 at default128. Compare eager/JIT selected indices and distances against brute force. Cover both public interpolation variants and verify mappings refer to the coordinates used to calculate weights.
- Promote the strict expected-failure coverage in audit#603 after the fix; run focused NumPy tests and JAX workspace checks, full library suite and applicable smoke. No production repair belongs in the audit PR.
Classification: Both. Filing only: no worktree or implementation authorized by this bug registration. Queue behind the currently active audit; reuse the normal start-dev/start-library process when scheduled. User explicitly requested that audit-discovered defects be filed separately.
Original Prompt
Audit finding and authorized follow-up
Fix KNN neighbor search for a partial final point block
Type: bug
Target: PyAutoArray
Repos:
- PyAutoArray
- autolens_workspace_test
Difficulty: small
Autonomy: supervised
Priority: high
Status: formalised
Consequence: glance
Witness: At N=130 with point_block=128, exact tail-node queries select indices128/129 with zero distance; eager/JIT results match a brute-force oracle at block boundaries for both KNN variants.
Review-minutes: 5
Unattended: ready
Fix KNN neighbor search for a partial final point block
Type: bug
Target: autoarray
Repos:
- PyAutoArray
- autolens_workspace_test
Difficulty: small
Autonomy: supervised
Priority: high
Witness: At N=130 with point_block=128, exact tail-node queries select indices128/129 with zero distance; eager/JIT results match a brute-force oracle at block boundaries for both KNN variants.
Review-minutes: 5
Found while executing PyAutoArray#603, the approved final numerics audit. User authorization from the original audit prompt: "Any bug found is filed separately; this task is the audit, not the fixes."
In autoarray/inversion/mesh/interpolator/knn.py:get_interpolation_weights, lax.dynamic_slice clamps a requested final-block start when N is not divisible by point_block. For N=130 and default point_block=128, the last requested start128 actually slices from2. The code still labels candidate rows with start128 and masks only2 rows, excluding or mislabelling the true final nodes.
Minimal witness on untouched main: points (0,0) through (129,0), query exact points128 and129, k_neighbors3. Expected first neighbors128 and129 with zero distance. Actual selected indices are [127,126,125] for both, with distances[1,2,3] and[2,3,4]. Both InterpolatorKNearestNeighbor and InterpolatorKNNBarycentric share the selection path.
Fix in a separate task by padding point blocks and masking padded rows, or otherwise keeping slice start, point coordinates and emitted indices consistent. Test N below/equal/above block size and nonmultiples (including129/130/257), compare eager/JIT neighbor indices/distances with a brute-force oracle on unique-distance data, cover both interpolation variants, and promote the audit's strict expected-failure regression to ordinary passing coverage. Preserve memory-bounded block behavior and full-block results. No production repair is part of audit#603.
Activity
Jammy2211 commentedon Oct 29, 2026
Finding from arc phase 4b (#665), 2026-10-29. Not fixed there; split out by human ruling.
The fix works on its own terms. Slicing the last block from a zero-padded array (below) makes
get_interpolation_weightsmatch a brute-force kNN oracle eagerly and under jit, for N ∈ {127, 128, 129, 130, 200, 256, 300} atpoint_block=128. The old strict-xfail witness then passes. As a control, the old code fails 5 of those cases.But it changes the science. In autolens_workspace_test,
scripts/imaging/jax_grad/knn.pypasses on main but fails with the fix:KNearestNeighbor + reg.AdaptSplit(inner=0.1, outer=10), has eager vs jit log-likelihood differences of 2e-9 to 6e-9 relative (the script's bar is 1e-10).KNearestNeighbor + ConstantSplit, stays clean (eager/jit 1e-12, gradients match).Likely mechanism. The meshes append the zeroed circle-edge ring at the END of the vertex array, so the bug hid exactly those nodes from every neighbour search. The fix makes them real neighbours near the boundary. The Wendland kernel at
radius_scale=1.5still gives the 10th neighbour about 4% weight, so a neighbour swap moves the likelihood discontinuously, and with zeroed edge nodes plus the stiff AdaptSplit outer coefficient that becomes visible. Not yet confirmed.Next step: confirm the mechanism (count neighbour-set changes across the finite-difference steps for variant B), then decide whether to (a) ship the fix with the KNN edge handling revisited, or (b) also change how zeroed edge nodes enter the kNN search.
Patch (fix + brute-force oracle test)
Jammy2211 commentedon Nov 8, 2026
Mechanism confirmed (2026-11-08): the bug was masking a near-singular regularization matrix
Short version. The padded-slice fix is correct. It breaks
jax_grad/knn.pyvariant B because the bug had been accidentally regularizing the constant mode of the split regularization matrixH. With the bug fixed,H's constant mode is held up only by the 1e-8 diagonal jitter, andlog det Hthen amplifies eps-level rounding. The neighbour-swap hypothesis in the comment above is not the cause. Delaunay + AdaptSplit already has the same near-singularHon main today.Evidence (jax_grad/knn.py setup: 300 Hilbert + 30 zeroed edge vertices, N = 330,
point_block= 128)1. What the bug did at N = 330. The last block's start (256) is clamped to 202:
2. Where variant B's eager/jit drift lives (padded fix, inversion internals eager vs
jax.jit):log det(F+H),sᵀHslog det H3. Spectrum of
H:Delaunay +
AdaptSplit(0.1, 10)on main already showslog det Heager/jit drift of 1.2e-8 (figure of merit 1.6e-9).4. Why main's KNN
Hwas well-conditioned. Split regularization rows are(interpolation weights) − e_self, which sum to about 0, so the constant vector is a null vector ofHby construction. On main, 279 split rows across 72 pixels (256–329) don't contain their own pixel: the pixel was hidden or mislabelled by the bug. The KNN split tables are full width (10 columns, all sizes 10), soreg_split_from(JAX branch) has no slot to insert the −1 self term and silently drops it. Each such row becomes−w, summing to −1. That is a zeroth-order "pull to zero" penalty with weight up to about 8.5e3, and it lifts the constant mode. This is also why variant B's log-likelihood moves so much (−23422 → −5906): main'ssᵀHswas 23646, against 5891 with the fix.5. Why only variant B fails. ConstantSplit(1.0) gives an
Hof order 1, so eps·‖H‖ is about 1e-15 against the 1e-8 jitter and the noise is harmless. AdaptSplit with outer = 10 enters the matrix as about 10⁴, so ‖H‖ ≈ 3e4. Rounding of about 1e-12 then moves λ_min by roughly 1e-4 relative, which is both the eager/jit drift and the noise behind the 1–3% AD-vs-FD gap.6. Treating the constant mode fixes both failures. With the padded fix in place, I ran the unmodified
scripts/imaging/jax_grad/knn.py(all variants A, B, C and thereg.Constantboundary check) under two prototype treatments (monkeypatched, not committed). Both pass end to end: eager/jit within 1e-10, and AD = FD on the failing parameters 7, 11 and 13 to about 1e-5 relative (e.g. −2958.358 vs −2958.358).Proposed fix (needs a decision: consequence = judge)
Ship the padded-slice fix (plus the oracle tests and promoting the strict xfail) together with an explicit treatment of
H's constant null mode. Two candidates:Hhas the constant vector as an exact null mode by construction (the split family; gated on that property, not applied to non-singularH), computelog det(H + 11ᵀ/P)instead oflog det(H + 1e-8·I).log(1e-8 + O(eps‖H‖))becomes an exactlog 1, so the noise is gone.log det(F+H)andlog det Hover the solved parameters only (solve_ids_to_keep). Given edge = 0, the conditional prior precision is exactlyH_kk, and the zeroed ring anchors the constant mode.Also recommended (separate, via intake): the JAX branch of
reg_split_fromsilently drops the self term when a stencil is full, whereas the NumPy branch raises. That silent drop is what turned this bug into a hidden regularization change, and it should raise or guard instead.Witness for the PR (unchanged from the prompt):
point_block= 128, exact tail-node queries return 128 and 129 at zero distance.jax_grad/knn.pyandjax_grad/delaunay.pypass with no tolerance changes.Waiting for a maintainer decision (L, K, or other) before changing likelihoods or gradients.
Generated by Claude Code
Jammy2211 commentedon Nov 8, 2026
Resume note (2026-11-08): picked up next session
Decided by the maintainer: two PRs.
H's constant null mode. This goes through intake as its own Mind prompt and PR, because it changes evidence for Delaunay and every other split-regularized mesh, not just KNN.test_knn_partial_final_block_matches_independent_neighbor_oraclefrom strict xfail to a passing test. This PR lands after (1), sojax_grad/knn.pyis green with no tolerance changes.Still open: whether (1) uses L (pseudo-det,
log det(H + 11ᵀ/P), gated to schemes with an exact constant null mode) or K (kept-subspace log-dets). See the comment above for numbers.Branch state:
feature/knn-partial-point-blockhas not been pushed. Nothing is committed; the padded fix exists only as the patch above.Prototypes used for the measurements (monkeypatch on
AbstractInversion, applied before running the unmodified script)Diagnostic used to localise the drift: build
fit = analysis.fit_from(model.instance_from_vector(p, ignore_assertions=True))and compare eager vsjax.jitonfit.inversion.{log_det_regularization_matrix_term, log_det_curvature_reg_matrix_term, regularization_term, reconstruction, regularization_matrix_reduced}. Then takenp.linalg.eighofHto find λ_min and check its overlap with1/√P.Main control:
jax_grad/knn.pypasses on main in about 2 minutes on a CPU container. With the padded fix alone, variant B failsassert_eager_jit_consistent(3.9e-9 rel against the 1e-10 bar).Generated by Claude Code
Jammy2211 commentedon Nov 9, 2026
Library PR Created: #684 (stacked on #683)
jax_grad/knn.pypasses all variants with no tolerance changes. Variant B passes eager/jit, and AD = FD on parameters 7, 11 and 13 (e.g. −2958.358 vs −2958.358).Generated by Claude Code
Jammy2211 commentedon Nov 9, 2026
Shipped — 2026-11-09
/prmwith CI 3/3 green. It follows fix: pseudo-determinant for intrinsic regularization log det H #683 (pseudo-determinant, merged 6ae33d4), which it needed.autolens_workspace_test/scripts/imaging/jax_grad/knn.pypasses all variants with no tolerance changes.Generated by Claude Code