Spaces:
Running on Zero
Running on Zero
File size: 2,650 Bytes
72f8c75 | 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | """ChunkedSparseConv3d — submanifold SparseConv3d that splits its GEMM across batch-index
groups when the packed B*F tensor would exceed spconv's int32 limit (else fast path).
Submanifold convs preserve coords and are per-batch-index independent, so running the conv
on consecutive batch-index groups and concatenating outputs is exactly lossless. Param names
are unchanged, so pretrained SAM-3D / TRELLIS checkpoints warm-start 1:1. Ported from
`structured_latent_flow.ChunkedSparseConv3d`; only the import base differs (SAM-3D's `sp`).
"""
import torch
from spconv.pytorch import SubMConv3d
from sam3d_objects.model.backbone.tdfy_dit.modules import sparse as sp
_CONV_CHUNK_SAFETY = 4
class ChunkedSparseConv3d(sp.SparseConv3d):
"""Stride-1 (submanifold) SparseConv3d whose GEMM is chunked across batch-index groups when
the packed tensor would overflow spconv's int32 limit; full-tensor fast path otherwise."""
chunk_safety: int = _CONV_CHUNK_SAFETY
def forward(self, x: "sp.SparseTensor") -> "sp.SparseTensor":
feats = x.feats
if not isinstance(self.conv, SubMConv3d):
return super().forward(x)
limit = (1 << 31) // self.chunk_safety
nbytes = feats.shape[0] * feats.shape[1] * feats.element_size()
if x.shape[0] <= 1 or nbytes <= limit:
return super().forward(x)
budget = max(1, limit // (feats.shape[1] * feats.element_size()))
groups, cur, cur_n = [], [], 0
for i, sl in enumerate(x.layout):
n = sl.stop - sl.start
if cur and cur_n + n > budget:
groups.append(cur)
cur, cur_n = [], 0
cur.append(i)
cur_n += n
if cur:
groups.append(cur)
if len(groups) <= 1:
return super().forward(x)
out_feats = [
super(ChunkedSparseConv3d, self)
.forward(x[torch.as_tensor(g, dtype=torch.long, device=feats.device)])
.feats
for g in groups
]
return x.replace(torch.cat(out_feats, dim=0))
def chunkify_subm_convs(model: torch.nn.Module) -> int:
"""Swap every stride-1 (submanifold) `sp.SparseConv3d` in `model` to `ChunkedSparseConv3d`
in place (only `__class__` changes — no new attributes, weights untouched). Returns the count.
Strided convs (patchify uses a separate `SparseDownsample`, not SparseConv3d) are left alone."""
n = 0
for m in model.modules():
if type(m) is sp.SparseConv3d and isinstance(getattr(m, "conv", None), SubMConv3d):
m.__class__ = ChunkedSparseConv3d
n += 1
return n
|