Skip to content

Fix norm gradients with keepdims=True - #885

Open
imsurya26 wants to merge 1 commit into
HIPS:masterfrom
imsurya26:fix/norm-keepdims
Open

imsurya26 wants to merge 1 commit into
HIPS:masterfrom
imsurya26:fix/norm-keepdims

Conversation

@imsurya26

@imsurya26 imsurya26 commented Nov 20, 2026 •

Copy link
Copy Markdown

np.linalg.norm(x, axis=..., keepdims=True) gives gradients of the wrong shape in both modes, e.g. for the common row-normalising pattern x / np.linalg.norm(x, axis=1, keepdims=True):

x = npr.randn(4, 3)
w = npr.randn(4, 1)
grad(lambda x: np.sum(w * np.linalg.norm(x, axis=1, keepdims=True)))(x).shape  # (4, 4, 3), expected (4, 3)

In forward mode the tangent has shape (4, 4) while the output has shape (4, 1).

keepdims was passed through **kwargs and ignored by norm_vjp and norm_jvp:

  • norm_vjp always re-inserts the reduced axes with expand_dims, but with keepdims=True they are already there.
  • norm_jvp sums over axis without keepdims.

Both rules now take keepdims explicitly: the vjp skips the expansion when keepdims is set, and the jvp sums with keepdims=keepdims. Behaviour with keepdims=False is unchanged.

Added a parametrised test_norm_keepdims (vector, matrix and nuclear norms, positive/negative/tuple axes) that checks forward and reverse gradients; 4 of its cases fail without the change. tests/test_linalg.py passes (70 tests) and ruff is clean. Order 1 only, as in the other norm tests that go through the SVD.

Note: #833 edits the same contract line in norm_jvp for complex inputs. Whichever lands second only needs anp.real(anp.sum(a, axis=axis, keepdims=keepdims)).

This branch has not been deployed

No deployments
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.

1 participant