feat: flexible numpy/torch backend and tensor type checking #69
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
TL;DR
Flexible Backend + Type Checking
We want CamTools to seamlessly work with NumPy/Torch, and enforce dtype and shape checking for tensors. We want all these to work automagically with the help of decorators. This PR provides the initial infrastructure to do that while future PRs will incrementally migrate the existing functions.Overall goals
Key usages
With this PR, the key functions include:
jaxtyping
, specifying the shape and dtype. A single tensor type or a union of tensor types can be used. Flexible shape (e.g. "... 3") or context-dependent shape (e.g. "n 3") can be specified.@ct.backend.tensor_backend_auto
: Automatically determines the backend from the input arguments. Compatible list inputs are automatically converted to the native tensor format. This will only handle arguments that are hinted as tensors.@ct.backend.tensor_backend_numpy
and@ct.backend.tensor_backend_torch
: Enforces the use of NumPy and Torch backends by converting input tensors to NumPy or Torch, respectively. Compatible list inputs are automatically converted to the native tensor format. This will only handle arguments that are hinted as tensors.ct.backend.enable_tensor_check()
andct.backend.disable_tensor_check()
: Enable or disable tensor type checking (for dtype and shape) globally. By default, the tensor type checking is enabled. The checks will be done if@ct.backend.tensor_backend_xxx
decorators are used and the argument is hinted as a tensor.ivy
to for computation or use native Python operators. The goal is to make the functions compatible with both NumPy and Torch.Here are some examples.
Other notes
ct.backend.create_array
,ct.backend.create_ones
,ct.backend.create_zeros
, andct.backend.create_empty
.Union[Float[Tensor, "3 4"], Float[Tensor, "N 3 4"]]
.ivy
andtorch
fromcamtools.backend
, as this sets up some internal configurations for the backend.