Skip to content

Validate axis1 != axis2 in ops.diagonal#22593

Open
rstar327 wants to merge 1 commit intokeras-team:masterfrom
rstar327:fix-diagonal-same-axis-validation
Open

Validate axis1 != axis2 in ops.diagonal#22593
rstar327 wants to merge 1 commit intokeras-team:masterfrom
rstar327:fix-diagonal-same-axis-validation

Conversation

@rstar327
Copy link
Copy Markdown
Contributor

Summary

Add validation that axis1 and axis2 are not the same in keras.ops.diagonal, matching NumPy's behavior (ValueError: axis1 and axis2 cannot be the same).

Previously, passing axis1 == axis2 on eager TensorFlow tensors caused a cryptic InvalidArgumentError from the transpose op. Now it raises a clear ValueError for both symbolic and eager inputs.

Fixes #22528

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds axis normalization and validation to the diagonal operation in keras/src/ops/numpy.py, specifically handling negative indices and ensuring axis1 and axis2 are not identical. The reviewer suggests using the canonicalize_axis utility instead of manual calculations to improve robustness and maintain consistency with the rest of the codebase.

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Mar 29, 2026

Codecov Report

❌ Patch coverage is 60.00000% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.30%. Comparing base (8a941a4) to head (c02ff4f).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
keras/src/ops/numpy.py 60.00% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #22593   +/-   ##
=======================================
  Coverage   83.30%   83.30%           
=======================================
  Files         596      596           
  Lines       67951    67989   +38     
  Branches    10577    10590   +13     
=======================================
+ Hits        56604    56640   +36     
- Misses       8600     8601    +1     
- Partials     2747     2748    +1     
Flag Coverage Δ
keras 83.11% <60.00%> (+<0.01%) ⬆️
keras-jax 59.73% <60.00%> (+<0.01%) ⬆️
keras-numpy 54.36% <60.00%> (+<0.01%) ⬆️
keras-openvino 51.79% <60.00%> (+<0.01%) ⬆️
keras-tensorflow 61.04% <60.00%> (+<0.01%) ⬆️
keras-torch 59.93% <60.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@keerthanakadiri keerthanakadiri added the stat:awaiting keras-eng Awaiting response from Keras engineer label Mar 30, 2026
Copy link
Copy Markdown

@amadhan882 amadhan882 left a comment

Choose a reason for hiding this comment

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

@rstar327 Thank you for this contribution. Aligning the validation with NumPy's behavior for identical axes is a great fix for the issue mentioned.

As a community reviewer, I have a few suggestions to make this PR merge-ready:

Utility Usage: Please consider using the existing keras.src.utils.axis_utils.canonicalize_axis utility instead of manual axis normalization. It ensures consistency across the codebase and provides built-in bounds checking.

Coverage Improvement: The Codecov report indicates a 60% patch coverage failure. To resolve this, please add a specific test case in keras/src/ops/numpy_test.py that passes axis1 == axis2 to verify the ValueError is correctly raised.

Once these updates are implemented, the coverage issue should resolve, making it easier for the Keras engineering team to provide a final approval.

Copy link
Copy Markdown
Collaborator

@hertschuh hertschuh left a comment

Choose a reason for hiding this comment

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

Thanks for looking at this!

Please also add a unit test exercising this in this method:
https://github.com/keras-team/keras/blob/master/keras/src/ops/numpy_test.py#L5195

Comment on lines +2698 to +2699
ax1 = self.axis1 if self.axis1 >= 0 else self.axis1 + ndim
ax2 = self.axis2 if self.axis2 >= 0 else self.axis2 + ndim
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

please use ax1 = canonicalize_axis(self.axis1, ndim) which does some validation.

Comment on lines +2779 to +2786
x_ndim = len(x.shape)
ax1 = axis1 if axis1 >= 0 else axis1 + x_ndim
ax2 = axis2 if axis2 >= 0 else axis2 + x_ndim
if ax1 == ax2:
raise ValueError(
"`axis1` and `axis2` cannot be the same. "
f"Received: axis1={axis1}, axis2={axis2}"
)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The current pattern used is to not have any code in these functions, they're supposed to delegate to the backend functions.

So please move to whichever backend doesn't throw a proper exception (tensorflow is sounds like).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually, never mind. Validation is fine. But:

  • use canonicalize_axis here
  • move it before the if any_symbolic_tensor
  • remove the other one in compute_output_shape, it's not longer needed

@hertschuh hertschuh added stat:awaiting response from contributor and removed stat:awaiting keras-eng Awaiting response from Keras engineer labels Mar 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

keras.ops.diagonal fails on eager TensorFlow tensors when axis1 == axis2

6 participants