Skip to content

Implement numpy.view for OpenVINO backend#22407

Open
rishi-sangare wants to merge 1 commit intokeras-team:masterfrom
rishi-sangare:feat/openvino-numpy-view
Open

Implement numpy.view for OpenVINO backend#22407
rishi-sangare wants to merge 1 commit intokeras-team:masterfrom
rishi-sangare:feat/openvino-numpy-view

Conversation

@rishi-sangare
Copy link

Summary

Implements numpy.view for the OpenVINO backend, resolving the NotImplementedError that was previously raised.

Implementation approach

Since OpenVINO's opset doesn't include a native bitcast operation, the implementation uses three complementary strategies:

  • Constant inputs (numpy arrays and OV Constant nodes): Extracts the underlying numpy data and uses numpy.ndarray.view() for lossless bitwise reinterpretation. This handles all dtype pairs including float↔integer.
  • Same-width integer↔integer on dynamic tensors: Uses ov_opset.convert, which preserves bit patterns for signed/unsigned pairs of the same width (e.g. int32↔uint32).
  • Cross-width integer↔integer on dynamic tensors: Decomposes and recomposes individual bytes using bitwise right-shift, mask (AND), left-shift, and OR operations through an unsigned intermediate type.

Tests

Removes four entries from excluded_concrete_tests.txt:

  • NumpyDtypeTest::test_view
  • NumpyOneInputOpsCorrectnessTest::test_view
  • NumpyOneInputOpsDynamicShapeTest::test_view
  • NumpyOneInputOpsStaticShapeTest::test_view

Verified locally with OpenVINO that all three paths (constant folding, int expand, int contract) produce correct results matching numpy's view behavior.

Fixes #34217

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces comprehensive support for numpy.view within the OpenVINO backend, a functionality previously unavailable. The implementation addresses the lack of a native bitcast operation in OpenVINO by employing a multi-pronged approach that intelligently handles various data types and tensor characteristics, including constant folding for NumPy arrays and bitwise manipulation for dynamic integer tensors of differing widths. This enhancement significantly expands the capabilities of the OpenVINO backend for data manipulation.

Highlights

  • numpy.view implementation: Implemented numpy.view for the OpenVINO backend, resolving the NotImplementedError that was previously raised.
  • Implementation strategies: Utilized three distinct strategies to handle numpy.view operations: constant inputs, same-width integer-to-integer conversions, and cross-width integer-to-integer conversions using bitwise operations.
  • Test updates: Removed four numpy.view related test entries from excluded_concrete_tests.txt, indicating successful implementation and testing.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • keras/src/backend/openvino/excluded_concrete_tests.txt
    • Removed NumpyDtypeTest::test_view.
    • Removed NumpyOneInputOpsCorrectnessTest::test_view.
    • Removed NumpyOneInputOpsDynamicShapeTest::test_view.
    • Removed NumpyOneInputOpsStaticShapeTest::test_view.
  • keras/src/backend/openvino/numpy.py
    • Implemented the view function to support numpy.view operations.
    • Added _view_int_expand helper function for viewing larger integers as smaller ones.
    • Added _view_int_contract helper function for viewing smaller integers as larger ones.
Activity
  • No human activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist
Copy link
Contributor

Warning

Gemini is experiencing higher than usual traffic and was unable to create the review. Please try again in a few hours by commenting /gemini review.

@codecov-commenter
Copy link

codecov-commenter commented Mar 12, 2026

Codecov Report

❌ Patch coverage is 26.04167% with 71 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.95%. Comparing base (d8e68b0) to head (a5ee876).

Files with missing lines Patch % Lines
keras/src/backend/openvino/numpy.py 26.04% 67 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #22407      +/-   ##
==========================================
- Coverage   83.04%   82.95%   -0.09%     
==========================================
  Files         596      596              
  Lines       66693    66789      +96     
  Branches    10383    10394      +11     
==========================================
+ Hits        55382    55407      +25     
- Misses       8675     8742      +67     
- Partials     2636     2640       +4     
Flag Coverage Δ
keras 82.78% <26.04%> (-0.09%) ⬇️
keras-jax 60.46% <3.12%> (-0.09%) ⬇️
keras-numpy 54.70% <0.00%> (-0.08%) ⬇️
keras-openvino 49.92% <26.04%> (-0.02%) ⬇️
keras-tensorflow 61.71% <3.12%> (-0.09%) ⬇️
keras-torch 60.53% <3.12%> (-0.09%) ⬇️

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.

@goyaladitya05
Copy link
Contributor

/gemini review

Copy link
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 implements numpy.view for the OpenVINO backend, which is a great addition. The implementation correctly handles constant inputs, same-width integer conversions, and more complex cross-width integer conversions using bitwise operations. The approach is solid. I have a few suggestions to improve code maintainability and readability by reducing duplication and simplifying some logic. Also, adding a docstring to the new view function would be beneficial for users to understand its backend-specific limitations.

@@ -612,7 +612,180 @@ def array(x, dtype=None):


def view(x, dtype=None):
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This function has a complex implementation with backend-specific limitations (e.g., only supporting integer-to-integer conversions for non-constant tensors). It would be beneficial to add a docstring explaining its behavior and limitations for the OpenVINO backend, as per the Keras API design guidelines (lines 135-151).

Comment on lines +691 to +698
shifted = x_uint
if i > 0:
shift = ov_opset.constant(
i * bits_per_elem, src_uint_type
).output(0)
shifted = ov_opset.bitwise_right_shift(
x_uint, shift
).output(0)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The if i > 0 check is not strictly necessary. A right shift by 0 is a no-op and will likely be optimized by the compiler. You can simplify this block by always performing the shift. This would make the code more linear and easier to read.

For example:

shift = ov_opset.constant(
    i * bits_per_elem, src_uint_type
).output(0)
shifted = ov_opset.bitwise_right_shift(x_uint, shift).output(0)

Comment on lines +711 to +722
leading = ov_opset.slice(
old_shape,
ov_opset.constant([0], Type.i64).output(0),
ov_opset.constant([-1], Type.i64).output(0),
ov_opset.constant([1], Type.i64).output(0),
ov_opset.constant([0], Type.i64).output(0),
).output(0)
last_dim = ov_opset.gather(
old_shape,
ov_opset.constant([-1], Type.i64).output(0),
ov_opset.constant(0, Type.i64).output(0),
).output(0)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This block of code for splitting a shape into its leading dimensions and the last dimension is duplicated in _view_int_contract (lines 746-757). To improve maintainability and reduce code duplication, consider extracting this logic into a private helper function. This would be consistent with existing patterns in this file, like _resolve_axis, and would also improve readability by giving a name to this operation.

Comment on lines +777 to +784
if i > 0:
shift = ov_opset.constant(
i * bits_per_elem, dst_uint_type
).output(0)
byte_i = ov_opset.bitwise_left_shift(byte_i, shift).output(0)
result = byte_i if result is None else (
ov_opset.bitwise_or(result, byte_i).output(0)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This block can be simplified for better readability and maintainability:

  1. The if i > 0 check for shifting is not necessary, as a left shift by 0 is a no-op. Removing the conditional would make the code more linear.
  2. The result = byte_i if result is None else ... pattern for initialization can be made cleaner. You could initialize result to a tensor of zeros with the correct shape before the loop, and then use bitwise_or on every iteration.

@rishi-sangare rishi-sangare force-pushed the feat/openvino-numpy-view branch 3 times, most recently from f7bdc1c to f7ad5c6 Compare March 12, 2026 18:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants