[Feature suggestion] Add a simple shape assertion in einops-style notation
I find that when I use einops, I end up with a mix of einops operations and regular asserts like this:
x = repeat(target, "b t h w c -> b t k h w c", k=K)
x = do_thing(x)
assert x.shape == (batch_size, T, H, W, C)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:
from einops import check_shape
check_shape(x, "b t h w c", t=T, h=H, c=3)This is preferable to the normal assert for a few reasons:
- if we're already using einops, it's nice to have a standard notation format, rather than mixing two notation formats. It makes the code more readable.
- i like the "b t h w c" style notation better than the assert-style notation, it allows you to give a "name" to each axis as opposed to just specifying its value.
- this notation allows you to only check certain axes. eg I don't normally care to check the
batch_sizedim, but doingassert x.shape[1:] = (T, H, W, C)is kinda yucky - and worse for axes not at the beginning or end.
Source: arogozhnikov/einops