-
Notifications
You must be signed in to change notification settings - Fork 19.7k
Add _maybe_convert_to_int utility to handle symbolic tensor dimensions safely #21848
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MalyalaKarthik66
wants to merge
2
commits into
keras-team:master
Choose a base branch
from
MalyalaKarthik66:fix-ops-prod-int-conversion
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+76
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import numpy as np | ||
| import pytest | ||
|
|
||
| import keras | ||
| from keras import backend | ||
| from keras import layers | ||
| from keras import ops | ||
| from keras.src.utils.arg_casts import _maybe_convert_to_int | ||
|
|
||
|
|
||
| @pytest.mark.skipif( | ||
| backend.backend() in ["numpy", "openvino"], | ||
| reason="fit() not implemented for NumPy/OpenVINO backends", | ||
| ) | ||
| def test_dense_accepts_ops_prod_units_and_call_ops_prod(): | ||
| class ProdDenseLayer(layers.Layer): | ||
| def __init__(self, **kwargs): | ||
| super().__init__(**kwargs) | ||
|
|
||
| def build(self, input_shape): | ||
| units = ops.prod(input_shape[1:]) | ||
| self.dense = layers.Dense(_maybe_convert_to_int(units)) | ||
| self.dense.build(input_shape) | ||
|
|
||
| def call(self, inputs): | ||
| scale_factor = ops.prod(ops.shape(inputs)[1:]) | ||
| scaled_inputs = inputs * ops.cast(scale_factor, inputs.dtype) | ||
| return self.dense(scaled_inputs) | ||
|
|
||
| batch_size = 4 | ||
| input_shape = (10,) | ||
| X_train = np.random.randn(batch_size * 2, *input_shape).astype(np.float32) | ||
| y_train = np.random.randint(0, 2, (batch_size * 2, 10)).astype(np.float32) | ||
|
|
||
| inp = keras.Input(shape=input_shape) | ||
| out = ProdDenseLayer()(inp) | ||
| model = keras.Model(inputs=inp, outputs=out) | ||
|
|
||
| model.compile(optimizer="adam", loss="binary_crossentropy") | ||
| model.fit(X_train, y_train, epochs=1, batch_size=batch_size, verbose=0) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
|
|
||
| from keras import ops | ||
|
|
||
|
|
||
| def _maybe_convert_to_int(x: Any) -> Any: | ||
| if isinstance(x, int): | ||
| return x | ||
| if isinstance(x, (tuple, list)): | ||
| try: | ||
| return tuple(int(v) for v in x) | ||
| except Exception: | ||
| return x | ||
|
|
||
| try: | ||
| np_val = ops.convert_to_numpy(x) | ||
| except Exception: | ||
| return x | ||
|
|
||
| if np.isscalar(np_val): | ||
| try: | ||
| return int(np_val) | ||
| except Exception: | ||
| return x | ||
|
|
||
| arr = np.asarray(np_val).ravel() | ||
| if arr.size == 0: | ||
| return x | ||
| if arr.size == 1: | ||
| return int(arr[0]) | ||
| try: | ||
| return tuple(int(v) for v in arr.tolist()) | ||
| except Exception: | ||
| return x | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The function can be made more robust and slightly cleaner. Using
except Exceptionforint()conversions is too broad and can mask unexpected errors. It's better to catch specific exceptions likeValueErrorandTypeError. Additionally, the conversionint(arr[0])on line 32 is not wrapped in atry...exceptblock and could raise an unhandled exception if the element is not convertible to an integer.I've suggested a refactoring that addresses these points by using more specific exceptions and ensuring all integer conversions are safely handled. The broad
except Exceptionforops.convert_to_numpyis kept, as it's intended to handle various failures from different backends, especially for symbolic tensors.