-
Notifications
You must be signed in to change notification settings - Fork 27
Add torch.compile() support for BAE’s PyPose LieTensor operations and sparse Jacobian traversal
#41
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c2e3762
dynamo working on froward pass
ZihangFang aad651d
backward works in dynamo
ZihangFang 17ab957
update plan
ZihangFang 300d64c
reorder
ZihangFang bdd3210
remove AMGX plan as distributed PCG is finished
ZihangFang 64aad04
deprecate the dict type optrace.
ZihangFang 3eb722c
Update README.md
ZihangFang 54081a1
fix the none comment
ZihangFang e2ce068
fix torch.where comments
ZihangFang 1f1772c
fix comment:
ZihangFang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| from .utils.pypose_compile import maybe_install_pypose_torch_compile_monkeypatch | ||
| from .utils.pypose_ambient_grad import maybe_install_pypose_ambient_grad_monkeypatch | ||
|
|
||
| maybe_install_pypose_torch_compile_monkeypatch() | ||
| maybe_install_pypose_ambient_grad_monkeypatch() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ | |
| import numpy as np | ||
| import pypose as pp | ||
| from functools import wraps | ||
| from torch.utils._pytree import tree_map | ||
|
|
||
| WHITELISTED_MAPS = tuple( | ||
| func for func in ( | ||
|
|
@@ -23,6 +24,8 @@ | |
| torch._C.TensorBase.to, | ||
| } | ||
|
|
||
| _INDEXED_TRACE_TAG = "bae.indexed" | ||
|
|
||
|
|
||
| def _iter_tracked_tensors(values): | ||
| if isinstance(values, torch.Tensor): | ||
|
|
@@ -36,9 +39,7 @@ def _iter_tracked_tensors(values): | |
|
|
||
|
|
||
| def _attach_index_trace(result, index, tensor): | ||
| if not hasattr(result, 'optrace'): | ||
| result.optrace = {} | ||
| result.optrace[id(result)] = ("index", index, tensor) | ||
| result.optrace = ("index", index, tensor) | ||
| return result | ||
|
|
||
|
|
||
|
|
@@ -47,18 +48,31 @@ def _attach_cat_trace(result, tensors, dim): | |
| offset = 0 | ||
| for t in tensors: | ||
| n = t.shape[0] | ||
| if hasattr(t, 'optrace') or isinstance(t, torch.nn.Parameter): | ||
| if ( | ||
| hasattr(t, "optrace") | ||
| or isinstance(t, TrackingTensor) | ||
| or isinstance(t, torch.nn.Parameter) | ||
| ): | ||
| tracked.append((offset, offset + n, t)) | ||
| offset += n | ||
| result.optrace = {id(result): ("cat", dim, tuple(tracked))} | ||
| result.optrace = ("cat", dim, tuple(tracked)) | ||
| return result | ||
|
|
||
|
|
||
| def _attach_map_trace(result, func, args): | ||
| result.optrace = {id(result): ("map", func, args)} | ||
| compact_args = tuple(_compact_map_arg(arg) for arg in args) | ||
| result.optrace = ("map", func, compact_args) | ||
| return result | ||
|
|
||
|
|
||
| def _compact_map_arg(arg): | ||
| if isinstance(arg, TrackingTensor) and hasattr(arg, "optrace"): | ||
| trace = arg.optrace | ||
| if trace[0] == "index": | ||
| return (_INDEXED_TRACE_TAG, trace[2], trace[1]) | ||
| return arg | ||
|
|
||
|
|
||
| def _find_tracking_source(values, cls): | ||
| for value in _iter_tracked_tensors(values): | ||
| if isinstance(value, cls): | ||
|
|
@@ -69,23 +83,16 @@ def _find_tracking_source(values, cls): | |
| def _unwrap_tracking_tensor(value): | ||
| if not isinstance(value, TrackingTensor): | ||
| return value | ||
| base = torch.Tensor(value) | ||
| if isinstance(value, pp.LieTensor): | ||
| unwrapped = torch.Tensor.as_subclass(value, pp.LieTensor) | ||
| unwrapped = base.as_subclass(pp.LieTensor) | ||
| unwrapped.ltype = value.ltype | ||
| return unwrapped | ||
| return torch.Tensor.as_subclass(value, torch.Tensor) | ||
| return base | ||
|
|
||
|
|
||
| def _unwrap_tracking_tensors(values): | ||
| if isinstance(values, TrackingTensor): | ||
| return _unwrap_tracking_tensor(values) | ||
| if isinstance(values, dict): | ||
| return {key: _unwrap_tracking_tensors(value) for key, value in values.items()} | ||
| if isinstance(values, tuple): | ||
| return tuple(_unwrap_tracking_tensors(value) for value in values) | ||
| if isinstance(values, list): | ||
| return [_unwrap_tracking_tensors(value) for value in values] | ||
| return values | ||
| return tree_map(_unwrap_tracking_tensor, values) | ||
|
|
||
|
|
||
| def _rewrap_tracking_tensor(result, tracking_source): | ||
|
|
@@ -103,7 +110,7 @@ def _retain_ltype(result, tracking_source, cls, func): | |
| return result | ||
| if result.shape[-1:] != tracking_source.ltype.dimension: | ||
| return result | ||
| wrapped = torch.Tensor.as_subclass(result, cls) | ||
| wrapped = torch.Tensor(result).as_subclass(cls) | ||
| wrapped.ltype = tracking_source.ltype | ||
| return wrapped | ||
|
|
||
|
|
@@ -178,7 +185,7 @@ def __format__(self, format_spec): | |
| return format(str(self), format_spec) | ||
|
|
||
| def tensor(self) -> torch.Tensor: | ||
| return torch.Tensor.as_subclass(self, torch.Tensor) | ||
| return torch.Tensor(self) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
|
|
||
| class _TrackingLieTensor(TrackingTensor, pp.LieTensor): | ||
|
|
@@ -195,31 +202,13 @@ def __new__(cls, data, *args, **kwargs): | |
| return instance | ||
|
|
||
| def detach(self): | ||
| detached = torch.Tensor.as_subclass(super().detach(), type(self)) | ||
| detached = torch.Tensor(self).detach().as_subclass(type(self)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| detached.ltype = self.ltype | ||
| return detached | ||
| """ | ||
| graph design | ||
| Node: (tensor_type: [nn.Parameter, tensor, pp.LieTensor]) | ||
| Edge: (indexing, mapping) | ||
|
|
||
| G: (V: [Node...], E: [Edge...]) | ||
|
|
||
| for each e = (u, v) \in E | ||
| parent[loss] = (project, [camera_indexed, point_indexed]) | ||
| parent[camera_indexed] = ((indexing, indices), camera_parameters) | ||
|
|
||
| build | ||
| parent: key: id(tensor), value: map edge (edge_type, func, [input_args]), index edge (edge_type, indicies, orig_arg) | ||
|
|
||
| backward | ||
| 1. access loss.parent | ||
| 2. check edge type | ||
| 3.1. if indexing, permute value | ||
| 3.2. if mapping, revise value | ||
|
|
||
| recusively call 1-3 until input node is reached. | ||
| """ | ||
| # Each tracked tensor stores its incoming edge directly as | ||
| # ``(edge_type, edge_metadata, inputs)`` in ``tensor.optrace``. A tensor owns | ||
| # exactly one incoming edge, so an additional dictionary keyed by ``id(tensor)`` | ||
| # would be redundant. | ||
|
|
||
|
|
||
| # ============================================================================= | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using
torch.Tensor(value)to cast a subclass tensor to a basetorch.Tensoris unsafe in PyTorch. It can trigger data copying, move the tensor to the default device (usually CPU), or reset the dtype to the default (usually float32), which leads to device/dtype mismatches or silent performance degradation.The standard, safe, and zero-copy way to cast a subclass tensor to a base
torch.Tensorwhile preserving its device, dtype, and autograd history isvalue.view(torch.Tensor).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is to make sure torch dynamo can compile