Replace cast+multiply masking with ops.where to reduce memory#22392
Replace cast+multiply masking with ops.where to reduce memory#22392rstar327 wants to merge 3 commits intokeras-team:masterfrom
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #22392 +/- ##
=======================================
Coverage 82.97% 82.97%
=======================================
Files 596 596
Lines 66330 66336 +6
Branches 10334 10334
=======================================
+ Hits 55038 55044 +6
Misses 8663 8663
Partials 2629 2629
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary of ChangesHello, 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 memory efficiency across the Keras codebase by refactoring how boolean masks are applied to tensors. By transitioning from a cast-and-multiply pattern to using Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
Code Review
This pull request replaces the cast and multiply pattern with ops.where for masking across various files to improve memory efficiency, particularly for the Torch backend. The changes are generally correct and well-implemented. I've identified a minor issue in keras/src/constraints/constraints.py where the change could lead to unintended data type promotion, and I've provided a suggestion to address it. The addition of del statements for intermediate tensors in batch_normalization.py is also a good optimization for memory management.
| def __call__(self, w): | ||
| w = backend.convert_to_tensor(w) | ||
| return ops.multiply(w, ops.greater_equal(w, 0.0)) | ||
| return ops.where(ops.greater_equal(w, 0.0), w, 0.0) |
There was a problem hiding this comment.
Using 0.0 here could cause unintended dtype promotion if the input tensor w is of an integer type. The original implementation preserved the dtype. Using 0 will be correctly cast to either float or int depending on the dtype of w, preserving the original behavior and making the constraint more robust.
An even more idiomatic way to implement this constraint would be ops.maximum(w, 0).
| return ops.where(ops.greater_equal(w, 0.0), w, 0.0) | |
| return ops.where(ops.greater_equal(w, 0.0), w, 0) |
There was a problem hiding this comment.
Nice idea, a few things that need fixing before this can land. Thanks for the work on this pr!
OpenVINO failures (all 10)
Every failure is the same:
Argument 0 must have boolean element type (element type: f32)
OpenVINO's Select op requires the condition to be strictly boolean. In several places the mask argument can arrive as float or int after round-tripping through backend masking logic see inline comments.
| mask_broadcasted, ops.shape(inputs) | ||
| ) | ||
| weighted_inputs = broadcasted_mask * inputs | ||
| mask_broadcasted = ops.cast(mask_broadcasted, "bool") |
There was a problem hiding this comment.
This is one of the OpenVINO failures. mask from the layer masking system can arrive as float, so mask_broadcasted inherits that dtype. OpenVINO's Select op (which backs ops.where) requires argument 0 to be strictly boolean.
Needs a mask = ops.cast(mask, "bool") guard at the top of this block, before the expand/broadcast.
| mask, 2 if self.data_format == "channels_last" else 1 | ||
| ) | ||
| inputs *= mask | ||
| mask_expanded = ops.cast(mask_expanded, "bool") |
There was a problem hiding this comment.
Same OpenVINO issue. mask comes in as i32 here, not boolean. Needs mask = ops.cast(mask, "bool") before the expand_dims.
| mask *= ops.divide_no_nan(total, valid) | ||
| valid = ops.sum(ops.cast(mask, dtype=dtype)) # May be 0! | ||
| mask_weight = ops.divide_no_nan(total, valid) | ||
| float_mask = ops.where(ops.cast(mask, "bool"), mask_weight, 0) |
There was a problem hiding this comment.
Same OpenVINO issue mask can be float after squeeze_or_expand_to_same_rank. Needs a bool cast before being used as the ops.where condition.
| mask_weight = ops.divide_no_nan(total, valid) | ||
| float_mask = ops.where(ops.cast(mask, "bool"), mask_weight, 0) | ||
| else: | ||
| float_mask = ops.cast(mask, dtype=dtype) |
There was a problem hiding this comment.
This else branch still does ops.cast(mask, dtype=dtype) and then sample_weight *= float_mask below that's the original cast+multiply pattern this PR is trying to remove. Should use ops.where here too.
| @@ -567,7 +567,11 @@ def update_confusion_matrix_variables( | |||
| def weighted_assign_add(label, pred, weights, var): | |||
| label_and_pred = ops.cast(ops.logical_and(label, pred), dtype=var.dtype) | |||
There was a problem hiding this comment.
When weights is not None, this cast allocates a float tensor that gets immediately thrown away on the next line. And ops.logical_and(label, pred) is recomputed inside the ops.where below. Could keep the boolean and branch instead:
label_and_pred = ops.logical_and(label, pred)
if weights is not None:
result = ops.where(label_and_pred, ops.cast(weights, dtype=var.dtype), 0)
else:
result = ops.cast(label_and_pred, dtype=var.dtype)
var.assign(var + ops.sum(result, 1))|
Sorry just saw you fixed those changes the fixes I flagged on loss.py and metrics_utils.py still exist none the less. |
905bf00 to
a2022ed
Compare
Summary
tensor * ops.cast(bool_mask, tensor.dtype)withops.where(bool_mask, tensor, 0)across 12 filesops.whereskips the float copy of the mask entirely.delon batch norm intermediates for earlier garbage collectionFixes #22386