File size: 961 Bytes
732cab0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # From sam3d_objects/data/utils.py (SAM License): expand_right / expand_as_right as they are;
# tree_tensor_map on torch.utils._pytree instead of optree.
import torch
from torch.utils import _pytree
def tree_tensor_map(fn, tree, *rest):
return _pytree.tree_map(fn, tree, *rest)
def expand_right(tensor, target_shape):
"""
e.g. Takes tensor of (a, b, c) and returns a tensor of (a, b, c, 1, 1, ...)
"""
current_shape = tensor.shape
dims_to_add = len(target_shape) - len(current_shape)
result = tensor
for _ in range(dims_to_add):
result = result.unsqueeze(-1)
expand_shape = list(current_shape) + [-1] * dims_to_add
for i in range(len(target_shape)):
if i < len(expand_shape) and expand_shape[i] == -1:
expand_shape[i] = target_shape[i]
return result.expand(*expand_shape)
def expand_as_right(tensor, target):
return expand_right(tensor, target.shape)
|