Skip to content

Fix late-binding closure in RBF params_gradient#1

Merged
JonasTurnwald merged 1 commit into
JonasTurnwald:mainfrom
timpara:fix/params-gradient-closure-bug
Apr 14, 2026
Merged

Fix late-binding closure in RBF params_gradient#1
JonasTurnwald merged 1 commit into
JonasTurnwald:mainfrom
timpara:fix/params-gradient-closure-bug

Conversation

@timpara
Copy link
Copy Markdown
Contributor

@timpara timpara commented Apr 13, 2026

Summary

  • Fixed a late-binding closure bug in RadialBasisFunction.params_gradient() where the loop variable i was captured by reference instead of by value. With multi-dimensional lengthscales, all gradient functions incorrectly computed the gradient for the last lengthscale dimension only.
  • Added test_rbf_params_gradient which validates the analytical gradient against central finite differences for both 1D and 2D lengthscale cases.

Details

The fix is a single i=i default argument addition on the lambda at kernels.py:167. Without it, Python's late-binding closures cause every lambda created in the loop to share the final value of i, producing wrong gradients for all but the last lengthscale when log_likelihood_grad() is called on a kernel with multiple lengthscale dimensions.

…cales

The lambda in the loop captured the loop variable i by reference,
so all lengthscale gradient functions ended up using the last index.
Added i=i default arg to bind the value at each iteration.

Also added a finite-difference test for params_gradient covering
both 1D and 2D lengthscale cases.
@timpara timpara force-pushed the fix/params-gradient-closure-bug branch from aa69be7 to 1521ec0 Compare April 13, 2026 11:56
Copy link
Copy Markdown
Owner

@JonasTurnwald JonasTurnwald left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch, thank you!

@JonasTurnwald JonasTurnwald merged commit 09b03af into JonasTurnwald:main Apr 14, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants