Runtime type annotations for the shape, dtype etc. of PyTorch Tensors.
pip install torchtypingtorchtyping
Type annotations for a tensor's shape, dtype, names, ...
Welcome! For new projects I now strongly recommend using my newer jaxtyping project instead. It supports PyTorch, doesn't actually depend on JAX, and unlike TorchTyping it is compatible with static type checkers. :)
Turn this:
def batch_outer_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
# x has shape (batch, x_channels)
# y has shape (batch, y_channels)
# return has shape (batch, x_channels, y_channels)
return x.unsqueeze(-1) * y.unsqueeze(-2)
into this:
def batch_outer_product(x: TensorType["batch", "x_channels"],
y: TensorType["batch", "y_channels"]
) -> TensorType["batch", "x_channels", "y_channels"]:
return x.unsqueeze(-1) * y.unsqueeze(-2)
with programmatic checking that the shape (dtype, ...) specification is met.
Bye-bye bugs! Say hello to enforced, clear documentation of your code.
If (like me) you find yourself littering your code with comments like # x has shape (batch, hidden_state) or statements like assert x.shape == y.shape , just to keep track of what shape everything is, then this is for you.
Installation
pip install torchtyping
Requires Python >=3.7 and PyTorch >=1.7.0.
If using typeguard then it must be a version <3.0.0.
Usage
torchtyping allows for type annotating:
- shape: size, number of dimensions;
- dtype (float, integer, etc.);
- layout (dense, sparse);
- names of dimensions as per named tensors;
- arbitrary number of batch dimensions with
...; - ...plus anything else you like, as
torchtypingis highly extensible.
If typeguard is (optionally) installed then to ensure that the tensors really are of the advertised shape, dtype, etc.