Skip to content

Conversation

@wenyi-guo
Copy link
Collaborator

Support scalar view for tf backend. Only works if new dtype item size is same as old dtype. This is same implementation as other backends.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @wenyi-guo, 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 enhances the view operation within the Keras TensorFlow backend to properly support scalar tensors. It introduces logic to ensure that scalar views are only permitted when the new and old data types have the same item size, aligning its behavior with other backends. This change improves the robustness and consistency of the view function across different tensor shapes, particularly for single-element arrays.

Highlights

  • Scalar View Support: The view function in the TensorFlow backend now correctly handles scalar tensors, allowing them to be viewed as a different dtype only if the item sizes are identical, aligning with the behavior of other backends.
  • Refactored view Logic: The internal logic of the view function has been updated to explicitly account for scalar shapes in its validation checks and to remove redundant variable declarations, improving code clarity and efficiency.
  • New Test Cases: Specific unit tests have been added for scalar view operations, covering both successful conversions (when item sizes match) and expected failures (when item sizes differ), ensuring the new behavior is thoroughly validated.
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.

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 adds support for scalar views in the TensorFlow backend by modifying the view operation. The changes correctly handle scalar inputs, which would previously cause an error. The logic has been updated to check item sizes for scalars and ensure compatibility. Additionally, new tests have been added to verify this new functionality for scalar inputs. While the fix for scalars is correct, the logic for tensors with a zero-sized last dimension has been made overly restrictive. I've provided a suggestion to correct this, making the behavior consistent with other backends for such edge cases.

Comment on lines 1013 to 1017
old_shape = list(shape_op(x))
last_dim_size = old_shape[-1] if len(old_shape) > 0 else 0
if (last_dim_size == 0 and old_itemsize != new_itemsize) or (
last_dim_size * old_itemsize % new_itemsize != 0
):
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The current logic to handle scalars and tensors with a last dimension of size 0 is a bit too broad. The condition last_dim_size == 0 is true for both scalars and tensors with a shape like (2, 0). For scalars, it's correct to only allow views if the item size is the same. However, for tensors with a zero-sized last dimension, this is too restrictive. For example, numpy.zeros((2,0), 'int16').view('int8') is a valid operation, but this implementation would reject it.

A better approach is to explicitly distinguish between a scalar tensor (ndim == 0) and a tensor with a zero-sized dimension. This will make the behavior consistent with NumPy for this edge case.

    old_shape = list(shape_op(x))
    is_scalar = not old_shape
    last_dim_size = old_shape[-1] if not is_scalar else 0
    if (is_scalar and old_itemsize != new_itemsize) or (
        not is_scalar and last_dim_size * old_itemsize % new_itemsize != 0
    ):

@codecov-commenter
Copy link

codecov-commenter commented Oct 30, 2025

Codecov Report

❌ Patch coverage is 0% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.85%. Comparing base (08f102d) to head (a9d72e1).

Files with missing lines Patch % Lines
keras/src/backend/tensorflow/numpy.py 0.00% 3 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (08f102d) and HEAD (a9d72e1). Click for more details.

HEAD has 2 uploads less than BASE
Flag BASE (08f102d) HEAD (a9d72e1)
keras 5 4
keras-tensorflow 1 0
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #21802      +/-   ##
==========================================
- Coverage   82.63%   76.85%   -5.78%     
==========================================
  Files         577      577              
  Lines       59415    59415              
  Branches     9313     9313              
==========================================
- Hits        49097    45663    -3434     
- Misses       7913    11302    +3389     
- Partials     2405     2450      +45     
Flag Coverage Δ
keras 76.72% <0.00%> (-5.74%) ⬇️
keras-jax 63.33% <0.00%> (ø)
keras-numpy 57.56% <0.00%> (ø)
keras-openvino 34.30% <0.00%> (ø)
keras-tensorflow ?
keras-torch 63.63% <0.00%> (ø)

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.

@google-ml-butler google-ml-butler bot added kokoro:force-run ready to pull Ready to be merged into the codebase labels Oct 31, 2025
@hertschuh hertschuh merged commit 3973b15 into keras-team:master Oct 31, 2025
10 of 11 checks passed
@google-ml-butler google-ml-butler bot removed awaiting review ready to pull Ready to be merged into the codebase labels Oct 31, 2025
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.

5 participants