equinox icon indicating copy to clipboard operation
equinox copied to clipboard

Broadcasting error when using eqx.nn.Linear with use_bias=True

Open geomlyd opened this issue 4 years ago • 5 comments

I'm pretty new to both jax and equinox, so there's a chance I'm missing something, but I think that there's a bug in the implementation of eqx.nn.Linear when using a bias. Namely, the addition of the bias to the product weight*input fails whenever the input has more than one dimensions due to a broadcasting error. Example:

import jax
import jax.numpy as jnp
import equinox as eqx

key = jax.random.PRNGKey(0)
k1, k2, k3, k4 = jax.random.split(key, 4)
layer1 = eqx.nn.Linear(10, 8, use_bias=True, key=k1)
layer2 = eqx.nn.Linear(10, 8, use_bias=False, key=k2)

arr1 = jax.random.normal(k3, shape=(10, 100))
arr2 = jax.random.normal(k4, shape=(10,))

layer1(arr1) #fails with "Incompatible shapes for broadcasting: ((8, 100), (1, 8))"
layer2(arr1) #ok

layer1(arr2) #ok
layer2(arr2) #ok

Thanks for the cool library!

geomlyd avatar Sep 29 '22 14:09 geomlyd

This is expected! JAX has a transform called vmap, which you can use to vectorise operations over additional dimensions. (Such as batch dimensions.)

Equinox uses this to handle any such additional dimensions. See the FAQ entry here.

Does that make sense?

patrick-kidger avatar Sep 29 '22 15:09 patrick-kidger

Ah, it does, yes. I was aware of vmap and its use cases, just didn't occur to me that it could be the reason here. So in general your functions (and the functions of other libraries, I guess) are always written with a single data sample in mind, leaving all vectorisation to vmap?

geomlyd avatar Sep 29 '22 15:09 geomlyd

Depends on the library author's preferences! But yes, everything I write leaves the vectorisation to vmap :)

patrick-kidger avatar Sep 29 '22 15:09 patrick-kidger

Great, thanks for the clarification!

geomlyd avatar Sep 29 '22 18:09 geomlyd

Fwiw, the place where this behavior has bitten me the most is with LayerNorm as it happily broadcasts, so it ends up being a silent issue. Happy to open another issue if you think you'd like to do something about it, but I could also see leaving it as is.

dlwh avatar Sep 29 '22 19:09 dlwh