Skip to content

Add support for dynamic dimensions in ops.slice.compute_output_spec.#22154

Merged
hertschuh merged 1 commit intokeras-team:masterfrom
hertschuh:slice_dyn
Feb 11, 2026
Merged

Add support for dynamic dimensions in ops.slice.compute_output_spec.#22154
hertschuh merged 1 commit intokeras-team:masterfrom
hertschuh:slice_dyn

Conversation

@hertschuh
Copy link
Copy Markdown
Collaborator

Also added verification that the shape of the inputs, the shape parameter and the indices have the same length.

Also added verification that the shape of the inputs, the `shape` parameter and the `indices` have the same length.
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @hertschuh, 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 significantly improves the slice operation's compute_output_spec method by introducing support for dynamic output dimensions. It ensures that when a dimension is specified as -1 for slicing, the output shape correctly reflects dynamic behavior (e.g., None) if the input or start index is also dynamic. Additionally, robust validation has been added to prevent dimension mismatches between the input tensor, the slice shape parameter, and the start_indices.

Highlights

  • Dynamic Dimension Support: Enabled dynamic dimension support in ops.slice.compute_output_spec when -1 is used in the shape parameter, allowing for more flexible slicing operations.
  • Input Validation: Implemented new validation checks to ensure that the number of dimensions in inputs, the shape parameter, and start_indices are consistent, preventing dimension mismatches.
  • Revised KerasTensor Handling: Revised the handling of KerasTensor start_indices with -1 in shape to correctly infer None for dynamic output dimensions, rather than raising a ValueError.

🧠 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/ops/core.py
    • Updated compute_output_spec to correctly handle dynamic dimensions when -1 is used in the shape parameter.
    • Added checks to validate that the lengths of inputs.shape, shape, and start_indices are equal.
  • keras/src/ops/core_test.py
    • Added new test cases for slice to verify correct behavior with KerasTensor start_indices and dynamic input shapes when -1 is used in the shape.
    • Introduced test cases to confirm ValueError is raised for invalid dimension mismatches between inputs, shape, and start_indices.
    • Removed the test_slice_negative_one_shape_raises test, as the previous error condition is now correctly handled.
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
Copy Markdown
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 enhances ops.slice.compute_output_spec to support dynamic dimensions and adds input validation. The changes correctly handle dynamic shapes when shape contains -1 and start_indices is a KerasTensor. The added tests cover these new scenarios.

I've identified a potential issue in the validation logic for start_indices when it's a KerasTensor, where its length isn't checked against the input rank. I've provided a suggestion to make this validation more robust.

Comment thread keras/src/ops/core.py
Comment on lines +410 to 417
if hasattr(start_indices, "__len__") and len(start_indices) != len(
inputs.shape
):
raise ValueError(
"When using -1 in `shape`, `start_indices` should not be a "
"KerasTensor. "
"The number of dimensions in `start_indices` must match the "
"number of dimensions in `inputs`. Received "
f"start_indices={start_indices} and inputs.shape={inputs.shape}"
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The validation for start_indices does not correctly handle KerasTensor inputs. The hasattr(start_indices, "__len__") check returns False for a KerasTensor, causing the validation of its length against the input rank to be skipped. This could lead to runtime errors or incorrect behavior if a KerasTensor with an incorrect number of indices is provided.

I suggest a more robust validation that explicitly handles KerasTensor and provides clearer error messages. It would also be good to add a test case for an invalid KerasTensor start_indices to test_slice_invalid_inputs.

Suggested change
if hasattr(start_indices, "__len__") and len(start_indices) != len(
inputs.shape
):
raise ValueError(
"When using -1 in `shape`, `start_indices` should not be a "
"KerasTensor. "
"The number of dimensions in `start_indices` must match the "
"number of dimensions in `inputs`. Received "
f"start_indices={start_indices} and inputs.shape={inputs.shape}"
)
num_dims = len(inputs.shape)
indices_len = None
if isinstance(start_indices, KerasTensor):
if len(start_indices.shape) != 1:
raise ValueError(
"Argument `start_indices` must be a 1D tensor, but got "
f"a tensor of rank {len(start_indices.shape)}."
)
indices_len = start_indices.shape[0]
elif hasattr(start_indices, "__len__"):
indices_len = len(start_indices)
if indices_len is not None and indices_len != num_dims:
raise ValueError(
"The number of values in `start_indices` must match the rank "
f"of `inputs`. Expected {num_dims} but got {indices_len}. "
f"Received: start_indices={start_indices}, "
f"inputs.shape={inputs.shape}"
)

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Feb 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.79%. Comparing base (441d184) to head (a92d2f4).

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #22154   +/-   ##
=======================================
  Coverage   82.78%   82.79%           
=======================================
  Files         592      592           
  Lines       63357    63365    +8     
  Branches     9941     9945    +4     
=======================================
+ Hits        52452    52460    +8     
  Misses       8354     8354           
  Partials     2551     2551           
Flag Coverage Δ
keras 82.61% <100.00%> (+<0.01%) ⬆️
keras-jax 62.33% <100.00%> (+<0.01%) ⬆️
keras-numpy 56.50% <100.00%> (+<0.01%) ⬆️
keras-openvino 37.48% <100.00%> (+<0.01%) ⬆️
keras-tensorflow 63.54% <100.00%> (+<0.01%) ⬆️
keras-torch 62.37% <100.00%> (+<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.

@google-ml-butler google-ml-butler Bot added kokoro:force-run ready to pull Ready to be merged into the codebase labels Feb 11, 2026
@hertschuh hertschuh merged commit 233417f into keras-team:master Feb 11, 2026
13 checks passed
@hertschuh hertschuh deleted the slice_dyn branch February 11, 2026 23:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready to pull Ready to be merged into the codebase size:M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants