Skip to content

Conversation

@MalyalaKarthik66
Copy link
Contributor

@MalyalaKarthik66 MalyalaKarthik66 commented Nov 13, 2025

Fix: #21655
This PR adds a helper utility _maybe_convert_to_int to safely handle cases where shape dimensions or layer units are symbolic tensors. It ensures that numeric values are properly converted to integers when possible, improving backend compatibility.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @MalyalaKarthik66, 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 a new helper utility, _maybe_convert_to_int, designed to robustly handle the conversion of symbolic tensor dimensions or layer units into integer values. This enhancement is crucial for maintaining compatibility across different backends by ensuring that numeric representations are consistently and safely cast to integers, thereby preventing potential type-related issues in Keras operations. A dedicated test file has also been added to demonstrate and verify its correct behavior.

Highlights

  • New Utility Function: Introduced _maybe_convert_to_int in keras/src/utils/arg_casts.py to safely convert symbolic tensor dimensions or layer units to integers.
  • Improved Backend Compatibility: Ensures that numeric values derived from symbolic operations are correctly cast to integers, enhancing robustness across different Keras backends.
  • New Test Case: Added test_ops_int_cast.py to validate the functionality of _maybe_convert_to_int within a custom Dense layer that uses ops.prod for unit calculation.
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 introduces a new utility function, _maybe_convert_to_int, to safely convert values, including symbolic tensors, to integers. This is a valuable addition for improving backend compatibility. The accompanying test case effectively demonstrates the utility's functionality within a Dense layer. My review focuses on enhancing the robustness of the new utility function by improving its error handling.

Comment on lines +8 to +36
def _maybe_convert_to_int(x: Any) -> Any:
if isinstance(x, int):
return x
if isinstance(x, (tuple, list)):
try:
return tuple(int(v) for v in x)
except Exception:
return x

try:
np_val = ops.convert_to_numpy(x)
except Exception:
return x

if np.isscalar(np_val):
try:
return int(np_val)
except Exception:
return x

arr = np.asarray(np_val).ravel()
if arr.size == 0:
return x
if arr.size == 1:
return int(arr[0])
try:
return tuple(int(v) for v in arr.tolist())
except Exception:
return x
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 function can be made more robust and slightly cleaner. Using except Exception for int() conversions is too broad and can mask unexpected errors. It's better to catch specific exceptions like ValueError and TypeError. Additionally, the conversion int(arr[0]) on line 32 is not wrapped in a try...except block and could raise an unhandled exception if the element is not convertible to an integer.

I've suggested a refactoring that addresses these points by using more specific exceptions and ensuring all integer conversions are safely handled. The broad except Exception for ops.convert_to_numpy is kept, as it's intended to handle various failures from different backends, especially for symbolic tensors.

def _maybe_convert_to_int(x: Any) -> Any:
    if isinstance(x, int):
        return x
    if isinstance(x, (tuple, list)):
        try:
            return tuple(int(v) for v in x)
        except (ValueError, TypeError):
            return x

    try:
        np_val = ops.convert_to_numpy(x)
    except Exception:
        return x

    if np.isscalar(np_val):
        try:
            return int(np_val)
        except (ValueError, TypeError):
            return x

    arr = np.asarray(np_val).ravel()
    if arr.size == 0:
        return x

    try:
        if arr.size == 1:
            return int(arr[0])
        return tuple(int(v) for v in arr.tolist())
    except (ValueError, TypeError):
        return x

@codecov-commenter
Copy link

codecov-commenter commented Nov 13, 2025

Codecov Report

❌ Patch coverage is 63.79310% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.64%. Comparing base (19ca9c1) to head (90eaa13).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
keras/src/utils/arg_casts.py 27.58% 16 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #21848      +/-   ##
==========================================
- Coverage   82.66%   82.64%   -0.02%     
==========================================
  Files         577      579       +2     
  Lines       59477    59564      +87     
  Branches     9329     9335       +6     
==========================================
+ Hits        49167    49228      +61     
- Misses       7907     7927      +20     
- Partials     2403     2409       +6     
Flag Coverage Δ
keras 82.47% <63.79%> (-0.02%) ⬇️
keras-jax 63.31% <63.79%> (+<0.01%) ⬆️
keras-numpy 57.52% <22.41%> (-0.03%) ⬇️
keras-openvino 34.34% <22.41%> (-0.01%) ⬇️
keras-tensorflow 64.12% <63.79%> (-0.01%) ⬇️
keras-torch 63.61% <63.79%> (+<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.

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.

ValueError: Invalid dtype: property object - ops.prod with layers.Dense

3 participants