jennyxue's picture
fp16 build of SAM 3D Objects
732cab0 verified
Raw History Blame Contribute Delete
9.71 kB
# From sam3d_objects/pipeline/inference_utils.py (SAM License): the pose decoder and the sparse-structure
# pruning / downsampling, as they are.
import torch
import numpy as np
import logging
logger = logging.getLogger(__name__)
from pytorch3d.transforms import quaternion_to_matrix, Transform3d, matrix_to_quaternion
from sam3d_objects.data.dataset.tdfy.transforms_3d import compose_transform, decompose_transform
from sam3d_objects.data.dataset.tdfy.pose_target import PoseTargetConverter
ROTATION_6D_MEAN = torch.tensor(
[
-0.06366084883674913,
0.008438224692279752,
0.00017084786438302483,
0.0007126610473540038,
-0.0030916726538816417,
0.5166093753457688,
]
)
ROTATION_6D_STD = torch.tensor(
[
0.6656971967514863,
0.6787012271867754,
0.30345010594844524,
0.4394504420678794,
0.39817973931717104,
0.6176286868761914,
]
)
def pose_decoder(
pose_target_convention,
):
def decode(model_output_dict, scene_scale=None, scene_shift=None):
x = model_output_dict
# BEGIN: copied from generative.py
key_mapping = {
"shape": "x_shape_latent",
"quaternion": "x_instance_rotation",
"6drotation": "x_instance_rotation_6d",
"6drotation_normalized": "x_instance_rotation_6d_normalized",
"translation": "x_instance_translation",
"scale": "x_instance_scale",
"translation_scale": "x_translation_scale",
}
# Decodes for metrics
pose_target_dict = {}
for k, v in x.items():
pose_target_dict[key_mapping.get(k, k)] = v
# TODO: Hao & Bowen please do clean this up!
# Convert 6D rotation to quaternion if needed
if (
"x_instance_rotation_6d" in pose_target_dict
or "x_instance_rotation_6d_normalized" in pose_target_dict
):
# Extract the two 3D vectors
if "x_instance_rotation_6d_normalized" in pose_target_dict:
rot_6d = pose_target_dict[
"x_instance_rotation_6d_normalized"
] * ROTATION_6D_STD.to(
pose_target_dict["x_instance_rotation_6d_normalized"].device
) + ROTATION_6D_MEAN.to(
pose_target_dict["x_instance_rotation_6d_normalized"].device
)
else:
rot_6d = pose_target_dict["x_instance_rotation_6d"]
a1 = rot_6d[..., 0:3]
a2 = rot_6d[..., 3:6]
# Normalize first vector
b1 = torch.nn.functional.normalize(a1, dim=-1)
# Make second vector orthogonal to first
b2 = a2 - torch.sum(b1 * a2, dim=-1, keepdim=True) * b1
b2 = torch.nn.functional.normalize(b2, dim=-1)
# Compute third vector as cross product
b3 = torch.cross(b1, b2, dim=-1)
# Stack to create rotation matrix
rotation_matrix = torch.stack([b1, b2, b3], dim=-1)
# Convert to quaternion
quaternion = matrix_to_quaternion(rotation_matrix)
pose_target_dict["x_instance_rotation"] = quaternion
if "x_instance_scale" in pose_target_dict:
pose_target_dict["x_instance_scale"] = torch.exp(
pose_target_dict["x_instance_scale"]
)
if "x_translation_scale" in pose_target_dict:
pose_target_dict["x_translation_scale"] = torch.exp(
pose_target_dict["x_translation_scale"]
)
pose_target_dict["pose_target_convention"] = [pose_target_convention] * x[
"shape"
].shape[0]
# END: copied from generative.py
# Fake pointmap moments
device = x["shape"].device
_scene_scale = (
scene_scale if scene_scale is not None else torch.tensor(1.0, device=device)
)
_scene_shift = (
scene_shift
if scene_shift is not None
else torch.tensor([[0, 0, 0]], device=device)
)
pose_target_dict["x_scene_scale"] = _scene_scale
pose_target_dict["x_scene_center"] = _scene_shift
# Convert to instance pose
pose_instance_dict = PoseTargetConverter.dicts_pose_target_to_instance_pose(
pose_target_convention=pose_target_convention,
x_instance_scale=pose_target_dict["x_instance_scale"],
x_instance_translation=pose_target_dict["x_instance_translation"],
x_instance_rotation=pose_target_dict["x_instance_rotation"],
x_translation_scale=pose_target_dict["x_translation_scale"],
x_scene_scale=pose_target_dict["x_scene_scale"],
x_scene_center=pose_target_dict["x_scene_center"],
)
return {
"translation": pose_instance_dict["instance_position_l2c"].squeeze(0),
"rotation": pose_instance_dict["instance_quaternion_l2c"].squeeze(0),
"scale": pose_instance_dict["instance_scale_l2c"].squeeze(0).mean(-1, keepdim=True).expand(1,3),
}
return decode
def prune_sparse_structure(
coord_batch,
max_neighbor_axes_dist=1,
):
coords, batch = coord_batch[:, 1:], coord_batch[:, 0].unsqueeze(-1)
device = coords.device
# 1) shift coords so minimum is zero
min_xyz = coords.min(0)[0]
coords0 = coords - min_xyz
# 2) build occupancy grid
max_xyz = coords0.max(0)[0] + 1 # size in each dim
D, H, W = max_xyz.tolist()
# shape (1,1,D,H,W)
occ = torch.zeros((1, 1, D, H, W), dtype=torch.uint8, device=device)
x, y, z = coords0.unbind(1)
occ[0, 0, x, y, z] = 1
# 3) 3×3×3 convolution to count each voxel + neighbors
kernel = torch.ones(
(
1,
1,
2 * max_neighbor_axes_dist + 1,
2 * max_neighbor_axes_dist + 1,
2 * max_neighbor_axes_dist + 1,
),
dtype=torch.uint8,
device=device,
)
# pad so output is same size
pad = max_neighbor_axes_dist
counts = torch.nn.functional.conv3d(occ.float(), kernel.float(), padding=pad)
# interior voxels have count == (2*max_neighbor_axes_dist+1)**3
full_count = (2 * max_neighbor_axes_dist + 1) ** 3
# 4) lookup counts at each original coord
counts_at_pts = counts[0, 0, x, y, z] # (N,)
is_surface = counts_at_pts < full_count
# 5) return filtered batch+coords (shift back if you want original coords)
kept = is_surface.nonzero(as_tuple=False).squeeze(1)
out_batch = batch[kept]
out_coords = coords[kept]
coords = torch.cat([out_batch, out_coords], dim=1)
return torch.cat([out_batch, out_coords], dim=1)
def downsample_sparse_structure(
coord_batch,
max_coords=42000,
downsample_factor=2,
):
"""
Downsample sparse structure coordinates when there are more than max_coords.
Downsamples by rescaling coordinates, effectively shrinking the grid while preserving
the structure. The downsampled grid is centered in the original space.
Args:
coord_batch: tensor of shape (N, 4) where [:, 0] is batch index and [:, 1:] are coords
max_coords: maximum number of coordinates to keep
42000 should be safe number. Calculation: max(int32) / (64*768) ~= 43691
Only needed for mesh decoding.
downsample_factor: factor by which to downsample (e.g., 2 means half resolution)
Returns:
Downsampled coord_batch with coordinates rescaled if downsampling is needed
"""
if coord_batch.shape[0] <= max_coords:
return coord_batch, 1
# Extract coordinates and batch indices
coords = coord_batch[:, 1:].float() # Shape: (N, 3), convert to float for scaling
batch_indices = coord_batch[:, 0:1] # Shape: (N, 1)
# Find the actual coordinate bounds
coords_min = coords.min(dim=0)[0] # Shape: (3,)
coords_max = coords.max(dim=0)[0] # Shape: (3,)
original_size = coords_max - coords_min + 1 # Add 1 since coordinates are discrete
# Calculate target size after downsampling
target_size = original_size / downsample_factor
# Calculate the offset to center the downsampled grid
offset = (original_size - target_size) / 2
target_min = coords_min + offset
target_max = coords_min + offset + target_size - 1
# Normalize coordinates to [0, 1] within their actual range
coords_normalized = (coords - coords_min) / (coords_max - coords_min)
# Scale to the target range
coords_rescaled = coords_normalized * (target_size - 1) + target_min
# Round to integers to get discrete grid coordinates
coords_rescaled = torch.round(coords_rescaled).int()
# Clamp to ensure we stay within bounds
coords_rescaled = torch.clamp(coords_rescaled, target_min.int(), target_max.int())
# Remove duplicates that may have been created by the downsampling
# Concatenate batch and coords for duplicate removal
combined = torch.cat([batch_indices, coords_rescaled], dim=1)
unique_combined = torch.unique(combined, dim=0)
# If still too many after deduplication, randomly subsample
if unique_combined.shape[0] > max_coords:
indices = torch.randperm(unique_combined.shape[0], device=coord_batch.device)[
:max_coords
]
unique_combined = unique_combined[indices]
return unique_combined.int(), downsample_factor