Skip to content
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

BatchNormalization gives incorrect output with masked inputs > 3 dimensions #19848

Open
drasmuss opened this issue Jun 12, 2024 · 3 comments
Open
Assignees
Labels

Comments

@drasmuss
Copy link

The mean/variance calculations are incorrect, which means the inputs are not normalized correctly. E.g.

import keras

x = keras.ops.ones((1, 2, 3, 4))
x._keras_mask = keras.ops.ones((1, 2, 1))

y = keras.layers.BatchNormalization()(x, training=True)

print(keras.ops.mean(y, axis=-1))

gives output

tf.Tensor([-0.57732624 -0.57732624 -0.57732624 -0.57732624], shape=(4,), dtype=float32)

instead of the correct normalized output ([0, 0, 0, 0]).

The basic issue is that this calculation is incorrect:

sum_of_weights = ops.sum(
mask_weights_broadcasted,
self._reduction_axes,
keepdims=True,
)

because it doesn't account for the broadcasting (i.e. it gives a value of 2 in the above example, when it should be 2 * 3 * 4).

See #19818 for more discussion/background.

@Grvzard
Copy link
Contributor

Grvzard commented Jun 13, 2024

I think a better workaround is to validate the shape of the mask in keras.

@drasmuss
Copy link
Author

The shape of the mask is correct in this example (according to #19818 (comment)), so validation wouldn't help in this case.

@Grvzard
Copy link
Contributor

Grvzard commented Jun 13, 2024

because it doesn't account for the broadcasting (i.e. it gives a value of 2 in the above example, when it should be 2 * 3 * 4).

broadcasting from (2,) to (2, 3, 4) makes sense here, but elsewhere, "broadcasting" may starts with the rightmost dimension, i.e. broadcast (4,) to (2, 3, 4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants