-
Notifications
You must be signed in to change notification settings - Fork 357
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
[Feature suggestion] Add a simple shape assertion in einops-style notation #168
Comments
Hi @zplizzi, assert x.shape == (batch_size, T, H, W, C) is worse than check_shape(x, "b t h w c", t=T, h=H, c=3) As for skip dimensions, I'd prefer a function like check_shape(x, [None, T, H, W, C]) ... which does not require einops style |
Well, supposing you only want to check a couple axes,
is certainly more descriptive than Taken further, I could imagine just using which would just check that there are 5 axes, but primarily serves as documentation of the shape. |
It also allows for usage like
(depending on if we strictly enforced that all kwargs must exist in the shape specifier or not) |
I've personally found useful assert_shape as a decorator for a function/layer. Basically something like
The above means that Dense should have the same signature as einsum('...a->...b'). It should check that the last dimension is indeed of the same size etc. I've implemented this idea in Trax, here (there are aksi sine examples and documentation): https://github.com/google/trax/blob/master/trax/layers/assert_shape.py |
I didn't check the performance implications, but for now you may be able to get away with def check_shape(tensor, pattern, **kwargs):
return einops.rearrange(tensor, f"{pattern} -> {pattern}", **kwargs) |
I find that when I use einops, I end up with a mix of einops operations and regular
asserts
like this:I love the einops notation, and I can remove shape assertions immediately before or after an einops operation. But when I don't need to do a reshape/repeat/etc, I have to fall back to the
assert
notation to check the shape. I like to include lots of shape asserts in general both to make sure I haven't accidentally included a bug, but also for improving readability, so the reader always knows the shape of tensors. Asserts are superior to comments, as they will fail if you forget to update them, ensuring that they're always accurate.So I propose a new einops "operation", which does nothing except check shapes, and would raise an assertion error if the shape is incorrect. It would have a notation analogous to other einops operations:
This is preferable to the normal
assert
for a few reasons:batch_size
dim, but doingassert x.shape[1:] = (T, H, W, C)
is kinda yucky - and worse for axes not at the beginning or end.The text was updated successfully, but these errors were encountered: