Skip to content

Conversation

@danielenricocahall
Copy link
Contributor

@danielenricocahall danielenricocahall commented Oct 20, 2025

Addresses #21624. Inspired by #21727, except made to be compatible with all backends

Notes

  • Should we try to coerce the ExtractPatches and ExtractVolumePatches Operations into a common base/mixin or is would that obfuscate?
  • Should ExtractPatches have the same validation added to it's __init__ as was suggested (and added) by Gemini in ExtractVolumePatches?

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @danielenricocahall, 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 extract_volume_patches operation to the Keras ops.image module, fulfilling a requested feature for extracting 3D patches from volumetric data. The implementation ensures broad backend compatibility and provides flexible control over patch size, strides, dilation, and padding, significantly enhancing Keras's capabilities for 3D image processing tasks.

Highlights

  • New extract_volume_patches function: Introduces a new function keras.ops.image.extract_volume_patches for extracting 3D patches from volumetric data.
  • Backend Compatibility: The implementation is designed to be compatible with all Keras backends, leveraging backend.nn.conv for core functionality.
  • Comprehensive Testing: Adds extensive unit tests covering various scenarios such as different padding types ("valid", "same"), dilation rates, overlapping patches, channels_first and channels_last data formats, and handling of integer size and strides arguments.
  • Symbolic and Eager Execution: Implements both a functional _extract_volume_patches for eager execution and an ExtractVolumePatches Operation class for symbolic tensor handling.
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 extracting volume patches, which is a great addition for 3D data processing. The implementation is well-structured and follows the pattern of the existing extract_patches operation. The tests are also quite thorough.

I've found a few areas for improvement, mainly related to documentation accuracy, consistency in the implementation, and test correctness. Specifically, the docstring for the new function contains incorrect examples and descriptions, the Operation's call method has a minor inconsistency, and some of the new tests don't fully utilize their parameterization.

Please see my detailed comments below.

@codecov-commenter
Copy link

codecov-commenter commented Oct 20, 2025

Codecov Report

❌ Patch coverage is 85.71429% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.65%. Comparing base (61ac8c1) to head (e9f4e26).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
keras/src/ops/image.py 86.76% 6 Missing and 3 partials ⚠️
keras/api/_tf_keras/keras/ops/image/__init__.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #21759      +/-   ##
==========================================
- Coverage   82.68%   82.65%   -0.03%     
==========================================
  Files         572      573       +1     
  Lines       58588    58958     +370     
  Branches     9161     9236      +75     
==========================================
+ Hits        48442    48734     +292     
- Misses       7819     7868      +49     
- Partials     2327     2356      +29     
Flag Coverage Δ
keras 82.48% <85.71%> (-0.01%) ⬇️
keras-jax 63.26% <85.71%> (+0.07%) ⬆️
keras-numpy 57.75% <85.71%> (+0.11%) ⬆️
keras-openvino 34.37% <11.42%> (-0.12%) ⬇️
keras-tensorflow 64.04% <85.71%> (+0.09%) ⬆️
keras-torch 63.57% <85.71%> (+0.06%) ⬆️

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.

@danielenricocahall
Copy link
Contributor Author

/gemini review

@danielenricocahall
Copy link
Contributor Author

/gemini summary

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 extract_volume_patches for extracting patches from 3D volumes, which is a valuable addition. The implementation cleverly uses conv3d. However, I've identified some issues regarding clarity, correctness, and documentation. There's an inconsistency in the handling and documentation of the size parameter's dimensions, which could cause confusion and bugs. The variable names in the implementation are also misleading. Furthermore, a docstring example provides an incorrect output shape. I've also recommended enhancing the tests with a case for non-cubic patch sizes to improve robustness.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

This pull request introduces a new capability to Keras by adding extract_volume_patches to the ops.image module. This function allows users to extract 3D patches from volumetric data, addressing a previously identified issue and expanding Keras's utility for 3D image processing tasks. The implementation is designed for broad backend compatibility and includes robust testing.

Highlights

  • New extract_volume_patches function: A new function keras.ops.image.extract_volume_patches has been added to extract 3D patches from volumetric data.
  • Backend Compatibility: The implementation is designed to work across all Keras backends, utilizing backend.nn.conv for its core functionality.
  • Comprehensive Testing: Extensive unit tests have been added to cover various scenarios, including different padding types, dilation rates, overlapping patches, and both channels_first and channels_last data formats.
  • Symbolic and Eager Execution Support: The feature includes both a functional _extract_volume_patches for eager execution and an ExtractVolumePatches Operation class for handling symbolic tensors.
Changelog
  • keras/api/_tf_keras/keras/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/api/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/src/ops/image.py
    • Implemented the ExtractVolumePatches class, an Operation for symbolic execution.
    • Implemented the _extract_volume_patches function, providing the core logic for patch extraction.
    • Exposed extract_volume_patches as a public API, complete with detailed docstrings and usage examples.
  • keras/src/ops/image_test.py
    • Added a new test method test_extract_volume_patches within ImageOpsTest to verify functionality with KerasTensor inputs, covering both batched and unbatched cases, and channels_last/channels_first data formats.
    • Introduced the ExtractVolumePatchesTest class, containing a suite of parameterized tests for various scenarios, including basic functionality, "valid" and "same" padding, dilation, overlapping patches, channels_first data format, integer size and strides, unbatched inputs, value correctness checks, and error handling for invalid size and strides arguments.
Activity
  • Initial Summary by gemini-code-assist[bot]: Provided an initial overview and highlights of the PR.
  • Codecov Report by codecov-commenter: Reported patch coverage at 83.87%, with 10 lines missing coverage, and noted a decrease in overall project coverage.
  • Author Requests: danielenricocahall requested a review and then a summary from gemini-code-assist[bot].
  • Review Comments by gemini-code-assist[bot]:
    • High Priority: Identified incorrect examples in the extract_volume_patches docstring, specifically for the unbatched case's output shape, and suggested corrections.
    • Medium Priority: Recommended that the call method in ExtractVolumePatches directly invoke _extract_volume_patches for consistency and to avoid indirection.
    • Medium Priority: Suggested updating the data_format description in the docstring to correctly reflect 3D volume shapes.
    • Medium Priority: Pointed out inconsistent dtype casting for the PyTorch backend in tests, specifically in test_extract_volume_patches_basic, test_extract_volume_patches_same_padding, and test_extract_volume_patches_overlapping.
    • Medium Priority: Advised renaming patch_h, patch_w, patch_d variables for clarity and consistency with Keras conventions.
    • Medium Priority: Suggested clarifying the size parameter documentation to align with the (depth, height, width) convention.
    • Medium Priority: Recommended adding a test case for non-cubic patch sizes to ensure correct dimension ordering.

danielenricocahall and others added 5 commits October 19, 2025 22:50
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@danielenricocahall
Copy link
Contributor Author

/gemini summary

@danielenricocahall
Copy link
Contributor Author

/gemini review

@gemini-code-assist
Copy link
Contributor

Summary of Changes

This pull request introduces a new extract_volume_patches operation to Keras, enabling the extraction of 3D patches from volumetric data. This feature significantly enhances Keras's capabilities for 3D image processing by providing a flexible and backend-compatible method for generating patches, crucial for tasks like medical imaging or 3D object recognition.

Highlights

  • New extract_volume_patches function: Introduces a new function keras.ops.image.extract_volume_patches for extracting 3D patches from volumetric data, addressing a previously identified issue.
  • Backend Compatibility: The implementation is designed to be compatible with all Keras backends, leveraging backend.nn.conv for its core functionality.
  • Comprehensive Testing: Adds extensive unit tests covering various scenarios such as different padding types ('valid', 'same'), dilation rates, overlapping patches, channels_first and channels_last data formats, handling of integer size and strides arguments, and non-cubic patch sizes.
  • Symbolic and Eager Execution Support: Implements both a functional _extract_volume_patches for eager execution and an ExtractVolumePatches Operation class for symbolic tensor handling.
Changelog
  • keras/api/_tf_keras/keras/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/api/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/src/ops/image.py
    • Implemented the ExtractVolumePatches class, an Operation for symbolic execution.
    • Implemented the _extract_volume_patches function, providing the core logic for patch extraction.
    • Exposed extract_volume_patches as a public API, complete with detailed docstrings and usage examples for 3D data.
  • keras/src/ops/image_test.py
    • Added a new test method test_extract_volume_patches within ImageOpsTest to verify functionality with KerasTensor inputs, covering both batched and unbatched cases, and channels_last/channels_first data formats.
    • Introduced the ExtractVolumePatchesTest class, containing a suite of parameterized tests for various scenarios, including basic functionality, 'valid' and 'same' padding, dilation, overlapping patches, channels_first data format, integer size and strides, unbatched inputs, value correctness checks, error handling for invalid size and strides arguments, and a test for non-cubic patch sizes.
Activity
  • An initial summary and highlights of the PR were provided by gemini-code-assist[bot].
  • codecov-commenter reported a patch coverage of 95.16% with 3 lines missing coverage, noting a decrease in overall project coverage.
  • The author, danielenricocahall, requested a review and subsequently a summary from gemini-code-assist[bot].
  • gemini-code-assist[bot] provided several review comments, including:
  • A high-priority comment identified an incorrect output shape in the unbatched example within the docstring, suggesting a correction to (3, 3, 3, 81) for default strides.
  • A medium-priority comment recommended that the call method in ExtractVolumePatches directly invoke _extract_volume_patches for consistency.
  • A medium-priority comment suggested updating the data_format description in the docstring to accurately reflect 3D volume shapes.
  • A medium-priority comment pointed out inconsistent dtype casting for the PyTorch backend in tests.
  • A medium-priority comment advised renaming patch_h, patch_w, patch_d variables for improved clarity and consistency.
  • A medium-priority comment suggested clarifying the size parameter documentation to align with the (depth, height, width) convention.
  • A medium-priority comment recommended adding a test case for non-cubic patch sizes to ensure correct dimension ordering.

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 extracting patches from 3D volumes, analogous to the existing extract_patches for 2D images. The implementation is solid and follows the established pattern of using backend.nn.conv with an identity kernel. The tests are comprehensive, covering various scenarios including padding, strides, dilation, and data formats. I've identified a few areas for improvement, mainly in the docstrings for clarity and in the Operation class __init__ for more robust argument validation during symbolic execution.

@danielenricocahall
Copy link
Contributor Author

/gemini summary

@gemini-code-assist
Copy link
Contributor

Summary of Changes

This pull request introduces a new extract_volume_patches operation to Keras's ops.image module. This function enables the extraction of 3D patches from volumetric data, addressing a feature request and significantly enhancing Keras's capabilities for 3D image processing tasks. The implementation is designed for broad backend compatibility and includes robust testing to ensure its reliability across various scenarios.

Highlights

  • New extract_volume_patches function: A new function keras.ops.image.extract_volume_patches has been added to extract 3D patches from volumetric data, addressing a previously identified issue.
  • Backend Compatibility: The implementation is designed to work across all Keras backends, utilizing backend.nn.conv for its core functionality.
  • Comprehensive Testing: Extensive unit tests have been added to cover various scenarios, including different padding types, dilation rates, overlapping patches, and both channels_first and channels_last data formats, as well as non-cubic patch sizes.
  • Symbolic and Eager Execution Support: The feature includes both a functional _extract_volume_patches for eager execution and an ExtractVolumePatches Operation class for handling symbolic tensors.
Changelog
  • keras/api/_tf_keras/keras/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/api/ops/image/init.py
    • Added an import for extract_volume_patches.
  • keras/src/ops/image.py
    • Implemented the ExtractVolumePatches class, an Operation for symbolic execution.
    • Implemented the _extract_volume_patches function, providing the core logic for patch extraction.
    • Exposed extract_volume_patches as a public API, complete with detailed docstrings and usage examples for 3D data.
  • keras/src/ops/image_test.py
    • Added a new test method test_extract_volume_patches within ImageOpsTest to verify functionality with KerasTensor inputs, covering both batched and unbatched cases, and channels_last/channels_first data formats.
    • Introduced the ExtractVolumePatchesTest class, containing a suite of parameterized tests for various scenarios, including basic functionality, 'valid' and 'same' padding, dilation, overlapping patches, channels_first data format, integer size and strides, unbatched inputs, value correctness checks, error handling for invalid size and strides arguments, and a test for non-cubic patch sizes.
Activity
  • An initial summary and highlights of the PR were provided by gemini-code-assist[bot].
  • codecov-commenter reported a patch coverage of 86.11% with 10 lines missing coverage, noting a decrease in overall project coverage.
  • The author, danielenricocahall, requested a review and subsequently a summary from gemini-code-assist[bot] multiple times.
  • gemini-code-assist[bot] provided several review comments, including:
  • A high-priority comment identified incorrect examples in the extract_volume_patches docstring, specifically for the unbatched case's output shape, and suggested corrections.
  • A medium-priority comment recommended that the call method in ExtractVolumePatches directly invoke _extract_volume_patches for consistency.
  • A medium-priority comment suggested updating the data_format description in the docstring to accurately reflect 3D volume shapes.
  • A medium-priority comment pointed out inconsistent dtype casting for the PyTorch backend in tests.
  • A medium-priority comment advised renaming patch_h, patch_w, patch_d variables for improved clarity and consistency.
  • A medium-priority comment suggested clarifying the size parameter documentation to align with the (depth, height, width) convention.
  • A medium-priority comment recommended adding a test case for non-cubic patch sizes to ensure correct dimension ordering.
  • A high-priority comment suggested moving argument validation for size and strides to the __init__ method for early error detection.
  • A medium-priority comment recommended correcting the strides dimension order in the docstring to depth, height, and width.
  • A medium-priority comment suggested clarifying the dilation_rate limitation for the TensorFlow backend in the docstring.
  • A medium-priority comment advised correcting an inaccurate comment about TensorFlow backend's dilation_rate and strides interaction.

@danielenricocahall
Copy link
Contributor Author

/gemini review

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 extract_volume_patches, a 3D counterpart to the existing extract_patches function, which is a valuable addition for handling volumetric data. The implementation cleverly uses backend.nn.conv with an identity kernel for efficient patch extraction. The accompanying tests are thorough, covering various parameters like padding, strides, and data formats.

My review focuses on enhancing code clarity and maintainability. I've identified a couple of minor redundancies in the implementation of ExtractVolumePatches and suggested simplifications. Additionally, I've proposed changes to a few test cases to make them more explicit and easier to understand by ensuring the input data shape always aligns with the data_format being tested. Overall, this is a well-executed feature addition.

danielenricocahall and others added 6 commits October 20, 2025 16:10
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@fchollet
Copy link
Collaborator

Thanks for the PR!

Should we try to coerce the ExtractPatches and ExtractVolumePatches Operations into a common base/mixin or is would that obfuscate?

Keeping them separate sounds fine to me.



@keras_export("keras.ops.image.extract_volume_patches")
def extract_volume_patches(
Copy link
Collaborator

Choose a reason for hiding this comment

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

For API consistency with our conv ops, we might want to name it extract_patches_3d or extract_3d_patches. "volume" could be any dimension beyond 2.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Okay fixed! Went with extract_patches_3d to be closer to existing API

`(batch, depth, height, width, channels)`, while `"channels_first"`
corresponds to inputs with shape
`(batch, channels, depth, height, width)`. If not specified,
the value will default to `keras.config.image_data_format`.
Copy link
Collaborator

Choose a reason for hiding this comment

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

It's a function, keras.config.image_data_format()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah yes sorry, fixed

@danielenricocahall
Copy link
Contributor Author

/gemini summary

@gemini-code-assist
Copy link
Contributor

Summary of Changes

This pull request introduces a new extract_patches_3d operation within Keras's ops.image module, significantly extending its capabilities to handle 3D volumetric data. This feature allows users to extract three-dimensional patches from volumes, which is crucial for applications in medical imaging, 3D object recognition, and other deep learning tasks involving volumetric data. The implementation is designed for broad compatibility across all Keras backends and includes robust validation and comprehensive testing to ensure reliability and ease of use.

Highlights

  • New 3D Patch Extraction Function: Introduction of extract_patches_3d for extracting patches from 3D volumetric data, addressing a long-standing feature request.
  • Backend Agnostic Implementation: The new operation is designed to be compatible with all Keras backends, leveraging backend.nn.conv for its core functionality.
  • Comprehensive Testing: Extensive unit tests cover various scenarios including different padding types ('valid', 'same'), dilation rates, overlapping patches, and data formats (channels_first/channels_last), as well as non-cubic patch sizes.
  • Symbolic and Eager Execution Support: The feature includes both a functional eager execution (_extract_patches_3d) and a dedicated ExtractPatches3D Operation class for symbolic tensor handling, with argument validation moved to __init__ for early error detection.
Changelog
  • keras/api/_tf_keras/keras/ops/image/init.py
    • Added extract_patches_3d to the TensorFlow Keras API for image operations.
  • keras/api/ops/image/init.py
    • Added extract_patches_3d to the Keras API for image operations.
  • keras/src/ops/image.py
    • Implemented the ExtractPatches3D class, an Operation for symbolic execution of 3D patch extraction.
    • Developed the _extract_patches_3d function, which contains the core logic for extracting 3D patches.
    • Exposed extract_patches_3d as a public API, complete with detailed docstrings, usage examples, and argument validation for size and strides moved to __init__.
  • keras/src/ops/image_test.py
    • Added a new test method test_extract_patches_3d within ImageOpsTest to verify functionality with KerasTensor inputs, covering both batched and unbatched cases, and channels_last/channels_first data formats.
    • Introduced the ExtractPatches3DTest class, containing a suite of parameterized tests for various scenarios, including basic functionality, 'valid' and 'same' padding, dilation, overlapping patches, channels_first data format, integer size and strides, unbatched inputs, value correctness checks, error handling for invalid size and strides arguments, and tests for non-cubic patch sizes with improved input tensor shaping.
Activity
  • An initial summary and highlights of the PR were provided by gemini-code-assist[bot].
  • codecov-commenter reported patch coverage at 85.71% with 10 lines missing coverage, noting a slight decrease in overall project coverage.
  • The author, danielenricocahall, requested a review and summary from gemini-code-assist[bot] multiple times.
  • gemini-code-assist[bot] provided several review comments, including high priority suggestions for correcting docstring examples and moving size/strides validation to __init__. Medium priority suggestions included ensuring the call method directly invokes _extract_patches_3d, updating data_format description for 3D shapes, consistent dtype casting in tests, renaming internal variables, clarifying size parameter documentation, adding non-cubic patch size tests, correcting strides dimension order in docstring, clarifying TensorFlow's dilation_rate limitation, and improving test input tensor shaping for channels_first/channels_last.
  • fchollet provided feedback, suggesting renaming the function from extract_volume_patches to extract_patches_3d for API consistency and correcting the keras.config.image_data_format() call.
  • danielenricocahall confirmed fixes based on fchollet's suggestions, including the function name change to extract_patches_3d.

Copy link
Collaborator

@fchollet fchollet left a comment

Choose a reason for hiding this comment

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

Nice, thanks for the updates! LGTM

@google-ml-butler google-ml-butler bot added kokoro:force-run ready to pull Ready to be merged into the codebase labels Oct 24, 2025
@fchollet fchollet merged commit 18e0364 into keras-team:master Oct 24, 2025
8 checks passed
@google-ml-butler google-ml-butler bot removed awaiting review ready to pull Ready to be merged into the codebase kokoro:force-run labels Oct 24, 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.

4 participants