Skip to content

Conversation

JyotinderSingh
Copy link
Collaborator

Description of the change

For some reason when using a Keras Variable of type int64, TF's casting behavior goes bonkers. This adds an explicit cast to avoid a runtime exception of mismatched dtypes.

The existing code would lead to the following state at the tf.where(...) call site (the modified code):

>>> i.dtype
int64
>>> tf.shape(x)[axis].dtype
int32
>>> tf.cast(tf.shape(x)[axis], i.dtype).dtype
int64
>>> (i + tf.cast(tf.shape(x)[axis], i.dtype).dtype
int32 

As shown above, the addition operation weirdly ends up with int32 dtype. This change explicitly casts the result to a 64 bit integer to avoid a dtype mismatch between the two arguments of tf.where

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.

Summary of Changes

Hello @JyotinderSingh, 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 resolves a subtle data type casting issue within the Keras TensorFlow backend, ensuring that operations involving int64 Keras Variables behave as expected. The change specifically targets the ops.take function to prevent runtime exceptions caused by TensorFlow's unexpected implicit type conversions.

Highlights

  • TensorFlow Backend Fix: Corrected an int64 casting bug in the tf.where call within the ops.take function for the TensorFlow backend, specifically when using keras.Variable as indices.
  • Explicit Type Casting: Introduced an explicit cast to int64 for the result of an addition operation in the fix_negative_indices helper function to prevent dtype mismatches that occur due to TensorFlow's implicit casting behavior.
  • New Test Case: Added a dedicated test case in numpy_test.py to validate the fix for int64 keras.Variable indices in ops.take.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 effectively addresses a TensorFlow-specific casting bug that occurs when using an int64 keras.Variable with ops.take. The fix, which involves an explicit cast, is correct. The addition of a new test case to cover this specific scenario is also a great way to prevent regressions. I have one suggestion to improve the readability of the fix, which will make the code easier to maintain in the future.

Comment on lines +2406 to +2408
return tf.where(
i < 0, tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype), i
)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

While this fix is correct, the implementation is a bit dense. Refactoring it to use an intermediate variable for the corrected indices would make the code more readable and easier to maintain. This also provides a good place to add a comment explaining why this explicit cast is necessary, which is helpful for future contributors.

Suggested change
return tf.where(
i < 0, tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype), i
)
positive_i = tf.cast(i + tf.cast(tf.shape(x)[axis], i.dtype), i.dtype)
# Explicitly cast back to original dtype to fix TF casting issue for int64.
return tf.where(i < 0, positive_i, i)

@JyotinderSingh JyotinderSingh marked this pull request as draft September 10, 2025 17:16
@codecov-commenter
Copy link

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.32%. Comparing base (7c4679f) to head (f897c94).
⚠️ Report is 9 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (7c4679f) and HEAD (f897c94). Click for more details.

HEAD has 6 uploads less than BASE
Flag BASE (7c4679f) HEAD (f897c94)
keras 5 2
keras-openvino 1 0
keras-numpy 1 0
keras-tensorflow 1 0
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #21656       +/-   ##
===========================================
- Coverage   82.53%   69.32%   -13.22%     
===========================================
  Files         571      571               
  Lines       57526    57626      +100     
  Branches     8991     9001       +10     
===========================================
- Hits        47478    39948     -7530     
- Misses       7755    15524     +7769     
+ Partials     2293     2154      -139     
Flag Coverage Δ
keras 69.18% <100.00%> (-13.16%) ⬇️
keras-jax 63.51% <100.00%> (-0.05%) ⬇️
keras-numpy ?
keras-openvino ?
keras-tensorflow ?
keras-torch 63.73% <100.00%> (-0.05%) ⬇️

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.

@JyotinderSingh
Copy link
Collaborator Author

The underlying issue here was discovered to be related to #21677.

@JyotinderSingh
Copy link
Collaborator Author

Fixed in #21679

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.

3 participants