Skip to content

Conversation

@ma7555
Copy link
Contributor

@ma7555 ma7555 commented Dec 8, 2025

Summary

keras.ops.diag() uses tf.cond() wrapper that generates dynamic shapes (f32[<=n,<=n]), causing XLA OpDynamismSupport to fail with RET_CHECK when slicing the result in @tf.function(jit_compile=True).

tf.linalg.diag() works perfectly - direct static shapes.

Minimal Repro

import keras
import tensorflow as tf

@tf.function(jit_compile=True)
def spectral_graph_laplacian(use_tf_diag=True):
    n = 8
    feats_all = keras.random.normal((n, 64))
    
    feats_norm = keras.ops.normalize(feats_all, axis=-1)
    W = keras.ops.matmul(feats_norm, keras.ops.transpose(feats_norm))
    mask = 1.0 - keras.ops.eye(n)
    W = W * mask
    
    diag_vals = keras.ops.sum(W, axis=1)
    
    # SINGLE LINE DIFFERENCE
    if use_tf_diag:
        D = tf.linalg.diag(diag_vals)      # ✅ XLA-safe
    else:
        D = keras.ops.diag(diag_vals)      # ❌ Dynamic shapes
    
    L = D - W
    _, v = keras.ops.linalg.eigh(L)
    return v[:, 1]

print("=== Spectral Graph Test ===")
print("keras.ops.diag():")
try:
    result1 = spectral_graph_laplacian(use_tf_diag=False)
    print(f"  ✅ WORKS: shape {result1.shape}")
except Exception as e:
    print(f"  ❌ CRASH: {str(e)}")

print("\ntf.linalg.diag():")
try:
    result2 = spectral_graph_laplacian(use_tf_diag=True)
    print(f"  ✅ WORKS: shape {result2.shape}")
except Exception as e:
    print(f"  ❌ CRASH: {str(e)}")
=== Spectral Graph Test ===
keras.ops.diag():
  ❌ CRASH: RET_CHECK failure (external/local_xla/xla/service/dynamic_padder.cc:1992) op_support != OpDynamismSupport::kNoSupport Dynamic input unexpectedly found for unsupported instruction: %slice.441 = f32[<=8,1]{1,0} slice(f32[<=8,<=8]{1,0} %get-tuple-element.439), slice={[0:8], [1:2]}, metadata={op_type="StridedSlice" op_name="strided_slice" source_file="/usr/local/lib/python3.12/dist-packages/tensorflow/python/framework/ops.py" source_line=1200} [Op:__inference_spectral_graph_laplacian_3080]

tf.linalg.diag():
  ✅ WORKS: shape (8,)

Empty Tensor Handling (tf.cond Purpose)

Original tf.cond preserved empty case correctness, however, i see that tf.linalg.diag already handles it as well exactly in the same way. That makes this problematic tf.cond a redundant condition and possibly affect XLA graph compilation for no reason.

import keras, tensorflow as tf

@tf.function(jit_compile=True)
def test_empty_diag(use_tf_diag=True, k=1):
    empty_vec = tf.constant([], dtype=tf.float32)
    
    if use_tf_diag:
        D = tf.linalg.diag(empty_vec, k=k)
    else:
        D = keras.ops.diag(empty_vec, k=k)
    
    return D

for k in range(10):
    keras_D = test_empty_diag(use_tf_diag=False, k=k)
    tf_D = test_empty_diag(use_tf_diag=True, k=k)
    assert keras_D.shape == tf_D.shape, f"k={k}: shapes {keras_D.shape} != {tf_D.shape}"
    assert tf.reduce_all(tf.equal(keras_D, tf_D)), f"k={k}: values differ"
    print(f"✅ k={k}: shapes {keras_D.shape}, all zeros ✓")
✅ k=0: shapes (0, 0), all zeros ✓
✅ k=1: shapes (1, 1), all zeros ✓
✅ k=2: shapes (2, 2), all zeros ✓
✅ k=3: shapes (3, 3), all zeros ✓
✅ k=4: shapes (4, 4), all zeros ✓
✅ k=5: shapes (5, 5), all zeros ✓
✅ k=6: shapes (6, 6), all zeros ✓
✅ k=7: shapes (7, 7), all zeros ✓
✅ k=8: shapes (8, 8), all zeros ✓
✅ k=9: shapes (9, 9), all zeros ✓

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ma7555, 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 critical issue where keras.ops.diag() caused XLA JIT compilation failures on the TensorFlow backend. The problem stemmed from tf.cond() generating dynamic shapes, which is incompatible with XLA's static shape requirements. By removing the unnecessary tf.cond() wrapper and directly utilizing tf.linalg.diag(), the fix ensures static shape generation, enabling seamless XLA JIT compilation and improving the robustness of Keras operations.

Highlights

  • XLA JIT Crash Fix: Addresses a crash in keras.ops.diag() when used with XLA JIT compilation on the TensorFlow backend. The original implementation used tf.cond() which generated dynamic shapes, leading to RET_CHECK failures during tensor slicing.
  • tf.cond() Removal: The problematic tf.cond() wrapper in keras.ops.diag() has been removed. This wrapper was found to be redundant as tf.linalg.diag() inherently handles empty tensor cases correctly and produces static shapes, resolving the XLA compilation issue.
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 addresses a critical XLA JIT crash in keras.ops.diag() on the TensorFlow backend. The root cause was correctly identified as a tf.cond statement generating dynamic shapes for empty tensors. The fix, which involves removing the redundant tf.cond and relying directly on tf.linalg.diag(), is clean, effective, and well-justified by the thorough analysis provided in the description. This change not only resolves the bug but also simplifies the codebase. Excellent work on diagnosing and fixing this issue.

@codecov-commenter
Copy link

codecov-commenter commented Dec 8, 2025

Codecov Report

❌ Patch coverage is 0% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 76.30%. Comparing base (f0a48a6) to head (f8e3ac1).

Files with missing lines Patch % Lines
keras/src/backend/tensorflow/numpy.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #21906   +/-   ##
=======================================
  Coverage   76.30%   76.30%           
=======================================
  Files         580      580           
  Lines       60029    60029           
  Branches     9432     9432           
=======================================
  Hits        45803    45803           
  Misses      11750    11750           
  Partials     2476     2476           
Flag Coverage Δ
keras 76.16% <0.00%> (ø)
keras-jax 62.12% <0.00%> (ø)
keras-numpy 57.32% <0.00%> (ø)
keras-openvino 34.30% <0.00%> (ø)
keras-torch 63.22% <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.

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