repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_group/utils.py | pointcept/models/point_group/utils.py | import torch
from torch.autograd import Function
import pointgroup_ops
class BallQueryBatchP(Function):
@staticmethod
def forward(ctx, coords, batch_idxs, batch_offsets, radius, meanActive):
"""
:param ctx:
:param coords: (n, 3) float
:param batch_idxs: (n) int
:param batch_offsets: (B+1) int
:param radius: float
:param meanActive: int
:return: idx (nActive), int
:return: start_len (n, 2), int
"""
n = coords.size(0)
assert coords.is_contiguous() and coords.is_cuda
assert batch_idxs.is_contiguous() and batch_idxs.is_cuda
assert batch_offsets.is_contiguous() and batch_offsets.is_cuda
while True:
idx = torch.cuda.IntTensor(n * meanActive).zero_()
start_len = torch.cuda.IntTensor(n, 2).zero_()
nActive = pointgroup_ops.ballquery_batch_p(
coords, batch_idxs, batch_offsets, idx, start_len, n, meanActive, radius
)
if nActive <= n * meanActive:
break
meanActive = int(nActive // n + 1)
idx = idx[:nActive]
return idx, start_len
@staticmethod
def backward(ctx, a=None, b=None):
return None, None, None
ballquery_batch_p = BallQueryBatchP.apply
class Clustering:
def __init__(
self,
ignored_labels,
class_mapping,
thresh=0.03,
closed_points=300,
min_points=50,
propose_points=100,
score_func=torch.max,
) -> None:
self.ignored_labels = ignored_labels
self.thresh = thresh
self.closed_points = closed_points
self.min_points = min_points
self.class_mapping = class_mapping
self.propose_points = propose_points
self.score_func = score_func
def cluster(self, vertices, scores):
labels = torch.max(scores, 1)[1] # (N) long, cuda
proposals_idx, proposals_offset = self.cluster_(vertices, labels)
## debug
# import ipdb; ipdb.set_trace()
# colors = np.array(create_color_palette())[labels.cpu()]
# write_triangle_mesh(vertices, colors, None, 'semantics.ply')
# scatter
proposals_pred = torch.zeros(
(proposals_offset.shape[0] - 1, vertices.shape[0]), dtype=torch.int
) # (nProposal, N), int, cuda
proposals_pred[proposals_idx[:, 0].long(), proposals_idx[:, 1].long()] = 1
labels = labels[proposals_idx[:, 1][proposals_offset[:-1].long()].long()]
proposals_pointnum = proposals_pred.sum(1)
npoint_mask = proposals_pointnum > self.propose_points
proposals_pred = proposals_pred[npoint_mask]
labels = labels[npoint_mask]
return proposals_pred, labels
def cluster_(self, vertices, labels):
"""
:param batch_idxs: (N), int, cuda
:labels: 0-19
"""
batch_idxs = torch.zeros_like(labels)
mask_non_ignored = torch.ones_like(labels).bool()
for ignored_label in self.ignored_labels:
mask_non_ignored = mask_non_ignored & (
self.class_mapping[labels] != ignored_label
)
object_idxs = mask_non_ignored.nonzero().view(-1)
vertices_ = vertices[object_idxs].float()
labels_ = labels[object_idxs].int()
if vertices_.numel() == 0:
return torch.zeros((0, 2)).int(), torch.zeros(1).int()
batch_idxs_ = batch_idxs[object_idxs].int()
batch_offsets_ = torch.FloatTensor([0, object_idxs.shape[0]]).int().cuda()
idx, start_len = ballquery_batch_p(
vertices_, batch_idxs_, batch_offsets_, self.thresh, self.closed_points
)
proposals_idx, proposals_offset = bfs_cluster(
labels_.cpu(), idx.cpu(), start_len.cpu(), self.min_points
)
proposals_idx[:, 1] = object_idxs[proposals_idx[:, 1].long()].int()
return proposals_idx, proposals_offset
def get_instances(self, vertices, scores):
proposals_pred, labels = self.cluster(vertices, scores)
instances = {}
for proposal_id in range(len(proposals_pred)):
clusters_i = proposals_pred[proposal_id]
score = scores[clusters_i.bool(), labels[proposal_id]]
score = self.score_func(score)
instances[proposal_id] = {}
instances[proposal_id]["conf"] = score.cpu().numpy()
instances[proposal_id]["label_id"] = self.class_mapping.cpu()[
labels[proposal_id]
]
instances[proposal_id]["pred_mask"] = clusters_i.cpu().numpy()
return instances
class BFSCluster(Function):
@staticmethod
def forward(ctx, semantic_label, ball_query_idxs, start_len, threshold):
"""
:param ctx:
:param semantic_label: (N), int
:param ball_query_idxs: (nActive), int
:param start_len: (N, 2), int
:return: cluster_idxs: int (sumNPoint, 2), dim 0 for cluster_id, dim 1 for corresponding point idxs in N
:return: cluster_offsets: int (nCluster + 1)
"""
N = start_len.size(0)
assert semantic_label.is_contiguous()
assert ball_query_idxs.is_contiguous()
assert start_len.is_contiguous()
cluster_idxs = semantic_label.new()
cluster_offsets = semantic_label.new()
pointgroup_ops.bfs_cluster(
semantic_label,
ball_query_idxs,
start_len,
cluster_idxs,
cluster_offsets,
N,
threshold,
)
return cluster_idxs, cluster_offsets
@staticmethod
def backward(ctx, a=None):
return None
bfs_cluster = BFSCluster.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_group/__init__.py | pointcept/models/point_group/__init__.py | from .point_group_v1m1_base import PointGroup
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_group/point_group_v1m1_base.py | pointcept/models/point_group/point_group_v1m1_base.py | """
PointGroup for instance segmentation
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Chengyao Wang
Please cite our work if the code is helpful to you.
"""
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
try:
from pointgroup_ops import ballquery_batch_p, bfs_cluster
except ImportError:
ballquery_batch_p, bfs_cluster = None, None
from pointcept.models.utils import offset2batch, batch2offset
from pointcept.models.builder import MODELS, build_model
@MODELS.register_module("PG-v1m1")
class PointGroup(nn.Module):
def __init__(
self,
backbone,
backbone_out_channels=64,
semantic_num_classes=20,
semantic_ignore_index=-1,
segment_ignore_index=(-1, 0, 1),
instance_ignore_index=-1,
cluster_thresh=1.5,
cluster_closed_points=300,
cluster_propose_points=100,
cluster_min_points=50,
voxel_size=0.02,
):
super().__init__()
norm_fn = partial(nn.BatchNorm1d, eps=1e-3, momentum=0.01)
self.semantic_num_classes = semantic_num_classes
self.segment_ignore_index = segment_ignore_index
self.semantic_ignore_index = semantic_ignore_index
self.instance_ignore_index = instance_ignore_index
self.cluster_thresh = cluster_thresh
self.cluster_closed_points = cluster_closed_points
self.cluster_propose_points = cluster_propose_points
self.cluster_min_points = cluster_min_points
self.voxel_size = voxel_size
self.backbone = build_model(backbone)
self.bias_head = nn.Sequential(
nn.Linear(backbone_out_channels, backbone_out_channels),
norm_fn(backbone_out_channels),
nn.ReLU(),
nn.Linear(backbone_out_channels, 3),
)
self.seg_head = nn.Linear(backbone_out_channels, semantic_num_classes)
self.ce_criteria = torch.nn.CrossEntropyLoss(ignore_index=semantic_ignore_index)
def forward(self, data_dict):
coord = data_dict["coord"]
segment = data_dict["segment"]
instance = data_dict["instance"]
instance_centroid = data_dict["instance_centroid"]
offset = data_dict["offset"]
feat = self.backbone(data_dict)
bias_pred = self.bias_head(feat)
logit_pred = self.seg_head(feat)
# compute loss
seg_loss = self.ce_criteria(logit_pred, segment)
mask = (instance != self.instance_ignore_index).float()
bias_gt = instance_centroid - coord
bias_dist = torch.sum(torch.abs(bias_pred - bias_gt), dim=-1)
bias_l1_loss = torch.sum(bias_dist * mask) / (torch.sum(mask) + 1e-8)
bias_pred_norm = bias_pred / (
torch.norm(bias_pred, p=2, dim=1, keepdim=True) + 1e-8
)
bias_gt_norm = bias_gt / (torch.norm(bias_gt, p=2, dim=1, keepdim=True) + 1e-8)
cosine_similarity = -(bias_pred_norm * bias_gt_norm).sum(-1)
bias_cosine_loss = torch.sum(cosine_similarity * mask) / (
torch.sum(mask) + 1e-8
)
loss = seg_loss + bias_l1_loss + bias_cosine_loss
return_dict = dict(
loss=loss,
seg_loss=seg_loss,
bias_l1_loss=bias_l1_loss,
bias_cosine_loss=bias_cosine_loss,
)
if not self.training:
center_pred = coord + bias_pred
center_pred /= self.voxel_size
logit_pred = F.softmax(logit_pred, dim=-1)
segment_pred = torch.max(logit_pred, 1)[1] # [n]
# cluster
mask = (
~torch.concat(
[
(segment_pred == index).unsqueeze(-1)
for index in self.segment_ignore_index
],
dim=1,
)
.sum(-1)
.bool()
)
if mask.sum() == 0:
proposals_idx = torch.zeros(0).int()
proposals_offset = torch.zeros(1).int()
else:
center_pred_ = center_pred[mask]
segment_pred_ = segment_pred[mask]
batch_ = offset2batch(offset)[mask]
offset_ = nn.ConstantPad1d((1, 0), 0)(batch2offset(batch_))
idx, start_len = ballquery_batch_p(
center_pred_,
batch_.int(),
offset_.int(),
self.cluster_thresh,
self.cluster_closed_points,
)
proposals_idx, proposals_offset = bfs_cluster(
segment_pred_.int().cpu(),
idx.cpu(),
start_len.cpu(),
self.cluster_min_points,
)
proposals_idx[:, 1] = (
mask.nonzero().view(-1)[proposals_idx[:, 1].long()].int()
)
# get proposal
proposals_pred = torch.zeros(
(proposals_offset.shape[0] - 1, center_pred.shape[0]), dtype=torch.int
)
proposals_pred[proposals_idx[:, 0].long(), proposals_idx[:, 1].long()] = 1
instance_pred = segment_pred[
proposals_idx[:, 1][proposals_offset[:-1].long()].long()
]
proposals_point_num = proposals_pred.sum(1)
proposals_mask = proposals_point_num > self.cluster_propose_points
proposals_pred = proposals_pred[proposals_mask]
instance_pred = instance_pred[proposals_mask]
pred_scores = []
pred_classes = []
pred_masks = proposals_pred.detach().cpu()
for proposal_id in range(len(proposals_pred)):
segment_ = proposals_pred[proposal_id]
confidence_ = logit_pred[
segment_.bool(), instance_pred[proposal_id]
].mean()
object_ = instance_pred[proposal_id]
pred_scores.append(confidence_)
pred_classes.append(object_)
if len(pred_scores) > 0:
pred_scores = torch.stack(pred_scores).cpu()
pred_classes = torch.stack(pred_classes).cpu()
else:
pred_scores = torch.tensor([])
pred_classes = torch.tensor([])
return_dict["pred_scores"] = pred_scores
return_dict["pred_masks"] = pred_masks
return_dict["pred_classes"] = pred_classes
return return_dict
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/spvcnn/ts_spvcnn.py | pointcept/models/spvcnn/ts_spvcnn.py | """
SPVCNN
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
import torch.nn as nn
try:
import torchsparse
import torchsparse.nn as spnn
import torchsparse.nn.functional as F
from torchsparse.nn.utils import get_kernel_offsets
from torchsparse import PointTensor, SparseTensor
except ImportError:
torchsparse = None
from pointcept.models.utils import offset2batch
from pointcept.models.builder import MODELS
def initial_voxelize(z):
pc_hash = F.sphash(torch.floor(z.C).int())
sparse_hash = torch.unique(pc_hash)
idx_query = F.sphashquery(pc_hash, sparse_hash)
counts = F.spcount(idx_query.int(), len(sparse_hash))
inserted_coords = F.spvoxelize(torch.floor(z.C), idx_query, counts)
inserted_coords = torch.round(inserted_coords).int()
inserted_feat = F.spvoxelize(z.F, idx_query, counts)
new_tensor = SparseTensor(inserted_feat, inserted_coords, 1)
new_tensor.cmaps.setdefault(new_tensor.stride, new_tensor.coords)
z.additional_features["idx_query"][1] = idx_query
z.additional_features["counts"][1] = counts
return new_tensor
# x: SparseTensor, z: PointTensor
# return: SparseTensor
def point_to_voxel(x, z):
if (
z.additional_features is None
or z.additional_features.get("idx_query") is None
or z.additional_features["idx_query"].get(x.s) is None
):
pc_hash = F.sphash(
torch.cat(
[
torch.floor(z.C[:, :3] / x.s[0]).int() * x.s[0],
z.C[:, -1].int().view(-1, 1),
],
1,
)
)
sparse_hash = F.sphash(x.C)
idx_query = F.sphashquery(pc_hash, sparse_hash)
counts = F.spcount(idx_query.int(), x.C.shape[0])
z.additional_features["idx_query"][x.s] = idx_query
z.additional_features["counts"][x.s] = counts
else:
idx_query = z.additional_features["idx_query"][x.s]
counts = z.additional_features["counts"][x.s]
inserted_feat = F.spvoxelize(z.F, idx_query, counts)
new_tensor = SparseTensor(inserted_feat, x.C, x.s)
new_tensor.cmaps = x.cmaps
new_tensor.kmaps = x.kmaps
return new_tensor
# x: SparseTensor, z: PointTensor
# return: PointTensor
def voxel_to_point(x, z, nearest=False):
if (
z.idx_query is None
or z.weights is None
or z.idx_query.get(x.s) is None
or z.weights.get(x.s) is None
):
off = spnn.utils.get_kernel_offsets(2, x.s, 1, device=z.F.device)
old_hash = F.sphash(
torch.cat(
[
torch.floor(z.C[:, :3] / x.s[0]).int() * x.s[0],
z.C[:, -1].int().view(-1, 1),
],
1,
),
off,
)
pc_hash = F.sphash(x.C.to(z.F.device))
idx_query = F.sphashquery(old_hash, pc_hash)
weights = (
F.calc_ti_weights(z.C, idx_query, scale=x.s[0]).transpose(0, 1).contiguous()
)
idx_query = idx_query.transpose(0, 1).contiguous()
if nearest:
weights[:, 1:] = 0.0
idx_query[:, 1:] = -1
new_feat = F.spdevoxelize(x.F, idx_query, weights)
new_tensor = PointTensor(
new_feat, z.C, idx_query=z.idx_query, weights=z.weights
)
new_tensor.additional_features = z.additional_features
new_tensor.idx_query[x.s] = idx_query
new_tensor.weights[x.s] = weights
z.idx_query[x.s] = idx_query
z.weights[x.s] = weights
else:
new_feat = F.spdevoxelize(x.F, z.idx_query.get(x.s), z.weights.get(x.s))
new_tensor = PointTensor(
new_feat, z.C, idx_query=z.idx_query, weights=z.weights
)
new_tensor.additional_features = z.additional_features
return new_tensor
class BasicConvolutionBlock(nn.Module):
def __init__(self, inc, outc, ks=3, stride=1, dilation=1):
super().__init__()
self.net = nn.Sequential(
spnn.Conv3d(inc, outc, kernel_size=ks, dilation=dilation, stride=stride),
spnn.BatchNorm(outc),
spnn.ReLU(True),
)
def forward(self, x):
out = self.net(x)
return out
class BasicDeconvolutionBlock(nn.Module):
def __init__(self, inc, outc, ks=3, stride=1):
super().__init__()
self.net = nn.Sequential(
spnn.Conv3d(inc, outc, kernel_size=ks, stride=stride, transposed=True),
spnn.BatchNorm(outc),
spnn.ReLU(True),
)
def forward(self, x):
return self.net(x)
class ResidualBlock(nn.Module):
def __init__(self, inc, outc, ks=3, stride=1, dilation=1):
super().__init__()
self.net = nn.Sequential(
spnn.Conv3d(inc, outc, kernel_size=ks, dilation=dilation, stride=stride),
spnn.BatchNorm(outc),
spnn.ReLU(True),
spnn.Conv3d(outc, outc, kernel_size=ks, dilation=dilation, stride=1),
spnn.BatchNorm(outc),
)
if inc == outc and stride == 1:
self.downsample = nn.Identity()
else:
self.downsample = nn.Sequential(
spnn.Conv3d(inc, outc, kernel_size=1, dilation=1, stride=stride),
spnn.BatchNorm(outc),
)
self.relu = spnn.ReLU(True)
def forward(self, x):
out = self.relu(self.net(x) + self.downsample(x))
return out
@MODELS.register_module()
class SPVCNN(nn.Module):
def __init__(
self,
in_channels,
out_channels,
base_channels=32,
channels=(32, 64, 128, 256, 256, 128, 96, 96),
layers=(2, 2, 2, 2, 2, 2, 2, 2),
): # not implement
super().__init__()
assert (
torchsparse is not None
), "Please follow `README.md` to install torchsparse.`"
assert len(layers) % 2 == 0
assert len(layers) == len(channels)
self.in_channels = in_channels
self.out_channels = out_channels
self.base_channels = base_channels
self.channels = channels
self.layers = layers
self.num_stages = len(layers) // 2
self.stem = nn.Sequential(
spnn.Conv3d(in_channels, base_channels, kernel_size=3, stride=1),
spnn.BatchNorm(base_channels),
spnn.ReLU(True),
spnn.Conv3d(base_channels, base_channels, kernel_size=3, stride=1),
spnn.BatchNorm(base_channels),
spnn.ReLU(True),
)
self.stage1 = nn.Sequential(
*[
BasicConvolutionBlock(
base_channels, base_channels, ks=2, stride=2, dilation=1
),
ResidualBlock(base_channels, channels[0], ks=3, stride=1, dilation=1),
]
+ [
ResidualBlock(channels[0], channels[0], ks=3, stride=1, dilation=1)
for _ in range(layers[0] - 1)
]
)
self.stage2 = nn.Sequential(
*[
BasicConvolutionBlock(
channels[0], channels[0], ks=2, stride=2, dilation=1
),
ResidualBlock(channels[0], channels[1], ks=3, stride=1, dilation=1),
]
+ [
ResidualBlock(channels[1], channels[1], ks=3, stride=1, dilation=1)
for _ in range(layers[1] - 1)
]
)
self.stage3 = nn.Sequential(
*[
BasicConvolutionBlock(
channels[1], channels[1], ks=2, stride=2, dilation=1
),
ResidualBlock(channels[1], channels[2], ks=3, stride=1, dilation=1),
]
+ [
ResidualBlock(channels[2], channels[2], ks=3, stride=1, dilation=1)
for _ in range(layers[2] - 1)
]
)
self.stage4 = nn.Sequential(
*[
BasicConvolutionBlock(
channels[2], channels[2], ks=2, stride=2, dilation=1
),
ResidualBlock(channels[2], channels[3], ks=3, stride=1, dilation=1),
]
+ [
ResidualBlock(channels[3], channels[3], ks=3, stride=1, dilation=1)
for _ in range(layers[3] - 1)
]
)
self.up1 = nn.ModuleList(
[
BasicDeconvolutionBlock(channels[3], channels[4], ks=2, stride=2),
nn.Sequential(
*[
ResidualBlock(
channels[4] + channels[2],
channels[4],
ks=3,
stride=1,
dilation=1,
)
]
+ [
ResidualBlock(
channels[4], channels[4], ks=3, stride=1, dilation=1
)
for _ in range(layers[4] - 1)
]
),
]
)
self.up2 = nn.ModuleList(
[
BasicDeconvolutionBlock(channels[4], channels[5], ks=2, stride=2),
nn.Sequential(
*[
ResidualBlock(
channels[5] + channels[1],
channels[5],
ks=3,
stride=1,
dilation=1,
)
]
+ [
ResidualBlock(
channels[5], channels[5], ks=3, stride=1, dilation=1
)
for _ in range(layers[5] - 1)
]
),
]
)
self.up3 = nn.ModuleList(
[
BasicDeconvolutionBlock(channels[5], channels[6], ks=2, stride=2),
nn.Sequential(
*[
ResidualBlock(
channels[6] + channels[0],
channels[6],
ks=3,
stride=1,
dilation=1,
)
]
+ [
ResidualBlock(
channels[6], channels[6], ks=3, stride=1, dilation=1
)
for _ in range(layers[6] - 1)
]
),
]
)
self.up4 = nn.ModuleList(
[
BasicDeconvolutionBlock(channels[6], channels[7], ks=2, stride=2),
nn.Sequential(
*[
ResidualBlock(
channels[7] + base_channels,
channels[7],
ks=3,
stride=1,
dilation=1,
)
]
+ [
ResidualBlock(
channels[7], channels[7], ks=3, stride=1, dilation=1
)
for _ in range(layers[7] - 1)
]
),
]
)
self.classifier = nn.Sequential(nn.Linear(channels[7], out_channels))
self.point_transforms = nn.ModuleList(
[
nn.Sequential(
nn.Linear(base_channels, channels[3]),
nn.BatchNorm1d(channels[3]),
nn.ReLU(True),
),
nn.Sequential(
nn.Linear(channels[3], channels[5]),
nn.BatchNorm1d(channels[5]),
nn.ReLU(True),
),
nn.Sequential(
nn.Linear(channels[5], channels[7]),
nn.BatchNorm1d(channels[7]),
nn.ReLU(True),
),
]
)
self.weight_initialization()
self.dropout = nn.Dropout(0.3, True)
def weight_initialization(self):
for m in self.modules():
if isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, data_dict):
grid_coord = data_dict["grid_coord"]
feat = data_dict["feat"]
offset = data_dict["offset"]
batch = offset2batch(offset)
# x: SparseTensor z: PointTensor
z = PointTensor(
feat,
torch.cat(
[grid_coord.float(), batch.unsqueeze(-1).float()], dim=1
).contiguous(),
)
x0 = initial_voxelize(z)
x0 = self.stem(x0)
z0 = voxel_to_point(x0, z, nearest=False)
z0.F = z0.F
x1 = point_to_voxel(x0, z0)
x1 = self.stage1(x1)
x2 = self.stage2(x1)
x3 = self.stage3(x2)
x4 = self.stage4(x3)
z1 = voxel_to_point(x4, z0)
z1.F = z1.F + self.point_transforms[0](z0.F)
y1 = point_to_voxel(x4, z1)
y1.F = self.dropout(y1.F)
y1 = self.up1[0](y1)
y1 = torchsparse.cat([y1, x3])
y1 = self.up1[1](y1)
y2 = self.up2[0](y1)
y2 = torchsparse.cat([y2, x2])
y2 = self.up2[1](y2)
z2 = voxel_to_point(y2, z1)
z2.F = z2.F + self.point_transforms[1](z1.F)
y3 = point_to_voxel(y2, z2)
y3.F = self.dropout(y3.F)
y3 = self.up3[0](y3)
y3 = torchsparse.cat([y3, x1])
y3 = self.up3[1](y3)
y4 = self.up4[0](y3)
y4 = torchsparse.cat([y4, x0])
y4 = self.up4[1](y4)
z3 = voxel_to_point(y4, z2)
z3.F = z3.F + self.point_transforms[2](z2.F)
out = self.classifier(z3.F)
return out
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/spvcnn/__init__.py | pointcept/models/spvcnn/__init__.py | from .ts_spvcnn import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/masked_scene_contrast/masked_scene_contrast_v1m2_csc.py | pointcept/models/masked_scene_contrast/masked_scene_contrast_v1m2_csc.py | """
Masked Scene Contrast v1m2
contrastive learning backend with CSC (https://arxiv.org/abs/2012.09165)
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com), Chengyao Wang (cywang22@cse.cuhk.edu.hk)
Please cite our work if the code is helpful to you.
"""
import random
from itertools import chain
import torch
import torch.nn as nn
import torch.distributed as dist
from torch_geometric.nn.pool import voxel_grid
from timm.models.layers import trunc_normal_
import pointops
from pointcept.models.builder import MODELS, build_model
from pointcept.models.utils import offset2batch
from pointcept.utils.comm import get_world_size
@MODELS.register_module("MSC-v1m2")
class MaskedSceneContrast(nn.Module):
def __init__(
self,
backbone,
backbone_in_channels,
backbone_out_channels,
mask_grid_size=0.1,
mask_rate=0.4,
view1_mix_prob=0,
view2_mix_prob=0,
matching_max_k=8,
matching_max_radius=0.03,
matching_max_pair=8192,
nce_t=0.4,
contrast_weight=1,
reconstruct_weight=1,
reconstruct_color=True,
reconstruct_normal=True,
partitions=4,
r1=0.125,
r2=2,
):
super().__init__()
self.backbone = build_model(backbone)
self.mask_grid_size = mask_grid_size
self.mask_rate = mask_rate
self.view1_mix_prob = view1_mix_prob
self.view2_mix_prob = view2_mix_prob
self.matching_max_k = matching_max_k
self.matching_max_radius = matching_max_radius
self.matching_max_pair = matching_max_pair
self.nce_t = nce_t
self.contrast_weight = contrast_weight
self.reconstruct_weight = reconstruct_weight
self.reconstruct_color = reconstruct_color
self.reconstruct_normal = reconstruct_normal
# csc partition
self.partitions = partitions
self.r1 = r1
self.r2 = r2
self.mask_token = nn.Parameter(torch.zeros(1, backbone_in_channels))
trunc_normal_(self.mask_token, mean=0.0, std=0.02)
self.color_head = (
nn.Linear(backbone_out_channels, 3) if reconstruct_color else None
)
self.normal_head = (
nn.Linear(backbone_out_channels, 3) if reconstruct_normal else None
)
self.nce_criteria = torch.nn.CrossEntropyLoss(reduction="mean")
@torch.no_grad()
def generate_cross_masks(
self, view1_origin_coord, view1_offset, view2_origin_coord, view2_offset
):
# union origin coord
view1_batch = offset2batch(view1_offset)
view2_batch = offset2batch(view2_offset)
view1_batch_count = view1_batch.bincount()
view2_batch_count = view2_batch.bincount()
view1_origin_coord_split = view1_origin_coord.split(list(view1_batch_count))
view2_origin_coord_split = view2_origin_coord.split(list(view2_batch_count))
union_origin_coord = torch.cat(
list(
chain.from_iterable(
zip(view1_origin_coord_split, view2_origin_coord_split)
)
)
)
union_offset = torch.cat(
[view1_offset.unsqueeze(-1), view2_offset.unsqueeze(-1)], dim=-1
).sum(-1)
union_batch = offset2batch(union_offset)
# grid partition
mask_patch_coord = union_origin_coord.div(self.mask_grid_size)
mask_patch_grid_coord = torch.floor(mask_patch_coord)
mask_patch_cluster = voxel_grid(
pos=mask_patch_grid_coord, size=1, batch=union_batch, start=0
)
unique, cluster, counts = torch.unique(
mask_patch_cluster, sorted=True, return_inverse=True, return_counts=True
)
patch_num = unique.shape[0]
patch_max_point = counts.max().item()
patch2point_map = cluster.new_zeros(patch_num, patch_max_point)
patch2point_mask = torch.lt(
torch.arange(patch_max_point).cuda().unsqueeze(0), counts.unsqueeze(-1)
)
sorted_cluster_value, sorted_cluster_indices = torch.sort(cluster)
patch2point_map[patch2point_mask] = sorted_cluster_indices
# generate cross masks
assert self.mask_rate <= 0.5
patch_mask = torch.zeros(patch_num, device=union_origin_coord.device).int()
rand_perm = torch.randperm(patch_num)
mask_patch_num = int(patch_num * self.mask_rate)
# mask1 tag with 1, mask2 tag with 2
patch_mask[rand_perm[0:mask_patch_num]] = 1
patch_mask[rand_perm[mask_patch_num : mask_patch_num * 2]] = 2
point_mask = torch.zeros(
union_origin_coord.shape[0], device=union_origin_coord.device
).int()
point_mask[
patch2point_map[patch_mask == 1][patch2point_mask[patch_mask == 1]]
] = 1
point_mask[
patch2point_map[patch_mask == 2][patch2point_mask[patch_mask == 2]]
] = 2
# separate mask to view1 and view2
point_mask_split = point_mask.split(
list(
torch.cat(
[view1_batch_count.unsqueeze(-1), view2_batch_count.unsqueeze(-1)],
dim=-1,
).flatten()
)
)
view1_point_mask = torch.cat(point_mask_split[0::2]) == 1
view2_point_mask = torch.cat(point_mask_split[1::2]) == 2
return view1_point_mask, view2_point_mask
@torch.no_grad()
def match_contrastive_pair(
self, view1_coord, view1_offset, view2_coord, view2_offset, max_k, max_radius
):
index, distance = pointops.knn_query(
max_k,
view2_coord.float(),
view2_offset.int(),
view1_coord.float(),
view1_offset.int(),
)
index = torch.cat(
[
torch.arange(index.shape[0], device=index.device, dtype=torch.long)
.view(-1, 1, 1)
.expand(-1, max_k, 1),
index.view(-1, max_k, 1),
],
dim=-1,
)[distance.squeeze(-1) < max_radius]
unique, count = index[:, 0].unique(return_counts=True)
select = (
torch.cumsum(count, dim=0)
- torch.randint(count.max(), count.shape, device=count.device) % count
- 1
)
index = index[select]
if index.shape[0] > self.matching_max_pair:
index = index[torch.randperm(index.shape[0])[: self.matching_max_pair]]
return index
def compute_partitions(self, coord1, coord2):
partition_matrix = torch.zeros((coord1.shape[0], coord2.shape[0]))
partition_matrix = partition_matrix.cuda() - 1e7
rel_trans = coord1.unsqueeze(0) - coord2.unsqueeze(1)
mask_up = rel_trans[:, :, 2] > 0.0
mask_down = rel_trans[:, :, 2] < 0.0
distance_matrix = torch.sqrt(torch.sum(rel_trans.pow(2), 2).add(1e-7))
mask = (distance_matrix[:, :] > self.r1) & (distance_matrix[:, :] <= self.r2)
partition_matrix[mask & mask_up] = 0
partition_matrix[mask & mask_down] = 1
mask = distance_matrix[:, :] > self.r2
partition_matrix[mask & mask_up] = 2
partition_matrix[mask & mask_down] = 3
return partition_matrix
def compute_contrastive_loss(
self,
view1_feat,
view1_coord,
view1_offset,
view2_feat,
view2_coord,
view2_offset,
match_index,
):
assert view1_offset.shape == view2_offset.shape
device = view1_feat.device
loss = torch.tensor(0.0, device=device)
pos_sim = torch.tensor(0.0, device=device)
neg_sim = torch.tensor(0.0, device=device)
large_num = 1e9
view1_feat = view1_feat[match_index[:, 0]]
view2_feat = view2_feat[match_index[:, 1]]
view1_feat = view1_feat / (
torch.norm(view1_feat, p=2, dim=1, keepdim=True) + 1e-7
)
view2_feat = view2_feat / (
torch.norm(view2_feat, p=2, dim=1, keepdim=True) + 1e-7
)
view1_coord = view1_coord[match_index[:, 0]]
view2_coord = view2_coord[match_index[:, 1]]
batch = offset2batch(view1_offset)[match_index[:, 0]]
for batch_id in batch.unique():
batch_mask = batch == batch_id
sim = torch.mm(view1_feat[batch_mask], view2_feat[batch_mask].T)
with torch.no_grad():
pos_sim += torch.diagonal(sim).mean()
neg_sim += sim.mean(dim=-1).mean() - pos_sim / batch_mask.sum()
labels = torch.arange(sim.shape[0], device=view1_feat.device).long()
part = self.compute_partitions(
view1_coord[batch_mask], view2_coord[batch_mask]
)
for part_id in part.unique():
part_mask = part == part_id
part_mask.fill_diagonal_(True)
loss += self.nce_criteria(
torch.div(sim, self.nce_t) - large_num * (~part_mask).float(),
labels,
)
loss /= len(view1_offset) * self.partitions
pos_sim /= len(view1_offset)
neg_sim /= len(view1_offset)
if get_world_size() > 1:
dist.all_reduce(loss)
dist.all_reduce(pos_sim)
dist.all_reduce(neg_sim)
return (
loss / get_world_size(),
pos_sim / get_world_size(),
neg_sim / get_world_size(),
)
def forward(self, data_dict):
view1_origin_coord = data_dict["view1_origin_coord"]
view1_coord = data_dict["view1_coord"]
view1_feat = data_dict["view1_feat"]
view1_offset = data_dict["view1_offset"].int()
view2_origin_coord = data_dict["view2_origin_coord"]
view2_coord = data_dict["view2_coord"]
view2_feat = data_dict["view2_feat"]
view2_offset = data_dict["view2_offset"].int()
# mask generation by union original coord (without spatial augmentation)
view1_point_mask, view2_point_mask = self.generate_cross_masks(
view1_origin_coord, view1_offset, view2_origin_coord, view2_offset
)
view1_mask_tokens = self.mask_token.expand(view1_coord.shape[0], -1)
view1_weight = view1_point_mask.unsqueeze(-1).type_as(view1_mask_tokens)
view1_feat = view1_feat * (1 - view1_weight) + view1_mask_tokens * view1_weight
view2_mask_tokens = self.mask_token.expand(view2_coord.shape[0], -1)
view2_weight = view2_point_mask.unsqueeze(-1).type_as(view2_mask_tokens)
view2_feat = view2_feat * (1 - view2_weight) + view2_mask_tokens * view2_weight
view1_data_dict = dict(
origin_coord=view1_origin_coord,
coord=view1_coord,
feat=view1_feat,
offset=view1_offset,
)
view2_data_dict = dict(
origin_coord=view2_origin_coord,
coord=view2_coord,
feat=view2_feat,
offset=view2_offset,
)
# SparseConv based method need grid coord
if "view1_grid_coord" in data_dict.keys():
view1_data_dict["grid_coord"] = data_dict["view1_grid_coord"]
if "view2_grid_coord" in data_dict.keys():
view2_data_dict["grid_coord"] = data_dict["view2_grid_coord"]
# view mixing strategy
if random.random() < self.view1_mix_prob:
view1_data_dict["offset"] = torch.cat(
[view1_offset[1:-1:2], view1_offset[-1].unsqueeze(0)], dim=0
)
if random.random() < self.view2_mix_prob:
view2_data_dict["offset"] = torch.cat(
[view2_offset[1:-1:2], view2_offset[-1].unsqueeze(0)], dim=0
)
view1_feat = self.backbone(view1_data_dict)
view2_feat = self.backbone(view2_data_dict)
match_index = self.match_contrastive_pair(
view1_origin_coord,
view1_offset,
view2_origin_coord,
view2_offset,
max_k=self.matching_max_k,
max_radius=self.matching_max_radius,
)
nce_loss, pos_sim, neg_sim = self.compute_contrastive_loss(
view1_feat,
view1_origin_coord,
view1_offset,
view2_feat,
view2_origin_coord,
view2_offset,
match_index,
)
loss = nce_loss * self.contrast_weight
result_dict = dict(nce_loss=nce_loss, pos_sim=pos_sim, neg_sim=neg_sim)
if self.color_head is not None:
assert "view1_color" in data_dict.keys()
assert "view2_color" in data_dict.keys()
view1_color = data_dict["view1_color"]
view2_color = data_dict["view2_color"]
view1_color_pred = self.color_head(view1_feat[view1_point_mask])
view2_color_pred = self.color_head(view2_feat[view2_point_mask])
color_loss = (
torch.sum((view1_color_pred - view1_color[view1_point_mask]) ** 2)
+ torch.sum((view2_color_pred - view2_color[view2_point_mask]) ** 2)
) / (view1_color_pred.shape[0] + view2_color_pred.shape[0])
loss = loss + color_loss * self.reconstruct_weight
result_dict["color_loss"] = color_loss
if self.normal_head is not None:
assert "view1_normal" in data_dict.keys()
assert "view2_normal" in data_dict.keys()
view1_normal = data_dict["view1_normal"]
view2_normal = data_dict["view2_normal"]
view1_normal_pred = self.normal_head(view1_feat[view1_point_mask])
view2_normal_pred = self.normal_head(view2_feat[view2_point_mask])
view1_normal_pred = view1_normal_pred / (
torch.norm(view1_normal_pred, p=2, dim=1, keepdim=True) + 1e-10
)
view2_normal_pred = view2_normal_pred / (
torch.norm(view2_normal_pred, p=2, dim=1, keepdim=True) + 1e-10
)
normal_loss = (
torch.sum(view1_normal_pred * view1_normal[view1_point_mask])
+ torch.sum(view2_normal_pred * view2_normal[view2_point_mask])
) / (view1_normal_pred.shape[0] + view2_normal_pred.shape[0])
loss = loss + normal_loss * self.reconstruct_weight
result_dict["normal_loss"] = normal_loss
result_dict["loss"] = loss
return result_dict
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/masked_scene_contrast/__init__.py | pointcept/models/masked_scene_contrast/__init__.py | from .masked_scene_contrast_v1m1_base import MaskedSceneContrast
from .masked_scene_contrast_v1m2_csc import MaskedSceneContrast
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/masked_scene_contrast/masked_scene_contrast_v1m1_base.py | pointcept/models/masked_scene_contrast/masked_scene_contrast_v1m1_base.py | """
Masked Scene Contrast
https://arxiv.org/abs/2303.14191
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import random
from itertools import chain
import torch
import torch.nn as nn
import torch.distributed as dist
from torch_geometric.nn.pool import voxel_grid
from timm.models.layers import trunc_normal_
import pointops
from pointcept.models.builder import MODELS, build_model
from pointcept.models.utils import offset2batch
from pointcept.utils.comm import get_world_size
@MODELS.register_module("MSC-v1m1")
class MaskedSceneContrast(nn.Module):
def __init__(
self,
backbone,
backbone_in_channels,
backbone_out_channels,
mask_grid_size=0.1,
mask_rate=0.4,
view1_mix_prob=0,
view2_mix_prob=0,
matching_max_k=8,
matching_max_radius=0.03,
matching_max_pair=8192,
nce_t=0.4,
contrast_weight=1,
reconstruct_weight=1,
reconstruct_color=True,
reconstruct_normal=True,
):
super().__init__()
self.backbone = build_model(backbone)
self.mask_grid_size = mask_grid_size
self.mask_rate = mask_rate
self.view1_mix_prob = view1_mix_prob
self.view2_mix_prob = view2_mix_prob
self.matching_max_k = matching_max_k
self.matching_max_radius = matching_max_radius
self.matching_max_pair = matching_max_pair
self.nce_t = nce_t
self.contrast_weight = contrast_weight
self.reconstruct_weight = reconstruct_weight
self.reconstruct_color = reconstruct_color
self.reconstruct_normal = reconstruct_normal
self.mask_token = nn.Parameter(torch.zeros(1, backbone_in_channels))
trunc_normal_(self.mask_token, mean=0.0, std=0.02)
self.color_head = (
nn.Linear(backbone_out_channels, 3) if reconstruct_color else None
)
self.normal_head = (
nn.Linear(backbone_out_channels, 3) if reconstruct_normal else None
)
self.nce_criteria = torch.nn.CrossEntropyLoss(reduction="mean")
@torch.no_grad()
def generate_cross_masks(
self, view1_origin_coord, view1_offset, view2_origin_coord, view2_offset
):
# union origin coord
view1_batch = offset2batch(view1_offset)
view2_batch = offset2batch(view2_offset)
view1_batch_count = view1_batch.bincount()
view2_batch_count = view2_batch.bincount()
view1_origin_coord_split = view1_origin_coord.split(list(view1_batch_count))
view2_origin_coord_split = view2_origin_coord.split(list(view2_batch_count))
union_origin_coord = torch.cat(
list(
chain.from_iterable(
zip(view1_origin_coord_split, view2_origin_coord_split)
)
)
)
union_offset = torch.cat(
[view1_offset.unsqueeze(-1), view2_offset.unsqueeze(-1)], dim=-1
).sum(-1)
union_batch = offset2batch(union_offset)
# grid partition
mask_patch_coord = union_origin_coord.div(self.mask_grid_size)
mask_patch_grid_coord = torch.floor(mask_patch_coord)
mask_patch_cluster = voxel_grid(
pos=mask_patch_grid_coord, size=1, batch=union_batch, start=0
)
unique, cluster, counts = torch.unique(
mask_patch_cluster, sorted=True, return_inverse=True, return_counts=True
)
patch_num = unique.shape[0]
patch_max_point = counts.max().item()
patch2point_map = cluster.new_zeros(patch_num, patch_max_point)
patch2point_mask = torch.lt(
torch.arange(patch_max_point).cuda().unsqueeze(0), counts.unsqueeze(-1)
)
sorted_cluster_value, sorted_cluster_indices = torch.sort(cluster)
patch2point_map[patch2point_mask] = sorted_cluster_indices
# generate cross masks
assert self.mask_rate <= 0.5
patch_mask = torch.zeros(patch_num, device=union_origin_coord.device).int()
rand_perm = torch.randperm(patch_num)
mask_patch_num = int(patch_num * self.mask_rate)
# mask1 tag with 1, mask2 tag with 2
patch_mask[rand_perm[0:mask_patch_num]] = 1
patch_mask[rand_perm[mask_patch_num : mask_patch_num * 2]] = 2
point_mask = torch.zeros(
union_origin_coord.shape[0], device=union_origin_coord.device
).int()
point_mask[
patch2point_map[patch_mask == 1][patch2point_mask[patch_mask == 1]]
] = 1
point_mask[
patch2point_map[patch_mask == 2][patch2point_mask[patch_mask == 2]]
] = 2
# separate mask to view1 and view2
point_mask_split = point_mask.split(
list(
torch.cat(
[view1_batch_count.unsqueeze(-1), view2_batch_count.unsqueeze(-1)],
dim=-1,
).flatten()
)
)
view1_point_mask = torch.cat(point_mask_split[0::2]) == 1
view2_point_mask = torch.cat(point_mask_split[1::2]) == 2
return view1_point_mask, view2_point_mask
@torch.no_grad()
def match_contrastive_pair(
self, view1_coord, view1_offset, view2_coord, view2_offset, max_k, max_radius
):
index, distance = pointops.knn_query(
max_k,
view2_coord.float(),
view2_offset.int(),
view1_coord.float(),
view1_offset.int(),
)
index = torch.cat(
[
torch.arange(index.shape[0], device=index.device, dtype=torch.long)
.view(-1, 1, 1)
.expand(-1, max_k, 1),
index.view(-1, max_k, 1),
],
dim=-1,
)[distance.squeeze(-1) < max_radius]
unique, count = index[:, 0].unique(return_counts=True)
select = (
torch.cumsum(count, dim=0)
- torch.randint(count.max(), count.shape, device=count.device) % count
- 1
)
index = index[select]
if index.shape[0] > self.matching_max_pair:
index = index[torch.randperm(index.shape[0])[: self.matching_max_pair]]
return index
def compute_contrastive_loss(
self, view1_feat, view1_offset, view2_feat, view2_offset, match_index
):
assert view1_offset.shape == view2_offset.shape
view1_feat = view1_feat[match_index[:, 0]]
view2_feat = view2_feat[match_index[:, 1]]
view1_feat = view1_feat / (
torch.norm(view1_feat, p=2, dim=1, keepdim=True) + 1e-7
)
view2_feat = view2_feat / (
torch.norm(view2_feat, p=2, dim=1, keepdim=True) + 1e-7
)
sim = torch.mm(view1_feat, view2_feat.transpose(1, 0))
with torch.no_grad():
pos_sim = torch.diagonal(sim).mean()
neg_sim = sim.mean(dim=-1).mean() - pos_sim / match_index.shape[0]
labels = torch.arange(sim.shape[0], device=view1_feat.device).long()
loss = self.nce_criteria(torch.div(sim, self.nce_t), labels)
if get_world_size() > 1:
dist.all_reduce(loss)
dist.all_reduce(pos_sim)
dist.all_reduce(neg_sim)
return (
loss / get_world_size(),
pos_sim / get_world_size(),
neg_sim / get_world_size(),
)
def forward(self, data_dict):
view1_origin_coord = data_dict["view1_origin_coord"]
view1_coord = data_dict["view1_coord"]
view1_feat = data_dict["view1_feat"]
view1_offset = data_dict["view1_offset"].int()
view2_origin_coord = data_dict["view2_origin_coord"]
view2_coord = data_dict["view2_coord"]
view2_feat = data_dict["view2_feat"]
view2_offset = data_dict["view2_offset"].int()
# mask generation by union original coord (without spatial augmentation)
view1_point_mask, view2_point_mask = self.generate_cross_masks(
view1_origin_coord, view1_offset, view2_origin_coord, view2_offset
)
view1_mask_tokens = self.mask_token.expand(view1_coord.shape[0], -1)
view1_weight = view1_point_mask.unsqueeze(-1).type_as(view1_mask_tokens)
view1_feat = view1_feat * (1 - view1_weight) + view1_mask_tokens * view1_weight
view2_mask_tokens = self.mask_token.expand(view2_coord.shape[0], -1)
view2_weight = view2_point_mask.unsqueeze(-1).type_as(view2_mask_tokens)
view2_feat = view2_feat * (1 - view2_weight) + view2_mask_tokens * view2_weight
view1_data_dict = dict(
origin_coord=view1_origin_coord,
coord=view1_coord,
feat=view1_feat,
offset=view1_offset,
)
view2_data_dict = dict(
origin_coord=view2_origin_coord,
coord=view2_coord,
feat=view2_feat,
offset=view2_offset,
)
# SparseConv based method need grid coord
if "view1_grid_coord" in data_dict.keys():
view1_data_dict["grid_coord"] = data_dict["view1_grid_coord"]
if "view2_grid_coord" in data_dict.keys():
view2_data_dict["grid_coord"] = data_dict["view2_grid_coord"]
# view mixing strategy
if random.random() < self.view1_mix_prob:
view1_data_dict["offset"] = torch.cat(
[view1_offset[1:-1:2], view1_offset[-1].unsqueeze(0)], dim=0
)
if random.random() < self.view2_mix_prob:
view2_data_dict["offset"] = torch.cat(
[view2_offset[1:-1:2], view2_offset[-1].unsqueeze(0)], dim=0
)
view1_feat = self.backbone(view1_data_dict)
view2_feat = self.backbone(view2_data_dict)
match_index = self.match_contrastive_pair(
view1_origin_coord,
view1_offset,
view2_origin_coord,
view2_offset,
max_k=self.matching_max_k,
max_radius=self.matching_max_radius,
)
nce_loss, pos_sim, neg_sim = self.compute_contrastive_loss(
view1_feat, view1_offset, view2_feat, view2_offset, match_index
)
loss = nce_loss * self.contrast_weight
result_dict = dict(nce_loss=nce_loss, pos_sim=pos_sim, neg_sim=neg_sim)
if self.color_head is not None:
assert "view1_color" in data_dict.keys()
assert "view2_color" in data_dict.keys()
view1_color = data_dict["view1_color"]
view2_color = data_dict["view2_color"]
view1_color_pred = self.color_head(view1_feat[view1_point_mask])
view2_color_pred = self.color_head(view2_feat[view2_point_mask])
color_loss = (
torch.sum((view1_color_pred - view1_color[view1_point_mask]) ** 2)
+ torch.sum((view2_color_pred - view2_color[view2_point_mask]) ** 2)
) / (view1_color_pred.shape[0] + view2_color_pred.shape[0])
loss = loss + color_loss * self.reconstruct_weight
result_dict["color_loss"] = color_loss
if self.normal_head is not None:
assert "view1_normal" in data_dict.keys()
assert "view2_normal" in data_dict.keys()
view1_normal = data_dict["view1_normal"]
view2_normal = data_dict["view2_normal"]
view1_normal_pred = self.normal_head(view1_feat[view1_point_mask])
view2_normal_pred = self.normal_head(view2_feat[view2_point_mask])
view1_normal_pred = view1_normal_pred / (
torch.norm(view1_normal_pred, p=2, dim=1, keepdim=True) + 1e-10
)
view2_normal_pred = view2_normal_pred / (
torch.norm(view2_normal_pred, p=2, dim=1, keepdim=True) + 1e-10
)
normal_loss = (
torch.sum(view1_normal_pred * view1_normal[view1_point_mask])
+ torch.sum(view2_normal_pred * view2_normal[view2_point_mask])
) / (view1_normal_pred.shape[0] + view2_normal_pred.shape[0])
loss = loss + normal_loss * self.reconstruct_weight
result_dict["normal_loss"] = normal_loss
result_dict["loss"] = loss
return result_dict
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v2/point_transformer_v2m3_pdnorm.py | pointcept/models/point_transformer_v2/point_transformer_v2m3_pdnorm.py | """
Point Transformer V2M3
Enable Prompt-Driven Normalization for Point Prompt Training
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from functools import partial
from copy import deepcopy
import math
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from torch_geometric.nn.pool import voxel_grid
from torch_scatter import segment_csr
import einops
from timm.models.layers import DropPath
import pointops
from pointcept.models.builder import MODELS
from pointcept.models.utils import offset2batch, batch2offset
class PDBatchNorm(torch.nn.Module):
def __init__(
self,
num_features,
context_channels=256,
eps=1e-3,
momentum=0.01,
conditions=("ScanNet", "S3DIS", "Structured3D"),
decouple=True,
adaptive=False,
affine=True,
):
super().__init__()
self.conditions = conditions
self.decouple = decouple
self.adaptive = adaptive
self.affine = affine
if self.decouple:
self.bns = nn.ModuleList(
[
nn.BatchNorm1d(
num_features=num_features,
eps=eps,
momentum=momentum,
affine=affine,
)
for _ in conditions
]
)
else:
self.bn = nn.BatchNorm1d(
num_features=num_features, eps=eps, momentum=momentum, affine=affine
)
if self.adaptive:
self.modulation = nn.Sequential(
nn.SiLU(), nn.Linear(context_channels, 2 * num_features, bias=True)
)
def forward(self, feat, condition=None, context=None):
if self.decouple:
assert condition in self.conditions
bn = self.bns[self.conditions.index(condition)]
else:
bn = self.bn
feat = bn(feat)
if self.adaptive:
assert context is not None
shift, scale = self.modulation(context).chunk(2, dim=1)
feat = feat * (1.0 + scale) + shift
return feat
class PointBatchNorm(nn.Module):
"""
Batch Normalization for Point Clouds data in shape of [B*N, C], [B*N, L, C]
"""
def __init__(self, embed_channels):
super().__init__()
self.norm = nn.BatchNorm1d(embed_channels)
def forward(self, input: torch.Tensor) -> torch.Tensor:
if input.dim() == 3:
return (
self.norm(input.transpose(1, 2).contiguous())
.transpose(1, 2)
.contiguous()
)
elif input.dim() == 2:
return self.norm(input)
else:
raise NotImplementedError
class GroupedVectorAttention(nn.Module):
def __init__(
self,
embed_channels,
groups,
attn_drop_rate=0.0,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
):
super(GroupedVectorAttention, self).__init__()
self.embed_channels = embed_channels
self.groups = groups
assert embed_channels % groups == 0
self.attn_drop_rate = attn_drop_rate
self.qkv_bias = qkv_bias
self.pe_multiplier = pe_multiplier
self.pe_bias = pe_bias
self.linear_q = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_k = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_v = nn.Linear(embed_channels, embed_channels, bias=qkv_bias)
if self.pe_multiplier:
self.linear_p_multiplier = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
if self.pe_bias:
self.linear_p_bias = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
self.weight_encoding = nn.Sequential(
nn.Linear(embed_channels, groups),
PointBatchNorm(groups),
nn.ReLU(inplace=True),
nn.Linear(groups, groups),
)
self.softmax = nn.Softmax(dim=1)
self.attn_drop = nn.Dropout(attn_drop_rate)
def forward(self, feat, coord, reference_index):
query, key, value = (
self.linear_q(feat),
self.linear_k(feat),
self.linear_v(feat),
)
key = pointops.grouping(reference_index, key, coord, with_xyz=True)
value = pointops.grouping(reference_index, value, coord, with_xyz=False)
pos, key = key[:, :, 0:3], key[:, :, 3:]
relation_qk = key - query.unsqueeze(1)
if self.pe_multiplier:
pem = self.linear_p_multiplier(pos)
relation_qk = relation_qk * pem
if self.pe_bias:
peb = self.linear_p_bias(pos)
relation_qk = relation_qk + peb
value = value + peb
weight = self.weight_encoding(relation_qk)
weight = self.attn_drop(self.softmax(weight))
mask = torch.sign(reference_index + 1)
weight = torch.einsum("n s g, n s -> n s g", weight, mask)
value = einops.rearrange(value, "n ns (g i) -> n ns g i", g=self.groups)
feat = torch.einsum("n s g i, n s g -> n g i", value, weight)
feat = einops.rearrange(feat, "n g i -> n (g i)")
return feat
class Block(nn.Module):
def __init__(
self,
embed_channels,
groups,
norm_fn=None,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(Block, self).__init__()
self.attn = GroupedVectorAttention(
embed_channels=embed_channels,
groups=groups,
qkv_bias=qkv_bias,
attn_drop_rate=attn_drop_rate,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
)
assert norm_fn is not None
self.fc1 = nn.Linear(embed_channels, embed_channels, bias=False)
self.fc3 = nn.Linear(embed_channels, embed_channels, bias=False)
self.norm1 = norm_fn(embed_channels)
self.norm2 = norm_fn(embed_channels)
self.norm3 = norm_fn(embed_channels)
self.act = nn.ReLU(inplace=True)
self.enable_checkpoint = enable_checkpoint
self.drop_path = (
DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
)
def forward(self, points, reference_index):
coord, feat, offset, condition, context = points
identity = feat
feat = self.act(self.norm1(self.fc1(feat), condition, context))
feat = (
self.attn(feat, coord, reference_index)
if not self.enable_checkpoint
else checkpoint(self.attn, feat, coord, reference_index)
)
feat = self.act(self.norm2(feat, condition, context))
feat = self.norm3(self.fc3(feat), condition, context)
feat = identity + self.drop_path(feat)
feat = self.act(feat)
return [coord, feat, offset, condition, context]
class BlockSequence(nn.Module):
def __init__(
self,
depth,
embed_channels,
groups,
neighbours=16,
norm_fn=None,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(BlockSequence, self).__init__()
if isinstance(drop_path_rate, list):
drop_path_rates = drop_path_rate
assert len(drop_path_rates) == depth
elif isinstance(drop_path_rate, float):
drop_path_rates = [deepcopy(drop_path_rate) for _ in range(depth)]
else:
drop_path_rates = [0.0 for _ in range(depth)]
self.neighbours = neighbours
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
embed_channels=embed_channels,
groups=groups,
norm_fn=norm_fn,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rates[i],
enable_checkpoint=enable_checkpoint,
)
self.blocks.append(block)
def forward(self, points):
coord, feat, offset, condition, context = points
# reference index query of neighbourhood attention
# for windows attention, modify reference index query method
reference_index, _ = pointops.knn_query(self.neighbours, coord, offset)
for block in self.blocks:
points = block(points, reference_index)
return points
class GridPool(nn.Module):
"""
Partition-based Pooling (Grid Pooling)
"""
def __init__(self, in_channels, out_channels, grid_size, norm_fn, bias=False):
super(GridPool, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.grid_size = grid_size
self.fc = nn.Linear(in_channels, out_channels, bias=bias)
self.norm = norm_fn(out_channels)
self.act = nn.ReLU(inplace=True)
def forward(self, points, start=None):
coord, feat, offset, condition, context = points
batch = offset2batch(offset)
feat = self.act(self.norm(self.fc(feat), condition, context))
start = (
segment_csr(
coord,
torch.cat([batch.new_zeros(1), torch.cumsum(batch.bincount(), dim=0)]),
reduce="min",
)
if start is None
else start
)
cluster = voxel_grid(
pos=coord - start[batch], size=self.grid_size, batch=batch, start=0
)
unique, cluster, counts = torch.unique(
cluster, sorted=True, return_inverse=True, return_counts=True
)
_, sorted_cluster_indices = torch.sort(cluster)
idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
coord = segment_csr(coord[sorted_cluster_indices], idx_ptr, reduce="mean")
feat = segment_csr(feat[sorted_cluster_indices], idx_ptr, reduce="max")
batch = batch[idx_ptr[:-1]]
offset = batch2offset(batch)
return [coord, feat, offset, condition, context], cluster
class UnpoolWithSkip(nn.Module):
"""
Map Unpooling with skip connection
"""
def __init__(
self,
in_channels,
skip_channels,
out_channels,
norm_fn,
bias=True,
skip=True,
backend="map",
):
super(UnpoolWithSkip, self).__init__()
self.in_channels = in_channels
self.skip_channels = skip_channels
self.out_channels = out_channels
self.skip = skip
self.backend = backend
assert self.backend in ["map", "interp"]
self.proj_linear = nn.Linear(in_channels, out_channels, bias=bias)
self.proj_norm = norm_fn(out_channels)
self.proj_act = nn.ReLU(inplace=True)
self.proj_skip_linear = nn.Linear(skip_channels, out_channels, bias=bias)
self.proj_skip_norm = norm_fn(out_channels)
self.proj_skip_act = nn.ReLU(inplace=True)
def forward(self, points, skip_points, cluster=None):
coord, feat, offset, condition, context = points
skip_coord, skip_feat, skip_offset, _, _ = skip_points
feat = self.proj_act(self.proj_norm(self.proj_linear(feat), condition, context))
if self.backend == "map" and cluster is not None:
feat = feat[cluster]
else:
feat = pointops.interpolation(coord, skip_coord, feat, offset, skip_offset)
if self.skip:
feat = feat + self.proj_skip_act(
self.proj_skip_norm(
self.proj_skip_linear(skip_feat), condition, context
)
)
return [skip_coord, feat, skip_offset, condition, context]
class Encoder(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
norm_fn,
grid_size=None,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
):
super(Encoder, self).__init__()
self.down = GridPool(
in_channels=in_channels,
out_channels=embed_channels,
grid_size=grid_size,
norm_fn=norm_fn,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
norm_fn=norm_fn,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
points, cluster = self.down(points)
return self.blocks(points), cluster
class Decoder(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
embed_channels,
groups,
depth,
norm_fn,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
unpool_backend="map",
):
super(Decoder, self).__init__()
self.up = UnpoolWithSkip(
in_channels=in_channels,
out_channels=embed_channels,
skip_channels=skip_channels,
backend=unpool_backend,
norm_fn=norm_fn,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
norm_fn=norm_fn,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points, skip_points, cluster):
points = self.up(points, skip_points, cluster)
return self.blocks(points)
class GVAPatchEmbed(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
norm_fn,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(GVAPatchEmbed, self).__init__()
self.in_channels = in_channels
self.embed_channels = embed_channels
self.proj_linear = nn.Linear(in_channels, embed_channels, bias=False)
self.proj_norm = norm_fn(embed_channels)
self.proj_act = nn.ReLU(inplace=True)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
norm_fn=norm_fn,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rate,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
coord, feat, offset, condition, context = points
feat = self.proj_act(self.proj_norm(self.proj_linear(feat), condition, context))
return self.blocks([coord, feat, offset, condition, context])
@MODELS.register_module("PT-v2m3")
class PointTransformerV2(nn.Module):
def __init__(
self,
in_channels,
num_classes,
patch_embed_depth=1,
patch_embed_channels=48,
patch_embed_groups=6,
patch_embed_neighbours=8,
enc_depths=(2, 2, 6, 2),
enc_channels=(96, 192, 384, 512),
enc_groups=(12, 24, 48, 64),
enc_neighbours=(16, 16, 16, 16),
dec_depths=(1, 1, 1, 1),
dec_channels=(48, 96, 192, 384),
dec_groups=(6, 12, 24, 48),
dec_neighbours=(16, 16, 16, 16),
grid_sizes=(0.06, 0.12, 0.24, 0.48),
attn_qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0,
enable_checkpoint=False,
unpool_backend="map",
context_channels=256,
conditions=("ScanNet", "S3DIS", "Structured3D"),
norm_decouple=True,
norm_adaptive=True,
norm_affine=False,
):
super(PointTransformerV2, self).__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.num_stages = len(enc_depths)
assert self.num_stages == len(dec_depths)
assert self.num_stages == len(enc_channels)
assert self.num_stages == len(dec_channels)
assert self.num_stages == len(enc_groups)
assert self.num_stages == len(dec_groups)
assert self.num_stages == len(enc_neighbours)
assert self.num_stages == len(dec_neighbours)
assert self.num_stages == len(grid_sizes)
norm_fn = partial(
PDBatchNorm,
eps=1e-3,
momentum=0.01,
conditions=conditions,
context_channels=context_channels,
decouple=norm_decouple,
adaptive=norm_adaptive,
affine=norm_affine,
)
self.patch_embed = GVAPatchEmbed(
in_channels=in_channels,
embed_channels=patch_embed_channels,
groups=patch_embed_groups,
depth=patch_embed_depth,
neighbours=patch_embed_neighbours,
norm_fn=norm_fn,
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
enable_checkpoint=enable_checkpoint,
)
enc_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(enc_depths))
]
dec_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(dec_depths))
]
enc_channels = [patch_embed_channels] + list(enc_channels)
dec_channels = list(dec_channels) + [enc_channels[-1]]
self.enc_stages = nn.ModuleList()
self.dec_stages = nn.ModuleList()
for i in range(self.num_stages):
enc = Encoder(
depth=enc_depths[i],
in_channels=enc_channels[i],
embed_channels=enc_channels[i + 1],
groups=enc_groups[i],
grid_size=grid_sizes[i],
neighbours=enc_neighbours[i],
norm_fn=norm_fn,
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=enc_dp_rates[
sum(enc_depths[:i]) : sum(enc_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
)
dec = Decoder(
depth=dec_depths[i],
in_channels=dec_channels[i + 1],
skip_channels=enc_channels[i],
embed_channels=dec_channels[i],
groups=dec_groups[i],
neighbours=dec_neighbours[i],
norm_fn=norm_fn,
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=dec_dp_rates[
sum(dec_depths[:i]) : sum(dec_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
unpool_backend=unpool_backend,
)
self.enc_stages.append(enc)
self.dec_stages.append(dec)
self.seg_head = (
nn.Sequential(nn.Linear(dec_channels[0], num_classes))
if num_classes > 0
else nn.Identity()
)
def forward(self, data_dict):
coord = data_dict["coord"]
feat = data_dict["feat"]
offset = data_dict["offset"].int()
condition = data_dict["condition"][0]
context = data_dict["context"] if "context" in data_dict.keys() else None
# a batch of point cloud is a list of coord, feat and offset
points = [coord, feat, offset, condition, context]
points = self.patch_embed(points)
skips = [[points]]
for i in range(self.num_stages):
points, cluster = self.enc_stages[i](points)
skips[-1].append(cluster) # record grid cluster of pooling
skips.append([points]) # record points info of current stage
points = skips.pop(-1)[0] # unpooling points info in the last enc stage
for i in reversed(range(self.num_stages)):
skip_points, cluster = skips.pop(-1)
points = self.dec_stages[i](points, skip_points, cluster)
coord, feat, offset, _, _ = points
seg_logits = self.seg_head(feat)
return seg_logits
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v2/point_transformer_v2m2_base.py | pointcept/models/point_transformer_v2/point_transformer_v2m2_base.py | """
Point Transformer V2 Mode 2 (recommend)
Disable Grouped Linear
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from copy import deepcopy
import math
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from torch_geometric.nn.pool import voxel_grid
from torch_scatter import segment_csr
import einops
from timm.models.layers import DropPath
import pointops
from pointcept.models.builder import MODELS
from pointcept.models.utils import offset2batch, batch2offset
class PointBatchNorm(nn.Module):
"""
Batch Normalization for Point Clouds data in shape of [B*N, C], [B*N, L, C]
"""
def __init__(self, embed_channels):
super().__init__()
self.norm = nn.BatchNorm1d(embed_channels)
def forward(self, input: torch.Tensor) -> torch.Tensor:
if input.dim() == 3:
return (
self.norm(input.transpose(1, 2).contiguous())
.transpose(1, 2)
.contiguous()
)
elif input.dim() == 2:
return self.norm(input)
else:
raise NotImplementedError
class GroupedVectorAttention(nn.Module):
def __init__(
self,
embed_channels,
groups,
attn_drop_rate=0.0,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
):
super(GroupedVectorAttention, self).__init__()
self.embed_channels = embed_channels
self.groups = groups
assert embed_channels % groups == 0
self.attn_drop_rate = attn_drop_rate
self.qkv_bias = qkv_bias
self.pe_multiplier = pe_multiplier
self.pe_bias = pe_bias
self.linear_q = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_k = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_v = nn.Linear(embed_channels, embed_channels, bias=qkv_bias)
if self.pe_multiplier:
self.linear_p_multiplier = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
if self.pe_bias:
self.linear_p_bias = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
self.weight_encoding = nn.Sequential(
nn.Linear(embed_channels, groups),
PointBatchNorm(groups),
nn.ReLU(inplace=True),
nn.Linear(groups, groups),
)
self.softmax = nn.Softmax(dim=1)
self.attn_drop = nn.Dropout(attn_drop_rate)
def forward(self, feat, coord, reference_index):
query, key, value = (
self.linear_q(feat),
self.linear_k(feat),
self.linear_v(feat),
)
key = pointops.grouping(reference_index, key, coord, with_xyz=True)
value = pointops.grouping(reference_index, value, coord, with_xyz=False)
pos, key = key[:, :, 0:3], key[:, :, 3:]
relation_qk = key - query.unsqueeze(1)
if self.pe_multiplier:
pem = self.linear_p_multiplier(pos)
relation_qk = relation_qk * pem
if self.pe_bias:
peb = self.linear_p_bias(pos)
relation_qk = relation_qk + peb
value = value + peb
weight = self.weight_encoding(relation_qk)
weight = self.attn_drop(self.softmax(weight))
mask = torch.sign(reference_index + 1)
weight = torch.einsum("n s g, n s -> n s g", weight, mask)
value = einops.rearrange(value, "n ns (g i) -> n ns g i", g=self.groups)
feat = torch.einsum("n s g i, n s g -> n g i", value, weight)
feat = einops.rearrange(feat, "n g i -> n (g i)")
return feat
class Block(nn.Module):
def __init__(
self,
embed_channels,
groups,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(Block, self).__init__()
self.attn = GroupedVectorAttention(
embed_channels=embed_channels,
groups=groups,
qkv_bias=qkv_bias,
attn_drop_rate=attn_drop_rate,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
)
self.fc1 = nn.Linear(embed_channels, embed_channels, bias=False)
self.fc3 = nn.Linear(embed_channels, embed_channels, bias=False)
self.norm1 = PointBatchNorm(embed_channels)
self.norm2 = PointBatchNorm(embed_channels)
self.norm3 = PointBatchNorm(embed_channels)
self.act = nn.ReLU(inplace=True)
self.enable_checkpoint = enable_checkpoint
self.drop_path = (
DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
)
def forward(self, points, reference_index):
coord, feat, offset = points
identity = feat
feat = self.act(self.norm1(self.fc1(feat)))
feat = (
self.attn(feat, coord, reference_index)
if not self.enable_checkpoint
else checkpoint(self.attn, feat, coord, reference_index)
)
feat = self.act(self.norm2(feat))
feat = self.norm3(self.fc3(feat))
feat = identity + self.drop_path(feat)
feat = self.act(feat)
return [coord, feat, offset]
class BlockSequence(nn.Module):
def __init__(
self,
depth,
embed_channels,
groups,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(BlockSequence, self).__init__()
if isinstance(drop_path_rate, list):
drop_path_rates = drop_path_rate
assert len(drop_path_rates) == depth
elif isinstance(drop_path_rate, float):
drop_path_rates = [deepcopy(drop_path_rate) for _ in range(depth)]
else:
drop_path_rates = [0.0 for _ in range(depth)]
self.neighbours = neighbours
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
embed_channels=embed_channels,
groups=groups,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rates[i],
enable_checkpoint=enable_checkpoint,
)
self.blocks.append(block)
def forward(self, points):
coord, feat, offset = points
# reference index query of neighbourhood attention
# for windows attention, modify reference index query method
reference_index, _ = pointops.knn_query(self.neighbours, coord, offset)
for block in self.blocks:
points = block(points, reference_index)
return points
class GridPool(nn.Module):
"""
Partition-based Pooling (Grid Pooling)
"""
def __init__(self, in_channels, out_channels, grid_size, bias=False):
super(GridPool, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.grid_size = grid_size
self.fc = nn.Linear(in_channels, out_channels, bias=bias)
self.norm = PointBatchNorm(out_channels)
self.act = nn.ReLU(inplace=True)
def forward(self, points, start=None):
coord, feat, offset = points
batch = offset2batch(offset)
feat = self.act(self.norm(self.fc(feat)))
start = (
segment_csr(
coord,
torch.cat([batch.new_zeros(1), torch.cumsum(batch.bincount(), dim=0)]),
reduce="min",
)
if start is None
else start
)
cluster = voxel_grid(
pos=coord - start[batch], size=self.grid_size, batch=batch, start=0
)
unique, cluster, counts = torch.unique(
cluster, sorted=True, return_inverse=True, return_counts=True
)
_, sorted_cluster_indices = torch.sort(cluster)
idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
coord = segment_csr(coord[sorted_cluster_indices], idx_ptr, reduce="mean")
feat = segment_csr(feat[sorted_cluster_indices], idx_ptr, reduce="max")
batch = batch[idx_ptr[:-1]]
offset = batch2offset(batch)
return [coord, feat, offset], cluster
class UnpoolWithSkip(nn.Module):
"""
Map Unpooling with skip connection
"""
def __init__(
self,
in_channels,
skip_channels,
out_channels,
bias=True,
skip=True,
backend="map",
):
super(UnpoolWithSkip, self).__init__()
self.in_channels = in_channels
self.skip_channels = skip_channels
self.out_channels = out_channels
self.skip = skip
self.backend = backend
assert self.backend in ["map", "interp"]
self.proj = nn.Sequential(
nn.Linear(in_channels, out_channels, bias=bias),
PointBatchNorm(out_channels),
nn.ReLU(inplace=True),
)
self.proj_skip = nn.Sequential(
nn.Linear(skip_channels, out_channels, bias=bias),
PointBatchNorm(out_channels),
nn.ReLU(inplace=True),
)
def forward(self, points, skip_points, cluster=None):
coord, feat, offset = points
skip_coord, skip_feat, skip_offset = skip_points
if self.backend == "map" and cluster is not None:
feat = self.proj(feat)[cluster]
else:
feat = pointops.interpolation(
coord, skip_coord, self.proj(feat), offset, skip_offset
)
if self.skip:
feat = feat + self.proj_skip(skip_feat)
return [skip_coord, feat, skip_offset]
class Encoder(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
grid_size=None,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
):
super(Encoder, self).__init__()
self.down = GridPool(
in_channels=in_channels,
out_channels=embed_channels,
grid_size=grid_size,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
points, cluster = self.down(points)
return self.blocks(points), cluster
class Decoder(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
embed_channels,
groups,
depth,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
unpool_backend="map",
):
super(Decoder, self).__init__()
self.up = UnpoolWithSkip(
in_channels=in_channels,
out_channels=embed_channels,
skip_channels=skip_channels,
backend=unpool_backend,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points, skip_points, cluster):
points = self.up(points, skip_points, cluster)
return self.blocks(points)
class GVAPatchEmbed(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(GVAPatchEmbed, self).__init__()
self.in_channels = in_channels
self.embed_channels = embed_channels
self.proj = nn.Sequential(
nn.Linear(in_channels, embed_channels, bias=False),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rate,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
coord, feat, offset = points
feat = self.proj(feat)
return self.blocks([coord, feat, offset])
@MODELS.register_module("PT-v2m2")
class PointTransformerV2(nn.Module):
def __init__(
self,
in_channels,
num_classes,
patch_embed_depth=1,
patch_embed_channels=48,
patch_embed_groups=6,
patch_embed_neighbours=8,
enc_depths=(2, 2, 6, 2),
enc_channels=(96, 192, 384, 512),
enc_groups=(12, 24, 48, 64),
enc_neighbours=(16, 16, 16, 16),
dec_depths=(1, 1, 1, 1),
dec_channels=(48, 96, 192, 384),
dec_groups=(6, 12, 24, 48),
dec_neighbours=(16, 16, 16, 16),
grid_sizes=(0.06, 0.12, 0.24, 0.48),
attn_qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0,
enable_checkpoint=False,
unpool_backend="map",
):
super(PointTransformerV2, self).__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.num_stages = len(enc_depths)
assert self.num_stages == len(dec_depths)
assert self.num_stages == len(enc_channels)
assert self.num_stages == len(dec_channels)
assert self.num_stages == len(enc_groups)
assert self.num_stages == len(dec_groups)
assert self.num_stages == len(enc_neighbours)
assert self.num_stages == len(dec_neighbours)
assert self.num_stages == len(grid_sizes)
self.patch_embed = GVAPatchEmbed(
in_channels=in_channels,
embed_channels=patch_embed_channels,
groups=patch_embed_groups,
depth=patch_embed_depth,
neighbours=patch_embed_neighbours,
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
enable_checkpoint=enable_checkpoint,
)
enc_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(enc_depths))
]
dec_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(dec_depths))
]
enc_channels = [patch_embed_channels] + list(enc_channels)
dec_channels = list(dec_channels) + [enc_channels[-1]]
self.enc_stages = nn.ModuleList()
self.dec_stages = nn.ModuleList()
for i in range(self.num_stages):
enc = Encoder(
depth=enc_depths[i],
in_channels=enc_channels[i],
embed_channels=enc_channels[i + 1],
groups=enc_groups[i],
grid_size=grid_sizes[i],
neighbours=enc_neighbours[i],
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=enc_dp_rates[
sum(enc_depths[:i]) : sum(enc_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
)
dec = Decoder(
depth=dec_depths[i],
in_channels=dec_channels[i + 1],
skip_channels=enc_channels[i],
embed_channels=dec_channels[i],
groups=dec_groups[i],
neighbours=dec_neighbours[i],
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=dec_dp_rates[
sum(dec_depths[:i]) : sum(dec_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
unpool_backend=unpool_backend,
)
self.enc_stages.append(enc)
self.dec_stages.append(dec)
self.seg_head = (
nn.Sequential(
nn.Linear(dec_channels[0], dec_channels[0]),
PointBatchNorm(dec_channels[0]),
nn.ReLU(inplace=True),
nn.Linear(dec_channels[0], num_classes),
)
if num_classes > 0
else nn.Identity()
)
def forward(self, data_dict):
coord = data_dict["coord"]
feat = data_dict["feat"]
offset = data_dict["offset"].int()
# a batch of point cloud is a list of coord, feat and offset
points = [coord, feat, offset]
points = self.patch_embed(points)
skips = [[points]]
for i in range(self.num_stages):
points, cluster = self.enc_stages[i](points)
skips[-1].append(cluster) # record grid cluster of pooling
skips.append([points]) # record points info of current stage
points = skips.pop(-1)[0] # unpooling points info in the last enc stage
for i in reversed(range(self.num_stages)):
skip_points, cluster = skips.pop(-1)
points = self.dec_stages[i](points, skip_points, cluster)
coord, feat, offset = points
seg_logits = self.seg_head(feat)
return seg_logits
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v2/point_transformer_v2m1_origin.py | pointcept/models/point_transformer_v2/point_transformer_v2m1_origin.py | """
Point Transformer V2 mode 1
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from copy import deepcopy
import math
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from torch_geometric.nn.pool import voxel_grid
from torch_scatter import segment_csr
import einops
from timm.models.layers import DropPath
import pointops
from pointcept.models.builder import MODELS
from pointcept.models.utils import offset2batch, batch2offset
class GroupedLinear(nn.Module):
__constants__ = ["in_features", "out_features", "groups"]
in_features: int
out_features: int
groups: int
weight: torch.Tensor
def __init__(
self, in_features: int, out_features: int, groups: int, device=None, dtype=None
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(GroupedLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.groups = groups
assert in_features & groups == 0
assert out_features % groups == 0
# for convenient, currently only support out_features == groups, one output
assert out_features == groups
self.weight = nn.Parameter(torch.empty((1, in_features), **factory_kwargs))
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
def forward(self, input: torch.Tensor) -> torch.Tensor:
return (
(input * self.weight)
.reshape(
list(input.shape[:-1]) + [self.groups, input.shape[-1] // self.groups]
)
.sum(-1)
)
def extra_repr(self) -> str:
return "in_features={}, out_features={}, bias={}".format(
self.in_features, self.out_features, self.bias is not None
)
class PointBatchNorm(nn.Module):
"""
Batch Normalization for Point Clouds data in shape of [B*N, C], [B*N, L, C]
"""
def __init__(self, embed_channels):
super().__init__()
self.norm = nn.BatchNorm1d(embed_channels)
def forward(self, input: torch.Tensor) -> torch.Tensor:
if input.dim() == 3:
return (
self.norm(input.transpose(1, 2).contiguous())
.transpose(1, 2)
.contiguous()
)
elif input.dim() == 2:
return self.norm(input)
else:
raise NotImplementedError
class GroupedVectorAttention(nn.Module):
def __init__(
self,
embed_channels,
groups,
attn_drop_rate=0.0,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
):
super(GroupedVectorAttention, self).__init__()
self.embed_channels = embed_channels
self.groups = groups
assert embed_channels % groups == 0
self.attn_drop_rate = attn_drop_rate
self.qkv_bias = qkv_bias
self.pe_multiplier = pe_multiplier
self.pe_bias = pe_bias
self.linear_q = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_k = nn.Sequential(
nn.Linear(embed_channels, embed_channels, bias=qkv_bias),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.linear_v = nn.Linear(embed_channels, embed_channels, bias=qkv_bias)
if self.pe_multiplier:
self.linear_p_multiplier = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
if self.pe_bias:
self.linear_p_bias = nn.Sequential(
nn.Linear(3, embed_channels),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
nn.Linear(embed_channels, embed_channels),
)
self.weight_encoding = nn.Sequential(
GroupedLinear(embed_channels, groups, groups),
PointBatchNorm(groups),
nn.ReLU(inplace=True),
nn.Linear(groups, groups),
)
self.softmax = nn.Softmax(dim=1)
self.attn_drop = nn.Dropout(attn_drop_rate)
def forward(self, feat, coord, reference_index):
query, key, value = (
self.linear_q(feat),
self.linear_k(feat),
self.linear_v(feat),
)
key = pointops.grouping(reference_index, key, coord, with_xyz=True)
value = pointops.grouping(reference_index, value, coord, with_xyz=False)
pos, key = key[:, :, 0:3], key[:, :, 3:]
relation_qk = key - query.unsqueeze(1)
if self.pe_multiplier:
pem = self.linear_p_multiplier(pos)
relation_qk = relation_qk * pem
if self.pe_bias:
peb = self.linear_p_bias(pos)
relation_qk = relation_qk + peb
value = value + peb
weight = self.weight_encoding(relation_qk)
weight = self.attn_drop(self.softmax(weight))
mask = torch.sign(reference_index + 1)
weight = torch.einsum("n s g, n s -> n s g", weight, mask)
value = einops.rearrange(value, "n ns (g i) -> n ns g i", g=self.groups)
feat = torch.einsum("n s g i, n s g -> n g i", value, weight)
feat = einops.rearrange(feat, "n g i -> n (g i)")
return feat
class Block(nn.Module):
def __init__(
self,
embed_channels,
groups,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(Block, self).__init__()
self.attn = GroupedVectorAttention(
embed_channels=embed_channels,
groups=groups,
qkv_bias=qkv_bias,
attn_drop_rate=attn_drop_rate,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
)
self.fc1 = nn.Linear(embed_channels, embed_channels, bias=False)
self.fc3 = nn.Linear(embed_channels, embed_channels, bias=False)
self.norm1 = PointBatchNorm(embed_channels)
self.norm2 = PointBatchNorm(embed_channels)
self.norm3 = PointBatchNorm(embed_channels)
self.act = nn.ReLU(inplace=True)
self.enable_checkpoint = enable_checkpoint
self.drop_path = (
DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
)
def forward(self, points, reference_index):
coord, feat, offset = points
identity = feat
feat = self.act(self.norm1(self.fc1(feat)))
feat = (
self.attn(feat, coord, reference_index)
if not self.enable_checkpoint
else checkpoint(self.attn, feat, coord, reference_index)
)
feat = self.act(self.norm2(feat))
feat = self.norm3(self.fc3(feat))
feat = identity + self.drop_path(feat)
feat = self.act(feat)
return [coord, feat, offset]
class BlockSequence(nn.Module):
def __init__(
self,
depth,
embed_channels,
groups,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(BlockSequence, self).__init__()
if isinstance(drop_path_rate, list):
drop_path_rates = drop_path_rate
assert len(drop_path_rates) == depth
elif isinstance(drop_path_rate, float):
drop_path_rates = [deepcopy(drop_path_rate) for _ in range(depth)]
else:
drop_path_rates = [0.0 for _ in range(depth)]
self.neighbours = neighbours
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
embed_channels=embed_channels,
groups=groups,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rates[i],
enable_checkpoint=enable_checkpoint,
)
self.blocks.append(block)
def forward(self, points):
coord, feat, offset = points
# reference index query of neighbourhood attention
# for windows attention, modify reference index query method
reference_index, _ = pointops.knn_query(self.neighbours, coord, offset)
for block in self.blocks:
points = block(points, reference_index)
return points
class GridPool(nn.Module):
"""
Partition-based Pooling (Grid Pooling)
"""
def __init__(self, in_channels, out_channels, grid_size, bias=False):
super(GridPool, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.grid_size = grid_size
self.fc = nn.Linear(in_channels, out_channels, bias=bias)
self.norm = PointBatchNorm(out_channels)
self.act = nn.ReLU(inplace=True)
def forward(self, points, start=None):
coord, feat, offset = points
batch = offset2batch(offset)
feat = self.act(self.norm(self.fc(feat)))
start = (
segment_csr(
coord,
torch.cat([batch.new_zeros(1), torch.cumsum(batch.bincount(), dim=0)]),
reduce="min",
)
if start is None
else start
)
cluster = voxel_grid(
pos=coord - start[batch], size=self.grid_size, batch=batch, start=0
)
unique, cluster, counts = torch.unique(
cluster, sorted=True, return_inverse=True, return_counts=True
)
_, sorted_cluster_indices = torch.sort(cluster)
idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
coord = segment_csr(coord[sorted_cluster_indices], idx_ptr, reduce="mean")
feat = segment_csr(feat[sorted_cluster_indices], idx_ptr, reduce="max")
batch = batch[idx_ptr[:-1]]
offset = batch2offset(batch)
return [coord, feat, offset], cluster
class UnpoolWithSkip(nn.Module):
"""
Map Unpooling with skip connection
"""
def __init__(
self,
in_channels,
skip_channels,
out_channels,
bias=True,
skip=True,
backend="map",
):
super(UnpoolWithSkip, self).__init__()
self.in_channels = in_channels
self.skip_channels = skip_channels
self.out_channels = out_channels
self.skip = skip
self.backend = backend
assert self.backend in ["map", "interp"]
self.proj = nn.Sequential(
nn.Linear(in_channels, out_channels, bias=bias),
PointBatchNorm(out_channels),
nn.ReLU(inplace=True),
)
self.proj_skip = nn.Sequential(
nn.Linear(skip_channels, out_channels, bias=bias),
PointBatchNorm(out_channels),
nn.ReLU(inplace=True),
)
def forward(self, points, skip_points, cluster=None):
coord, feat, offset = points
skip_coord, skip_feat, skip_offset = skip_points
if self.backend == "map" and cluster is not None:
feat = self.proj(feat)[cluster]
else:
feat = pointops.interpolation(
coord, skip_coord, self.proj(feat), offset, skip_offset
)
if self.skip:
feat = feat + self.proj_skip(skip_feat)
return [skip_coord, feat, skip_offset]
class Encoder(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
grid_size=None,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
):
super(Encoder, self).__init__()
self.down = GridPool(
in_channels=in_channels,
out_channels=embed_channels,
grid_size=grid_size,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
points, cluster = self.down(points)
return self.blocks(points), cluster
class Decoder(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
embed_channels,
groups,
depth,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=None,
drop_path_rate=None,
enable_checkpoint=False,
unpool_backend="map",
):
super(Decoder, self).__init__()
self.up = UnpoolWithSkip(
in_channels=in_channels,
out_channels=embed_channels,
skip_channels=skip_channels,
backend=unpool_backend,
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate if attn_drop_rate is not None else 0.0,
drop_path_rate=drop_path_rate if drop_path_rate is not None else 0.0,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points, skip_points, cluster):
points = self.up(points, skip_points, cluster)
return self.blocks(points)
class GVAPatchEmbed(nn.Module):
def __init__(
self,
depth,
in_channels,
embed_channels,
groups,
neighbours=16,
qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0.0,
enable_checkpoint=False,
):
super(GVAPatchEmbed, self).__init__()
self.in_channels = in_channels
self.embed_channels = embed_channels
self.proj = nn.Sequential(
nn.Linear(in_channels, embed_channels, bias=False),
PointBatchNorm(embed_channels),
nn.ReLU(inplace=True),
)
self.blocks = BlockSequence(
depth=depth,
embed_channels=embed_channels,
groups=groups,
neighbours=neighbours,
qkv_bias=qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=drop_path_rate,
enable_checkpoint=enable_checkpoint,
)
def forward(self, points):
coord, feat, offset = points
feat = self.proj(feat)
return self.blocks([coord, feat, offset])
@MODELS.register_module("PT-v2m1")
class PointTransformerV2(nn.Module):
def __init__(
self,
in_channels,
num_classes,
patch_embed_depth=1,
patch_embed_channels=48,
patch_embed_groups=6,
patch_embed_neighbours=8,
enc_depths=(2, 2, 6, 2),
enc_channels=(96, 192, 384, 512),
enc_groups=(12, 24, 48, 64),
enc_neighbours=(16, 16, 16, 16),
dec_depths=(1, 1, 1, 1),
dec_channels=(48, 96, 192, 384),
dec_groups=(6, 12, 24, 48),
dec_neighbours=(16, 16, 16, 16),
grid_sizes=(0.06, 0.12, 0.24, 0.48),
attn_qkv_bias=True,
pe_multiplier=False,
pe_bias=True,
attn_drop_rate=0.0,
drop_path_rate=0,
enable_checkpoint=False,
unpool_backend="map",
):
super(PointTransformerV2, self).__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.num_stages = len(enc_depths)
assert self.num_stages == len(dec_depths)
assert self.num_stages == len(enc_channels)
assert self.num_stages == len(dec_channels)
assert self.num_stages == len(enc_groups)
assert self.num_stages == len(dec_groups)
assert self.num_stages == len(enc_neighbours)
assert self.num_stages == len(dec_neighbours)
assert self.num_stages == len(grid_sizes)
self.patch_embed = GVAPatchEmbed(
in_channels=in_channels,
embed_channels=patch_embed_channels,
groups=patch_embed_groups,
depth=patch_embed_depth,
neighbours=patch_embed_neighbours,
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
enable_checkpoint=enable_checkpoint,
)
enc_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(enc_depths))
]
dec_dp_rates = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(dec_depths))
]
enc_channels = [patch_embed_channels] + list(enc_channels)
dec_channels = list(dec_channels) + [enc_channels[-1]]
self.enc_stages = nn.ModuleList()
self.dec_stages = nn.ModuleList()
for i in range(self.num_stages):
enc = Encoder(
depth=enc_depths[i],
in_channels=enc_channels[i],
embed_channels=enc_channels[i + 1],
groups=enc_groups[i],
grid_size=grid_sizes[i],
neighbours=enc_neighbours[i],
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=enc_dp_rates[
sum(enc_depths[:i]) : sum(enc_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
)
dec = Decoder(
depth=dec_depths[i],
in_channels=dec_channels[i + 1],
skip_channels=enc_channels[i],
embed_channels=dec_channels[i],
groups=dec_groups[i],
neighbours=dec_neighbours[i],
qkv_bias=attn_qkv_bias,
pe_multiplier=pe_multiplier,
pe_bias=pe_bias,
attn_drop_rate=attn_drop_rate,
drop_path_rate=dec_dp_rates[
sum(dec_depths[:i]) : sum(dec_depths[: i + 1])
],
enable_checkpoint=enable_checkpoint,
unpool_backend=unpool_backend,
)
self.enc_stages.append(enc)
self.dec_stages.append(dec)
self.seg_head = (
nn.Sequential(
nn.Linear(dec_channels[0], dec_channels[0]),
PointBatchNorm(dec_channels[0]),
nn.ReLU(inplace=True),
nn.Linear(dec_channels[0], num_classes),
)
if num_classes > 0
else nn.Identity()
)
def forward(self, data_dict):
coord = data_dict["coord"]
feat = data_dict["feat"]
offset = data_dict["offset"].int()
# a batch of point cloud is a list of coord, feat and offset
points = [coord, feat, offset]
points = self.patch_embed(points)
skips = [[points]]
for i in range(self.num_stages):
points, cluster = self.enc_stages[i](points)
skips[-1].append(cluster) # record grid cluster of pooling
skips.append([points]) # record points info of current stage
points = skips.pop(-1)[0] # unpooling points info in the last enc stage
for i in reversed(range(self.num_stages)):
skip_points, cluster = skips.pop(-1)
points = self.dec_stages[i](points, skip_points, cluster)
coord, feat, offset = points
seg_logits = self.seg_head(feat)
return seg_logits
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v2/__init__.py | pointcept/models/point_transformer_v2/__init__.py | """
Point Transformer V2
Copyright (c) Xiaoyang Wu (xiaoyang.wu@connect.hku.hk). All Rights Reserved.
Please cite our work if you use any part of the code.
"""
from .point_transformer_v2m1_origin import *
from .point_transformer_v2m2_base import *
from .point_transformer_v2m3_pdnorm import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/swin3d/swin3d_v1m1_base.py | pointcept/models/swin3d/swin3d_v1m1_base.py | import torch
import torch.nn as nn
import MinkowskiEngine as ME
from MinkowskiEngine import SparseTensor
from timm.models.layers import trunc_normal_
from .mink_layers import MinkConvBNRelu, MinkResBlock
from .swin3d_layers import GridDownsample, GridKNNDownsample, BasicLayer, Upsample
from pointcept.models.builder import MODELS
from pointcept.models.utils import offset2batch, batch2offset
@MODELS.register_module("Swin3D-v1m1")
class Swin3DUNet(nn.Module):
def __init__(
self,
in_channels,
num_classes,
base_grid_size,
depths,
channels,
num_heads,
window_sizes,
quant_size,
drop_path_rate=0.2,
up_k=3,
num_layers=5,
stem_transformer=True,
down_stride=2,
upsample="linear",
knn_down=True,
cRSE="XYZ_RGB",
fp16_mode=0,
):
super().__init__()
dpr = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
] # stochastic depth decay rule
if knn_down:
downsample = GridKNNDownsample
else:
downsample = GridDownsample
self.cRSE = cRSE
if stem_transformer:
self.stem_layer = MinkConvBNRelu(
in_channels=in_channels,
out_channels=channels[0],
kernel_size=3,
stride=1,
)
self.layer_start = 0
else:
self.stem_layer = nn.Sequential(
MinkConvBNRelu(
in_channels=in_channels,
out_channels=channels[0],
kernel_size=3,
stride=1,
),
MinkResBlock(in_channels=channels[0], out_channels=channels[0]),
)
self.downsample = downsample(
channels[0], channels[1], kernel_size=down_stride, stride=down_stride
)
self.layer_start = 1
self.layers = nn.ModuleList(
[
BasicLayer(
dim=channels[i],
depth=depths[i],
num_heads=num_heads[i],
window_size=window_sizes[i],
quant_size=quant_size,
drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])],
downsample=downsample if i < num_layers - 1 else None,
down_stride=down_stride if i == 0 else 2,
out_channels=channels[i + 1] if i < num_layers - 1 else None,
cRSE=cRSE,
fp16_mode=fp16_mode,
)
for i in range(self.layer_start, num_layers)
]
)
if "attn" in upsample:
up_attn = True
else:
up_attn = False
self.upsamples = nn.ModuleList(
[
Upsample(
channels[i],
channels[i - 1],
num_heads[i - 1],
window_sizes[i - 1],
quant_size,
attn=up_attn,
up_k=up_k,
cRSE=cRSE,
fp16_mode=fp16_mode,
)
for i in range(num_layers - 1, 0, -1)
]
)
self.classifier = nn.Sequential(
nn.Linear(channels[0], channels[0]),
nn.BatchNorm1d(channels[0]),
nn.ReLU(inplace=True),
nn.Linear(channels[0], num_classes),
)
self.num_classes = num_classes
self.base_grid_size = base_grid_size
self.init_weights()
def forward(self, data_dict):
grid_coord = data_dict["grid_coord"]
feat = data_dict["feat"]
coord_feat = data_dict["coord_feat"]
coord = data_dict["coord"]
offset = data_dict["offset"]
batch = offset2batch(offset)
in_field = ME.TensorField(
features=torch.cat(
[
batch.unsqueeze(-1),
coord / self.base_grid_size,
coord_feat / 1.001,
feat,
],
dim=1,
),
coordinates=torch.cat([batch.unsqueeze(-1).int(), grid_coord.int()], dim=1),
quantization_mode=ME.SparseTensorQuantizationMode.UNWEIGHTED_AVERAGE,
minkowski_algorithm=ME.MinkowskiAlgorithm.SPEED_OPTIMIZED,
device=feat.device,
)
sp = in_field.sparse()
coords_sp = SparseTensor(
features=sp.F[:, : coord_feat.shape[-1] + 4],
coordinate_map_key=sp.coordinate_map_key,
coordinate_manager=sp.coordinate_manager,
)
sp = SparseTensor(
features=sp.F[:, coord_feat.shape[-1] + 4 :],
coordinate_map_key=sp.coordinate_map_key,
coordinate_manager=sp.coordinate_manager,
)
sp_stack = []
coords_sp_stack = []
sp = self.stem_layer(sp)
if self.layer_start > 0:
sp_stack.append(sp)
coords_sp_stack.append(coords_sp)
sp, coords_sp = self.downsample(sp, coords_sp)
for i, layer in enumerate(self.layers):
coords_sp_stack.append(coords_sp)
sp, sp_down, coords_sp = layer(sp, coords_sp)
sp_stack.append(sp)
assert (coords_sp.C == sp_down.C).all()
sp = sp_down
sp = sp_stack.pop()
coords_sp = coords_sp_stack.pop()
for i, upsample in enumerate(self.upsamples):
sp_i = sp_stack.pop()
coords_sp_i = coords_sp_stack.pop()
sp = upsample(sp, coords_sp, sp_i, coords_sp_i)
coords_sp = coords_sp_i
output = self.classifier(sp.slice(in_field).F)
return output
def init_weights(self):
"""Initialize the weights in backbone."""
def _init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm) or isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
self.apply(_init_weights)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/swin3d/swin3d_layers.py | pointcept/models/swin3d/swin3d_layers.py | """
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
import numpy as np
import torch
import torch.nn as nn
from timm.models.layers import DropPath, trunc_normal_
import MinkowskiEngine as ME
from MinkowskiEngine import SparseTensor
from Swin3D.sparse_dl.attn.attn_coff import (
SelfAttnAIOFunction,
PosEmb,
TableDims,
IndexMode,
PrecisionMode,
)
import Swin3D.sparse_dl.knn
from Swin3D.sparse_dl.knn import KNN
from .mink_layers import (
assign_feats,
SparseTensorLayerNorm,
SparseTensorLinear,
)
def query_knn_feature(
K, src_xyz, query_xyz, src_feat, src_offset, query_offset, return_idx=False
):
"""
gather feature in the KNN neighborhood
"""
assert (
src_xyz.is_contiguous()
and query_xyz.is_contiguous()
and src_feat.is_contiguous()
)
if query_xyz is None:
query_xyz = src_xyz
query_offset = src_offset
idx, _ = KNN.apply(K, src_xyz, query_xyz, src_offset, query_offset)
n, m, c = src_xyz.shape[0], query_xyz.shape[0], src_feat.shape[1]
grouped_feat = src_feat[idx.view(-1).long(), :].view(m, K, c)
if return_idx:
return grouped_feat, idx
else:
return grouped_feat
def knn_linear_interpolation(
src_xyz, query_xyz, src_feat, src_offset, query_offset, K=3
):
"""
interpolation feature using distance in KNN neighborhood
"""
N, C = query_xyz.shape[0], src_feat.shape[1]
assert (
src_xyz.is_contiguous()
and query_xyz.is_contiguous()
and src_feat.is_contiguous()
)
# (N, K)
idx, dist = KNN.apply(K, src_xyz, query_xyz, src_offset, query_offset)
weight = 1.0 / (dist + 1e-8)
norm = torch.sum(weight, dim=1, keepdim=True)
weight = weight / norm
query_feat = torch.zeros((N, C), dtype=src_feat.dtype, device=src_feat.device)
for i in range(K):
query_feat += src_feat[idx[:, i].long(), :] * weight[:, i].unsqueeze(-1)
return query_feat
def sparse_self_attention(
w_w_id: torch.Tensor, w_sizes: torch.Tensor, protocol: str = "v1"
):
"""
Args:
indices [torch.Tensor]: sparse window index with shape [N, 2], N is the total
number of non-empty voxels with indices (window_id, within_window_id). window_id
is ordered and starts from 0; within_window_id is a sparse index to indicate the
offset of kernel_size ** 3.
feats [torch.Tensor]: sprase features of each non-empty voxel with shape [N, C]
Outputs:
[M, 3]: sparse indices of cofficient matrix (window_id, att_a_id, att_b_id). att_a_id
and att_b_id are the within_window_id
[M, 1]: the sparse coffient matrix
Spaces:
W: total number of windows
N: total number of input voxels
M: total number of output cofficients
"""
w_sizes_2 = w_sizes**2
# w2n_indices - [W], mapping window index to window global offset in input
# space
w_cumsum = torch.cumsum(w_sizes, dim=-1)
w2n_indices = torch.cat(
[torch.zeros(1, dtype=w_cumsum.dtype, device=w_cumsum.device), w_cumsum[:-1]]
)
# w2m indices - [W], mapping window index to window global offset in output
# space
w2_cumsum = torch.cumsum(w_sizes_2, dim=-1)
w2m_indices = torch.cat(
[torch.zeros(1, dtype=w2_cumsum.dtype, device=w2_cumsum.device), w2_cumsum[:-1]]
)
# m2w indices - [M], mapping element global offset to the window index
m2w_indices = torch.zeros(
[w2_cumsum[-1]], dtype=w_sizes.dtype, device=w_sizes.device
)
m2w_offset = torch.zeros(
[w2_cumsum[-1]], dtype=w_sizes.dtype, device=w_sizes.device
)
m2w_indices[w2m_indices[1:]] = 1
m2w_offset[w2m_indices[1:]] = w_sizes_2[:-1]
m2w_indices = torch.cumsum(m2w_indices, dim=-1)
m2w_offset = torch.cumsum(m2w_offset, dim=-1)
# m_indices = [M], element global offset in output space
m_indices = torch.arange(
0, w2_cumsum[-1], dtype=w_sizes.dtype, device=w_sizes.device
)
# m2n_indices - [M], mapping element global offset to the window global offset
# in input space
m2n_indices = w2n_indices[m2w_indices]
m_offset = m_indices - m2w_offset
m2w_sizes = w_sizes[m2w_indices]
# print_log_main("m_offset:", m_offset, m_offset.shape)
# print_log_main("m2n_indices:", m2n_indices, m2n_indices.shape)
y_offset = m2n_indices + m_offset % m2w_sizes
x_offset = m2n_indices + torch.div(m_offset, m2w_sizes, rounding_mode="floor")
# print_log_main("=================================")
# print_log_main(w_sizes[:5])
# print_log_main(x_offset[:50])
# print_log_main(y_offset[:50])
# coord = torch.stack([m2w_indices, w_w_id[x_offset], w_w_id[y_offset]], axis=-1)
if protocol == "v1":
return x_offset, y_offset
elif protocol == "v2":
return x_offset, y_offset, m2w_indices, w_sizes, w2n_indices, w2m_indices
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class GridCoordsDown(nn.Module):
"""
downsample the grid coordinates
keep the nearest point to the average point of the downsampled grid
"""
def __init__(self, stride):
super().__init__()
self.stride = stride
self.avg_pool = ME.MinkowskiAvgPooling(
kernel_size=self.stride, stride=self.stride, dimension=3
)
self.unpool = ME.MinkowskiPoolingTranspose(
kernel_size=stride, stride=stride, dimension=3
)
self.max_pool = ME.MinkowskiMaxPooling(
kernel_size=self.stride, stride=self.stride, dimension=3
)
def forward(self, coords_sp, sp, return_map=False):
device = sp.C.device
# is_pool = True means pooling map
# is_pool = False means conv map (query as center)
N = sp.shape[0]
avg_coords_sp = self.avg_pool(coords_sp)
dist_sp = self.unpool(avg_coords_sp) - coords_sp
dist = dist_sp.F
dist = -torch.sqrt((dist**2).sum(dim=1)).unsqueeze(1)
dist_sp = assign_feats(dist_sp, dist)
min_dist_sp = self.max_pool(dist_sp)
map_pair = sp.coordinate_manager.kernel_map(
dist_sp.coordinate_map_key,
min_dist_sp.coordinate_map_key,
stride=self.stride,
kernel_size=self.stride,
is_pool=True,
)[0]
in_map, out_map = map_pair
broad_min_dist_sp = self.unpool(min_dist_sp)
mask = (broad_min_dist_sp.F == dist_sp.F).squeeze(1)
in_map = in_map[mask].long()
out_map = out_map[mask].long()
downsample_map = torch.zeros(N, dtype=torch.long, device=device) - 1
downsample_map[out_map] = in_map
assert (downsample_map >= 0).all()
assert (dist_sp.F[downsample_map] == min_dist_sp.F).all()
new_coords = coords_sp.F[downsample_map]
new_coords_sp = assign_feats(sp, new_coords)
if return_map:
return new_coords_sp, downsample_map
else:
return new_coords_sp
def get_offset(batch):
offset = []
bs = batch.max() + 1
for i in range(bs):
offset.append(torch.sum(batch == i))
offset = torch.cuda.IntTensor(offset)
offset = offset.cumsum(dim=0).int()
return offset
class GridDownsample(nn.Module):
"""
use stride to downsample voxel
use grid maxpooling with kernel_size
"""
def __init__(self, in_channels, out_channels, kernel_size=2, stride=2):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.in_channels = in_channels
self.out_channels = out_channels
self.sp_pool = ME.MinkowskiMaxPooling(
kernel_size=kernel_size, stride=stride, dimension=3
)
self.coords_pool = GridCoordsDown(stride=stride)
self.norm = SparseTensorLayerNorm(in_channels)
self.linear = SparseTensorLinear(in_channels, out_channels)
def forward(self, sp, coords_sp):
sp_down = self.sp_pool(self.linear(self.norm(sp)))
coords_sp_down = self.coords_pool(coords_sp, sp_down)
return sp_down, coords_sp_down
def extra_repr(self) -> str:
return f"kernel_size={self.kernel_size}, stride={self.stride}, in_channels={self.in_channels}, out_channels={self.out_channels}"
class GridKNNDownsample(nn.Module):
"""
use stride to downsample voxel
use KNN to do maxpooling
"""
def __init__(self, in_channels, out_channels, kernel_size=2, stride=2):
super().__init__()
self.stride = stride
self.in_channels = in_channels
self.out_channels = out_channels
self.k = 16
self.sp_pool = ME.MinkowskiMaxPooling(
kernel_size=stride, stride=stride, dimension=3
)
self.coords_pool = GridCoordsDown(stride=stride)
self.norm = nn.LayerNorm(in_channels)
self.linear = nn.Linear(in_channels, out_channels, bias=False)
self.pool = nn.MaxPool1d(self.k)
def forward(self, sp, coords_sp):
# calculate the voxel
sp_down = self.sp_pool(sp)
# for downsampled cRSE
coords_sp_down = self.coords_pool(coords_sp, sp_down)
offset = get_offset(sp.C[:, 0])
n_offset = get_offset(sp_down.C[:, 0])
xyz = coords_sp.F[:, 1:4].detach().contiguous()
n_xyz = coords_sp_down.F[:, 1:4].detach().contiguous()
feats = query_knn_feature(self.k, xyz, n_xyz, sp.F, offset, n_offset)
m, k, c = feats.shape
feats = (
self.linear(self.norm(feats.view(m * k, c)).view(m, k, c))
.transpose(1, 2)
.contiguous()
)
feats = self.pool(feats).squeeze(-1)
sp = assign_feats(sp_down, feats.float())
coords_sp = coords_sp_down
return sp, coords_sp
def extra_repr(self) -> str:
return f"kernel_size={self.k}, stride={self.stride}, in_channels={self.in_channels}, out_channels={self.out_channels}"
class Upsample(nn.Module):
"""
upsample using trilinear interpolation
follower by attn block according to self.attn
"""
def __init__(
self,
in_channels,
out_channels,
num_heads,
window_size,
quant_size,
attn=True,
up_k=3,
cRSE="XYZ_RGB",
fp16_mode=0,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.linear1 = nn.Sequential(
nn.LayerNorm(out_channels), nn.Linear(out_channels, out_channels)
)
self.linear2 = nn.Sequential(
nn.LayerNorm(in_channels), nn.Linear(in_channels, out_channels)
)
self.up_k = up_k
self.attn = attn and window_size > 0
if self.attn:
self.block = BasicLayer(
dim=out_channels,
depth=1,
num_heads=num_heads,
window_size=window_size,
quant_size=quant_size,
drop_path=0.1,
downsample=None,
out_channels=None,
cRSE=cRSE,
fp16_mode=fp16_mode,
)
def forward(self, sp, coords_sp, sp_up, coords_sp_up):
feats = sp.F
support_feats = sp_up.F
xyz = coords_sp.F[:, 1:4].detach().contiguous()
support_xyz = coords_sp_up.F[:, 1:4].detach().contiguous()
offset = get_offset(sp.C[:, 0])
support_offset = get_offset(sp_up.C[:, 0])
feats = self.linear1(support_feats) + knn_linear_interpolation(
xyz, support_xyz, self.linear2(feats), offset, support_offset, K=self.up_k
)
sp_up = assign_feats(sp_up, feats)
if self.attn:
sp_up, _, _ = self.block(sp_up, coords_sp_up)
return sp_up
def extra_repr(self) -> str:
return f"up_k={self.up_k}, in_channels={self.in_channels}, out_channels={self.out_channels}, attn={self.attn}"
class WindowAttention(nn.Module):
"""
Window based multi-head self attention (W-MSA) module with cRSE.
Designed for sparse structure
It supports both of shifted and non-shifted window.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
quant_size (int): quant_size for for finer cRSE table
num_heads (int): Number of attention heads.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
cRSE (str | 'XYZ', 'XYZ_RGB', 'XYZ_RGB_NORM'): cRSE mode. Default: 'XYZ_RGB'
fp16_mode (int | 0, 1, 2): fp16 mode for attention module, Default: 0
0: fp32 forward and fp32 backward
1: fp16 forward and fp32 backward
2: fp16 forward and fp16 backward
"""
def __init__(
self,
dim,
window_size,
quant_size,
num_heads,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
cRSE="XYZ_RGB",
fp16_mode=0,
):
super().__init__()
self.dim = dim
self.window_size = window_size
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim**-0.5
# color in [-1, 1], color_windowsize = 2
# normal in [-1, 1], normal_windowsize = 2
self.color_windowsize = 2
self.normal_windowsize = 2
self.fp16_mode = fp16_mode
table_offsets = []
self.cRSE = cRSE
if "XYZ" in cRSE:
self.xyz_quant_size = quant_size
quant_grid_length_xyz = window_size * self.xyz_quant_size
table_shape_xyz = (3, 2 * quant_grid_length_xyz, num_heads, head_dim)
self.query_xyz_table = nn.Parameter(torch.zeros(table_shape_xyz))
trunc_normal_(self.query_xyz_table, std=0.02)
self.key_xyz_table = nn.Parameter(torch.zeros(table_shape_xyz))
trunc_normal_(self.key_xyz_table, std=0.02)
self.value_xyz_table = nn.Parameter(torch.zeros(table_shape_xyz))
trunc_normal_(self.value_xyz_table, std=0.02)
table_offsets += [np.prod(table_shape_xyz[1:])] * 3
if "RGB" in cRSE:
self.color_quant_size = quant_size * 2
quant_grid_length_rgb = self.color_windowsize * self.color_quant_size
table_shape_rgb = (3, 2 * quant_grid_length_rgb, num_heads, head_dim)
self.query_rgb_table = nn.Parameter(torch.zeros(table_shape_rgb))
trunc_normal_(self.query_rgb_table, std=0.02)
self.key_rgb_table = nn.Parameter(torch.zeros(table_shape_rgb))
trunc_normal_(self.key_rgb_table, std=0.02)
self.value_rgb_table = nn.Parameter(torch.zeros(table_shape_rgb))
trunc_normal_(self.value_rgb_table, std=0.02)
table_offsets += [np.prod(table_shape_rgb[1:])] * 3
if "NORM" in cRSE:
self.normal_quant_size = quant_size * 2
quant_grid_length_norm = self.normal_windowsize * self.normal_quant_size
table_shape_norm = (3, 2 * quant_grid_length_norm, num_heads, head_dim)
self.query_norm_table = nn.Parameter(torch.zeros(table_shape_norm))
trunc_normal_(self.query_norm_table, std=0.02)
self.key_norm_table = nn.Parameter(torch.zeros(table_shape_norm))
trunc_normal_(self.key_norm_table, std=0.02)
self.value_norm_table = nn.Parameter(torch.zeros(table_shape_norm))
trunc_normal_(self.value_norm_table, std=0.02)
table_offsets += [np.prod(table_shape_norm[1:])] * 3
self.table_offsets = table_offsets
self.quant_size = quant_size
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop, inplace=True)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop, inplace=True)
self.softmax = nn.Softmax(dim=-1)
def forward(self, feats: torch.Tensor, attn_args):
"""Forward function.
Args:
feats: N, C
attn_args: arguments for computing attention
"""
num_v, _ = feats.shape
num_sc = self.dim // self.num_heads
(
x_offset,
y_offset,
m2w_indices,
w_sizes,
w2n_indices,
n2n_indices,
w2m_indices,
n_coords,
) = attn_args
# Query, Key, Value
qkv = self.qkv(feats)
qkv = (
qkv.reshape(num_v, 3, self.num_heads, num_sc)
.permute(1, 0, 2, 3)
.contiguous()
)
query, key, value = qkv[0], qkv[1], qkv[2] # [N, num_heads, C//num_heads]
query = query * self.scale
table_offsets = torch.IntTensor(self.table_offsets).cuda()
query_table, key_table, value_table = [], [], []
n_cRSE = []
if "XYZ" in self.cRSE:
n_xyz = n_coords[:, 0:3]
n_xyz = n_xyz * self.quant_size
n_cRSE.append(n_xyz)
query_table.append(self.query_xyz_table.view(-1))
key_table.append(self.key_xyz_table.view(-1))
value_table.append(self.value_xyz_table.view(-1))
if "RGB" in self.cRSE:
n_rgb = n_coords[:, 3:6]
n_rgb = n_rgb * self.color_quant_size
n_cRSE.append(n_rgb)
query_table.append(self.query_rgb_table.view(-1))
key_table.append(self.key_rgb_table.view(-1))
value_table.append(self.value_rgb_table.view(-1))
if "NORM" in self.cRSE:
n_norm = n_coords[:, 6:9]
n_norm = n_norm * self.normal_quant_size
n_cRSE.append(n_norm)
query_table.append(self.query_norm_table.view(-1))
key_table.append(self.key_norm_table.view(-1))
value_table.append(self.value_norm_table.view(-1))
n_cRSE = torch.cat(n_cRSE, dim=1)
indices = [m2w_indices, w_sizes, w2m_indices, w2n_indices, n2n_indices, n_cRSE]
query_table = torch.cat(query_table)
key_table = torch.cat(key_table)
value_table = torch.cat(value_table)
if self.fp16_mode == 0:
# do not use fp16
# cast q,k,v to fp32 in forward and backward
fp16_mode = PrecisionMode.HALF_NONE
elif self.fp16_mode == 1:
# use fp16 only in forward
fp16_mode = PrecisionMode.HALF_FORWARD
elif self.fp16_mode == 2:
# use fp16 both in forward and backward
fp16_mode = PrecisionMode.HALF_ALL
updated_values = SelfAttnAIOFunction.apply(
query,
key,
value,
query_table,
key_table,
value_table,
table_offsets,
indices,
PosEmb.SEPARATE,
TableDims.D0,
IndexMode.INDIRECT,
fp16_mode,
)
updated_values = updated_values.flatten(1)
updated_feats = updated_values.view(num_v, self.dim)
updated_feats = self.proj(updated_feats)
updated_feats = self.proj_drop(updated_feats) # [N, C]
return updated_feats
class SwinTransformerBlock(nn.Module):
def __init__(
self,
dim,
num_heads,
window_size,
quant_size,
drop_path=0.0,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
cRSE="XYZ_RGB",
fp16_mode=0,
):
super().__init__()
self.window_size = window_size
self.norm1 = norm_layer(dim)
self.attn = WindowAttention(
dim,
window_size=self.window_size,
quant_size=quant_size,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
cRSE=cRSE,
fp16_mode=fp16_mode,
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer
)
def forward(self, feats, attn_args):
# feats: [N, c]
short_cut = feats
feats = self.norm1(feats)
feats = self.attn(feats, attn_args) # [N, c]
feats = short_cut + self.drop_path(feats)
feats = feats + self.drop_path(self.mlp(self.norm2(feats)))
return feats
class BasicLayer(nn.Module):
"""A basic Swin3D layer for one stage.
Args:
dim (int): Number of input channels.
depth (int): Number of blocks.
num_heads (int): Number of attention heads.
window_size (int): Local window size.
quant_size (int): quant_size for for finer cRSE table
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
cRSE (str | 'XYZ', 'XYZ_RGB', 'XYZ_RGB_NORM'): cRSE mode. Default: 'XYZ_RGB'
fp16_mode (int | 0, 1, 2): fp16 mode for attention module, Default: 0
0: fp32 forward and fp32 backward
1: fp16 forward and fp32 backward
2: fp16 forward and fp16 backward
"""
def __init__(
self,
dim,
depth,
num_heads,
window_size,
quant_size,
out_channels=None,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
drop_path=0.0,
norm_layer=nn.LayerNorm,
downsample=None,
down_stride=2,
cRSE="XYZ_RGB",
fp16_mode=0,
):
super().__init__()
self.window_size = window_size
self.depth = depth
self.dim = dim
self.num_heads = num_heads
self.quant_size = quant_size
self.cRSE = cRSE
self.fp16_mode = fp16_mode
self.shift_size = window_size // 2
# build blocks
self.blocks = nn.ModuleList(
[
SwinTransformerBlock(
dim,
num_heads,
window_size,
quant_size,
drop_path=(
drop_path[i] if isinstance(drop_path, list) else drop_path
),
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
norm_layer=norm_layer,
cRSE=cRSE,
fp16_mode=fp16_mode,
)
for i in range(depth)
]
)
self.pool = ME.MinkowskiMaxPooling(
kernel_size=self.window_size, stride=self.window_size, dimension=3
)
if downsample is not None:
if out_channels is None:
out_channels = dim * 2
self.downsample = downsample(
dim, out_channels, kernel_size=down_stride, stride=down_stride
)
else:
self.downsample = None
def get_map_pair(self, sp):
"""
use minkowski pool to calculate windows
get the mapping from voxel to window
"""
window_size = [self.window_size] * 3
pool_sp = self.pool(sp)
windows = pool_sp.C
window_N = windows.shape[0]
stride_in = sp.coordinate_map_key.get_tensor_stride()
x, y, z = [
torch.arange(window_size[i], device=self.device) * stride_in[i]
for i in range(3)
]
x, y, z = torch.meshgrid(x, y, z)
i = torch.zeros_like(x, device=self.device)
local_window = torch.stack([i, x, y, z], dim=-1).flatten(0, -2)
all_windows = windows.unsqueeze(1) + local_window.unsqueeze(0)
all_windows = all_windows.flatten(0, -2).int()
cm = sp.coordinate_manager
query_key, (map, inverse_map) = cm.insert_and_map(
all_windows, tensor_stride=stride_in
)
map_pair = cm.kernel_map(query_key, sp.coordinate_map_key, kernel_size=1)[0]
return map_pair, window_N
def get_window_mapping(self, sp):
"""
calculate the relationshape in the window:
w_w_id: non-empty idx inside the window(sorted by window)
w_w_xyz: xyz inside the window(sorted by window)
nempty_num: non-empty voxel number in each window
sort_idx: sort voxel according to window_id, to gather the point inside the same window
inv_sort_idx: inverse sort index
"""
map_pair, window_N = self.get_map_pair(sp)
window_size = self.window_size
nW = window_size**3
in_map, out_map = map_pair
in_map, sort_idx = torch.sort(in_map)
# assert out_map == arange(out_map.shape[0])
out_map = out_map[sort_idx]
sort_idx = out_map.long()
inv_sort_idx = torch.zeros_like(sort_idx)
inv_sort_idx[sort_idx] = torch.arange(
sort_idx.shape[0], dtype=sort_idx.dtype, device=self.device
)
N = window_N * nW
v2w_mask = torch.zeros(N, dtype=torch.bool, device=self.device)
w_id = (
torch.arange(window_N, dtype=torch.long, device=self.device)
.unsqueeze(1)
.repeat(1, nW)
.view(-1)
)
w_w_id = (
torch.arange(nW, dtype=torch.long, device=self.device)
.unsqueeze(0)
.repeat(window_N, 1)
.view(-1)
)
v2w_mask[in_map.long()] = True
nempty_num = v2w_mask.view(-1, nW).sum(dim=-1)
w_id = w_id[in_map.long()]
w_w_id = w_w_id[in_map.long()]
w_w_xyz = torch.stack(
[
w_w_id // window_size // window_size,
w_w_id // window_size % window_size,
w_w_id % window_size,
],
dim=-1,
)
return w_w_id, w_w_xyz, nempty_num, sort_idx, inv_sort_idx
def get_index01(self, sp, local_xyz, colors):
"""
calculate the arguments for sparse attention
"""
(
w_w_id,
w_w_xyz,
nempty_num,
n2n_indices,
inv_sort_idx,
) = self.get_window_mapping(sp)
local_xyz = local_xyz[n2n_indices]
colors = colors[n2n_indices]
# recover the relative pos in the voxel
n_coords = w_w_xyz + local_xyz
n_coords = torch.cat([n_coords, colors], dim=1)
(
x_offset,
y_offset,
m2w_indices,
w_sizes,
w2n_indices,
w2m_indices,
) = sparse_self_attention(w_w_id, nempty_num, protocol="v2")
return (
x_offset,
y_offset,
m2w_indices,
w_sizes,
w2n_indices,
n2n_indices,
w2m_indices,
n_coords,
)
def get_shifted_sp(self, sp):
"""
get the shifted sparse tensor for shift-window
"""
stride_in = sp.coordinate_map_key.get_tensor_stride()
shift_size = self.shift_size * stride_in[0]
shifted_C = sp.C.clone()
shifted_C[:, 1:] += shift_size
shifted_sp = SparseTensor(
features=sp.F,
coordinates=shifted_C,
device=self.device,
tensor_stride=stride_in,
)
return shifted_sp
def get_window_pos(self, sp):
stride_in = sp.coordinate_map_key.get_tensor_stride()
return (sp.C[:, 1:] / stride_in[0]) % self.window_size
def forward(self, sp, coords_sp):
"""
xyz: position of point inside voxel
colors: other signal for cRSE, include colors and normals
local_xyz: relative position of point indide voxel(using for finer cRSE table)
"""
colors = coords_sp.F[:, 4:]
xyz = coords_sp.F[:, :4]
local_xyz = (xyz - coords_sp.C)[
:, 1:
] / coords_sp.coordinate_map_key.get_tensor_stride()[0]
self.device = sp.device
sp_shift = self.get_shifted_sp(sp)
attn_args = self.get_index01(sp, local_xyz, colors)
attn_args_shift = self.get_index01(sp_shift, local_xyz, colors)
feats = sp.F
for i, blk in enumerate(self.blocks):
attn_args_blk = attn_args if i % 2 == 0 else attn_args_shift
feats = blk(feats, attn_args_blk) # [N, C]
sp = assign_feats(sp, feats)
if self.downsample is not None:
sp_down, coords_sp = self.downsample(sp, coords_sp)
return sp, sp_down, coords_sp
else:
return sp, sp, coords_sp
def extra_repr(self) -> str:
return f"window_size={self.window_size}, depth={self.depth}, channel={self.dim}, num_heads={self.num_heads}, quant_size={self.quant_size}, cRSE={self.cRSE}, fp16_mode={self.fp16_mode}"
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/swin3d/mink_layers.py | pointcept/models/swin3d/mink_layers.py | """
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import MinkowskiEngine as ME
import numpy as np
def assign_feats(sp, x):
return ME.SparseTensor(
features=x.float(),
coordinate_map_key=sp.coordinate_map_key,
coordinate_manager=sp.coordinate_manager,
)
class MinkConvBN(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size=3,
stride=1,
dilation=1,
bias=False,
dimension=3,
):
super().__init__()
self.conv_layers = nn.Sequential(
ME.MinkowskiConvolution(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
bias=bias,
dimension=dimension,
),
ME.MinkowskiBatchNorm(out_channels),
)
def forward(self, x):
x = self.conv_layers(x)
return x
class MinkConvBNRelu(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size=3,
stride=1,
dilation=1,
bias=False,
dimension=3,
):
super().__init__()
self.conv_layers = nn.Sequential(
ME.MinkowskiConvolution(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
bias=bias,
dimension=dimension,
),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiReLU(inplace=True),
)
def forward(self, x):
x = self.conv_layers(x)
if x.F.dtype == torch.float16:
x = assign_feats(x, x.F.float())
return x
class MinkDeConvBNRelu(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride,
dilation=1,
bias=False,
dimension=3,
):
super().__init__()
self.conv_layers = nn.Sequential(
ME.MinkowskiConvolutionTranspose(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
bias=bias,
dimension=dimension,
),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiReLU(),
)
def forward(self, x):
x = self.conv_layers(x)
return x
class MinkResBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, dilation=1):
super(MinkResBlock, self).__init__()
self.conv1 = ME.MinkowskiConvolution(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
dilation=dilation,
bias=False,
dimension=3,
)
self.norm1 = ME.MinkowskiBatchNorm(out_channels)
self.conv2 = ME.MinkowskiConvolution(
in_channels=out_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
dilation=dilation,
bias=False,
dimension=3,
)
self.norm2 = ME.MinkowskiBatchNorm(out_channels)
self.relu = ME.MinkowskiReLU(inplace=True)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.norm2(out)
out += residual
out = self.relu(out)
return out
class SparseTensorLinear(nn.Module):
def __init__(self, in_channels, out_channels, bias=False):
super().__init__()
self.linear = nn.Linear(in_channels, out_channels, bias=bias)
def forward(self, sp):
x = self.linear(sp.F)
return assign_feats(sp, x.float())
class SparseTensorLayerNorm(nn.Module):
def __init__(self, dim):
super().__init__()
self.norm = nn.LayerNorm(dim)
def forward(self, sp):
x = self.norm(sp.F)
return assign_feats(sp, x.float())
class MinkResBlock_v2(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
d_2 = out_channels // 4
self.conv1 = torch.nn.Sequential(
SparseTensorLinear(in_channels, d_2, bias=False),
ME.MinkowskiBatchNorm(d_2),
ME.MinkowskiReLU(),
)
self.unary_2 = torch.nn.Sequential(
SparseTensorLinear(d_2, out_channels, bias=False),
ME.MinkowskiBatchNorm(out_channels),
ME.MinkowskiReLU(),
)
self.spconv = ME.MinkowskiConvolution(
in_channels=d_2,
out_channels=d_2,
kernel_size=5,
stride=1,
dilation=1,
bias=False,
dimension=3,
)
if in_channels != out_channels:
self.shortcut_op = torch.nn.Sequential(
SparseTensorLinear(in_channels, out_channels, bias=False),
ME.MinkowskiBatchNorm(out_channels),
)
else:
self.shortcut_op = nn.Identity()
def forward(self, x):
# feats: [N, C]
# xyz: [N, 3]
# batch: [N,]
# neighbor_idx: [N, M]
shortcut = x
x = self.unary_1(x)
x = self.spconv(x)
x = self.unary_2(x)
shortcut = self.shortcut_op(shortcut)
x += shortcut
return x
class MinkResBlock_BottleNeck(nn.Module):
def __init__(self, in_channels, out_channels):
super(MinkResBlock_BottleNeck, self).__init__()
bottle_neck = out_channels // 4
self.conv1x1a = MinkConvBNRelu(
in_channels, bottle_neck, kernel_size=1, stride=1
)
self.conv3x3 = MinkConvBNRelu(bottle_neck, bottle_neck, kernel_size=3, stride=1)
self.conv1x1b = MinkConvBN(bottle_neck, out_channels, kernel_size=1, stride=1)
if in_channels != out_channels:
self.conv1x1c = MinkConvBN(
in_channels, out_channels, kernel_size=1, stride=1
)
else:
self.conv1x1c = None
self.relu = ME.MinkowskiReLU(inplace=True)
def forward(self, x):
residual = x
out = self.conv1x1a(x)
out = self.conv3x3(out)
out = self.conv1x1b(out)
if self.conv1x1c is not None:
residual = self.conv1x1c(residual)
out = self.relu(out + residual)
return out
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/swin3d/__init__.py | pointcept/models/swin3d/__init__.py | from .swin3d_v1m1_base import Swin3DUNet
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v3/__init__.py | pointcept/models/point_transformer_v3/__init__.py | from .point_transformer_v3m1_base import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer_v3/point_transformer_v3m1_base.py | pointcept/models/point_transformer_v3/point_transformer_v3m1_base.py | """
Point Transformer - V3 Mode1
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from functools import partial
from addict import Dict
import math
import torch
import torch.nn as nn
import torch.fft as fft
import spconv.pytorch as spconv
import torch_scatter
from einops import rearrange
from timm.models.layers import DropPath
try:
import flash_attn
except ImportError:
flash_attn = None
from pointcept.models.point_prompt_training import PDNorm
from pointcept.models.builder import MODELS
from pointcept.models.utils.misc import offset2bincount
from pointcept.models.utils.structure import Point
from pointcept.models.modules import PointModule, PointSequential
def swish(x):
return x * torch.sigmoid(x)
# ---- ScaleLong ----
def universal_scalling(s_feat,s_factor=2**(-0.5)):
return s_feat * s_factor
def exponentially_scalling(s_feat,k=0.8,i=1):
return s_feat * k**(i - 1)
# ---- ScaleLong ----
# ---- FreeU ----
def Fourier_filter(x, threshold, scale):
# F = FFT(h), equation(6)
x_freq = fft.fftn(x, dim=(-2, -1))
x_freq = fft.fftshift(x_freq, dim=(-2, -1))
# F' = F * B, equation(7)
mask = None
if(len(x.shape) == 3):
B, C, N = x_freq.shape
mask = torch.ones(size=x.shape).to(x.device)
crow = N // 2
mask[..., crow - threshold:crow + threshold] = scale
elif(len(x.shape) == 4):
B, C, H, W = x_freq.shape
mask = torch.ones((B, C, H, W)).to(x.device)
crow, ccol = H // 2, W // 2
mask[..., crow - threshold:crow + threshold, ccol - threshold:ccol + threshold] = scale
x_freq = x_freq * mask
# H = IFFT(F'), equation(8)
x_freq = fft.ifftshift(x_freq, dim=(-2, -1))
x_filtered = fft.ifftn(x_freq, dim=(-2, -1)).real
return x_filtered
def freeU(b_feat, s_feat, b=1.0, s=1.0, C_num=None):
'''
Adjusting b_feat and s_feat.
:param b_feat: backbone features, [B,C,N] or [B,C,H,W]
:param s_feat: skip connection features, [B,C,N] or [B,C,H,W]
:param b: the factor of backbone features, scale value
:param s: the factor of skip connection features, scale value
:param C_num: the channel num of scaling operation
:return: the adjust features of b_feat and s_feat, [B,C,N] or [B,C,H,W]
'''
if(b != 1.0 or s != 1.0):
# [B,C,N]/[B,C,H,W] -> [B,N]/[B,H,W] -> [B,1,N]/[B,1,H,W]
b_feat_mean = b_feat.mean(1).unsqueeze(1)
B, C = b_feat_mean.shape[0],b_feat_mean.shape[1]
if(C_num is None):
C_num = C // 2
b_feat_max, _ = torch.max(b_feat_mean.view(B, -1), dim=-1, keepdim=True)
b_feat_min, _ = torch.min(b_feat_mean.view(B, -1), dim=-1, keepdim=True)
if(len(b_feat.shape) == 3 and len(s_feat.shape) == 3):
b_feat_mean = (b_feat_mean - b_feat_min.unsqueeze(2)) / (b_feat_max - b_feat_min).unsqueeze(2)
elif(len(b_feat.shape) == 4 and len(s_feat.shape) == 4):
b_feat_mean = (b_feat_mean - b_feat_min.unsqueeze(2).unsqueeze(3)) / (b_feat_max - b_feat_min).unsqueeze(2).unsqueeze(3)
'''
a = (b - 1) * ((x_ - max(x_))/(x_ - min(x_)) + 1)
b_feat = b_feat[:, :C_num] * a
equation(4)
'''
b_feat[:, :C_num] = b_feat[:, :C_num] * ((b - 1) * b_feat_mean + 1)
s_feat = Fourier_filter(s_feat, threshold=1, scale=s)
return b_feat.squeeze().permute(1,0), s_feat.squeeze().permute(1,0)
# ---- FreeU ----
class RPE(torch.nn.Module):
def __init__(self, patch_size, num_heads):
super().__init__()
self.patch_size = patch_size
self.num_heads = num_heads
self.pos_bnd = int((4 * patch_size) ** (1 / 3) * 2)
self.rpe_num = 2 * self.pos_bnd + 1
self.rpe_table = torch.nn.Parameter(torch.zeros(3 * self.rpe_num, num_heads))
torch.nn.init.trunc_normal_(self.rpe_table, std=0.02)
def forward(self, coord):
idx = (
coord.clamp(-self.pos_bnd, self.pos_bnd) # clamp into bnd
+ self.pos_bnd # relative position to positive index
+ torch.arange(3, device=coord.device) * self.rpe_num # x, y, z stride
)
out = self.rpe_table.index_select(0, idx.reshape(-1))
out = out.view(idx.shape + (-1,)).sum(3)
out = out.permute(0, 3, 1, 2) # (N, K, K, H) -> (N, H, K, K)
return out
class SerializedAttention(PointModule):
def __init__(
self,
channels,
num_heads,
patch_size,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
order_index=0,
enable_rpe=False,
enable_flash=True,
upcast_attention=True,
upcast_softmax=True,
):
super().__init__()
assert channels % num_heads == 0
self.channels = channels
self.num_heads = num_heads
self.scale = qk_scale or (channels // num_heads) ** -0.5
self.order_index = order_index
self.upcast_attention = upcast_attention
self.upcast_softmax = upcast_softmax
self.enable_rpe = enable_rpe
self.enable_flash = enable_flash
if enable_flash:
assert (
enable_rpe is False
), "Set enable_rpe to False when enable Flash Attention"
assert (
upcast_attention is False
), "Set upcast_attention to False when enable Flash Attention"
assert (
upcast_softmax is False
), "Set upcast_softmax to False when enable Flash Attention"
assert flash_attn is not None, "Make sure flash_attn is installed."
self.patch_size = patch_size
self.attn_drop = attn_drop
else:
# when disable flash attention, we still don't want to use mask
# consequently, patch size will auto set to the
# min number of patch_size_max and number of points
self.patch_size_max = patch_size
self.patch_size = 0
self.attn_drop = torch.nn.Dropout(attn_drop)
self.qkv = torch.nn.Linear(channels, channels * 3, bias=qkv_bias)
self.proj = torch.nn.Linear(channels, channels)
self.proj_drop = torch.nn.Dropout(proj_drop)
self.softmax = torch.nn.Softmax(dim=-1)
self.rpe = RPE(patch_size, num_heads) if self.enable_rpe else None
@torch.no_grad()
def get_rel_pos(self, point, order):
K = self.patch_size
rel_pos_key = f"rel_pos_{self.order_index}"
if rel_pos_key not in point.keys():
grid_coord = point.grid_coord[order]
grid_coord = grid_coord.reshape(-1, K, 3)
point[rel_pos_key] = grid_coord.unsqueeze(2) - grid_coord.unsqueeze(1)
return point[rel_pos_key]
@torch.no_grad()
def get_padding_and_inverse(self, point):
pad_key = "pad"
unpad_key = "unpad"
cu_seqlens_key = "cu_seqlens_key"
if (
pad_key not in point.keys()
or unpad_key not in point.keys()
or cu_seqlens_key not in point.keys()
):
offset = point.offset
bincount = offset2bincount(offset)
bincount_pad = (
torch.div(
bincount + self.patch_size - 1,
self.patch_size,
rounding_mode="trunc",
)
* self.patch_size
)
# only pad point when num of points larger than patch_size
mask_pad = bincount > self.patch_size
bincount_pad = ~mask_pad * bincount + mask_pad * bincount_pad
_offset = nn.functional.pad(offset, (1, 0))
_offset_pad = nn.functional.pad(torch.cumsum(bincount_pad, dim=0), (1, 0))
pad = torch.arange(_offset_pad[-1], device=offset.device)
unpad = torch.arange(_offset[-1], device=offset.device)
cu_seqlens = []
for i in range(len(offset)):
unpad[_offset[i] : _offset[i + 1]] += _offset_pad[i] - _offset[i]
if bincount[i] != bincount_pad[i]:
pad[
_offset_pad[i + 1]
- self.patch_size
+ (bincount[i] % self.patch_size) : _offset_pad[i + 1]
] = pad[
_offset_pad[i + 1]
- 2 * self.patch_size
+ (bincount[i] % self.patch_size) : _offset_pad[i + 1]
- self.patch_size
]
pad[_offset_pad[i] : _offset_pad[i + 1]] -= _offset_pad[i] - _offset[i]
cu_seqlens.append(
torch.arange(
_offset_pad[i],
_offset_pad[i + 1],
step=self.patch_size,
dtype=torch.int32,
device=offset.device,
)
)
point[pad_key] = pad
point[unpad_key] = unpad
point[cu_seqlens_key] = nn.functional.pad(
torch.concat(cu_seqlens), (0, 1), value=_offset_pad[-1]
)
return point[pad_key], point[unpad_key], point[cu_seqlens_key]
def forward(self, point):
if not self.enable_flash:
self.patch_size = min(
offset2bincount(point.offset).min().tolist(), self.patch_size_max
)
H = self.num_heads
K = self.patch_size
C = self.channels
pad, unpad, cu_seqlens = self.get_padding_and_inverse(point)
order = point.serialized_order[self.order_index][pad]
inverse = unpad[point.serialized_inverse[self.order_index]]
# padding and reshape feat and batch for serialized point patch
qkv = self.qkv(point.feat)[order]
if not self.enable_flash:
# encode and reshape qkv: (N', K, 3, H, C') => (3, N', H, K, C')
q, k, v = (
qkv.reshape(-1, K, 3, H, C // H).permute(2, 0, 3, 1, 4).unbind(dim=0)
)
# attn
if self.upcast_attention:
q = q.float()
k = k.float()
attn = (q * self.scale) @ k.transpose(-2, -1) # (N', H, K, K)
if self.enable_rpe:
attn = attn + self.rpe(self.get_rel_pos(point, order))
if self.upcast_softmax:
attn = attn.float()
attn = self.softmax(attn)
attn = self.attn_drop(attn).to(qkv.dtype)
feat = (attn @ v).transpose(1, 2).reshape(-1, C)
else:
feat = flash_attn.flash_attn_varlen_qkvpacked_func(
qkv.half().reshape(-1, 3, H, C // H),
cu_seqlens,
max_seqlen=self.patch_size,
dropout_p=self.attn_drop if self.training else 0,
softmax_scale=self.scale,
).reshape(-1, C)
feat = feat.to(qkv.dtype)
feat = feat[inverse]
# ffn
feat = self.proj(feat)
feat = self.proj_drop(feat)
point.feat = feat
return point
class MLP(nn.Module):
def __init__(
self,
in_channels,
hidden_channels=None,
out_channels=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_channels = out_channels or in_channels
hidden_channels = hidden_channels or in_channels
self.fc1 = nn.Linear(in_channels, hidden_channels)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_channels, out_channels)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Block(PointModule):
def __init__(
self,
channels,
num_heads,
patch_size=48,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.0,
norm_layer=nn.LayerNorm,
act_layer=nn.GELU,
pre_norm=True,
order_index=0,
cpe_indice_key=None,
enable_rpe=False,
enable_flash=True,
upcast_attention=True,
upcast_softmax=True,
T_dim=-1
):
super().__init__()
self.channels = channels
self.pre_norm = pre_norm
self.T_dim = T_dim
self.cpe = PointSequential(
spconv.SubMConv3d(
channels,
channels,
kernel_size=3,
bias=True,
indice_key=cpe_indice_key,
),
nn.Linear(channels, channels),
norm_layer(channels),
)
self.norm1 = PointSequential(norm_layer(channels))
self.attn = SerializedAttention(
channels=channels,
patch_size=patch_size,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attn_drop=attn_drop,
proj_drop=proj_drop,
order_index=order_index,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=upcast_attention,
upcast_softmax=upcast_softmax,
)
self.norm2 = PointSequential(norm_layer(channels))
self.mlp = PointSequential(
MLP(
in_channels=channels,
hidden_channels=int(channels * mlp_ratio),
out_channels=channels,
act_layer=act_layer,
drop=proj_drop,
)
)
self.drop_path = PointSequential(
DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
)
if(self.T_dim != -1):
self.t_mlp = nn.Linear(T_dim,channels)
def forward(self, point: Point):
shortcut = point.feat
point = self.cpe(point)
point.feat = shortcut + point.feat
shortcut = point.feat
if (self.T_dim != -1 and "t_emb" in point.keys()):
t_emb = point['t_emb']
t_emb = self.t_mlp(t_emb)
# t_embed + x, (N,32)
point.feat = shortcut + t_emb
shortcut = point.feat
if self.pre_norm:
point = self.norm1(point)
point = self.drop_path(self.attn(point))
point.feat = shortcut + point.feat
if not self.pre_norm:
point = self.norm1(point)
shortcut = point.feat
if self.pre_norm:
point = self.norm2(point)
point = self.drop_path(self.mlp(point))
point.feat = shortcut + point.feat
if not self.pre_norm:
point = self.norm2(point)
point.sparse_conv_feat = point.sparse_conv_feat.replace_feature(point.feat)
return point
class SerializedPooling(PointModule):
def __init__(
self,
in_channels,
out_channels,
stride=2,
norm_layer=None,
act_layer=None,
reduce="max",
shuffle_orders=True,
traceable=True, # record parent and cluster
T_dim=-1
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.T_dim = T_dim
assert stride == 2 ** (math.ceil(stride) - 1).bit_length() # 2, 4, 8
# TODO: add support to grid pool (any stride)
self.stride = stride
assert reduce in ["sum", "mean", "min", "max"]
self.reduce = reduce
self.shuffle_orders = shuffle_orders
self.traceable = traceable
self.proj = nn.Linear(in_channels, out_channels)
if norm_layer is not None:
self.norm = PointSequential(norm_layer(out_channels))
if act_layer is not None:
self.act = PointSequential(act_layer())
def forward(self, point: Point):
pooling_depth = (math.ceil(self.stride) - 1).bit_length()
if pooling_depth > point.serialized_depth:
pooling_depth = 0
assert {
"serialized_code",
"serialized_order",
"serialized_inverse",
"serialized_depth",
}.issubset(
point.keys()
), "Run point.serialization() point cloud before SerializedPooling"
code = point.serialized_code >> pooling_depth * 3
code_, cluster, counts = torch.unique(
code[0],
sorted=True,
return_inverse=True,
return_counts=True,
)
# indices of point sorted by cluster, for torch_scatter.segment_csr
_, indices = torch.sort(cluster)
# index pointer for sorted point, for torch_scatter.segment_csr
idx_ptr = torch.cat([counts.new_zeros(1), torch.cumsum(counts, dim=0)])
# head_indices of each cluster, for reduce attr e.g. code, batch
head_indices = indices[idx_ptr[:-1]]
# generate down code, order, inverse
code = code[:, head_indices]
order = torch.argsort(code)
inverse = torch.zeros_like(order).scatter_(
dim=1,
index=order,
src=torch.arange(0, code.shape[1], device=order.device).repeat(
code.shape[0], 1
),
)
if self.shuffle_orders:
perm = torch.randperm(code.shape[0])
code = code[perm]
order = order[perm]
inverse = inverse[perm]
if(self.T_dim == -1):
# collect information
point_dict = Dict(
feat=torch_scatter.segment_csr(
self.proj(point.feat)[indices], idx_ptr, reduce=self.reduce
),
coord=torch_scatter.segment_csr(
point.coord[indices], idx_ptr, reduce="mean"
),
grid_coord=point.grid_coord[head_indices] >> pooling_depth,
serialized_code=code,
serialized_order=order,
serialized_inverse=inverse,
serialized_depth=point.serialized_depth - pooling_depth,
batch=point.batch[head_indices],
)
else:
# collect information
point_dict = Dict(
feat=torch_scatter.segment_csr(
self.proj(point.feat)[indices], idx_ptr, reduce=self.reduce
),
coord=torch_scatter.segment_csr(
point.coord[indices], idx_ptr, reduce="mean"
),
grid_coord=point.grid_coord[head_indices] >> pooling_depth,
serialized_code=code,
serialized_order=order,
serialized_inverse=inverse,
serialized_depth=point.serialized_depth - pooling_depth,
batch=point.batch[head_indices],
t_emb=point.t_emb[head_indices],
)
if "condition" in point.keys():
point_dict["condition"] = point.condition
if "context" in point.keys():
point_dict["context"] = point.context
if self.traceable:
point_dict["pooling_inverse"] = cluster
point_dict["pooling_parent"] = point
point = Point(point_dict)
if self.norm is not None:
point = self.norm(point)
if self.act is not None:
point = self.act(point)
point.sparsify()
return point
class SerializedUnpooling(PointModule):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
norm_layer=None,
act_layer=None,
traceable=False, # record parent and cluster
skip_connection_mode="add",
b=1.0,
s=1.0,
skip_connection_scale=False,
skip_connection_scale_i=False
):
super().__init__()
self.proj = PointSequential(nn.Linear(in_channels, out_channels))
self.proj_skip = PointSequential(nn.Linear(skip_channels, out_channels))
self.skip_connection_mode = skip_connection_mode
self.b = b
self.s = s
self.skip_connection_scale = skip_connection_scale
self.skip_connection_scale_i = skip_connection_scale_i
if(skip_connection_mode == "cat"):
self.proj_cat = PointSequential(nn.Linear(out_channels * 2, out_channels))
if norm_layer is not None:
self.proj.add(norm_layer(out_channels))
self.proj_skip.add(norm_layer(out_channels))
if act_layer is not None:
self.proj.add(act_layer())
self.proj_skip.add(act_layer())
self.traceable = traceable
def forward(self, point):
assert "pooling_parent" in point.keys()
assert "pooling_inverse" in point.keys()
parent = point.pop("pooling_parent")
inverse = point.pop("pooling_inverse")
# backbone feat
point = self.proj(point)
# skip feat
parent = self.proj_skip(parent)
# Scaling Skip Connection Features
if (self.skip_connection_scale):
parent.feat = universal_scalling(parent.feat)
if(self.skip_connection_scale_i is not None):
parent.feat = exponentially_scalling(parent.feat,i=self.skip_connection_scale_i)
# FreeU
if(self.b != 1 or self.s != 1):
point.feat, parent.feat = freeU(
point.feat.permute(1, 0).unsqueeze(0),
parent.feat.permute(1, 0).unsqueeze(0),
self.b,
self.s
)
# Skip Connection Mode
if (self.skip_connection_mode == "add"):
parent.feat = parent.feat + point.feat[inverse]
elif(self.skip_connection_mode == "cat"):
parent.feat = self.proj_cat(torch.cat([parent.feat, point.feat[inverse]], dim=-1))
if self.traceable:
parent["unpooling_parent"] = point
return parent
class Embedding(PointModule):
def __init__(
self,
in_channels,
embed_channels,
norm_layer=None,
act_layer=None,
):
super().__init__()
self.in_channels = in_channels
self.embed_channels = embed_channels
# TODO: check remove spconv
self.stem = PointSequential(
conv=spconv.SubMConv3d(
in_channels,
embed_channels,
kernel_size=5,
padding=1,
bias=False,
indice_key="stem",
)
)
if norm_layer is not None:
self.stem.add(norm_layer(embed_channels), name="norm")
if act_layer is not None:
self.stem.add(act_layer(), name="act")
def forward(self, point: Point):
point = self.stem(point)
return point
### ------------- Feature Fusion Module ------------- ###
class SerializedCrossRestomer(PointModule):
def __init__(
self,
q_channels,
kv_channels,
num_heads,
q_patch_size,
kv_patch_size,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
order_index=0,
enable_rpe=False,
enable_flash=False,
upcast_attention=True,
upcast_softmax=True,
):
super().__init__()
assert q_channels % num_heads == 0
assert kv_channels % num_heads == 0
self.q_channels = q_channels
self.kv_channels = kv_channels
self.num_heads = num_heads
self.scale = qk_scale or (q_channels // num_heads) ** -0.5
self.order_index = order_index
self.upcast_attention = upcast_attention
self.upcast_softmax = upcast_softmax
self.enable_rpe = enable_rpe
self.enable_flash = enable_flash
if enable_flash:
assert (
enable_rpe is False
), "Set enable_rpe to False when enable Flash Attention"
assert (
upcast_attention is False
), "Set upcast_attention to False when enable Flash Attention"
assert (
upcast_softmax is False
), "Set upcast_softmax to False when enable Flash Attention"
assert flash_attn is not None, "Make sure flash_attn is installed."
self.q_patch_size = q_patch_size
self.kv_patch_size = kv_patch_size
self.attn_drop = attn_drop
else:
# when disable flash attention, we still don't want to use mask
# consequently, patch size will auto set to the
# min number of patch_size_max and number of points
self.q_patch_size_max = q_patch_size
self.kv_patch_size_max = kv_patch_size
self.q_patch_size = 0
self.kv_patch_size = 0
self.attn_drop = torch.nn.Dropout(attn_drop)
self.q = nn.Conv1d(q_channels, q_channels, kernel_size=1, bias=qkv_bias)
self.q_dwconv = nn.Conv1d(q_channels, q_channels, kernel_size=3, stride=1, padding=1, groups=q_channels, bias=qkv_bias)
self.kv = nn.Conv1d(kv_channels, q_channels*2, kernel_size=1, bias=qkv_bias)
self.kv_dwconv = nn.Conv1d(q_channels* 2 , q_channels * 2, kernel_size=3, stride=1, padding=1, groups= q_channels * 2, bias=qkv_bias)
self.proj = nn.Conv1d(q_channels, q_channels, kernel_size=1, bias=qkv_bias)
self.softmax = torch.nn.Softmax(dim=-1)
self.rpe = RPE(q_patch_size, num_heads) if self.enable_rpe else None
self.temperature = nn.Parameter(torch.ones(num_heads, 1, 1))
@torch.no_grad()
def get_rel_pos(self, point, order):
K = self.patch_size
rel_pos_key = f"rel_pos_{self.order_index}"
if rel_pos_key not in point.keys():
grid_coord = point.grid_coord[order]
grid_coord = grid_coord.reshape(-1, K, 3)
point[rel_pos_key] = grid_coord.unsqueeze(2) - grid_coord.unsqueeze(1)
return point[rel_pos_key]
@torch.no_grad()
def get_padding_and_inverse(self, point):
pad_key = "pad"
unpad_key = "unpad"
cu_seqlens_key = "cu_seqlens_key"
if (
pad_key not in point.keys()
or unpad_key not in point.keys()
or cu_seqlens_key not in point.keys()
):
offset = point.offset
bincount = offset2bincount(offset)
bincount_pad = (
torch.div(
bincount + self.q_patch_size - 1,
self.q_patch_size,
rounding_mode="trunc",
)
* self.q_patch_size
)
# only pad point when num of points larger than patch_size
mask_pad = bincount > self.q_patch_size
bincount_pad = ~mask_pad * bincount + mask_pad * bincount_pad
_offset = nn.functional.pad(offset, (1, 0))
_offset_pad = nn.functional.pad(torch.cumsum(bincount_pad, dim=0), (1, 0))
pad = torch.arange(_offset_pad[-1], device=offset.device)
unpad = torch.arange(_offset[-1], device=offset.device)
cu_seqlens = []
for i in range(len(offset)):
unpad[_offset[i]: _offset[i + 1]] += _offset_pad[i] - _offset[i]
if bincount[i] != bincount_pad[i]:
pad[
_offset_pad[i + 1]
- self.q_patch_size
+ (bincount[i] % self.q_patch_size): _offset_pad[i + 1]
] = pad[
_offset_pad[i + 1]
- 2 * self.q_patch_size
+ (bincount[i] % self.q_patch_size): _offset_pad[i + 1]
- self.q_patch_size
]
pad[_offset_pad[i]: _offset_pad[i + 1]] -= _offset_pad[i] - _offset[i]
cu_seqlens.append(
torch.arange(
_offset_pad[i],
_offset_pad[i + 1],
step=self.q_patch_size,
dtype=torch.int32,
device=offset.device,
)
)
point[pad_key] = pad
point[unpad_key] = unpad
point[cu_seqlens_key] = nn.functional.pad(
torch.concat(cu_seqlens), (0, 1), value=_offset_pad[-1]
)
return point[pad_key], point[unpad_key], point[cu_seqlens_key]
def forward(self, q_point, kv_point):
if not self.enable_flash: # True
self.q_patch_size = min(
offset2bincount(q_point.offset).min().tolist(), self.q_patch_size_max
)
if not self.enable_flash: # True
self.kv_patch_size = min(
offset2bincount(kv_point.offset).min().tolist(), self.kv_patch_size_max
)
H = self.num_heads
q_K = self.q_patch_size
kv_K = self.kv_patch_size
q_C = self.q_channels
kv_C = self.kv_channels
# 这是为了填补batch size,以至于可以并行执行attention。填补所有batch至最大batch的点数量
q_pad, q_unpad, q_cu_seqlens = self.get_padding_and_inverse(q_point)
q_order = q_point.serialized_order[self.order_index][q_pad]
q_inverse = q_unpad[q_point.serialized_inverse[self.order_index]]
# kv_pad, kv_unpad, kv_cu_seqlens = self.get_padding_and_inverse(kv_point)
kv_pad, kv_unpad, kv_cu_seqlens = q_pad, q_unpad, q_cu_seqlens
kv_order = kv_point.serialized_order[self.order_index][kv_pad]
# kv_inverse = kv_unpad[kv_point.serialized_inverse[self.order_index]]
# padding and reshape feat and batch for serialized point patch
q = q_point.feat.unsqueeze(dim=0).permute(0,2,1)
kv = kv_point.feat.unsqueeze(dim=0).permute(0,2,1)
# q = q_point.feat[q_order].reshape(-1, q_K, q_C).permute(0,2,1)
# kv = kv_point.feat[kv_order].reshape(-1, kv_K, kv_C).permute(0,2,1)
q = self.q_dwconv(self.q(q)) # (N, C, K)
q = q.permute(0, 2, 1).squeeze()[q_order].unsqueeze(dim=0).permute(0, 2, 1)
k, v = self.kv_dwconv(self.kv(kv)).chunk(2, dim=1) # (N, 2 * C, K)
k = k.permute(0, 2, 1).squeeze()[kv_order].unsqueeze(dim=0).permute(0, 2, 1)
v = v.permute(0, 2, 1).squeeze()[kv_order].unsqueeze(dim=0).permute(0, 2, 1)
# (N, C, K) ===> (N, H, HC, K)
q, k, v = map(lambda t: rearrange(t, 'n (h hc) k -> n h hc k', h=H, hc=q_C // H), (q, k, v))
q = torch.nn.functional.normalize(q, dim=-1)
k = torch.nn.functional.normalize(k, dim=-1)
# restomer attention
attn = (q @ k.transpose(-2, -1)) * self.temperature
attn = self.softmax(attn)
attn = self.attn_drop(attn).to(q.dtype)
feat = (attn @ v)
# project
feat = rearrange(feat, ' n h hc k -> n (h hc) k', h = H, hc = q_C // H)
feat = self.proj(feat).transpose(1, 2).reshape(-1, q_C)
feat = feat[q_inverse].float() # return initial point. each index is unque.
q_point.feat = feat
return q_point
class SerializedCrossAttention(PointModule):
def __init__(
self,
q_channels,
kv_channels,
num_heads,
q_patch_size,
kv_patch_size,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
order_index=0,
enable_rpe=False,
enable_flash=True,
upcast_attention=True,
upcast_softmax=True,
):
super().__init__()
assert q_channels % num_heads == 0
assert kv_channels % num_heads == 0
self.q_channels = q_channels
self.kv_channels = kv_channels
self.num_heads = num_heads
self.scale = qk_scale or (q_channels // num_heads) ** -0.5
self.order_index = order_index
self.upcast_attention = upcast_attention
self.upcast_softmax = upcast_softmax
self.enable_rpe = enable_rpe
self.enable_flash = enable_flash
if enable_flash:
assert (
enable_rpe is False
), "Set enable_rpe to False when enable Flash Attention"
assert (
upcast_attention is False
), "Set upcast_attention to False when enable Flash Attention"
assert (
upcast_softmax is False
), "Set upcast_softmax to False when enable Flash Attention"
assert flash_attn is not None, "Make sure flash_attn is installed."
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | true |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/stratified_transformer/stratified_transformer_v1m2_refine.py | pointcept/models/stratified_transformer/stratified_transformer_v1m2_refine.py | """
Stratified Transformer
Modified from https://github.com/dvlab-research/Stratified-Transformer
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from copy import deepcopy
import torch
import torch.nn as nn
try:
import torch_points_kernels as tp
except ImportError:
tp = None
try:
from torch_points3d.modules.KPConv.kernels import KPConvLayer
from torch_points3d.core.common_modules import FastBatchNorm1d
except ImportError:
KPConvLayer = None
FastBatchNorm1d = None
from torch_scatter import scatter_softmax
from timm.models.layers import DropPath, trunc_normal_
from torch_geometric.nn.pool import voxel_grid
try:
import pointops2.pointops as pointops
except ImportError:
pointops = None
from pointcept.models.builder import MODELS
def offset2batch(offset):
return (
torch.cat(
[
(
torch.tensor([i] * (o - offset[i - 1]))
if i > 0
else torch.tensor([i] * o)
)
for i, o in enumerate(offset)
],
dim=0,
)
.long()
.to(offset.device)
)
def grid_sample(coords, batch, size, start, return_p2v=True):
cluster = voxel_grid(coords, batch, size, start=start)
if not return_p2v:
unique, cluster = torch.unique(cluster, sorted=True, return_inverse=True)
return cluster
else:
unique, cluster, counts = torch.unique(
cluster, sorted=True, return_inverse=True, return_counts=True
)
# obtain p2v_map
n = unique.shape[0]
k = counts.max().item()
p2v_map = cluster.new_zeros(n, k)
mask = torch.arange(k).cuda().unsqueeze(0) < counts.unsqueeze(-1)
p2v_map[mask] = torch.argsort(cluster)
return cluster, p2v_map, counts
class WindowAttention(nn.Module):
"""Window based multi-head self attention (W-MSA) module with relative position bias.
It supports both of shifted and non-shifted window.
"""
def __init__(
self,
embed_channels,
num_heads,
window_size,
quant_size,
attn_drop=0.0,
proj_drop=0.0,
scale=None,
rel_query=True,
rel_key=True,
rel_value=True,
qkv_bias=True,
):
super().__init__()
self.embed_channels = embed_channels
self.head_channels = embed_channels // num_heads
self.num_heads = num_heads
self.scale = scale or self.head_channels**-0.5
self.window_size = window_size
self.quant_size = quant_size
self.rel_query = rel_query
self.rel_key = rel_key
self.rel_value = rel_value
self.quant_grid_length = int((2 * window_size + 1e-4) // quant_size)
assert self.rel_query and self.rel_key
if rel_query:
self.relative_pos_query_table = nn.Parameter(
torch.zeros(
2 * self.quant_grid_length, self.num_heads, self.head_channels, 3
)
)
trunc_normal_(self.relative_pos_query_table, std=0.02)
if rel_key:
self.relative_pos_key_table = nn.Parameter(
torch.zeros(
2 * self.quant_grid_length, self.num_heads, self.head_channels, 3
)
)
trunc_normal_(self.relative_pos_query_table, std=0.02)
if rel_value:
self.relative_pos_value_table = nn.Parameter(
torch.zeros(
2 * self.quant_grid_length, self.num_heads, self.head_channels, 3
)
)
trunc_normal_(self.relative_pos_query_table, std=0.02)
self.qkv = nn.Linear(embed_channels, embed_channels * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop, inplace=True)
self.proj = nn.Linear(embed_channels, embed_channels)
self.proj_drop = nn.Dropout(proj_drop, inplace=True)
self.softmax = nn.Softmax(dim=-1)
def forward(self, feats, coords, index_0, index_1, index_0_offsets, n_max):
n, c = feats.shape
m = index_0.shape[0]
assert index_0.shape[0] == index_1.shape[0]
qkv = (
self.qkv(feats)
.reshape(n, 3, self.num_heads, c // self.num_heads)
.permute(1, 0, 2, 3)
.contiguous()
)
query, key, value = qkv[0], qkv[1], qkv[2]
query = query * self.scale
attn_flat = pointops.attention_step1_v2(
query.float(), key.float(), index_1.int(), index_0_offsets.int(), n_max
)
# Position embedding
relative_position = coords[index_0] - coords[index_1]
relative_position = torch.round(relative_position * 100000) / 100000
relative_position_index = torch.div(
relative_position + 2 * self.window_size - 1e-4,
self.quant_size,
rounding_mode="trunc",
)
# relative_position_index = (relative_position + 2 * self.window_size - 1e-4) // self.quant_size
assert (relative_position_index >= 0).all()
assert (relative_position_index <= 2 * self.quant_grid_length - 1).all()
if self.rel_query and self.rel_key:
relative_position_bias = pointops.dot_prod_with_idx_v3(
query.float(),
index_0_offsets.int(),
n_max,
key.float(),
index_1.int(),
self.relative_pos_query_table.float(),
self.relative_pos_key_table.float(),
relative_position_index.int(),
)
elif self.rel_query:
relative_position_bias = pointops.dot_prod_with_idx(
query.float(),
index_0.int(),
self.relative_pos_query_table.float(),
relative_position_index.int(),
) # [M, num_heads]
elif self.rel_key:
relative_position_bias = pointops.dot_prod_with_idx(
key.float(),
index_1.int(),
self.relative_pos_key_table.float(),
relative_position_index.int(),
) # [M, num_heads]
else:
relative_position_bias = 0.0
attn_flat += relative_position_bias
softmax_attn_flat = scatter_softmax(src=attn_flat, index=index_0, dim=0)
if self.rel_value:
x = pointops.attention_step2_with_rel_pos_value_v2(
softmax_attn_flat.float(),
value.float(),
index_0_offsets.int(),
n_max,
index_1.int(),
self.relative_pos_value_table.float(),
relative_position_index.int(),
)
else:
x = pointops.attention_step2(
softmax_attn_flat.float(), value.float(), index_0.int(), index_1.int()
)
x = x.view(n, c)
x = self.proj(x)
x = self.proj_drop(x)
return x
class MLP(nn.Module):
def __init__(self, in_channels, hidden_channels=None, out_channels=None, drop=0.0):
super().__init__()
out_channels = out_channels or in_channels
hidden_channels = hidden_channels or in_channels
self.fc1 = nn.Linear(in_channels, hidden_channels)
self.act = nn.GELU()
self.fc2 = nn.Linear(hidden_channels, out_channels)
self.drop = nn.Dropout(drop, inplace=True)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Block(nn.Module):
def __init__(
self,
embed_channels,
num_heads,
window_size,
quant_size,
mlp_expend_ratio=4.0,
drop_path=0.0,
qk_scale=None,
rel_query=True,
rel_key=True,
rel_value=True,
qkv_bias=True,
):
super().__init__()
self.norm1 = nn.LayerNorm(embed_channels)
self.attn = WindowAttention(
embed_channels,
num_heads,
window_size,
quant_size,
scale=qk_scale,
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
qkv_bias=qkv_bias,
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = nn.LayerNorm(embed_channels)
self.mlp = MLP(
in_channels=embed_channels,
hidden_channels=int(embed_channels * mlp_expend_ratio),
)
def forward(self, feats, coords, index_0, index_1, index_0_offsets, n_max):
short_cut = feats
feats = self.norm1(feats)
feats = self.attn(feats, coords, index_0, index_1, index_0_offsets, n_max)
feats = short_cut + self.drop_path(feats)
feats += self.drop_path(self.mlp(self.norm2(feats)))
return feats
class BasicLayer(nn.Module):
def __init__(
self,
embed_channels,
out_channels,
depth,
num_heads,
window_size,
quant_size,
mlp_expend_ratio=4.0,
down_ratio=0.25,
down_num_sample=16,
drop_path=None,
qk_scale=None,
down=True,
rel_query=True,
rel_key=True,
rel_value=True,
qkv_bias=True,
):
super().__init__()
self.depth = depth
self.window_size = window_size
self.quant_size = quant_size
self.down_ratio = down_ratio
if isinstance(drop_path, list):
drop_path = drop_path
assert len(drop_path) == depth
elif isinstance(drop_path, float):
drop_path = [deepcopy(drop_path) for _ in range(depth)]
else:
drop_path = [0.0 for _ in range(depth)]
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
embed_channels,
num_heads,
window_size,
quant_size,
mlp_expend_ratio=mlp_expend_ratio,
drop_path=drop_path[i],
qk_scale=qk_scale,
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
qkv_bias=qkv_bias,
)
self.blocks.append(block)
self.down = (
TransitionDown(embed_channels, out_channels, down_ratio, down_num_sample)
if down
else None
)
def forward(self, feats, coords, offset):
# window_size -> [window_size, window_size, window_size]
window_size = torch.tensor(
[self.window_size] * 3, dtype=coords.dtype, device=coords.device
)
new_window_size = 2 * torch.tensor(
[self.window_size] * 3, dtype=coords.dtype, device=coords.device
)
batch = offset2batch(offset)
# compute new offset
new_offset = [int(offset[0].item() * self.down_ratio) + 1]
count = int(offset[0].item() * self.down_ratio) + 1
for i in range(1, offset.shape[0]):
count += (
int((offset[i].item() - offset[i - 1].item()) * self.down_ratio) + 1
)
new_offset.append(count)
new_offset = torch.cuda.IntTensor(new_offset)
down_idx = pointops.furthestsampling(coords, offset.int(), new_offset.int())
# compute window mapping
coords_min = coords.min(0).values
v2p_map, p2v_map, counts = grid_sample(coords, batch, window_size, start=None)
shift_size = window_size * 1 / 2
shift_v2p_map, shift_p2v_map, shift_counts = grid_sample(
coords + shift_size, batch, window_size, start=coords_min
)
new_v2p_map, new_p2v_map, new_counts = grid_sample(
coords, batch, new_window_size, start=None
)
shift_size = new_window_size * 1 / 2
shift_new_v2p_map, shift_new_p2v_map, shift_new_counts = grid_sample(
coords + shift_size, batch, new_window_size, start=coords_min
)
# stratified attention
for i, blk in enumerate(self.blocks):
p2v_map_blk = p2v_map if i % 2 == 0 else shift_p2v_map
counts_blk = counts if i % 2 == 0 else shift_counts
new_p2v_map_blk = new_p2v_map if i % 2 == 0 else shift_new_p2v_map
new_counts_blk = new_counts if i % 2 == 0 else shift_new_counts
n, k = p2v_map_blk.shape
mask = torch.arange(k).unsqueeze(0).cuda() < counts_blk.unsqueeze(-1)
mask_mat = mask.unsqueeze(-1) & mask.unsqueeze(-2)
index_0 = p2v_map_blk.unsqueeze(-1).expand(-1, -1, k)[mask_mat]
index_1 = p2v_map_blk.unsqueeze(1).expand(-1, k, -1)[mask_mat]
down_mask = torch.zeros_like(batch).bool()
down_mask[down_idx.long()] = True
down_mask = down_mask[new_p2v_map_blk] # [n, k], down sample mask
n, k = new_p2v_map_blk.shape
mask = torch.arange(k).unsqueeze(0).cuda() < new_counts_blk.unsqueeze(
-1
) # [n, k]
down_mask = down_mask & mask # down sample and window mask
# [n, k, k] query: dense point in large windows; key: sparse point in large windows
mask_mat = mask.unsqueeze(-1) & down_mask.unsqueeze(-2)
if i % 2 == 0:
# [n, k, 3]
# window_coord = (coords[new_p2v_map_blk] - coords_min) // window_size
window_coord = torch.div(
coords[new_p2v_map_blk] - coords_min,
window_size,
rounding_mode="trunc",
)
else:
# [n, k, 3]
# window_coord = (coords[new_p2v_map_blk] - coords_min + 1/2 * window_size) // window_size
window_coord = torch.div(
coords[new_p2v_map_blk] - coords_min + 1 / 2 * window_size,
window_size,
rounding_mode="trunc",
)
# [n, k, k], whether pair points are in same small windows
mask_mat_prev = (
window_coord.unsqueeze(2) != window_coord.unsqueeze(1)
).any(-1)
mask_mat = mask_mat & mask_mat_prev
new_index_0 = new_p2v_map_blk.unsqueeze(-1).expand(-1, -1, k)[mask_mat]
new_index_1 = new_p2v_map_blk.unsqueeze(1).expand(-1, k, -1)[mask_mat]
index_0 = torch.cat([index_0, new_index_0], 0)
index_1 = torch.cat([index_1, new_index_1], 0)
# rearrange index for acceleration
index_0, indices = torch.sort(index_0)
index_1 = index_1[indices]
index_0_counts = index_0.bincount()
n_max = index_0_counts.max()
index_0_offsets = index_0_counts.cumsum(dim=-1)
index_0_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_0_offsets], 0
)
feats = blk(feats, coords, index_0, index_1, index_0_offsets, n_max)
if self.down:
feats_down, coords_down, offset_down = self.down(feats, coords, offset)
else:
feats_down, coords_down, offset_down = None, None, None
return feats, coords, offset, feats_down, coords_down, offset_down
class TransitionDown(nn.Module):
def __init__(self, in_channels, out_channels, ratio, k, norm_layer=nn.LayerNorm):
super().__init__()
self.ratio = ratio
self.k = k
self.norm = norm_layer(in_channels) if norm_layer else None
self.linear = nn.Linear(in_channels, out_channels, bias=False)
self.pool = nn.MaxPool1d(k)
def forward(self, feats, coords, offset):
new_offset, count = [int(offset[0].item() * self.ratio) + 1], int(
offset[0].item() * self.ratio
) + 1
for i in range(1, offset.shape[0]):
count += ((offset[i].item() - offset[i - 1].item()) * self.ratio) + 1
new_offset.append(count)
new_offset = torch.cuda.IntTensor(new_offset)
idx = pointops.furthestsampling(coords, offset, new_offset) # (m)
new_coords = coords[idx.long(), :] # (m, 3)
feats = pointops.queryandgroup(
self.k, coords, new_coords, feats, None, offset, new_offset, use_xyz=False
) # (m, nsample, 3+c)
m, k, c = feats.shape
feats = (
self.linear(self.norm(feats.view(m * k, c)).view(m, k, c))
.transpose(1, 2)
.contiguous()
)
feats = self.pool(feats).squeeze(-1) # (m, c)
return feats, new_coords, new_offset
class TransitionUp(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.linear1 = nn.Sequential(
nn.LayerNorm(out_channels), nn.Linear(out_channels, out_channels)
)
self.linear2 = nn.Sequential(
nn.LayerNorm(in_channels), nn.Linear(in_channels, out_channels)
)
def forward(self, feats, coords, offset, skip_feats, skip_coords, skip_offset):
feats = self.linear1(skip_feats) + pointops.interpolation(
coords, skip_coords, self.linear2(feats), offset, skip_offset
)
return feats, skip_coords, skip_offset
class KPConvSimpleBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
prev_grid_size,
sigma=1.0,
negative_slope=0.2,
bn_momentum=0.02,
):
super().__init__()
self.kpconv = KPConvLayer(
in_channels,
out_channels,
point_influence=prev_grid_size * sigma,
add_one=False,
)
self.bn = FastBatchNorm1d(out_channels, momentum=bn_momentum)
self.activation = nn.LeakyReLU(negative_slope=negative_slope)
def forward(self, feats, xyz, batch, neighbor_idx):
# feats: [N, C]
# coords: [N, 3]
# batch: [N,]
# neighbor_idx: [N, M]
feats = self.kpconv(xyz, xyz, neighbor_idx, feats)
feats = self.activation(self.bn(feats))
return feats
class KPConvResBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
prev_grid_size,
sigma=1.0,
negative_slope=0.2,
bn_momentum=0.02,
):
super().__init__()
d_2 = out_channels // 4
activation = nn.LeakyReLU(negative_slope=negative_slope)
self.unary_1 = torch.nn.Sequential(
nn.Linear(in_channels, d_2, bias=False),
FastBatchNorm1d(d_2, momentum=bn_momentum),
activation,
)
self.unary_2 = torch.nn.Sequential(
nn.Linear(d_2, out_channels, bias=False),
FastBatchNorm1d(out_channels, momentum=bn_momentum),
activation,
)
self.kpconv = KPConvLayer(
d_2, d_2, point_influence=prev_grid_size * sigma, add_one=False
)
self.bn = FastBatchNorm1d(out_channels, momentum=bn_momentum)
self.activation = activation
if in_channels != out_channels:
self.shortcut_op = torch.nn.Sequential(
nn.Linear(in_channels, out_channels, bias=False),
FastBatchNorm1d(out_channels, momentum=bn_momentum),
)
else:
self.shortcut_op = nn.Identity()
def forward(self, feats, xyz, batch, neighbor_idx):
# feats: [N, C]
# coords: [N, 3]
# batch: [N,]
# neighbor_idx: [N, M]
shortcut = feats
feats = self.unary_1(feats)
feats = self.kpconv(xyz, xyz, neighbor_idx, feats)
feats = self.unary_2(feats)
shortcut = self.shortcut_op(shortcut)
feats += shortcut
return feats
@MODELS.register_module("ST-v1m2")
class StratifiedTransformer(nn.Module):
def __init__(
self,
in_channels,
num_classes,
channels=(48, 96, 192, 384, 384),
num_heads=(6, 12, 24, 24),
depths=(3, 9, 3, 3),
window_size=(0.2, 0.4, 0.8, 1.6),
quant_size=(0.01, 0.02, 0.04, 0.08),
mlp_expend_ratio=4.0,
down_ratio=0.25,
down_num_sample=16,
kp_ball_radius=2.5 * 0.02,
kp_max_neighbor=34,
kp_grid_size=0.02,
kp_sigma=1.0,
drop_path_rate=0.2,
rel_query=True,
rel_key=True,
rel_value=True,
qkv_bias=True,
stem=True,
):
super().__init__()
assert (
KPConvLayer is not None and FastBatchNorm1d is not None
), "Please make sure torch_points3d is installed"
assert tp is not None, "Please make sure torch_points_kernels is installed"
assert pointops is not None, "Please make sure pointops2 is installed"
# stochastic depth decay rule
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
self.kp_ball_radius = kp_ball_radius
self.kp_max_neighbor = kp_max_neighbor
self.stem = stem
if stem:
self.point_embed = nn.ModuleList(
[
KPConvSimpleBlock(
in_channels, channels[0], kp_grid_size, sigma=kp_sigma
),
KPConvResBlock(
channels[0], channels[0], kp_grid_size, sigma=kp_sigma
),
]
)
self.down = TransitionDown(
channels[0], channels[1], down_ratio, down_num_sample
)
else:
assert channels[0] == channels[1]
self.point_embed = nn.ModuleList(
[
KPConvSimpleBlock(
in_channels, channels[1], kp_grid_size, sigma=kp_sigma
),
]
)
num_layers = len(depths)
self.layers = nn.ModuleList()
for i in range(num_layers):
layer = BasicLayer(
embed_channels=channels[i + 1],
out_channels=channels[i + 2] if i < num_layers - 1 else channels[i + 1],
depth=depths[i],
num_heads=num_heads[i],
window_size=window_size[i],
quant_size=quant_size[i],
mlp_expend_ratio=mlp_expend_ratio,
down_ratio=down_ratio,
down_num_sample=down_num_sample,
drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])],
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
qkv_bias=qkv_bias,
down=True if i < num_layers - 1 else False,
)
self.layers.append(layer)
self.up = nn.ModuleList(
[
TransitionUp(channels[i + 1], channels[i])
for i in reversed(range(1, num_layers))
]
)
if self.stem:
self.up.append(TransitionUp(channels[1], channels[0]))
self.classifier = nn.Sequential(
nn.Linear(channels[0], channels[0]),
nn.BatchNorm1d(channels[0]),
nn.ReLU(inplace=True),
nn.Linear(channels[0], num_classes),
)
self.init_weights()
def forward(self, data_dict):
feats = data_dict["feat"]
coords = data_dict["coord"]
offset = data_dict["offset"].int()
batch = offset2batch(offset)
neighbor_idx = tp.ball_query(
self.kp_ball_radius,
self.kp_max_neighbor,
coords,
coords,
mode="partial_dense",
batch_x=batch,
batch_y=batch,
)[0]
feats_stack = []
coords_stack = []
offset_stack = []
for i, layer in enumerate(self.point_embed):
feats = layer(feats, coords, batch, neighbor_idx)
feats = feats.contiguous()
if self.stem:
feats_stack.append(feats)
coords_stack.append(coords)
offset_stack.append(offset)
feats, coords, offset = self.down(feats, coords, offset)
for i, layer in enumerate(self.layers):
feats, coords, offset, feats_down, coords_down, offset_down = layer(
feats, coords, offset
)
feats_stack.append(feats)
coords_stack.append(coords)
offset_stack.append(offset)
feats = feats_down
coords = coords_down
offset = offset_down
feats = feats_stack.pop()
coords = coords_stack.pop()
offset = offset_stack.pop()
for i, up in enumerate(self.up):
feats, coords, offset = up(
feats,
coords,
offset,
feats_stack.pop(),
coords_stack.pop(),
offset_stack.pop(),
)
out = self.classifier(feats)
return out
def init_weights(self):
"""Initialize the weights in backbone."""
def _init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm) or isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
self.apply(_init_weights)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/stratified_transformer/stratified_transformer_v1m1_origin.py | pointcept/models/stratified_transformer/stratified_transformer_v1m1_origin.py | import torch
import torch.nn as nn
try:
import torch_points_kernels as tp
except ImportError:
tp = None
try:
from torch_points3d.modules.KPConv.kernels import KPConvLayer
from torch_points3d.core.common_modules import FastBatchNorm1d
except ImportError:
KPConvLayer = None
FastBatchNorm1d = None
from torch_scatter import scatter_softmax
from timm.models.layers import DropPath, trunc_normal_
from torch_geometric.nn.pool import voxel_grid
try:
import pointops2.pointops as pointops
except ImportError:
pointops = None
from pointcept.models.builder import MODELS
def offset2batch(offset):
return (
torch.cat(
[
(
torch.tensor([i] * (o - offset[i - 1]))
if i > 0
else torch.tensor([i] * o)
)
for i, o in enumerate(offset)
],
dim=0,
)
.long()
.to(offset.device)
)
def get_indice_pairs(
p2v_map, counts, new_p2v_map, new_counts, downsample_idx, batch, xyz, window_size, i
):
# p2v_map: [n, k]
# counts: [n, ]
n, k = p2v_map.shape
mask = torch.arange(k).unsqueeze(0).cuda() < counts.unsqueeze(-1) # [n, k]
mask_mat = mask.unsqueeze(-1) & mask.unsqueeze(-2) # [n, k, k]
index_0 = p2v_map.unsqueeze(-1).expand(-1, -1, k)[mask_mat] # [M, ]
index_1 = p2v_map.unsqueeze(1).expand(-1, k, -1)[mask_mat] # [M, ]
downsample_mask = torch.zeros_like(batch).bool() # [N, ]
downsample_mask[downsample_idx.long()] = True
downsample_mask = downsample_mask[new_p2v_map] # [n, k]
n, k = new_p2v_map.shape
mask = torch.arange(k).unsqueeze(0).cuda() < new_counts.unsqueeze(-1) # [n, k]
downsample_mask = downsample_mask & mask
mask_mat = mask.unsqueeze(-1) & downsample_mask.unsqueeze(-2) # [n, k, k]
xyz_min = xyz.min(0)[0]
if i % 2 == 0:
window_coord = (xyz[new_p2v_map] - xyz_min) // window_size # [n, k, 3]
else:
window_coord = (
xyz[new_p2v_map] + 1 / 2 * window_size - xyz_min
) // window_size # [n, k, 3]
mask_mat_prev = (window_coord.unsqueeze(2) != window_coord.unsqueeze(1)).any(
-1
) # [n, k, k]
mask_mat = mask_mat & mask_mat_prev # [n, k, k]
new_index_0 = new_p2v_map.unsqueeze(-1).expand(-1, -1, k)[mask_mat] # [M, ]
new_index_1 = new_p2v_map.unsqueeze(1).expand(-1, k, -1)[mask_mat] # [M, ]
index_0 = torch.cat([index_0, new_index_0], 0)
index_1 = torch.cat([index_1, new_index_1], 0)
return index_0, index_1
def grid_sample(pos, batch, size, start, return_p2v=True):
# pos: float [N, 3]
# batch: long [N]
# size: float [3, ]
# start: float [3, ] / None
cluster = voxel_grid(pos, batch, size, start=start) # [N, ]
if return_p2v == False:
unique, cluster = torch.unique(cluster, sorted=True, return_inverse=True)
return cluster
unique, cluster, counts = torch.unique(
cluster, sorted=True, return_inverse=True, return_counts=True
)
# obtain p2v_map
n = unique.shape[0]
k = counts.max().item()
p2v_map = cluster.new_zeros(n, k) # [n, k]
mask = torch.arange(k).cuda().unsqueeze(0) < counts.unsqueeze(-1) # [n, k]
p2v_map[mask] = torch.argsort(cluster)
return cluster, p2v_map, counts
class Mlp(nn.Module):
"""Multilayer perceptron."""
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop, inplace=True)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class TransitionDown(nn.Module):
def __init__(self, in_channels, out_channels, ratio, k, norm_layer=nn.LayerNorm):
super().__init__()
self.ratio = ratio
self.k = k
self.norm = norm_layer(in_channels) if norm_layer else None
self.linear = nn.Linear(in_channels, out_channels, bias=False)
self.pool = nn.MaxPool1d(k)
def forward(self, feats, xyz, offset):
n_offset, count = [int(offset[0].item() * self.ratio) + 1], int(
offset[0].item() * self.ratio
) + 1
for i in range(1, offset.shape[0]):
count += ((offset[i].item() - offset[i - 1].item()) * self.ratio) + 1
n_offset.append(count)
n_offset = torch.cuda.IntTensor(n_offset)
idx = pointops.furthestsampling(xyz, offset, n_offset) # (m)
n_xyz = xyz[idx.long(), :] # (m, 3)
feats = pointops.queryandgroup(
self.k, xyz, n_xyz, feats, None, offset, n_offset, use_xyz=False
) # (m, nsample, 3+c)
m, k, c = feats.shape
feats = (
self.linear(self.norm(feats.view(m * k, c)).view(m, k, c))
.transpose(1, 2)
.contiguous()
)
feats = self.pool(feats).squeeze(-1) # (m, c)
return feats, n_xyz, n_offset
class WindowAttention(nn.Module):
"""Window based multi-head self attention (W-MSA) module with relative position bias.
It supports both of shifted and non-shifted window.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
num_heads (int): Number of attention heads.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
"""
def __init__(
self,
dim,
window_size,
num_heads,
quant_size,
rel_query=True,
rel_key=False,
rel_value=False,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
):
super().__init__()
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim**-0.5
self.window_size = window_size
self.quant_size = quant_size
self.rel_query = rel_query
self.rel_key = rel_key
self.rel_value = rel_value
quant_grid_length = int((2 * window_size + 1e-4) // quant_size)
if rel_query:
self.relative_pos_query_table = nn.Parameter(
torch.zeros(2 * quant_grid_length, num_heads, head_dim, 3)
)
trunc_normal_(self.relative_pos_query_table, std=0.02)
if rel_key:
self.relative_pos_key_table = nn.Parameter(
torch.zeros(2 * quant_grid_length, num_heads, head_dim, 3)
)
trunc_normal_(self.relative_pos_key_table, std=0.02)
if rel_value:
self.relative_pos_value_table = nn.Parameter(
torch.zeros(2 * quant_grid_length, num_heads, head_dim, 3)
)
trunc_normal_(self.relative_pos_value_table, std=0.02)
self.quant_grid_length = quant_grid_length
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop, inplace=True)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop, inplace=True)
self.softmax = nn.Softmax(dim=-1)
# def forward(self, feats, xyz, index_0, index_1):
def forward(self, feats, xyz, index_0, index_1, index_0_offsets, n_max):
"""Forward function.
Args:
feats: N, C
xyz: N, 3
index_0: M,
index_1: M,
"""
N, C = feats.shape
M = index_0.shape[0]
assert index_0.shape[0] == index_1.shape[0]
# Query, Key, Value
qkv = (
self.qkv(feats)
.reshape(N, 3, self.num_heads, C // self.num_heads)
.permute(1, 0, 2, 3)
.contiguous()
)
query, key, value = qkv[0], qkv[1], qkv[2] # [N, num_heads, C//num_heads]
query = query * self.scale
attn_flat = pointops.attention_step1_v2(
query.float(), key.float(), index_1.int(), index_0_offsets.int(), n_max
)
# # Position embedding
relative_position = xyz[index_0] - xyz[index_1]
relative_position = torch.round(relative_position * 100000) / 100000
relative_position_index = (
relative_position + 2 * self.window_size - 0.0001
) // self.quant_size
assert (relative_position_index >= 0).all()
assert (relative_position_index <= 2 * self.quant_grid_length - 1).all()
assert self.rel_query and self.rel_key
if self.rel_query and self.rel_key:
relative_position_bias = pointops.dot_prod_with_idx_v3(
query.float(),
index_0_offsets.int(),
n_max,
key.float(),
index_1.int(),
self.relative_pos_query_table.float(),
self.relative_pos_key_table.float(),
relative_position_index.int(),
)
elif self.rel_query:
relative_position_bias = pointops.dot_prod_with_idx(
query.float(),
index_0.int(),
self.relative_pos_query_table.float(),
relative_position_index.int(),
) # [M, num_heads]
elif self.rel_key:
relative_position_bias = pointops.dot_prod_with_idx(
key.float(),
index_1.int(),
self.relative_pos_key_table.float(),
relative_position_index.int(),
) # [M, num_heads]
else:
relative_position_bias = 0.0
attn_flat = attn_flat + relative_position_bias # [M, num_heads]
softmax_attn_flat = scatter_softmax(
src=attn_flat, index=index_0, dim=0
) # [M, num_heads]
if self.rel_value:
x = pointops.attention_step2_with_rel_pos_value_v2(
softmax_attn_flat.float(),
value.float(),
index_0_offsets.int(),
n_max,
index_1.int(),
self.relative_pos_value_table.float(),
relative_position_index.int(),
)
else:
x = pointops.attention_step2(
softmax_attn_flat.float(), value.float(), index_0.int(), index_1.int()
)
x = x.view(N, C)
x = self.proj(x)
x = self.proj_drop(x) # [N, C]
return x
class SwinTransformerBlock(nn.Module):
def __init__(
self,
dim,
num_heads,
window_size,
quant_size,
rel_query=True,
rel_key=False,
rel_value=False,
drop_path=0.0,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
mode=4,
): # mode=4:mean
super().__init__()
self.mode = mode
self.norm1 = norm_layer(dim)
self.attn = WindowAttention(
dim,
window_size,
num_heads=num_heads,
quant_size=quant_size,
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer
)
def forward(self, feats, xyz, index_0, index_1, index_0_offsets, n_max):
# feats: [N, c]
# pos: [N, 3]
short_cut = feats
feats = self.norm1(feats)
feats = self.attn(
feats, xyz, index_0, index_1, index_0_offsets, n_max
) # index_0 MUST be in ascending order
feats = short_cut + self.drop_path(feats)
feats = feats + self.drop_path(self.mlp(self.norm2(feats)))
return feats
class BasicLayer(nn.Module):
def __init__(
self,
downsample_scale,
depth,
channel,
num_heads,
window_size,
grid_size,
quant_size,
rel_query=True,
rel_key=False,
rel_value=False,
drop_path=0.0,
mlp_ratio=4.0,
qkv_bias=True,
qk_scale=None,
norm_layer=nn.LayerNorm,
downsample=None,
ratio=0.25,
k=16,
out_channels=None,
):
super().__init__()
self.depth = depth
self.grid_size = grid_size
self.max_window_counts = 64
self.window_size = window_size
self.downsample_scale = downsample_scale
self.blocks = nn.ModuleList(
[
SwinTransformerBlock(
channel,
num_heads,
window_size,
quant_size,
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
drop_path=(
drop_path[i] if isinstance(drop_path, list) else drop_path
),
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
norm_layer=norm_layer,
)
for i in range(depth)
]
)
self.downsample = (
downsample(channel, out_channels, ratio, k) if downsample else None
)
def forward(self, feats, xyz, offset):
# feats: N, C
# xyz: N, 3
window_size = torch.tensor([self.window_size] * 3).type_as(xyz).to(xyz.device)
offset_ = offset.clone()
offset_[1:] = offset_[1:] - offset_[:-1]
batch = (
torch.cat([torch.tensor([ii] * o) for ii, o in enumerate(offset_)], 0)
.long()
.cuda()
)
v2p_map, p2v_map, counts = grid_sample(xyz, batch, window_size, start=None)
shift_size = 1 / 2 * window_size
shift_v2p_map, shift_p2v_map, shift_counts = grid_sample(
xyz + shift_size, batch, window_size, start=xyz.min(0)[0]
)
downsample_scale = self.downsample_scale
new_offset, count = [offset[0].item() // downsample_scale + 1], offset[
0
].item() // downsample_scale + 1
for i in range(1, offset.shape[0]):
count += (offset[i].item() - offset[i - 1].item()) // downsample_scale + 1
new_offset.append(count)
new_offset = torch.cuda.IntTensor(new_offset)
downsample_idx = pointops.furthestsampling(
xyz, offset.int(), new_offset.int()
) # [N/16,]
new_window_size = 2 * torch.tensor([self.window_size] * 3).type_as(xyz).to(
xyz.device
)
# offset_ = new_offset.clone()
# offset_[1:] = offset_[1:] - offset_[:-1]
# new_batch = torch.cat([torch.tensor([ii]*o) for ii,o in enumerate(offset_)], 0).long().cuda()
new_v2p_map, new_p2v_map, new_counts = grid_sample(
xyz, batch, new_window_size, start=None
)
shift_size = 1 / 2 * new_window_size
shift_new_v2p_map, shift_new_p2v_map, shift_new_counts = grid_sample(
xyz + shift_size, batch, new_window_size, start=xyz.min(0)[0]
)
for i, blk in enumerate(self.blocks):
p2v_map_blk = p2v_map if i % 2 == 0 else shift_p2v_map
counts_blk = counts if i % 2 == 0 else shift_counts
new_p2v_map_blk = new_p2v_map if i % 2 == 0 else shift_new_p2v_map
new_counts_blk = new_counts if i % 2 == 0 else shift_new_counts
index_0, index_1 = get_indice_pairs(
p2v_map_blk,
counts_blk,
new_p2v_map_blk,
new_counts_blk,
downsample_idx,
batch,
xyz,
window_size,
i,
)
# rearrange index for acceleration
index_0, indices = torch.sort(index_0) # [M,]
index_1 = index_1[indices] # [M,]
index_0_counts = index_0.bincount()
n_max = index_0_counts.max()
index_0_offsets = index_0_counts.cumsum(dim=-1) # [N]
index_0_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_0_offsets], 0
) # [N+1]
feats = blk(feats, xyz, index_0, index_1, index_0_offsets, n_max)
if self.downsample:
feats_down, xyz_down, offset_down = self.downsample(feats, xyz, offset)
else:
feats_down, xyz_down, offset_down = None, None, None
return feats, xyz, offset, feats_down, xyz_down, offset_down
class Upsample(nn.Module):
def __init__(self, k, in_channels, out_channels, bn_momentum=0.02):
super().__init__()
self.k = k
self.in_channels = in_channels
self.out_channels = out_channels
self.linear1 = nn.Sequential(
nn.LayerNorm(out_channels), nn.Linear(out_channels, out_channels)
)
self.linear2 = nn.Sequential(
nn.LayerNorm(in_channels), nn.Linear(in_channels, out_channels)
)
def forward(
self, feats, xyz, support_xyz, offset, support_offset, support_feats=None
):
feats = self.linear1(support_feats) + pointops.interpolation(
xyz, support_xyz, self.linear2(feats), offset, support_offset
)
return feats, support_xyz, support_offset
class KPConvSimpleBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
prev_grid_size,
sigma=1.0,
negative_slope=0.2,
bn_momentum=0.02,
):
super().__init__()
self.kpconv = KPConvLayer(
in_channels,
out_channels,
point_influence=prev_grid_size * sigma,
add_one=False,
)
self.bn = FastBatchNorm1d(out_channels, momentum=bn_momentum)
self.activation = nn.LeakyReLU(negative_slope=negative_slope)
def forward(self, feats, xyz, batch, neighbor_idx):
# feats: [N, C]
# xyz: [N, 3]
# batch: [N,]
# neighbor_idx: [N, M]
feats = self.kpconv(xyz, xyz, neighbor_idx, feats)
feats = self.activation(self.bn(feats))
return feats
class KPConvResBlock(nn.Module):
def __init__(
self,
in_channels,
out_channels,
prev_grid_size,
sigma=1.0,
negative_slope=0.2,
bn_momentum=0.02,
):
super().__init__()
d_2 = out_channels // 4
activation = nn.LeakyReLU(negative_slope=negative_slope)
self.unary_1 = torch.nn.Sequential(
nn.Linear(in_channels, d_2, bias=False),
FastBatchNorm1d(d_2, momentum=bn_momentum),
activation,
)
self.unary_2 = torch.nn.Sequential(
nn.Linear(d_2, out_channels, bias=False),
FastBatchNorm1d(out_channels, momentum=bn_momentum),
activation,
)
self.kpconv = KPConvLayer(
d_2, d_2, point_influence=prev_grid_size * sigma, add_one=False
)
self.bn = FastBatchNorm1d(out_channels, momentum=bn_momentum)
self.activation = activation
if in_channels != out_channels:
self.shortcut_op = torch.nn.Sequential(
nn.Linear(in_channels, out_channels, bias=False),
FastBatchNorm1d(out_channels, momentum=bn_momentum),
)
else:
self.shortcut_op = nn.Identity()
def forward(self, feats, xyz, batch, neighbor_idx):
# feats: [N, C]
# xyz: [N, 3]
# batch: [N,]
# neighbor_idx: [N, M]
shortcut = feats
feats = self.unary_1(feats)
feats = self.kpconv(xyz, xyz, neighbor_idx, feats)
feats = self.unary_2(feats)
shortcut = self.shortcut_op(shortcut)
feats += shortcut
return feats
@MODELS.register_module("ST-v1m1")
class StratifiedTransformer(nn.Module):
def __init__(
self,
downsample_scale,
depths,
channels,
num_heads,
window_size,
up_k,
grid_sizes,
quant_sizes,
rel_query=True,
rel_key=False,
rel_value=False,
drop_path_rate=0.2,
num_layers=4,
concat_xyz=False,
num_classes=13,
ratio=0.25,
k=16,
prev_grid_size=0.04,
sigma=1.0,
stem_transformer=False,
kp_ball_radius=0.02 * 2.5,
kp_max_neighbor=34,
):
super().__init__()
assert (
KPConvLayer is not None and FastBatchNorm1d is not None
), "Please make sure torch_points3d is installed"
assert tp is not None, "Please make sure torch_points_kernels is installed"
assert pointops is not None, "Please make sure pointops2 is installed"
dpr = [
x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
] # stochastic depth decay rule
self.kp_ball_radius = kp_ball_radius
self.kp_max_neighbor = kp_max_neighbor
if stem_transformer:
self.stem_layer = nn.ModuleList(
[
KPConvSimpleBlock(
3 if not concat_xyz else 6,
channels[0],
prev_grid_size,
sigma=sigma,
)
]
)
self.layer_start = 0
else:
self.stem_layer = nn.ModuleList(
[
KPConvSimpleBlock(
3 if not concat_xyz else 6,
channels[0],
prev_grid_size,
sigma=sigma,
),
KPConvResBlock(
channels[0], channels[0], prev_grid_size, sigma=sigma
),
]
)
self.downsample = TransitionDown(channels[0], channels[1], ratio, k)
self.layer_start = 1
self.layers = nn.ModuleList(
[
BasicLayer(
downsample_scale,
depths[i],
channels[i],
num_heads[i],
window_size[i],
grid_sizes[i],
quant_sizes[i],
rel_query=rel_query,
rel_key=rel_key,
rel_value=rel_value,
drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])],
downsample=TransitionDown if i < num_layers - 1 else None,
ratio=ratio,
k=k,
out_channels=channels[i + 1] if i < num_layers - 1 else None,
)
for i in range(self.layer_start, num_layers)
]
)
self.upsamples = nn.ModuleList(
[
Upsample(up_k, channels[i], channels[i - 1])
for i in range(num_layers - 1, 0, -1)
]
)
self.classifier = nn.Sequential(
nn.Linear(channels[0], channels[0]),
nn.BatchNorm1d(channels[0]),
nn.ReLU(inplace=True),
nn.Linear(channels[0], num_classes),
)
self.init_weights()
def forward(self, data_dict):
feats = data_dict["feat"]
xyz = data_dict["coord"]
offset = data_dict["offset"].int()
batch = offset2batch(offset)
neighbor_idx = tp.ball_query(
self.kp_ball_radius,
self.kp_max_neighbor,
xyz,
xyz,
mode="partial_dense",
batch_x=batch,
batch_y=batch,
)[0]
feats_stack = []
xyz_stack = []
offset_stack = []
for i, layer in enumerate(self.stem_layer):
feats = layer(feats, xyz, batch, neighbor_idx)
feats = feats.contiguous()
if self.layer_start == 1:
feats_stack.append(feats)
xyz_stack.append(xyz)
offset_stack.append(offset)
feats, xyz, offset = self.downsample(feats, xyz, offset)
for i, layer in enumerate(self.layers):
feats, xyz, offset, feats_down, xyz_down, offset_down = layer(
feats, xyz, offset
)
feats_stack.append(feats)
xyz_stack.append(xyz)
offset_stack.append(offset)
feats = feats_down
xyz = xyz_down
offset = offset_down
feats = feats_stack.pop()
xyz = xyz_stack.pop()
offset = offset_stack.pop()
for i, upsample in enumerate(self.upsamples):
feats, xyz, offset = upsample(
feats,
xyz,
xyz_stack.pop(),
offset,
offset_stack.pop(),
support_feats=feats_stack.pop(),
)
out = self.classifier(feats)
return out
def init_weights(self):
"""Initialize the weights in backbone."""
def _init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm) or isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
self.apply(_init_weights)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/stratified_transformer/__init__.py | pointcept/models/stratified_transformer/__init__.py | from .stratified_transformer_v1m1_origin import StratifiedTransformer
from .stratified_transformer_v1m2_refine import StratifiedTransformer
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer/point_transformer_partseg.py | pointcept/models/point_transformer/point_transformer_partseg.py | """
Point Transformer V1 for Part Segmentation
Might be a bit different from the original paper
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
import torch.nn as nn
import einops
import pointops
from pointcept.models.builder import MODELS
from .utils import LayerNorm1d
class PointTransformerLayer(nn.Module):
def __init__(self, in_planes, out_planes, share_planes=8, nsample=16):
super().__init__()
self.mid_planes = mid_planes = out_planes // 1
self.out_planes = out_planes
self.share_planes = share_planes
self.nsample = nsample
self.linear_q = nn.Linear(in_planes, mid_planes)
self.linear_k = nn.Linear(in_planes, mid_planes)
self.linear_v = nn.Linear(in_planes, out_planes)
self.linear_p = nn.Sequential(
nn.Linear(3, 3),
LayerNorm1d(3),
nn.ReLU(inplace=True),
nn.Linear(3, out_planes),
)
self.linear_w = nn.Sequential(
LayerNorm1d(mid_planes),
nn.ReLU(inplace=True),
nn.Linear(mid_planes, out_planes // share_planes),
LayerNorm1d(out_planes // share_planes),
nn.ReLU(inplace=True),
nn.Linear(out_planes // share_planes, out_planes // share_planes),
)
self.softmax = nn.Softmax(dim=1)
def forward(self, pxo) -> torch.Tensor:
p, x, o = pxo # (n, 3), (n, c), (b)
x_q, x_k, x_v = self.linear_q(x), self.linear_k(x), self.linear_v(x)
x_k, idx = pointops.knn_query_and_group(
x_k, p, o, new_xyz=p, new_offset=o, nsample=self.nsample, with_xyz=True
)
x_v, _ = pointops.knn_query_and_group(
x_v,
p,
o,
new_xyz=p,
new_offset=o,
idx=idx,
nsample=self.nsample,
with_xyz=False,
)
p_r, x_k = x_k[:, :, 0:3], x_k[:, :, 3:]
p_r = self.linear_p(p_r)
r_qk = (
x_k
- x_q.unsqueeze(1)
+ einops.reduce(
p_r, "n ns (i j) -> n ns j", reduction="sum", j=self.mid_planes
)
)
w = self.linear_w(r_qk) # (n, nsample, c)
w = self.softmax(w)
x = torch.einsum(
"n t s i, n t i -> n s i",
einops.rearrange(x_v + p_r, "n ns (s i) -> n ns s i", s=self.share_planes),
w,
)
x = einops.rearrange(x, "n s i -> n (s i)")
return x
class TransitionDown(nn.Module):
def __init__(self, in_planes, out_planes, stride=1, nsample=16):
super().__init__()
self.stride, self.nsample = stride, nsample
if stride != 1:
self.linear = nn.Linear(3 + in_planes, out_planes, bias=False)
self.pool = nn.MaxPool1d(nsample)
else:
self.linear = nn.Linear(in_planes, out_planes, bias=False)
self.bn = nn.BatchNorm1d(out_planes)
self.relu = nn.ReLU(inplace=True)
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
if self.stride != 1:
n_o, count = [o[0].item() // self.stride], o[0].item() // self.stride
for i in range(1, o.shape[0]):
count += (o[i].item() - o[i - 1].item()) // self.stride
n_o.append(count)
n_o = torch.cuda.IntTensor(n_o)
idx = pointops.farthest_point_sampling(p, o, n_o) # (m)
n_p = p[idx.long(), :] # (m, 3)
x, _ = pointops.knn_query_and_group(
x,
p,
offset=o,
new_xyz=n_p,
new_offset=n_o,
nsample=self.nsample,
with_xyz=True,
)
x = self.relu(
self.bn(self.linear(x).transpose(1, 2).contiguous())
) # (m, c, nsample)
x = self.pool(x).squeeze(-1) # (m, c)
p, o = n_p, n_o
else:
x = self.relu(self.bn(self.linear(x))) # (n, c)
return [p, x, o]
class TransitionUp(nn.Module):
def __init__(self, in_planes, out_planes=None, num_shape_class=None):
super().__init__()
if out_planes is None:
self.num_shape_class = num_shape_class
if num_shape_class is not None:
self.linear1 = nn.Sequential(
nn.Linear(2 * in_planes + 1024, in_planes),
nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True),
)
else:
self.linear1 = nn.Sequential(
nn.Linear(2 * in_planes, in_planes),
nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True),
)
self.linear2 = nn.Sequential(
nn.Linear(in_planes, in_planes), nn.ReLU(inplace=True)
)
if num_shape_class is not None:
self.linear3 = nn.Sequential(
nn.Linear(num_shape_class, 1024), nn.ReLU(inplace=True)
)
else:
self.linear1 = nn.Sequential(
nn.Linear(out_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True),
)
self.linear2 = nn.Sequential(
nn.Linear(in_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True),
)
def forward(self, pxo1, pxo2=None, y=None):
if pxo2 is None:
_, x, o = pxo1 # (n, 3), (n, c), (b)
x_tmp = []
for i in range(o.shape[0]):
if i == 0:
s_i, e_i, cnt = 0, o[0], o[0]
else:
s_i, e_i, cnt = o[i - 1], o[i], o[i] - o[i - 1]
x_b = x[s_i:e_i, :]
y_b = y[i].unsqueeze(-1).unsqueeze(-1).long()
y_onehot = torch.zeros(1, self.num_shape_class).cuda() # (1, l)
y_onehot.scatter_(1, y_b, 1) # (1, l)
x_b = torch.cat(
(
x_b,
self.linear2(x_b.sum(0, True) / cnt).repeat(cnt, 1),
self.linear3(y_onehot).repeat(cnt, 1),
),
dim=1,
)
x_tmp.append(x_b)
x = torch.cat(x_tmp, 0)
x = self.linear1(x)
else:
p1, x1, o1 = pxo1
p2, x2, o2 = pxo2
x = self.linear1(x1) + pointops.interpolation(
p2, p1, self.linear2(x2), o2, o1
)
return x
class Bottleneck(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, share_planes=8, nsample=16):
super(Bottleneck, self).__init__()
self.linear1 = nn.Linear(in_planes, planes, bias=False)
self.bn1 = nn.BatchNorm1d(planes)
self.transformer = PointTransformerLayer(planes, planes, share_planes, nsample)
self.bn2 = nn.BatchNorm1d(planes)
self.linear3 = nn.Linear(planes, planes * self.expansion, bias=False)
self.bn3 = nn.BatchNorm1d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
identity = x
x = self.relu(self.bn1(self.linear1(x)))
x = self.relu(self.bn2(self.transformer([p, x, o])))
x = self.bn3(self.linear3(x))
x += identity
x = self.relu(x)
return [p, x, o]
class PointTransformerSeg(nn.Module):
def __init__(
self, block, blocks, in_channels=6, num_classes=50, num_shape_classes=None
):
super().__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.num_shape_classes = num_shape_classes
self.in_planes, planes = in_channels, [32, 64, 128, 256, 512]
fpn_planes, fpnhead_planes, share_planes = 128, 64, 8
stride, nsample = [1, 4, 4, 4, 4], [8, 16, 16, 16, 16]
self.enc1 = self._make_enc(
block,
planes[0],
blocks[0],
share_planes,
stride=stride[0],
nsample=nsample[0],
) # N/1
self.enc2 = self._make_enc(
block,
planes[1],
blocks[1],
share_planes,
stride=stride[1],
nsample=nsample[1],
) # N/4
self.enc3 = self._make_enc(
block,
planes[2],
blocks[2],
share_planes,
stride=stride[2],
nsample=nsample[2],
) # N/16
self.enc4 = self._make_enc(
block,
planes[3],
blocks[3],
share_planes,
stride=stride[3],
nsample=nsample[3],
) # N/64
self.enc5 = self._make_enc(
block,
planes[4],
blocks[4],
share_planes,
stride=stride[4],
nsample=nsample[4],
) # N/256
self.dec5 = self._make_dec(
block,
planes[4],
1,
share_planes,
num_shape_classes=num_shape_classes,
nsample=nsample[4],
is_head=True,
) # transform p5
self.dec4 = self._make_dec(
block, planes[3], 1, share_planes, nsample=nsample[3]
) # fusion p5 and p4
self.dec3 = self._make_dec(
block, planes[2], 1, share_planes, nsample=nsample[2]
) # fusion p4 and p3
self.dec2 = self._make_dec(
block, planes[1], 1, share_planes, nsample=nsample[1]
) # fusion p3 and p2
self.dec1 = self._make_dec(
block, planes[0], 1, share_planes, nsample=nsample[0]
) # fusion p2 and p1
self.cls = nn.Sequential(
nn.Linear(planes[0], planes[0]),
nn.BatchNorm1d(planes[0]),
nn.ReLU(inplace=True),
nn.Linear(planes[0], num_classes),
)
def _make_enc(self, block, planes, blocks, share_planes=8, stride=1, nsample=16):
layers = [
TransitionDown(self.in_planes, planes * block.expansion, stride, nsample)
]
self.in_planes = planes * block.expansion
for _ in range(blocks):
layers.append(
block(self.in_planes, self.in_planes, share_planes, nsample=nsample)
)
return nn.Sequential(*layers)
def _make_dec(
self,
block,
planes,
blocks,
share_planes=8,
num_shape_classes=None,
nsample=16,
is_head=False,
):
layers = [
TransitionUp(
self.in_planes,
None if is_head else planes * block.expansion,
num_shape_classes,
)
]
self.in_planes = planes * block.expansion
for _ in range(blocks):
layers.append(
block(self.in_planes, self.in_planes, share_planes, nsample=nsample)
)
return nn.Sequential(*layers)
def forward(self, data_dict):
p0 = data_dict["coord"]
x0 = data_dict["feat"]
o0 = data_dict["offset"].int()
if self.num_shape_classes is not None:
y = data_dict["cls_token"]
p1, x1, o1 = self.enc1([p0, x0, o0])
p2, x2, o2 = self.enc2([p1, x1, o1])
p3, x3, o3 = self.enc3([p2, x2, o2])
p4, x4, o4 = self.enc4([p3, x3, o3])
p5, x5, o5 = self.enc5([p4, x4, o4])
if self.num_shape_classes is not None:
x5 = self.dec5[1:]([p5, self.dec5[0]([p5, x5, o5], y=y), o5])[1]
else:
x5 = self.dec5[1:]([p5, self.dec5[0]([p5, x5, o5]), o5])[1]
x4 = self.dec4[1:]([p4, self.dec4[0]([p4, x4, o4], [p5, x5, o5]), o4])[1]
x3 = self.dec3[1:]([p3, self.dec3[0]([p3, x3, o3], [p4, x4, o4]), o3])[1]
x2 = self.dec2[1:]([p2, self.dec2[0]([p2, x2, o2], [p3, x3, o3]), o2])[1]
x1 = self.dec1[1:]([p1, self.dec1[0]([p1, x1, o1], [p2, x2, o2]), o1])[1]
x = self.cls(x1)
return x
@MODELS.register_module("PointTransformer-PartSeg26")
class PointTransformerSeg26(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg26, self).__init__(
Bottleneck, [1, 1, 1, 1, 1], **kwargs
)
@MODELS.register_module("PointTransformer-PartSeg38")
class PointTransformerSeg38(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg38, self).__init__(
Bottleneck, [1, 2, 2, 2, 2], **kwargs
)
@MODELS.register_module("PointTransformer-PartSeg50")
class PointTransformerSeg50(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg50, self).__init__(
Bottleneck, [1, 2, 3, 5, 2], **kwargs
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer/utils.py | pointcept/models/point_transformer/utils.py | import torch
import torch.nn as nn
torch.nn.LayerNorm
class LayerNorm1d(nn.BatchNorm1d):
def forward(self, input: torch.Tensor) -> torch.Tensor:
return (
super()
.forward(input.transpose(1, 2).contiguous())
.transpose(1, 2)
.contiguous()
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer/__init__.py | pointcept/models/point_transformer/__init__.py | from .point_transformer_seg import *
from .point_transformer_partseg import *
from .point_transformer_cls import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer/point_transformer_cls.py | pointcept/models/point_transformer/point_transformer_cls.py | """
Point Transformer V1 for Object Classification
Might be a bit different from the original paper
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
import torch.nn as nn
from .point_transformer_seg import TransitionDown, Bottleneck
from pointcept.models.builder import MODELS
class PointTransformerCls(nn.Module):
def __init__(self, block, blocks, in_channels=6, num_classes=40):
super().__init__()
self.in_channels = in_channels
self.in_planes, planes = in_channels, [32, 64, 128, 256, 512]
fpn_planes, fpnhead_planes, share_planes = 128, 64, 8
stride, nsample = [1, 4, 4, 4, 4], [8, 16, 16, 16, 16]
self.enc1 = self._make_enc(
block,
planes[0],
blocks[0],
share_planes,
stride=stride[0],
nsample=nsample[0],
) # N/1
self.enc2 = self._make_enc(
block,
planes[1],
blocks[1],
share_planes,
stride=stride[1],
nsample=nsample[1],
) # N/4
self.enc3 = self._make_enc(
block,
planes[2],
blocks[2],
share_planes,
stride=stride[2],
nsample=nsample[2],
) # N/16
self.enc4 = self._make_enc(
block,
planes[3],
blocks[3],
share_planes,
stride=stride[3],
nsample=nsample[3],
) # N/64
self.enc5 = self._make_enc(
block,
planes[4],
blocks[4],
share_planes,
stride=stride[4],
nsample=nsample[4],
) # N/256
self.cls = nn.Sequential(
nn.Linear(planes[4], 256),
nn.BatchNorm1d(256),
nn.ReLU(inplace=True),
nn.Dropout(p=0.5),
nn.Linear(256, 128),
nn.BatchNorm1d(128),
nn.ReLU(inplace=True),
nn.Dropout(p=0.5),
nn.Linear(128, num_classes),
)
def _make_enc(self, block, planes, blocks, share_planes=8, stride=1, nsample=16):
layers = [
TransitionDown(self.in_planes, planes * block.expansion, stride, nsample)
]
self.in_planes = planes * block.expansion
for _ in range(1, blocks):
layers.append(
block(self.in_planes, self.in_planes, share_planes, nsample=nsample)
)
return nn.Sequential(*layers)
def forward(self, data_dict):
p0 = data_dict["coord"]
x0 = data_dict["feat"]
o0 = data_dict["offset"].int()
x0 = p0 if self.in_channels == 3 else torch.cat((p0, x0), 1)
p1, x1, o1 = self.enc1([p0, x0, o0])
p2, x2, o2 = self.enc2([p1, x1, o1])
p3, x3, o3 = self.enc3([p2, x2, o2])
p4, x4, o4 = self.enc4([p3, x3, o3])
p5, x5, o5 = self.enc5([p4, x4, o4])
x = []
for i in range(o5.shape[0]):
if i == 0:
s_i, e_i, cnt = 0, o5[0], o5[0]
else:
s_i, e_i, cnt = o5[i - 1], o5[i], o5[i] - o5[i - 1]
x_b = x5[s_i:e_i, :].sum(0, True) / cnt
x.append(x_b)
x = torch.cat(x, 0)
x = self.cls(x)
return x
@MODELS.register_module("PointTransformer-Cls26")
class PointTransformerCls26(PointTransformerCls):
def __init__(self, **kwargs):
super(PointTransformerCls26, self).__init__(
Bottleneck, [1, 1, 1, 1, 1], **kwargs
)
@MODELS.register_module("PointTransformer-Cls38")
class PointTransformerCls38(PointTransformerCls):
def __init__(self, **kwargs):
super(PointTransformerCls38, self).__init__(
Bottleneck, [1, 2, 2, 2, 2], **kwargs
)
@MODELS.register_module("PointTransformer-Cls50")
class PointTransformerCls50(PointTransformerCls):
def __init__(self, **kwargs):
super(PointTransformerCls50, self).__init__(
Bottleneck, [1, 2, 3, 5, 2], **kwargs
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/point_transformer/point_transformer_seg.py | pointcept/models/point_transformer/point_transformer_seg.py | """
Point Transformer V1 for Semantic Segmentation
Might be a bit different from the original paper
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
import torch.nn as nn
import einops
import pointops
from pointcept.models.builder import MODELS
from .utils import LayerNorm1d
class PointTransformerLayer(nn.Module):
def __init__(self, in_planes, out_planes, share_planes=8, nsample=16):
super().__init__()
self.mid_planes = mid_planes = out_planes // 1
self.out_planes = out_planes
self.share_planes = share_planes
self.nsample = nsample
self.linear_q = nn.Linear(in_planes, mid_planes)
self.linear_k = nn.Linear(in_planes, mid_planes)
self.linear_v = nn.Linear(in_planes, out_planes)
self.linear_p = nn.Sequential(
nn.Linear(3, 3),
LayerNorm1d(3),
nn.ReLU(inplace=True),
nn.Linear(3, out_planes),
)
self.linear_w = nn.Sequential(
LayerNorm1d(mid_planes),
nn.ReLU(inplace=True),
nn.Linear(mid_planes, out_planes // share_planes),
LayerNorm1d(out_planes // share_planes),
nn.ReLU(inplace=True),
nn.Linear(out_planes // share_planes, out_planes // share_planes),
)
self.softmax = nn.Softmax(dim=1)
def forward(self, pxo) -> torch.Tensor:
p, x, o = pxo # (n, 3), (n, c), (b)
x_q, x_k, x_v = self.linear_q(x), self.linear_k(x), self.linear_v(x)
x_k, idx = pointops.knn_query_and_group(
x_k, p, o, new_xyz=p, new_offset=o, nsample=self.nsample, with_xyz=True
)
x_v, _ = pointops.knn_query_and_group(
x_v,
p,
o,
new_xyz=p,
new_offset=o,
idx=idx,
nsample=self.nsample,
with_xyz=False,
)
p_r, x_k = x_k[:, :, 0:3], x_k[:, :, 3:]
p_r = self.linear_p(p_r)
r_qk = (
x_k
- x_q.unsqueeze(1)
+ einops.reduce(
p_r, "n ns (i j) -> n ns j", reduction="sum", j=self.mid_planes
)
)
w = self.linear_w(r_qk) # (n, nsample, c)
w = self.softmax(w)
x = torch.einsum(
"n t s i, n t i -> n s i",
einops.rearrange(x_v + p_r, "n ns (s i) -> n ns s i", s=self.share_planes),
w,
)
x = einops.rearrange(x, "n s i -> n (s i)")
return x
class TransitionDown(nn.Module):
def __init__(self, in_planes, out_planes, stride=1, nsample=16):
super().__init__()
self.stride, self.nsample = stride, nsample
if stride != 1:
self.linear = nn.Linear(3 + in_planes, out_planes, bias=False)
self.pool = nn.MaxPool1d(nsample)
else:
self.linear = nn.Linear(in_planes, out_planes, bias=False)
self.bn = nn.BatchNorm1d(out_planes)
self.relu = nn.ReLU(inplace=True)
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
if self.stride != 1:
n_o, count = [o[0].item() // self.stride], o[0].item() // self.stride
for i in range(1, o.shape[0]):
count += (o[i].item() - o[i - 1].item()) // self.stride
n_o.append(count)
n_o = torch.cuda.IntTensor(n_o)
idx = pointops.farthest_point_sampling(p, o, n_o) # (m)
n_p = p[idx.long(), :] # (m, 3)
x, _ = pointops.knn_query_and_group(
x,
p,
offset=o,
new_xyz=n_p,
new_offset=n_o,
nsample=self.nsample,
with_xyz=True,
)
x = self.relu(
self.bn(self.linear(x).transpose(1, 2).contiguous())
) # (m, c, nsample)
x = self.pool(x).squeeze(-1) # (m, c)
p, o = n_p, n_o
else:
x = self.relu(self.bn(self.linear(x))) # (n, c)
return [p, x, o]
class TransitionUp(nn.Module):
def __init__(self, in_planes, out_planes=None):
super().__init__()
if out_planes is None:
self.linear1 = nn.Sequential(
nn.Linear(2 * in_planes, in_planes),
nn.BatchNorm1d(in_planes),
nn.ReLU(inplace=True),
)
self.linear2 = nn.Sequential(
nn.Linear(in_planes, in_planes), nn.ReLU(inplace=True)
)
else:
self.linear1 = nn.Sequential(
nn.Linear(out_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True),
)
self.linear2 = nn.Sequential(
nn.Linear(in_planes, out_planes),
nn.BatchNorm1d(out_planes),
nn.ReLU(inplace=True),
)
def forward(self, pxo1, pxo2=None):
if pxo2 is None:
_, x, o = pxo1 # (n, 3), (n, c), (b)
x_tmp = []
for i in range(o.shape[0]):
if i == 0:
s_i, e_i, cnt = 0, o[0], o[0]
else:
s_i, e_i, cnt = o[i - 1], o[i], o[i] - o[i - 1]
x_b = x[s_i:e_i, :]
x_b = torch.cat(
(x_b, self.linear2(x_b.sum(0, True) / cnt).repeat(cnt, 1)), 1
)
x_tmp.append(x_b)
x = torch.cat(x_tmp, 0)
x = self.linear1(x)
else:
p1, x1, o1 = pxo1
p2, x2, o2 = pxo2
x = self.linear1(x1) + pointops.interpolation(
p2, p1, self.linear2(x2), o2, o1
)
return x
class Bottleneck(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, share_planes=8, nsample=16):
super(Bottleneck, self).__init__()
self.linear1 = nn.Linear(in_planes, planes, bias=False)
self.bn1 = nn.BatchNorm1d(planes)
self.transformer = PointTransformerLayer(planes, planes, share_planes, nsample)
self.bn2 = nn.BatchNorm1d(planes)
self.linear3 = nn.Linear(planes, planes * self.expansion, bias=False)
self.bn3 = nn.BatchNorm1d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
def forward(self, pxo):
p, x, o = pxo # (n, 3), (n, c), (b)
identity = x
x = self.relu(self.bn1(self.linear1(x)))
x = self.relu(self.bn2(self.transformer([p, x, o])))
x = self.bn3(self.linear3(x))
x += identity
x = self.relu(x)
return [p, x, o]
class PointTransformerSeg(nn.Module):
def __init__(self, block, blocks, in_channels=6, num_classes=13):
super().__init__()
self.in_channels = in_channels
self.in_planes, planes = in_channels, [32, 64, 128, 256, 512]
fpn_planes, fpnhead_planes, share_planes = 128, 64, 8
stride, nsample = [1, 4, 4, 4, 4], [8, 16, 16, 16, 16]
self.enc1 = self._make_enc(
block,
planes[0],
blocks[0],
share_planes,
stride=stride[0],
nsample=nsample[0],
) # N/1
self.enc2 = self._make_enc(
block,
planes[1],
blocks[1],
share_planes,
stride=stride[1],
nsample=nsample[1],
) # N/4
self.enc3 = self._make_enc(
block,
planes[2],
blocks[2],
share_planes,
stride=stride[2],
nsample=nsample[2],
) # N/16
self.enc4 = self._make_enc(
block,
planes[3],
blocks[3],
share_planes,
stride=stride[3],
nsample=nsample[3],
) # N/64
self.enc5 = self._make_enc(
block,
planes[4],
blocks[4],
share_planes,
stride=stride[4],
nsample=nsample[4],
) # N/256
self.dec5 = self._make_dec(
block, planes[4], 1, share_planes, nsample=nsample[4], is_head=True
) # transform p5
self.dec4 = self._make_dec(
block, planes[3], 1, share_planes, nsample=nsample[3]
) # fusion p5 and p4
self.dec3 = self._make_dec(
block, planes[2], 1, share_planes, nsample=nsample[2]
) # fusion p4 and p3
self.dec2 = self._make_dec(
block, planes[1], 1, share_planes, nsample=nsample[1]
) # fusion p3 and p2
self.dec1 = self._make_dec(
block, planes[0], 1, share_planes, nsample=nsample[0]
) # fusion p2 and p1
self.cls = nn.Sequential(
nn.Linear(planes[0], planes[0]),
nn.BatchNorm1d(planes[0]),
nn.ReLU(inplace=True),
nn.Linear(planes[0], num_classes),
)
def _make_enc(self, block, planes, blocks, share_planes=8, stride=1, nsample=16):
layers = [
TransitionDown(self.in_planes, planes * block.expansion, stride, nsample)
]
self.in_planes = planes * block.expansion
for _ in range(blocks):
layers.append(
block(self.in_planes, self.in_planes, share_planes, nsample=nsample)
)
return nn.Sequential(*layers)
def _make_dec(
self, block, planes, blocks, share_planes=8, nsample=16, is_head=False
):
layers = [
TransitionUp(self.in_planes, None if is_head else planes * block.expansion)
]
self.in_planes = planes * block.expansion
for _ in range(blocks):
layers.append(
block(self.in_planes, self.in_planes, share_planes, nsample=nsample)
)
return nn.Sequential(*layers)
def forward(self, data_dict):
p0 = data_dict["coord"]
x0 = data_dict["feat"]
o0 = data_dict["offset"].int()
p1, x1, o1 = self.enc1([p0, x0, o0])
p2, x2, o2 = self.enc2([p1, x1, o1])
p3, x3, o3 = self.enc3([p2, x2, o2])
p4, x4, o4 = self.enc4([p3, x3, o3])
p5, x5, o5 = self.enc5([p4, x4, o4])
x5 = self.dec5[1:]([p5, self.dec5[0]([p5, x5, o5]), o5])[1]
x4 = self.dec4[1:]([p4, self.dec4[0]([p4, x4, o4], [p5, x5, o5]), o4])[1]
x3 = self.dec3[1:]([p3, self.dec3[0]([p3, x3, o3], [p4, x4, o4]), o3])[1]
x2 = self.dec2[1:]([p2, self.dec2[0]([p2, x2, o2], [p3, x3, o3]), o2])[1]
x1 = self.dec1[1:]([p1, self.dec1[0]([p1, x1, o1], [p2, x2, o2]), o1])[1]
x = self.cls(x1)
return x
@MODELS.register_module("PointTransformer-Seg26")
class PointTransformerSeg26(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg26, self).__init__(
Bottleneck, [1, 1, 1, 1, 1], **kwargs
)
@MODELS.register_module("PointTransformer-Seg38")
class PointTransformerSeg38(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg38, self).__init__(
Bottleneck, [1, 2, 2, 2, 2], **kwargs
)
@MODELS.register_module("PointTransformer-Seg50")
class PointTransformerSeg50(PointTransformerSeg):
def __init__(self, **kwargs):
super(PointTransformerSeg50, self).__init__(
Bottleneck, [1, 2, 3, 5, 2], **kwargs
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/context_aware_classifier/__init__.py | pointcept/models/context_aware_classifier/__init__.py | from .context_aware_classifier_v1m1_base import CACSegmentor
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/models/context_aware_classifier/context_aware_classifier_v1m1_base.py | pointcept/models/context_aware_classifier/context_aware_classifier_v1m1_base.py | """
Context-aware Classifier for Semantic Segmentation
Author: Zhuotao Tian, Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from pointcept.models.losses import build_criteria
from pointcept.models.builder import MODELS, build_model
@MODELS.register_module("CAC-v1m1")
class CACSegmentor(nn.Module):
def __init__(
self,
num_classes,
backbone_out_channels,
backbone=None,
criteria=None,
cos_temp=15,
main_weight=1,
pre_weight=1,
pre_self_weight=1,
kl_weight=1,
conf_thresh=0,
detach_pre_logits=False,
):
super().__init__()
self.num_classes = num_classes
self.cos_temp = cos_temp
self.main_weight = main_weight
self.pre_weight = pre_weight
self.pre_self_weight = pre_self_weight
self.kl_weight = kl_weight
self.conf_thresh = conf_thresh
self.detach_pre_logits = detach_pre_logits
# backbone
self.backbone = build_model(backbone)
# heads
self.seg_head = nn.Linear(backbone_out_channels, num_classes)
self.proj = nn.Sequential(
nn.Linear(backbone_out_channels * 2, backbone_out_channels * 2, bias=False),
nn.ReLU(inplace=True),
nn.Linear(backbone_out_channels * 2, backbone_out_channels),
)
self.apd_proj = nn.Sequential(
nn.Linear(backbone_out_channels * 2, backbone_out_channels * 2, bias=False),
nn.ReLU(inplace=True),
nn.Linear(backbone_out_channels * 2, backbone_out_channels),
)
self.feat_proj_layer = nn.Sequential(
nn.Linear(backbone_out_channels, backbone_out_channels, bias=False),
nn.BatchNorm1d(backbone_out_channels),
nn.ReLU(inplace=True),
nn.Linear(backbone_out_channels, backbone_out_channels),
)
# Criteria
self.criteria = build_criteria(criteria)
@staticmethod
def get_pred(x, proto):
# x: [n,c]; proto: [cls, c]
x = F.normalize(x, 2, 1)
proto = F.normalize(proto, 2, 1)
pred = x @ proto.permute(1, 0) # [n,c] x [c, cls] -> [n, cls]
return pred
def get_adaptive_perspective(self, feat, target, new_proto, proto):
raw_feat = feat.clone()
# target: [n]
# feat: [n,c]
# proto: [cls, c]
unique_y = list(target.unique())
if -1 in unique_y:
unique_y.remove(-1)
target = target.unsqueeze(-1) # [n, 1]
for tmp_y in unique_y:
tmp_mask = (target == tmp_y).float()
tmp_proto = (feat * tmp_mask).sum(0) / (tmp_mask.sum(0) + 1e-4) # c
onehot_vec = torch.zeros(new_proto.shape[0], 1).cuda() # cls, 1
onehot_vec[tmp_y.long()] = 1
new_proto = (
new_proto * (1 - onehot_vec) + tmp_proto.unsqueeze(0) * onehot_vec
)
new_proto = torch.cat([new_proto, proto], -1)
new_proto = self.apd_proj(new_proto)
raw_feat = self.feat_proj_layer(raw_feat)
pred = self.get_pred(raw_feat, new_proto)
return pred
def post_refine_proto_batch(self, feat, pred, proto, offset=None):
# x: [n, c]; pred: [n, cls]; proto: [cls, c]
pred_list = []
x = feat
raw_x = x.clone()
if self.detach_pre_logits:
pred = pred.detach()
raw_pred = pred.clone()
if offset is None:
raw_x = x.clone()
n, n_cls = pred.shape[:]
pred = pred.view(n, n_cls)
pred = F.softmax(pred, 1).permute(1, 0) # [n, cls] -> [cls, n]
if self.conf_thresh > 0:
max_pred = (
(pred.max(0)[0] >= self.conf_thresh).float().unsqueeze(0)
) # 1, n
pred = pred * max_pred
pred_proto = (pred / (pred.sum(-1).unsqueeze(-1) + 1e-7)) @ raw_x # cls, c
pred_proto = torch.cat([pred_proto, proto], -1) # cls, 2c
pred_proto = self.proj(pred_proto)
raw_x = self.feat_proj_layer(raw_x)
new_pred = self.get_pred(raw_x, pred_proto)
else:
for i in range(len(offset)):
if i == 0:
start = 0
end = offset[i]
else:
start, end = offset[i - 1], offset[i]
tmp_x = raw_x[start:end]
pred = raw_pred[start:end]
n, n_cls = pred.shape[:]
pred = pred.view(n, n_cls)
pred = F.softmax(pred, 1).permute(1, 0) # [n, cls] -> [cls, n]
if self.conf_thresh > 0:
max_pred = (
(pred.max(0)[0] >= self.conf_thresh).float().unsqueeze(0)
) # 1, n
pred = pred * max_pred
pred_proto = (
pred / (pred.sum(-1).unsqueeze(-1) + 1e-7)
) @ tmp_x # cls, c
pred_proto = torch.cat([pred_proto, proto], -1) # cls, 2c
pred_proto = self.proj(pred_proto)
tmp_x = self.feat_proj_layer(tmp_x)
new_pred = self.get_pred(tmp_x, pred_proto)
pred_list.append(new_pred)
new_pred = torch.cat(pred_list, 0)
return new_pred
@staticmethod
def get_distill_loss(pred, soft, target, smoothness=0.5, eps=0):
"""
knowledge distillation loss
"""
n, c = soft.shape[:]
soft = soft.detach()
target = target.unsqueeze(-1) # n, 1
onehot = target.view(-1, 1) # n, 1
ignore_mask = (onehot == -1).float()
sm_soft = F.softmax(soft / 1, 1) # n, c
onehot = onehot * (1 - ignore_mask)
onehot = torch.zeros(n, c).cuda().scatter_(1, onehot.long(), 1) # n, c
smoothed_label = smoothness * sm_soft + (1 - smoothness) * onehot
if eps > 0:
smoothed_label = smoothed_label * (1 - eps) + (1 - smoothed_label) * eps / (
smoothed_label.shape[1] - 1
)
loss = torch.mul(-1 * F.log_softmax(pred, dim=1), smoothed_label) # b, n, h, w
loss = loss.sum(1)
sm_soft = F.softmax(soft / 1, 1) # n, c
entropy_mask = -1 * (sm_soft * torch.log(sm_soft + 1e-4)).sum(1)
# for class-wise entropy estimation
target = target.squeeze(-1)
unique_classes = list(target.unique())
if -1 in unique_classes:
unique_classes.remove(-1)
valid_mask = (target != -1).float()
entropy_mask = entropy_mask * valid_mask
loss_list = []
weight_list = []
for tmp_y in unique_classes:
tmp_mask = (target == tmp_y).float().squeeze()
tmp_entropy_mask = entropy_mask * tmp_mask
class_weight = 1
tmp_loss = (loss * tmp_entropy_mask).sum() / (tmp_entropy_mask.sum() + 1e-4)
loss_list.append(class_weight * tmp_loss)
weight_list.append(class_weight)
if len(weight_list) > 0:
loss = sum(loss_list) / (sum(weight_list) + 1e-4)
else:
loss = torch.zeros(1).cuda().mean()
return loss
def forward(self, data_dict):
offset = data_dict["offset"]
feat = self.backbone(data_dict)
seg_logits = self.seg_head(feat)
if self.training:
target = data_dict["segment"]
pre_logits = seg_logits.clone()
refine_logits = (
self.post_refine_proto_batch(
feat=feat,
pred=seg_logits,
proto=self.seg_head.weight.squeeze(),
offset=offset,
)
* self.cos_temp
)
cac_pred = (
self.get_adaptive_perspective(
feat=feat,
target=target,
new_proto=self.seg_head.weight.detach().data.squeeze(),
proto=self.seg_head.weight.squeeze(),
)
* self.cos_temp
)
seg_loss = self.criteria(refine_logits, target) * self.main_weight
pre_loss = self.criteria(cac_pred, target) * self.pre_weight
pre_self_loss = self.criteria(pre_logits, target) * self.pre_self_weight
kl_loss = (
self.get_distill_loss(
pred=refine_logits, soft=cac_pred.detach(), target=target
)
* self.kl_weight
)
loss = seg_loss + pre_loss + pre_self_loss + kl_loss
return dict(
loss=loss,
seg_loss=seg_loss,
pre_loss=pre_loss,
pre_self_loss=pre_self_loss,
kl_loss=kl_loss,
)
elif "segment" in data_dict.keys():
refine_logits = (
self.post_refine_proto_batch(
feat=feat,
pred=seg_logits,
proto=self.seg_head.weight.squeeze(),
offset=offset,
)
* self.cos_temp
)
loss = self.criteria(seg_logits, data_dict["segment"])
return dict(loss=loss, seg_logits=refine_logits)
else:
refine_logits = (
self.post_refine_proto_batch(
feat=feat,
pred=seg_logits,
proto=self.seg_head.weight.squeeze(),
offset=offset,
)
* self.cos_temp
)
return dict(seg_logits=refine_logits)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/path.py | pointcept/utils/path.py | # Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
from pathlib import Path
from .misc import is_str
def is_filepath(x):
return is_str(x) or isinstance(x, Path)
def fopen(filepath, *args, **kwargs):
if is_str(filepath):
return open(filepath, *args, **kwargs)
elif isinstance(filepath, Path):
return filepath.open(*args, **kwargs)
raise ValueError("`filepath` should be a string or a Path")
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
if not osp.isfile(filename):
raise FileNotFoundError(msg_tmpl.format(filename))
def mkdir_or_exist(dir_name, mode=0o777):
if dir_name == "":
return
dir_name = osp.expanduser(dir_name)
os.makedirs(dir_name, mode=mode, exist_ok=True)
def symlink(src, dst, overwrite=True, **kwargs):
if os.path.lexists(dst) and overwrite:
os.remove(dst)
os.symlink(src, dst, **kwargs)
def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True):
"""Scan a directory to find the interested files.
Args:
dir_path (str | obj:`Path`): Path of the directory.
suffix (str | tuple(str), optional): File suffix that we are
interested in. Default: None.
recursive (bool, optional): If set to True, recursively scan the
directory. Default: False.
case_sensitive (bool, optional) : If set to False, ignore the case of
suffix. Default: True.
Returns:
A generator for all the interested files with relative paths.
"""
if isinstance(dir_path, (str, Path)):
dir_path = str(dir_path)
else:
raise TypeError('"dir_path" must be a string or Path object')
if (suffix is not None) and not isinstance(suffix, (str, tuple)):
raise TypeError('"suffix" must be a string or tuple of strings')
if suffix is not None and not case_sensitive:
suffix = (
suffix.lower()
if isinstance(suffix, str)
else tuple(item.lower() for item in suffix)
)
root = dir_path
def _scandir(dir_path, suffix, recursive, case_sensitive):
for entry in os.scandir(dir_path):
if not entry.name.startswith(".") and entry.is_file():
rel_path = osp.relpath(entry.path, root)
_rel_path = rel_path if case_sensitive else rel_path.lower()
if suffix is None or _rel_path.endswith(suffix):
yield rel_path
elif recursive and os.path.isdir(entry.path):
# scan recursively if entry.path is a directory
yield from _scandir(entry.path, suffix, recursive, case_sensitive)
return _scandir(dir_path, suffix, recursive, case_sensitive)
def find_vcs_root(path, markers=(".git",)):
"""Finds the root directory (including itself) of specified markers.
Args:
path (str): Path of directory or file.
markers (list[str], optional): List of file or directory names.
Returns:
The directory contained one of the markers or None if not found.
"""
if osp.isfile(path):
path = osp.dirname(path)
prev, cur = None, osp.abspath(osp.expanduser(path))
while cur != prev:
if any(osp.exists(osp.join(cur, marker)) for marker in markers):
return cur
prev, cur = cur, osp.split(cur)[0]
return None
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/registry.py | pointcept/utils/registry.py | # Copyright (c) OpenMMLab. All rights reserved.
import inspect
import warnings
from functools import partial
from .misc import is_seq_of
def build_from_cfg(cfg, registry, default_args=None):
"""Build a module from configs dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
registry (:obj:`Registry`): The registry to search the type from.
default_args (dict, optional): Default initialization arguments.
Returns:
object: The constructed object.
"""
if not isinstance(cfg, dict):
raise TypeError(f"cfg must be a dict, but got {type(cfg)}")
if "type" not in cfg:
if default_args is None or "type" not in default_args:
raise KeyError(
'`cfg` or `default_args` must contain the key "type", '
f"but got {cfg}\n{default_args}"
)
if not isinstance(registry, Registry):
raise TypeError(
"registry must be an mmcv.Registry object, " f"but got {type(registry)}"
)
if not (isinstance(default_args, dict) or default_args is None):
raise TypeError(
"default_args must be a dict or None, " f"but got {type(default_args)}"
)
args = cfg.copy()
if default_args is not None:
for name, value in default_args.items():
args.setdefault(name, value)
obj_type = args.pop("type")
if isinstance(obj_type, str):
obj_cls = registry.get(obj_type)
if obj_cls is None:
raise KeyError(f"{obj_type} is not in the {registry.name} registry")
elif inspect.isclass(obj_type):
obj_cls = obj_type
else:
raise TypeError(f"type must be a str or valid type, but got {type(obj_type)}")
try:
return obj_cls(**args)
except Exception as e:
# Normal TypeError does not print class name.
raise type(e)(f"{obj_cls.__name__}: {e}")
class Registry:
"""A registry to map strings to classes.
Registered object could be built from registry.
Example:
>>> MODELS = Registry('models')
>>> @MODELS.register_module()
>>> class ResNet:
>>> pass
>>> resnet = MODELS.build(dict(type='ResNet'))
Please refer to
https://mmcv.readthedocs.io/en/latest/understand_mmcv/registry.html for
advanced usage.
Args:
name (str): Registry name.
build_func(func, optional): Build function to construct instance from
Registry, func:`build_from_cfg` is used if neither ``parent`` or
``build_func`` is specified. If ``parent`` is specified and
``build_func`` is not given, ``build_func`` will be inherited
from ``parent``. Default: None.
parent (Registry, optional): Parent registry. The class registered in
children registry could be built from parent. Default: None.
scope (str, optional): The scope of registry. It is the key to search
for children registry. If not specified, scope will be the name of
the package where class is defined, e.g. mmdet, mmcls, mmseg.
Default: None.
"""
def __init__(self, name, build_func=None, parent=None, scope=None):
self._name = name
self._module_dict = dict()
self._children = dict()
self._scope = self.infer_scope() if scope is None else scope
# self.build_func will be set with the following priority:
# 1. build_func
# 2. parent.build_func
# 3. build_from_cfg
if build_func is None:
if parent is not None:
self.build_func = parent.build_func
else:
self.build_func = build_from_cfg
else:
self.build_func = build_func
if parent is not None:
assert isinstance(parent, Registry)
parent._add_children(self)
self.parent = parent
else:
self.parent = None
def __len__(self):
return len(self._module_dict)
def __contains__(self, key):
return self.get(key) is not None
def __repr__(self):
format_str = (
self.__class__.__name__ + f"(name={self._name}, "
f"items={self._module_dict})"
)
return format_str
@staticmethod
def infer_scope():
"""Infer the scope of registry.
The name of the package where registry is defined will be returned.
Example:
# in mmdet/models/backbone/resnet.py
>>> MODELS = Registry('models')
>>> @MODELS.register_module()
>>> class ResNet:
>>> pass
The scope of ``ResNet`` will be ``mmdet``.
Returns:
scope (str): The inferred scope name.
"""
# inspect.stack() trace where this function is called, the index-2
# indicates the frame where `infer_scope()` is called
filename = inspect.getmodule(inspect.stack()[2][0]).__name__
split_filename = filename.split(".")
return split_filename[0]
@staticmethod
def split_scope_key(key):
"""Split scope and key.
The first scope will be split from key.
Examples:
>>> Registry.split_scope_key('mmdet.ResNet')
'mmdet', 'ResNet'
>>> Registry.split_scope_key('ResNet')
None, 'ResNet'
Return:
scope (str, None): The first scope.
key (str): The remaining key.
"""
split_index = key.find(".")
if split_index != -1:
return key[:split_index], key[split_index + 1 :]
else:
return None, key
@property
def name(self):
return self._name
@property
def scope(self):
return self._scope
@property
def module_dict(self):
return self._module_dict
@property
def children(self):
return self._children
def get(self, key):
"""Get the registry record.
Args:
key (str): The class name in string format.
Returns:
class: The corresponding class.
"""
scope, real_key = self.split_scope_key(key)
if scope is None or scope == self._scope:
# get from self
if real_key in self._module_dict:
return self._module_dict[real_key]
else:
# get from self._children
if scope in self._children:
return self._children[scope].get(real_key)
else:
# goto root
parent = self.parent
while parent.parent is not None:
parent = parent.parent
return parent.get(key)
def build(self, *args, **kwargs):
return self.build_func(*args, **kwargs, registry=self)
def _add_children(self, registry):
"""Add children for a registry.
The ``registry`` will be added as children based on its scope.
The parent registry could build objects from children registry.
Example:
>>> models = Registry('models')
>>> mmdet_models = Registry('models', parent=models)
>>> @mmdet_models.register_module()
>>> class ResNet:
>>> pass
>>> resnet = models.build(dict(type='mmdet.ResNet'))
"""
assert isinstance(registry, Registry)
assert registry.scope is not None
assert (
registry.scope not in self.children
), f"scope {registry.scope} exists in {self.name} registry"
self.children[registry.scope] = registry
def _register_module(self, module_class, module_name=None, force=False):
if not inspect.isclass(module_class):
raise TypeError("module must be a class, " f"but got {type(module_class)}")
if module_name is None:
module_name = module_class.__name__
if isinstance(module_name, str):
module_name = [module_name]
for name in module_name:
if not force and name in self._module_dict:
raise KeyError(f"{name} is already registered " f"in {self.name}")
self._module_dict[name] = module_class
def deprecated_register_module(self, cls=None, force=False):
warnings.warn(
"The old API of register_module(module, force=False) "
"is deprecated and will be removed, please use the new API "
"register_module(name=None, force=False, module=None) instead."
)
if cls is None:
return partial(self.deprecated_register_module, force=force)
self._register_module(cls, force=force)
return cls
def register_module(self, name=None, force=False, module=None):
"""Register a module.
A record will be added to `self._module_dict`, whose key is the class
name or the specified name, and value is the class itself.
It can be used as a decorator or a normal function.
Example:
>>> backbones = Registry('backbone')
>>> @backbones.register_module()
>>> class ResNet:
>>> pass
>>> backbones = Registry('backbone')
>>> @backbones.register_module(name='mnet')
>>> class MobileNet:
>>> pass
>>> backbones = Registry('backbone')
>>> class ResNet:
>>> pass
>>> backbones.register_module(ResNet)
Args:
name (str | None): The module name to be registered. If not
specified, the class name will be used.
force (bool, optional): Whether to override an existing class with
the same name. Default: False.
module (type): Module class to be registered.
"""
if not isinstance(force, bool):
raise TypeError(f"force must be a boolean, but got {type(force)}")
# NOTE: This is a walkaround to be compatible with the old api,
# while it may introduce unexpected bugs.
if isinstance(name, type):
return self.deprecated_register_module(name, force=force)
# raise the error ahead of time
if not (name is None or isinstance(name, str) or is_seq_of(name, str)):
raise TypeError(
"name must be either of None, an instance of str or a sequence"
f" of str, but got {type(name)}"
)
# use it as a normal method: x.register_module(module=SomeClass)
if module is not None:
self._register_module(module_class=module, module_name=name, force=force)
return module
# use it as a decorator: @x.register_module()
def _register(cls):
self._register_module(module_class=cls, module_name=name, force=force)
return cls
return _register
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/timer.py | pointcept/utils/timer.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# -*- coding: utf-8 -*-
from time import perf_counter
from typing import Optional
class Timer:
"""
A timer which computes the time elapsed since the start/reset of the timer.
"""
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
"""
Reset the timer.
"""
self._start = perf_counter()
self._paused: Optional[float] = None
self._total_paused = 0
self._count_start = 1
def pause(self) -> None:
"""
Pause the timer.
"""
if self._paused is not None:
raise ValueError("Trying to pause a Timer that is already paused!")
self._paused = perf_counter()
def is_paused(self) -> bool:
"""
Returns:
bool: whether the timer is currently paused
"""
return self._paused is not None
def resume(self) -> None:
"""
Resume the timer.
"""
if self._paused is None:
raise ValueError("Trying to resume a Timer that is not paused!")
# pyre-fixme[58]: `-` is not supported for operand types `float` and
# `Optional[float]`.
self._total_paused += perf_counter() - self._paused
self._paused = None
self._count_start += 1
def seconds(self) -> float:
"""
Returns:
(float): the total number of seconds since the start/reset of the
timer, excluding the time when the timer is paused.
"""
if self._paused is not None:
end_time: float = self._paused # type: ignore
else:
end_time = perf_counter()
return end_time - self._start - self._total_paused
def avg_seconds(self) -> float:
"""
Returns:
(float): the average number of seconds between every start/reset and
pause.
"""
return self.seconds() / self._count_start
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/optimizer.py | pointcept/utils/optimizer.py | """
Optimizer
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch
from pointcept.utils.logger import get_root_logger
from pointcept.utils.registry import Registry
OPTIMIZERS = Registry("optimizers")
OPTIMIZERS.register_module(module=torch.optim.SGD, name="SGD")
OPTIMIZERS.register_module(module=torch.optim.Adam, name="Adam")
OPTIMIZERS.register_module(module=torch.optim.AdamW, name="AdamW")
def build_optimizer(cfg, model, param_dicts=None):
if param_dicts is None:
cfg.params = model.parameters()
else:
cfg.params = [dict(names=[], params=[], lr=cfg.lr)]
for i in range(len(param_dicts)):
param_group = dict(names=[], params=[])
if "lr" in param_dicts[i].keys():
param_group["lr"] = param_dicts[i].lr
if "momentum" in param_dicts[i].keys():
param_group["momentum"] = param_dicts[i].momentum
if "weight_decay" in param_dicts[i].keys():
param_group["weight_decay"] = param_dicts[i].weight_decay
cfg.params.append(param_group)
for n, p in model.named_parameters():
flag = False
for i in range(len(param_dicts)):
if param_dicts[i].keyword in n:
cfg.params[i + 1]["names"].append(n)
cfg.params[i + 1]["params"].append(p)
flag = True
break
if not flag:
cfg.params[0]["names"].append(n)
cfg.params[0]["params"].append(p)
logger = get_root_logger()
for i in range(len(cfg.params)):
param_names = cfg.params[i].pop("names")
message = ""
for key in cfg.params[i].keys():
if key != "params":
message += f" {key}: {cfg.params[i][key]};"
logger.info(f"Params Group {i+1} -{message} Params: {param_names}.")
return OPTIMIZERS.build(cfg=cfg)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/logger.py | pointcept/utils/logger.py | """
Logger Utils
Modified from mmcv
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import logging
import torch
import torch.distributed as dist
from termcolor import colored
logger_initialized = {}
root_status = 0
class _ColorfulFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
self._root_name = kwargs.pop("root_name") + "."
super(_ColorfulFormatter, self).__init__(*args, **kwargs)
def formatMessage(self, record):
log = super(_ColorfulFormatter, self).formatMessage(record)
if record.levelno == logging.WARNING:
prefix = colored("WARNING", "red", attrs=["blink"])
elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
prefix = colored("ERROR", "red", attrs=["blink", "underline"])
else:
return log
return prefix + " " + log
def get_logger(name, log_file=None, log_level=logging.INFO, file_mode="a", color=False):
"""Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the
logger by adding one or two handlers, otherwise the initialized logger will
be directly returned. During initialization, a StreamHandler will always be
added. If `log_file` is specified and the process rank is 0, a FileHandler
will also be added.
Args:
name (str): Logger name.
log_file (str | None): The log filename. If specified, a FileHandler
will be added to the logger.
log_level (int): The logger level. Note that only the process of
rank 0 is affected, and other processes will set the level to
"Error" thus be silent most of the time.
file_mode (str): The file mode used in opening log file.
Defaults to 'a'.
color (bool): Colorful log output. Defaults to True
Returns:
logging.Logger: The expected logger.
"""
logger = logging.getLogger(name)
if name in logger_initialized:
return logger
# handle hierarchical names
# e.g., logger "a" is initialized, then logger "a.b" will skip the
# initialization since it is a child of "a".
for logger_name in logger_initialized:
if name.startswith(logger_name):
return logger
logger.propagate = False
stream_handler = logging.StreamHandler()
handlers = [stream_handler]
if dist.is_available() and dist.is_initialized():
rank = dist.get_rank()
else:
rank = 0
# only rank 0 will add a FileHandler
if rank == 0 and log_file is not None:
# Here, the default behaviour of the official logger is 'a'. Thus, we
# provide an interface to change the file mode to the default
# behaviour.
file_handler = logging.FileHandler(log_file, file_mode)
handlers.append(file_handler)
plain_formatter = logging.Formatter(
"[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
)
if color:
formatter = _ColorfulFormatter(
colored("[%(asctime)s %(name)s]: ", "green") + "%(message)s",
datefmt="%m/%d %H:%M:%S",
root_name=name,
)
else:
formatter = plain_formatter
for handler in handlers:
handler.setFormatter(formatter)
handler.setLevel(log_level)
logger.addHandler(handler)
if rank == 0:
logger.setLevel(log_level)
else:
logger.setLevel(logging.ERROR)
logger_initialized[name] = True
return logger
def print_log(msg, logger=None, level=logging.INFO):
"""Print a log message.
Args:
msg (str): The message to be logged.
logger (logging.Logger | str | None): The logger to be used.
Some special loggers are:
- "silent": no message will be printed.
- other str: the logger obtained with `get_root_logger(logger)`.
- None: The `print()` method will be used to print log messages.
level (int): Logging level. Only available when `logger` is a Logger
object or "root".
"""
if logger is None:
print(msg)
elif isinstance(logger, logging.Logger):
logger.log(level, msg)
elif logger == "silent":
pass
elif isinstance(logger, str):
_logger = get_logger(logger)
_logger.log(level, msg)
else:
raise TypeError(
"logger should be either a logging.Logger object, str, "
f'"silent" or None, but got {type(logger)}'
)
def get_root_logger(log_file=None, log_level=logging.INFO, file_mode="a"):
"""Get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is specified, a FileHandler will
also be added. The name of the root logger is the top-level package name.
Args:
log_file (str | None): The log filename. If specified, a FileHandler
will be added to the root logger.
log_level (int): The root logger level. Note that only the process of
rank 0 is affected, while other processes will set the level to
"Error" and be silent most of the time.
file_mode (str): File Mode of logger. (w or a)
Returns:
logging.Logger: The root logger.
"""
logger = get_logger(
name="pointcept", log_file=log_file, log_level=log_level, file_mode=file_mode
)
return logger
def _log_api_usage(identifier: str):
"""
Internal function used to log the usage of different detectron2 components
inside facebook's infra.
"""
torch._C._log_api_usage_once("pointcept." + identifier)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/events.py | pointcept/utils/events.py | """
Events Utils
Modified from Detectron2
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import datetime
import json
import logging
import os
import time
import torch
import numpy as np
from typing import List, Optional, Tuple
from collections import defaultdict
from contextlib import contextmanager
__all__ = [
"get_event_storage",
"JSONWriter",
"TensorboardXWriter",
"CommonMetricPrinter",
"EventStorage",
]
_CURRENT_STORAGE_STACK = []
def get_event_storage():
"""
Returns:
The :class:`EventStorage` object that's currently being used.
Throws an error if no :class:`EventStorage` is currently enabled.
"""
assert len(
_CURRENT_STORAGE_STACK
), "get_event_storage() has to be called inside a 'with EventStorage(...)' context!"
return _CURRENT_STORAGE_STACK[-1]
class EventWriter:
"""
Base class for writers that obtain events from :class:`EventStorage` and process them.
"""
def write(self):
raise NotImplementedError
def close(self):
pass
class JSONWriter(EventWriter):
"""
Write scalars to a json file.
It saves scalars as one json per line (instead of a big json) for easy parsing.
Examples parsing such a json file:
::
$ cat metrics.json | jq -s '.[0:2]'
[
{
"data_time": 0.008433341979980469,
"iteration": 19,
"loss": 1.9228371381759644,
"loss_box_reg": 0.050025828182697296,
"loss_classifier": 0.5316952466964722,
"loss_mask": 0.7236229181289673,
"loss_rpn_box": 0.0856662318110466,
"loss_rpn_cls": 0.48198649287223816,
"lr": 0.007173333333333333,
"time": 0.25401854515075684
},
{
"data_time": 0.007216215133666992,
"iteration": 39,
"loss": 1.282649278640747,
"loss_box_reg": 0.06222952902317047,
"loss_classifier": 0.30682939291000366,
"loss_mask": 0.6970193982124329,
"loss_rpn_box": 0.038663312792778015,
"loss_rpn_cls": 0.1471673548221588,
"lr": 0.007706666666666667,
"time": 0.2490077018737793
}
]
$ cat metrics.json | jq '.loss_mask'
0.7126231789588928
0.689423680305481
0.6776131987571716
...
"""
def __init__(self, json_file, window_size=20):
"""
Args:
json_file (str): path to the json file. New data will be appended if the file exists.
window_size (int): the window size of median smoothing for the scalars whose
`smoothing_hint` are True.
"""
self._file_handle = open(json_file, "a")
self._window_size = window_size
self._last_write = -1
def write(self):
storage = get_event_storage()
to_save = defaultdict(dict)
for k, (v, iter) in storage.latest_with_smoothing_hint(
self._window_size
).items():
# keep scalars that have not been written
if iter <= self._last_write:
continue
to_save[iter][k] = v
if len(to_save):
all_iters = sorted(to_save.keys())
self._last_write = max(all_iters)
for itr, scalars_per_iter in to_save.items():
scalars_per_iter["iteration"] = itr
self._file_handle.write(json.dumps(scalars_per_iter, sort_keys=True) + "\n")
self._file_handle.flush()
try:
os.fsync(self._file_handle.fileno())
except AttributeError:
pass
def close(self):
self._file_handle.close()
class TensorboardXWriter(EventWriter):
"""
Write all scalars to a tensorboard file.
"""
def __init__(self, log_dir: str, window_size: int = 20, **kwargs):
"""
Args:
log_dir (str): the directory to save the output events
window_size (int): the scalars will be median-smoothed by this window size
kwargs: other arguments passed to `torch.utils.tensorboard.SummaryWriter(...)`
"""
self._window_size = window_size
from torch.utils.tensorboard import SummaryWriter
self._writer = SummaryWriter(log_dir, **kwargs)
self._last_write = -1
def write(self):
storage = get_event_storage()
new_last_write = self._last_write
for k, (v, iter) in storage.latest_with_smoothing_hint(
self._window_size
).items():
if iter > self._last_write:
self._writer.add_scalar(k, v, iter)
new_last_write = max(new_last_write, iter)
self._last_write = new_last_write
# storage.put_{image,histogram} is only meant to be used by
# tensorboard writer. So we access its internal fields directly from here.
if len(storage._vis_data) >= 1:
for img_name, img, step_num in storage._vis_data:
self._writer.add_image(img_name, img, step_num)
# Storage stores all image data and rely on this writer to clear them.
# As a result it assumes only one writer will use its image data.
# An alternative design is to let storage store limited recent
# data (e.g. only the most recent image) that all writers can access.
# In that case a writer may not see all image data if its period is long.
storage.clear_images()
if len(storage._histograms) >= 1:
for params in storage._histograms:
self._writer.add_histogram_raw(**params)
storage.clear_histograms()
def close(self):
if hasattr(self, "_writer"): # doesn't exist when the code fails at import
self._writer.close()
class CommonMetricPrinter(EventWriter):
"""
Print **common** metrics to the terminal, including
iteration time, ETA, memory, all losses, and the learning rate.
It also applies smoothing using a window of 20 elements.
It's meant to print common metrics in common ways.
To print something in more customized ways, please implement a similar printer by yourself.
"""
def __init__(self, max_iter: Optional[int] = None, window_size: int = 20):
"""
Args:
max_iter: the maximum number of iterations to train.
Used to compute ETA. If not given, ETA will not be printed.
window_size (int): the losses will be median-smoothed by this window size
"""
self.logger = logging.getLogger(__name__)
self._max_iter = max_iter
self._window_size = window_size
self._last_write = (
None # (step, time) of last call to write(). Used to compute ETA
)
def _get_eta(self, storage) -> Optional[str]:
if self._max_iter is None:
return ""
iteration = storage.iter
try:
eta_seconds = storage.history("time").median(1000) * (
self._max_iter - iteration - 1
)
storage.put_scalar("eta_seconds", eta_seconds, smoothing_hint=False)
return str(datetime.timedelta(seconds=int(eta_seconds)))
except KeyError:
# estimate eta on our own - more noisy
eta_string = None
if self._last_write is not None:
estimate_iter_time = (time.perf_counter() - self._last_write[1]) / (
iteration - self._last_write[0]
)
eta_seconds = estimate_iter_time * (self._max_iter - iteration - 1)
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
self._last_write = (iteration, time.perf_counter())
return eta_string
def write(self):
storage = get_event_storage()
iteration = storage.iter
if iteration == self._max_iter:
# This hook only reports training progress (loss, ETA, etc) but not other data,
# therefore do not write anything after training succeeds, even if this method
# is called.
return
try:
data_time = storage.history("data_time").avg(20)
except KeyError:
# they may not exist in the first few iterations (due to warmup)
# or when SimpleTrainer is not used
data_time = None
try:
iter_time = storage.history("time").global_avg()
except KeyError:
iter_time = None
try:
lr = "{:.5g}".format(storage.history("lr").latest())
except KeyError:
lr = "N/A"
eta_string = self._get_eta(storage)
if torch.cuda.is_available():
max_mem_mb = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0
else:
max_mem_mb = None
# NOTE: max_mem is parsed by grep in "dev/parse_results.sh"
self.logger.info(
" {eta}iter: {iter} {losses} {time}{data_time}lr: {lr} {memory}".format(
eta=f"eta: {eta_string} " if eta_string else "",
iter=iteration,
losses=" ".join(
[
"{}: {:.4g}".format(k, v.median(self._window_size))
for k, v in storage.histories().items()
if "loss" in k
]
),
time=(
"time: {:.4f} ".format(iter_time) if iter_time is not None else ""
),
data_time=(
"data_time: {:.4f} ".format(data_time)
if data_time is not None
else ""
),
lr=lr,
memory=(
"max_mem: {:.0f}M".format(max_mem_mb)
if max_mem_mb is not None
else ""
),
)
)
class EventStorage:
"""
The user-facing class that provides metric storage functionalities.
In the future we may add support for storing / logging other types of data if needed.
"""
def __init__(self, start_iter=0):
"""
Args:
start_iter (int): the iteration number to start with
"""
self._history = defaultdict(AverageMeter)
self._smoothing_hints = {}
self._latest_scalars = {}
self._iter = start_iter
self._current_prefix = ""
self._vis_data = []
self._histograms = []
# def put_image(self, img_name, img_tensor):
# """
# Add an `img_tensor` associated with `img_name`, to be shown on
# tensorboard.
# Args:
# img_name (str): The name of the image to put into tensorboard.
# img_tensor (torch.Tensor or numpy.array): An `uint8` or `float`
# Tensor of shape `[channel, height, width]` where `channel` is
# 3. The image format should be RGB. The elements in img_tensor
# can either have values in [0, 1] (float32) or [0, 255] (uint8).
# The `img_tensor` will be visualized in tensorboard.
# """
# self._vis_data.append((img_name, img_tensor, self._iter))
def put_scalar(self, name, value, n=1, smoothing_hint=False):
"""
Add a scalar `value` to the `HistoryBuffer` associated with `name`.
Args:
smoothing_hint (bool): a 'hint' on whether this scalar is noisy and should be
smoothed when logged. The hint will be accessible through
:meth:`EventStorage.smoothing_hints`. A writer may ignore the hint
and apply custom smoothing rule.
It defaults to True because most scalars we save need to be smoothed to
provide any useful signal.
"""
name = self._current_prefix + name
history = self._history[name]
history.update(value, n)
self._latest_scalars[name] = (value, self._iter)
existing_hint = self._smoothing_hints.get(name)
if existing_hint is not None:
assert (
existing_hint == smoothing_hint
), "Scalar {} was put with a different smoothing_hint!".format(name)
else:
self._smoothing_hints[name] = smoothing_hint
# def put_scalars(self, *, smoothing_hint=True, **kwargs):
# """
# Put multiple scalars from keyword arguments.
# Examples:
# storage.put_scalars(loss=my_loss, accuracy=my_accuracy, smoothing_hint=True)
# """
# for k, v in kwargs.items():
# self.put_scalar(k, v, smoothing_hint=smoothing_hint)
#
# def put_histogram(self, hist_name, hist_tensor, bins=1000):
# """
# Create a histogram from a tensor.
# Args:
# hist_name (str): The name of the histogram to put into tensorboard.
# hist_tensor (torch.Tensor): A Tensor of arbitrary shape to be converted
# into a histogram.
# bins (int): Number of histogram bins.
# """
# ht_min, ht_max = hist_tensor.min().item(), hist_tensor.max().item()
#
# # Create a histogram with PyTorch
# hist_counts = torch.histc(hist_tensor, bins=bins)
# hist_edges = torch.linspace(start=ht_min, end=ht_max, steps=bins + 1, dtype=torch.float32)
#
# # Parameter for the add_histogram_raw function of SummaryWriter
# hist_params = dict(
# tag=hist_name,
# min=ht_min,
# max=ht_max,
# num=len(hist_tensor),
# sum=float(hist_tensor.sum()),
# sum_squares=float(torch.sum(hist_tensor**2)),
# bucket_limits=hist_edges[1:].tolist(),
# bucket_counts=hist_counts.tolist(),
# global_step=self._iter,
# )
# self._histograms.append(hist_params)
def history(self, name):
"""
Returns:
AverageMeter: the history for name
"""
ret = self._history.get(name, None)
if ret is None:
raise KeyError("No history metric available for {}!".format(name))
return ret
def histories(self):
"""
Returns:
dict[name -> HistoryBuffer]: the HistoryBuffer for all scalars
"""
return self._history
def latest(self):
"""
Returns:
dict[str -> (float, int)]: mapping from the name of each scalar to the most
recent value and the iteration number its added.
"""
return self._latest_scalars
def latest_with_smoothing_hint(self, window_size=20):
"""
Similar to :meth:`latest`, but the returned values
are either the un-smoothed original latest value,
or a median of the given window_size,
depend on whether the smoothing_hint is True.
This provides a default behavior that other writers can use.
"""
result = {}
for k, (v, itr) in self._latest_scalars.items():
result[k] = (
self._history[k].median(window_size) if self._smoothing_hints[k] else v,
itr,
)
return result
def smoothing_hints(self):
"""
Returns:
dict[name -> bool]: the user-provided hint on whether the scalar
is noisy and needs smoothing.
"""
return self._smoothing_hints
def step(self):
"""
User should either: (1) Call this function to increment storage.iter when needed. Or
(2) Set `storage.iter` to the correct iteration number before each iteration.
The storage will then be able to associate the new data with an iteration number.
"""
self._iter += 1
@property
def iter(self):
"""
Returns:
int: The current iteration number. When used together with a trainer,
this is ensured to be the same as trainer.iter.
"""
return self._iter
@iter.setter
def iter(self, val):
self._iter = int(val)
@property
def iteration(self):
# for backward compatibility
return self._iter
def __enter__(self):
_CURRENT_STORAGE_STACK.append(self)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
assert _CURRENT_STORAGE_STACK[-1] == self
_CURRENT_STORAGE_STACK.pop()
@contextmanager
def name_scope(self, name):
"""
Yields:
A context within which all the events added to this storage
will be prefixed by the name scope.
"""
old_prefix = self._current_prefix
self._current_prefix = name.rstrip("/") + "/"
yield
self._current_prefix = old_prefix
def clear_images(self):
"""
Delete all the stored images for visualization. This should be called
after images are written to tensorboard.
"""
self._vis_data = []
def clear_histograms(self):
"""
Delete all the stored histograms for visualization.
This should be called after histograms are written to tensorboard.
"""
self._histograms = []
def reset_history(self, name):
ret = self._history.get(name, None)
if ret is None:
raise KeyError("No history metric available for {}!".format(name))
ret.reset()
def reset_histories(self):
for name in self._history.keys():
self._history[name].reset()
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.total = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.total = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.total += val * n
self.count += n
self.avg = self.total / self.count
class HistoryBuffer:
"""
Track a series of scalar values and provide access to smoothed values over a
window or the global average of the series.
"""
def __init__(self, max_length: int = 1000000) -> None:
"""
Args:
max_length: maximal number of values that can be stored in the
buffer. When the capacity of the buffer is exhausted, old
values will be removed.
"""
self._max_length: int = max_length
self._data: List[Tuple[float, float]] = [] # (value, iteration) pairs
self._count: int = 0
self._global_avg: float = 0
def update(self, value: float, iteration: Optional[float] = None) -> None:
"""
Add a new scalar value produced at certain iteration. If the length
of the buffer exceeds self._max_length, the oldest element will be
removed from the buffer.
"""
if iteration is None:
iteration = self._count
if len(self._data) == self._max_length:
self._data.pop(0)
self._data.append((value, iteration))
self._count += 1
self._global_avg += (value - self._global_avg) / self._count
def latest(self) -> float:
"""
Return the latest scalar value added to the buffer.
"""
return self._data[-1][0]
def median(self, window_size: int) -> float:
"""
Return the median of the latest `window_size` values in the buffer.
"""
return np.median([x[0] for x in self._data[-window_size:]])
def avg(self, window_size: int) -> float:
"""
Return the mean of the latest `window_size` values in the buffer.
"""
return np.mean([x[0] for x in self._data[-window_size:]])
def global_avg(self) -> float:
"""
Return the mean of all the elements in the buffer. Note that this
includes those getting removed due to limited buffer storage.
"""
return self._global_avg
def values(self) -> List[Tuple[float, float]]:
"""
Returns:
list[(number, iteration)]: content of the current buffer.
"""
return self._data
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/misc.py | pointcept/utils/misc.py | """
Misc
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import warnings
from collections import abc
import numpy as np
import torch
from importlib import import_module
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def intersection_and_union(output, target, K, ignore_index=-1):
# 'K' classes, output and target sizes are N or N * L or N * H * W, each value in range 0 to K - 1.
assert output.ndim in [1, 2, 3]
assert output.shape == target.shape
output = output.reshape(output.size).copy()
target = target.reshape(target.size)
output[np.where(target == ignore_index)[0]] = ignore_index
intersection = output[np.where(output == target)[0]]
area_intersection, _ = np.histogram(intersection, bins=np.arange(K + 1))
area_output, _ = np.histogram(output, bins=np.arange(K + 1))
area_target, _ = np.histogram(target, bins=np.arange(K + 1))
area_union = area_output + area_target - area_intersection
return area_intersection, area_union, area_target
def intersection_and_union_gpu(output, target, k, ignore_index=-1):
# 'K' classes, output and target sizes are N or N * L or N * H * W, each value in range 0 to K - 1.
assert output.dim() in [1, 2, 3]
assert output.shape == target.shape
output = output.view(-1)
target = target.view(-1)
output[target == ignore_index] = ignore_index
intersection = output[output == target]
area_intersection = torch.histc(intersection, bins=k, min=0, max=k - 1)
area_output = torch.histc(output, bins=k, min=0, max=k - 1)
area_target = torch.histc(target, bins=k, min=0, max=k - 1)
area_union = area_output + area_target - area_intersection
return area_intersection, area_union, area_target
def make_dirs(dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name, exist_ok=True)
def find_free_port():
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Binding to port 0 will cause the OS to find an available port for us
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
# NOTE: there is still a chance the port could be taken by other processes.
return port
def is_seq_of(seq, expected_type, seq_type=None):
"""Check whether it is a sequence of some type.
Args:
seq (Sequence): The sequence to be checked.
expected_type (type): Expected type of sequence items.
seq_type (type, optional): Expected sequence type.
Returns:
bool: Whether the sequence is valid.
"""
if seq_type is None:
exp_seq_type = abc.Sequence
else:
assert isinstance(seq_type, type)
exp_seq_type = seq_type
if not isinstance(seq, exp_seq_type):
return False
for item in seq:
if not isinstance(item, expected_type):
return False
return True
def is_str(x):
"""Whether the input is an string instance.
Note: This method is deprecated since python 2 is no longer supported.
"""
return isinstance(x, str)
def import_modules_from_strings(imports, allow_failed_imports=False):
"""Import modules from the given list of strings.
Args:
imports (list | str | None): The given module names to be imported.
allow_failed_imports (bool): If True, the failed imports will return
None. Otherwise, an ImportError is raise. Default: False.
Returns:
list[module] | module | None: The imported modules.
Examples:
>>> osp, sys = import_modules_from_strings(
... ['os.path', 'sys'])
>>> import os.path as osp_
>>> import sys as sys_
>>> assert osp == osp_
>>> assert sys == sys_
"""
if not imports:
return
single_import = False
if isinstance(imports, str):
single_import = True
imports = [imports]
if not isinstance(imports, list):
raise TypeError(f"custom_imports must be a list but got type {type(imports)}")
imported = []
for imp in imports:
if not isinstance(imp, str):
raise TypeError(f"{imp} is of type {type(imp)} and cannot be imported.")
try:
imported_tmp = import_module(imp)
except ImportError:
if allow_failed_imports:
warnings.warn(f"{imp} failed to import and is ignored.", UserWarning)
imported_tmp = None
else:
raise ImportError
imported.append(imported_tmp)
if single_import:
imported = imported[0]
return imported
class DummyClass:
def __init__(self):
pass
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/comm.py | pointcept/utils/comm.py | # Copyright (c) Facebook, Inc. and its affiliates.
"""
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
Modified from detectron2(https://github.com/facebookresearch/detectron2)
Copyright (c) Xiaoyang Wu (xiaoyang.wu@connect.hku.hk). All Rights Reserved.
Please cite our work if you use any part of the code.
"""
import functools
import numpy as np
import torch
import torch.distributed as dist
_LOCAL_PROCESS_GROUP = None
"""
A torch process group which only includes processes that on the same machine as the current process.
This variable is set when processes are spawned by `launch()` in "engine/launch.py".
"""
def calc_t_emb(ts, t_emb_dim):
"""
Embed time steps into a higher dimension space
"""
assert t_emb_dim % 2 == 0
# input is of shape (B) of integer time steps
# output is of shape (B, t_emb_dim)
if(ts.shape == 1):
ts = ts.unsqueeze(1)
half_dim = t_emb_dim // 2
t_emb = np.log(10000) / (half_dim - 1)
t_emb = torch.exp(torch.arange(half_dim) * -t_emb)
t_emb = t_emb.to(ts.device) # shape (half_dim)
# ts is of shape (B,1)
t_emb = ts * t_emb
t_emb = torch.cat((torch.sin(t_emb), torch.cos(t_emb)), 1)
return t_emb
def get_world_size() -> int:
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def get_rank() -> int:
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_local_rank() -> int:
"""
Returns:
The rank of the current process within the local (per-machine) process group.
"""
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
assert (
_LOCAL_PROCESS_GROUP is not None
), "Local process group is not created! Please use launch() to spawn processes!"
return dist.get_rank(group=_LOCAL_PROCESS_GROUP)
def get_local_size() -> int:
"""
Returns:
The size of the per-machine process group,
i.e. the number of processes per machine.
"""
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
def is_main_process() -> bool:
return get_rank() == 0
def synchronize():
"""
Helper function to synchronize (barrier) among all processes when
using distributed training
"""
if not dist.is_available():
return
if not dist.is_initialized():
return
world_size = dist.get_world_size()
if world_size == 1:
return
if dist.get_backend() == dist.Backend.NCCL:
# This argument is needed to avoid warnings.
# It's valid only for NCCL backend.
dist.barrier(device_ids=[torch.cuda.current_device()])
else:
dist.barrier()
@functools.lru_cache()
def _get_global_gloo_group():
"""
Return a process group based on gloo backend, containing all the ranks
The result is cached.
"""
if dist.get_backend() == "nccl":
return dist.new_group(backend="gloo")
else:
return dist.group.WORLD
def all_gather(data, group=None):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors).
Args:
data: any picklable object
group: a torch process group. By default, will use a group which
contains all ranks on gloo backend.
Returns:
list[data]: list of data gathered from each rank
"""
if get_world_size() == 1:
return [data]
if group is None:
group = (
_get_global_gloo_group()
) # use CPU group by default, to reduce GPU RAM usage.
world_size = dist.get_world_size(group)
if world_size == 1:
return [data]
output = [None for _ in range(world_size)]
dist.all_gather_object(output, data, group=group)
return output
def gather(data, dst=0, group=None):
"""
Run gather on arbitrary picklable data (not necessarily tensors).
Args:
data: any picklable object
dst (int): destination rank
group: a torch process group. By default, will use a group which
contains all ranks on gloo backend.
Returns:
list[data]: on dst, a list of data gathered from each rank. Otherwise,
an empty list.
"""
if get_world_size() == 1:
return [data]
if group is None:
group = _get_global_gloo_group()
world_size = dist.get_world_size(group=group)
if world_size == 1:
return [data]
rank = dist.get_rank(group=group)
if rank == dst:
output = [None for _ in range(world_size)]
dist.gather_object(data, output, dst=dst, group=group)
return output
else:
dist.gather_object(data, None, dst=dst, group=group)
return []
def shared_random_seed():
"""
Returns:
int: a random number that is the same across all workers.
If workers need a shared RNG, they can use this shared seed to
create one.
All workers must call this function, otherwise it will deadlock.
"""
ints = np.random.randint(2**31)
all_ints = all_gather(ints)
return all_ints[0]
def reduce_dict(input_dict, average=True):
"""
Reduce the values in the dictionary from all processes so that process with rank
0 has the reduced results.
Args:
input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor.
average (bool): whether to do average or sum
Returns:
a dict with the same keys as input_dict, after reduction.
"""
world_size = get_world_size()
if world_size < 2:
return input_dict
with torch.no_grad():
names = []
values = []
# sort the keys so that they are consistent across processes
for k in sorted(input_dict.keys()):
names.append(k)
values.append(input_dict[k])
values = torch.stack(values, dim=0)
dist.reduce(values, dst=0)
if dist.get_rank() == 0 and average:
# only main process gets accumulated, so only divide by
# world_size in this case
values /= world_size
reduced_dict = {k: v for k, v in zip(names, values)}
return reduced_dict
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/config.py | pointcept/utils/config.py | # Copyright (c) OpenMMLab. All rights reserved.
import ast
import copy
import os
import os.path as osp
import platform
import shutil
import sys
import tempfile
import uuid
import warnings
from argparse import Action, ArgumentParser
from collections import abc
from importlib import import_module
from addict import Dict
from yapf.yapflib.yapf_api import FormatCode
from .misc import import_modules_from_strings
from .path import check_file_exist
if platform.system() == "Windows":
import regex as re
else:
import re
BASE_KEY = "_base_"
DELETE_KEY = "_delete_"
DEPRECATION_KEY = "_deprecation_"
RESERVED_KEYS = ["filename", "text", "pretty_text"]
class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(
f"'{self.__class__.__name__}' object has no " f"attribute '{name}'"
)
except Exception as e:
ex = e
else:
return value
raise ex
def add_args(parser, cfg, prefix=""):
for k, v in cfg.items():
if isinstance(v, str):
parser.add_argument("--" + prefix + k)
elif isinstance(v, int):
parser.add_argument("--" + prefix + k, type=int)
elif isinstance(v, float):
parser.add_argument("--" + prefix + k, type=float)
elif isinstance(v, bool):
parser.add_argument("--" + prefix + k, action="store_true")
elif isinstance(v, dict):
add_args(parser, v, prefix + k + ".")
elif isinstance(v, abc.Iterable):
parser.add_argument("--" + prefix + k, type=type(v[0]), nargs="+")
else:
print(f"cannot parse key {prefix + k} of type {type(v)}")
return parser
class Config:
"""A facility for config and config files.
It supports common file formats as configs: python/json/yaml. The interface
is the same as a dict object and also allows access config values as
attributes.
Example:
>>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
>>> cfg.a
1
>>> cfg.b
{'b1': [0, 1]}
>>> cfg.b.b1
[0, 1]
>>> cfg = Config.fromfile('tests/data/config/a.py')
>>> cfg.filename
"/home/kchen/projects/mmcv/tests/data/config/a.py"
>>> cfg.item4
'test'
>>> cfg
"Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: "
"{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}"
"""
@staticmethod
def _validate_py_syntax(filename):
with open(filename, "r", encoding="utf-8") as f:
# Setting encoding explicitly to resolve coding issue on windows
content = f.read()
try:
ast.parse(content)
except SyntaxError as e:
raise SyntaxError(
"There are syntax errors in config " f"file {filename}: {e}"
)
@staticmethod
def _substitute_predefined_vars(filename, temp_config_name):
file_dirname = osp.dirname(filename)
file_basename = osp.basename(filename)
file_basename_no_extension = osp.splitext(file_basename)[0]
file_extname = osp.splitext(filename)[1]
support_templates = dict(
fileDirname=file_dirname,
fileBasename=file_basename,
fileBasenameNoExtension=file_basename_no_extension,
fileExtname=file_extname,
)
with open(filename, "r", encoding="utf-8") as f:
# Setting encoding explicitly to resolve coding issue on windows
config_file = f.read()
for key, value in support_templates.items():
regexp = r"\{\{\s*" + str(key) + r"\s*\}\}"
value = value.replace("\\", "/")
config_file = re.sub(regexp, value, config_file)
with open(temp_config_name, "w", encoding="utf-8") as tmp_config_file:
tmp_config_file.write(config_file)
@staticmethod
def _pre_substitute_base_vars(filename, temp_config_name):
"""Substitute base variable placehoders to string, so that parsing
would work."""
with open(filename, "r", encoding="utf-8") as f:
# Setting encoding explicitly to resolve coding issue on windows
config_file = f.read()
base_var_dict = {}
regexp = r"\{\{\s*" + BASE_KEY + r"\.([\w\.]+)\s*\}\}"
base_vars = set(re.findall(regexp, config_file))
for base_var in base_vars:
randstr = f"_{base_var}_{uuid.uuid4().hex.lower()[:6]}"
base_var_dict[randstr] = base_var
regexp = r"\{\{\s*" + BASE_KEY + r"\." + base_var + r"\s*\}\}"
config_file = re.sub(regexp, f'"{randstr}"', config_file)
with open(temp_config_name, "w", encoding="utf-8") as tmp_config_file:
tmp_config_file.write(config_file)
return base_var_dict
@staticmethod
def _substitute_base_vars(cfg, base_var_dict, base_cfg):
"""Substitute variable strings to their actual values."""
cfg = copy.deepcopy(cfg)
if isinstance(cfg, dict):
for k, v in cfg.items():
if isinstance(v, str) and v in base_var_dict:
new_v = base_cfg
for new_k in base_var_dict[v].split("."):
new_v = new_v[new_k]
cfg[k] = new_v
elif isinstance(v, (list, tuple, dict)):
cfg[k] = Config._substitute_base_vars(v, base_var_dict, base_cfg)
elif isinstance(cfg, tuple):
cfg = tuple(
Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg
)
elif isinstance(cfg, list):
cfg = [
Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg
]
elif isinstance(cfg, str) and cfg in base_var_dict:
new_v = base_cfg
for new_k in base_var_dict[cfg].split("."):
new_v = new_v[new_k]
cfg = new_v
return cfg
@staticmethod
def _file2dict(filename, use_predefined_variables=True):
filename = osp.abspath(osp.expanduser(filename))
check_file_exist(filename)
fileExtname = osp.splitext(filename)[1]
if fileExtname not in [".py", ".json", ".yaml", ".yml"]:
raise IOError("Only py/yml/yaml/json type are supported now!")
with tempfile.TemporaryDirectory() as temp_config_dir:
temp_config_file = tempfile.NamedTemporaryFile(
dir=temp_config_dir, suffix=fileExtname
)
if platform.system() == "Windows":
temp_config_file.close()
temp_config_name = osp.basename(temp_config_file.name)
# Substitute predefined variables
if use_predefined_variables:
Config._substitute_predefined_vars(filename, temp_config_file.name)
else:
shutil.copyfile(filename, temp_config_file.name)
# Substitute base variables from placeholders to strings
base_var_dict = Config._pre_substitute_base_vars(
temp_config_file.name, temp_config_file.name
)
if filename.endswith(".py"):
temp_module_name = osp.splitext(temp_config_name)[0]
sys.path.insert(0, temp_config_dir)
Config._validate_py_syntax(filename)
mod = import_module(temp_module_name)
sys.path.pop(0)
cfg_dict = {
name: value
for name, value in mod.__dict__.items()
if not name.startswith("__")
}
# delete imported module
del sys.modules[temp_module_name]
elif filename.endswith((".yml", ".yaml", ".json")):
raise NotImplementedError
# close temp file
temp_config_file.close()
# check deprecation information
if DEPRECATION_KEY in cfg_dict:
deprecation_info = cfg_dict.pop(DEPRECATION_KEY)
warning_msg = (
f"The config file {filename} will be deprecated " "in the future."
)
if "expected" in deprecation_info:
warning_msg += f' Please use {deprecation_info["expected"]} ' "instead."
if "reference" in deprecation_info:
warning_msg += (
" More information can be found at "
f'{deprecation_info["reference"]}'
)
warnings.warn(warning_msg)
cfg_text = filename + "\n"
with open(filename, "r", encoding="utf-8") as f:
# Setting encoding explicitly to resolve coding issue on windows
cfg_text += f.read()
if BASE_KEY in cfg_dict:
cfg_dir = osp.dirname(filename)
base_filename = cfg_dict.pop(BASE_KEY)
base_filename = (
base_filename if isinstance(base_filename, list) else [base_filename]
)
cfg_dict_list = list()
cfg_text_list = list()
for f in base_filename:
_cfg_dict, _cfg_text = Config._file2dict(osp.join(cfg_dir, f))
cfg_dict_list.append(_cfg_dict)
cfg_text_list.append(_cfg_text)
base_cfg_dict = dict()
for c in cfg_dict_list:
duplicate_keys = base_cfg_dict.keys() & c.keys()
if len(duplicate_keys) > 0:
raise KeyError(
"Duplicate key is not allowed among bases. "
f"Duplicate keys: {duplicate_keys}"
)
base_cfg_dict.update(c)
# Substitute base variables from strings to their actual values
cfg_dict = Config._substitute_base_vars(
cfg_dict, base_var_dict, base_cfg_dict
)
base_cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict)
cfg_dict = base_cfg_dict
# merge cfg_text
cfg_text_list.append(cfg_text)
cfg_text = "\n".join(cfg_text_list)
return cfg_dict, cfg_text
@staticmethod
def _merge_a_into_b(a, b, allow_list_keys=False):
"""merge dict ``a`` into dict ``b`` (non-inplace).
Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid
in-place modifications.
Args:
a (dict): The source dict to be merged into ``b``.
b (dict): The origin dict to be fetch keys from ``a``.
allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
are allowed in source ``a`` and will replace the element of the
corresponding index in b if b is a list. Default: False.
Returns:
dict: The modified dict of ``b`` using ``a``.
Examples:
# Normally merge a into b.
>>> Config._merge_a_into_b(
... dict(obj=dict(a=2)), dict(obj=dict(a=1)))
{'obj': {'a': 2}}
# Delete b first and merge a into b.
>>> Config._merge_a_into_b(
... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1)))
{'obj': {'a': 2}}
# b is a list
>>> Config._merge_a_into_b(
... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True)
[{'a': 2}, {'b': 2}]
"""
b = b.copy()
for k, v in a.items():
if allow_list_keys and k.isdigit() and isinstance(b, list):
k = int(k)
if len(b) <= k:
raise KeyError(f"Index {k} exceeds the length of list {b}")
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
elif isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False):
allowed_types = (dict, list) if allow_list_keys else dict
if not isinstance(b[k], allowed_types):
raise TypeError(
f"{k}={v} in child config cannot inherit from base "
f"because {k} is a dict in the child config but is of "
f"type {type(b[k])} in base config. You may set "
f"`{DELETE_KEY}=True` to ignore the base config"
)
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
else:
b[k] = v
return b
@staticmethod
def fromfile(filename, use_predefined_variables=True, import_custom_modules=True):
cfg_dict, cfg_text = Config._file2dict(filename, use_predefined_variables)
if import_custom_modules and cfg_dict.get("custom_imports", None):
import_modules_from_strings(**cfg_dict["custom_imports"])
return Config(cfg_dict, cfg_text=cfg_text, filename=filename)
@staticmethod
def fromstring(cfg_str, file_format):
"""Generate config from config str.
Args:
cfg_str (str): Config str.
file_format (str): Config file format corresponding to the
config str. Only py/yml/yaml/json type are supported now!
Returns:
obj:`Config`: Config obj.
"""
if file_format not in [".py", ".json", ".yaml", ".yml"]:
raise IOError("Only py/yml/yaml/json type are supported now!")
if file_format != ".py" and "dict(" in cfg_str:
# check if users specify a wrong suffix for python
warnings.warn('Please check "file_format", the file format may be .py')
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", suffix=file_format, delete=False
) as temp_file:
temp_file.write(cfg_str)
# on windows, previous implementation cause error
# see PR 1077 for details
cfg = Config.fromfile(temp_file.name)
os.remove(temp_file.name)
return cfg
@staticmethod
def auto_argparser(description=None):
"""Generate argparser from config file automatically (experimental)"""
partial_parser = ArgumentParser(description=description)
partial_parser.add_argument("config", help="config file path")
cfg_file = partial_parser.parse_known_args()[0].config
cfg = Config.fromfile(cfg_file)
parser = ArgumentParser(description=description)
parser.add_argument("config", help="config file path")
add_args(parser, cfg)
return parser, cfg
def __init__(self, cfg_dict=None, cfg_text=None, filename=None):
if cfg_dict is None:
cfg_dict = dict()
elif not isinstance(cfg_dict, dict):
raise TypeError("cfg_dict must be a dict, but " f"got {type(cfg_dict)}")
for key in cfg_dict:
if key in RESERVED_KEYS:
raise KeyError(f"{key} is reserved for config file")
super(Config, self).__setattr__("_cfg_dict", ConfigDict(cfg_dict))
super(Config, self).__setattr__("_filename", filename)
if cfg_text:
text = cfg_text
elif filename:
with open(filename, "r") as f:
text = f.read()
else:
text = ""
super(Config, self).__setattr__("_text", text)
@property
def filename(self):
return self._filename
@property
def text(self):
return self._text
@property
def pretty_text(self):
indent = 4
def _indent(s_, num_spaces):
s = s_.split("\n")
if len(s) == 1:
return s_
first = s.pop(0)
s = [(num_spaces * " ") + line for line in s]
s = "\n".join(s)
s = first + "\n" + s
return s
def _format_basic_types(k, v, use_mapping=False):
if isinstance(v, str):
v_str = f"'{v}'"
else:
v_str = str(v)
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f"{k_str}: {v_str}"
else:
attr_str = f"{str(k)}={v_str}"
attr_str = _indent(attr_str, indent)
return attr_str
def _format_list(k, v, use_mapping=False):
# check if all items in the list are dict
if all(isinstance(_, dict) for _ in v):
v_str = "[\n"
v_str += "\n".join(
f"dict({_indent(_format_dict(v_), indent)})," for v_ in v
).rstrip(",")
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f"{k_str}: {v_str}"
else:
attr_str = f"{str(k)}={v_str}"
attr_str = _indent(attr_str, indent) + "]"
else:
attr_str = _format_basic_types(k, v, use_mapping)
return attr_str
def _contain_invalid_identifier(dict_str):
contain_invalid_identifier = False
for key_name in dict_str:
contain_invalid_identifier |= not str(key_name).isidentifier()
return contain_invalid_identifier
def _format_dict(input_dict, outest_level=False):
r = ""
s = []
use_mapping = _contain_invalid_identifier(input_dict)
if use_mapping:
r += "{"
for idx, (k, v) in enumerate(input_dict.items()):
is_last = idx >= len(input_dict) - 1
end = "" if outest_level or is_last else ","
if isinstance(v, dict):
v_str = "\n" + _format_dict(v)
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f"{k_str}: dict({v_str}"
else:
attr_str = f"{str(k)}=dict({v_str}"
attr_str = _indent(attr_str, indent) + ")" + end
elif isinstance(v, list):
attr_str = _format_list(k, v, use_mapping) + end
else:
attr_str = _format_basic_types(k, v, use_mapping) + end
s.append(attr_str)
r += "\n".join(s)
if use_mapping:
r += "}"
return r
cfg_dict = self._cfg_dict.to_dict()
text = _format_dict(cfg_dict, outest_level=True)
# copied from setup.cfg
yapf_style = dict(
based_on_style="pep8",
blank_line_before_nested_class_or_def=True,
split_before_expression_after_opening_paren=True,
)
text, _ = FormatCode(text, style_config=yapf_style, verify=True)
return text
def __repr__(self):
return f"Config (path: {self.filename}): {self._cfg_dict.__repr__()}"
def __len__(self):
return len(self._cfg_dict)
def __getattr__(self, name):
return getattr(self._cfg_dict, name)
def __getitem__(self, name):
return self._cfg_dict.__getitem__(name)
def __setattr__(self, name, value):
if isinstance(value, dict):
value = ConfigDict(value)
self._cfg_dict.__setattr__(name, value)
def __setitem__(self, name, value):
if isinstance(value, dict):
value = ConfigDict(value)
self._cfg_dict.__setitem__(name, value)
def __iter__(self):
return iter(self._cfg_dict)
def __getstate__(self):
return (self._cfg_dict, self._filename, self._text)
def __setstate__(self, state):
_cfg_dict, _filename, _text = state
super(Config, self).__setattr__("_cfg_dict", _cfg_dict)
super(Config, self).__setattr__("_filename", _filename)
super(Config, self).__setattr__("_text", _text)
def dump(self, file=None):
cfg_dict = super(Config, self).__getattribute__("_cfg_dict").to_dict()
if self.filename.endswith(".py"):
if file is None:
return self.pretty_text
else:
with open(file, "w", encoding="utf-8") as f:
f.write(self.pretty_text)
else:
import mmcv
if file is None:
file_format = self.filename.split(".")[-1]
return mmcv.dump(cfg_dict, file_format=file_format)
else:
mmcv.dump(cfg_dict, file)
def merge_from_dict(self, options, allow_list_keys=True):
"""Merge list into cfg_dict.
Merge the dict parsed by MultipleKVAction into this cfg.
Examples:
>>> options = {'models.backbone.depth': 50,
... 'models.backbone.with_cp':True}
>>> cfg = Config(dict(models=dict(backbone=dict(type='ResNet'))))
>>> cfg.merge_from_dict(options)
>>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
>>> assert cfg_dict == dict(
... models=dict(backbone=dict(depth=50, with_cp=True)))
# Merge list element
>>> cfg = Config(dict(pipeline=[
... dict(type='LoadImage'), dict(type='LoadAnnotations')]))
>>> options = dict(pipeline={'0': dict(type='SelfLoadImage')})
>>> cfg.merge_from_dict(options, allow_list_keys=True)
>>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
>>> assert cfg_dict == dict(pipeline=[
... dict(type='SelfLoadImage'), dict(type='LoadAnnotations')])
Args:
options (dict): dict of configs to merge from.
allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
are allowed in ``options`` and will replace the element of the
corresponding index in the config if the config is a list.
Default: True.
"""
option_cfg_dict = {}
for full_key, v in options.items():
d = option_cfg_dict
key_list = full_key.split(".")
for subkey in key_list[:-1]:
d.setdefault(subkey, ConfigDict())
d = d[subkey]
subkey = key_list[-1]
d[subkey] = v
cfg_dict = super(Config, self).__getattribute__("_cfg_dict")
super(Config, self).__setattr__(
"_cfg_dict",
Config._merge_a_into_b(
option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys
),
)
class DictAction(Action):
"""
argparse action to split an argument into KEY=VALUE form
on the first = and append to a dictionary. List options can
be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit
brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build
list/tuple values. e.g. 'KEY=[(V1,V2),(V3,V4)]'
"""
@staticmethod
def _parse_int_float_bool(val):
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
pass
if val.lower() in ["true", "false"]:
return True if val.lower() == "true" else False
return val
@staticmethod
def _parse_iterable(val):
"""Parse iterable values in the string.
All elements inside '()' or '[]' are treated as iterable values.
Args:
val (str): Value string.
Returns:
list | tuple: The expanded list or tuple from the string.
Examples:
>>> DictAction._parse_iterable('1,2,3')
[1, 2, 3]
>>> DictAction._parse_iterable('[a, b, c]')
['a', 'b', 'c']
>>> DictAction._parse_iterable('[(1, 2, 3), [a, b], c]')
[(1, 2, 3), ['a', 'b'], 'c']
"""
def find_next_comma(string):
"""Find the position of next comma in the string.
If no ',' is found in the string, return the string length. All
chars inside '()' and '[]' are treated as one element and thus ','
inside these brackets are ignored.
"""
assert (string.count("(") == string.count(")")) and (
string.count("[") == string.count("]")
), f"Imbalanced brackets exist in {string}"
end = len(string)
for idx, char in enumerate(string):
pre = string[:idx]
# The string before this ',' is balanced
if (
(char == ",")
and (pre.count("(") == pre.count(")"))
and (pre.count("[") == pre.count("]"))
):
end = idx
break
return end
# Strip ' and " characters and replace whitespace.
val = val.strip("'\"").replace(" ", "")
is_tuple = False
if val.startswith("(") and val.endswith(")"):
is_tuple = True
val = val[1:-1]
elif val.startswith("[") and val.endswith("]"):
val = val[1:-1]
elif "," not in val:
# val is a single value
return DictAction._parse_int_float_bool(val)
values = []
while len(val) > 0:
comma_idx = find_next_comma(val)
element = DictAction._parse_iterable(val[:comma_idx])
values.append(element)
val = val[comma_idx + 1 :]
if is_tuple:
values = tuple(values)
return values
def __call__(self, parser, namespace, values, option_string=None):
options = {}
for kv in values:
key, val = kv.split("=", maxsplit=1)
options[key] = self._parse_iterable(val)
setattr(namespace, self.dest, options)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/__init__.py | pointcept/utils/__init__.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/cache.py | pointcept/utils/cache.py | """
Data Cache Utils
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import SharedArray
try:
from multiprocessing.shared_memory import ShareableList
except ImportError:
import warnings
warnings.warn("Please update python version >= 3.8 to enable shared_memory")
import numpy as np
def shared_array(name, var=None):
if var is not None:
# check exist
if os.path.exists(f"/dev/shm/{name}"):
return SharedArray.attach(f"shm://{name}")
# create shared_array
data = SharedArray.create(f"shm://{name}", var.shape, dtype=var.dtype)
data[...] = var[...]
data.flags.writeable = False
else:
data = SharedArray.attach(f"shm://{name}").copy()
return data
def shared_dict(name, var=None):
name = str(name)
assert "." not in name # '.' is used as sep flag
data = {}
if var is not None:
assert isinstance(var, dict)
keys = var.keys()
# current version only cache np.array
keys_valid = []
for key in keys:
if isinstance(var[key], np.ndarray):
keys_valid.append(key)
keys = keys_valid
ShareableList(sequence=keys, name=name + ".keys")
for key in keys:
if isinstance(var[key], np.ndarray):
data[key] = shared_array(name=f"{name}.{key}", var=var[key])
else:
keys = list(ShareableList(name=name + ".keys"))
for key in keys:
data[key] = shared_array(name=f"{name}.{key}")
return data
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/scheduler.py | pointcept/utils/scheduler.py | """
Scheduler
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import torch.optim.lr_scheduler as lr_scheduler
from .registry import Registry
SCHEDULERS = Registry("schedulers")
@SCHEDULERS.register_module()
class MultiStepLR(lr_scheduler.MultiStepLR):
def __init__(
self,
optimizer,
milestones,
total_steps,
gamma=0.1,
last_epoch=-1,
verbose=False,
):
super().__init__(
optimizer=optimizer,
milestones=[rate * total_steps for rate in milestones],
gamma=gamma,
last_epoch=last_epoch,
verbose=verbose,
)
@SCHEDULERS.register_module()
class MultiStepWithWarmupLR(lr_scheduler.LambdaLR):
def __init__(
self,
optimizer,
milestones,
total_steps,
gamma=0.1,
warmup_rate=0.05,
warmup_scale=1e-6,
last_epoch=-1,
verbose=False,
):
milestones = [rate * total_steps for rate in milestones]
def multi_step_with_warmup(s):
factor = 1.0
for i in range(len(milestones)):
if s < milestones[i]:
break
factor *= gamma
if s <= warmup_rate * total_steps:
warmup_coefficient = 1 - (1 - s / warmup_rate / total_steps) * (
1 - warmup_scale
)
else:
warmup_coefficient = 1.0
return warmup_coefficient * factor
super().__init__(
optimizer=optimizer,
lr_lambda=multi_step_with_warmup,
last_epoch=last_epoch,
verbose=verbose,
)
@SCHEDULERS.register_module()
class PolyLR(lr_scheduler.LambdaLR):
def __init__(self, optimizer, total_steps, power=0.9, last_epoch=-1, verbose=False):
super().__init__(
optimizer=optimizer,
lr_lambda=lambda s: (1 - s / (total_steps + 1)) ** power,
last_epoch=last_epoch,
verbose=verbose,
)
@SCHEDULERS.register_module()
class ExpLR(lr_scheduler.LambdaLR):
def __init__(self, optimizer, total_steps, gamma=0.9, last_epoch=-1, verbose=False):
super().__init__(
optimizer=optimizer,
lr_lambda=lambda s: gamma ** (s / total_steps),
last_epoch=last_epoch,
verbose=verbose,
)
@SCHEDULERS.register_module()
class CosineAnnealingLR(lr_scheduler.CosineAnnealingLR):
def __init__(self, optimizer, total_steps, eta_min=0, last_epoch=-1, verbose=False):
super().__init__(
optimizer=optimizer,
T_max=total_steps,
eta_min=eta_min,
last_epoch=last_epoch,
verbose=verbose,
)
@SCHEDULERS.register_module()
class OneCycleLR(lr_scheduler.OneCycleLR):
r"""
torch.optim.lr_scheduler.OneCycleLR, Block total_steps
"""
def __init__(
self,
optimizer,
max_lr,
total_steps=None,
pct_start=0.3,
anneal_strategy="cos",
cycle_momentum=True,
base_momentum=0.85,
max_momentum=0.95,
div_factor=25.0,
final_div_factor=1e4,
three_phase=False,
last_epoch=-1,
verbose=False,
):
super().__init__(
optimizer=optimizer,
max_lr=max_lr,
total_steps=total_steps,
pct_start=pct_start,
anneal_strategy=anneal_strategy,
cycle_momentum=cycle_momentum,
base_momentum=base_momentum,
max_momentum=max_momentum,
div_factor=div_factor,
final_div_factor=final_div_factor,
three_phase=three_phase,
last_epoch=last_epoch,
verbose=verbose,
)
def build_scheduler(cfg, optimizer):
cfg.optimizer = optimizer
return SCHEDULERS.build(cfg=cfg)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/visualization.py | pointcept/utils/visualization.py | """
Visualization Utils
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import open3d as o3d
import numpy as np
import torch
def to_numpy(x):
if isinstance(x, torch.Tensor):
x = x.clone().detach().cpu().numpy()
assert isinstance(x, np.ndarray)
return x
def save_point_cloud(coord, color=None, file_path="pc.ply", logger=None):
os.makedirs(os.path.dirname(file_path), exist_ok=True)
coord = to_numpy(coord)
if color is not None:
color = to_numpy(color)
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(coord)
pcd.colors = o3d.utility.Vector3dVector(
np.ones_like(coord) if color is None else color
)
o3d.io.write_point_cloud(file_path, pcd)
if logger is not None:
logger.info(f"Save Point Cloud to: {file_path}")
def save_bounding_boxes(
bboxes_corners, color=(1.0, 0.0, 0.0), file_path="bbox.ply", logger=None
):
bboxes_corners = to_numpy(bboxes_corners)
# point list
points = bboxes_corners.reshape(-1, 3)
# line list
box_lines = np.array(
[
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[4, 5],
[5, 6],
[6, 7],
[7, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
]
)
lines = []
for i, _ in enumerate(bboxes_corners):
lines.append(box_lines + i * 8)
lines = np.concatenate(lines)
# color list
color = np.array([color for _ in range(len(lines))])
# generate line set
line_set = o3d.geometry.LineSet()
line_set.points = o3d.utility.Vector3dVector(points)
line_set.lines = o3d.utility.Vector2iVector(lines)
line_set.colors = o3d.utility.Vector3dVector(color)
o3d.io.write_line_set(file_path, line_set)
if logger is not None:
logger.info(f"Save Boxes to: {file_path}")
def save_lines(
points, lines, color=(1.0, 0.0, 0.0), file_path="lines.ply", logger=None
):
points = to_numpy(points)
lines = to_numpy(lines)
colors = np.array([color for _ in range(len(lines))])
line_set = o3d.geometry.LineSet()
line_set.points = o3d.utility.Vector3dVector(points)
line_set.lines = o3d.utility.Vector2iVector(lines)
line_set.colors = o3d.utility.Vector3dVector(colors)
o3d.io.write_line_set(file_path, line_set)
if logger is not None:
logger.info(f"Save Lines to: {file_path}")
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/utils/env.py | pointcept/utils/env.py | """
Environment Utils
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from datetime import datetime
def get_random_seed():
seed = (
os.getpid()
+ int(datetime.now().strftime("%S%f"))
+ int.from_bytes(os.urandom(2), "big")
)
return seed
def set_seed(seed=None):
if seed is None:
seed = get_random_seed()
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
cudnn.benchmark = False
cudnn.deterministic = True
os.environ["PYTHONHASHSEED"] = str(seed)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/train.py | pointcept/engines/train.py | """
Trainer
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import sys
import weakref
import torch
import torch.nn as nn
import torch.utils.data
from functools import partial
if sys.version_info >= (3, 10):
from collections.abc import Iterator
else:
from collections import Iterator
from tensorboardX import SummaryWriter
from .defaults import create_ddp_model, worker_init_fn
from .hooks import HookBase, build_hooks
import pointcept.utils.comm as comm
from pointcept.datasets import build_dataset, point_collate_fn, collate_fn
from pointcept.models import build_model
from pointcept.utils.logger import get_root_logger
from pointcept.utils.optimizer import build_optimizer
from pointcept.utils.scheduler import build_scheduler
from pointcept.utils.events import EventStorage
from pointcept.utils.registry import Registry
TRAINERS = Registry("trainers")
class TrainerBase:
def __init__(self) -> None:
self.hooks = []
self.epoch = 0
self.start_epoch = 0
self.max_epoch = 0
self.max_iter = 0
self.comm_info = dict()
self.data_iterator: Iterator = enumerate([])
self.storage: EventStorage
self.writer: SummaryWriter
def register_hooks(self, hooks) -> None:
hooks = build_hooks(hooks)
for h in hooks:
assert isinstance(h, HookBase)
# To avoid circular reference, hooks and trainer cannot own each other.
# This normally does not matter, but will cause memory leak if the
# involved objects contain __del__:
# See http://engineering.hearsaysocial.com/2013/06/16/circular-references-in-python/
h.trainer = weakref.proxy(self)
self.hooks.extend(hooks)
def train(self):
with EventStorage() as self.storage:
# => before train
self.before_train()
for self.epoch in range(self.start_epoch, self.max_epoch):
# => before epoch
self.before_epoch()
# => run_epoch
for (
self.comm_info["iter"],
self.comm_info["input_dict"],
) in self.data_iterator:
# => before_step
self.before_step()
# => run_step
self.run_step()
# => after_step
self.after_step()
# => after epoch
self.after_epoch()
# => after train
self.after_train()
def before_train(self):
for h in self.hooks:
h.before_train()
def before_epoch(self):
for h in self.hooks:
h.before_epoch()
def before_step(self):
for h in self.hooks:
h.before_step()
def run_step(self):
raise NotImplementedError
def after_step(self):
for h in self.hooks:
h.after_step()
def after_epoch(self):
for h in self.hooks:
h.after_epoch()
self.storage.reset_histories()
def after_train(self):
# Sync GPU before running train hooks
comm.synchronize()
for h in self.hooks:
h.after_train()
if comm.is_main_process():
self.writer.close()
@TRAINERS.register_module("DefaultTrainer")
class Trainer(TrainerBase):
def __init__(self, cfg):
super(Trainer, self).__init__()
self.epoch = 0
self.start_epoch = 0
self.max_epoch = cfg.eval_epoch
self.best_metric_value = -torch.inf
self.logger = get_root_logger(
log_file=os.path.join(cfg.save_path, "train.log"),
file_mode="a" if cfg.resume else "w",
)
self.logger.info("=> Loading config ...")
self.cfg = cfg
self.logger.info(f"Save path: {cfg.save_path}")
self.logger.info(f"Config:\n{cfg.pretty_text}")
self.logger.info("=> Building model ...")
self.model = self.build_model()
self.logger.info("=> Building writer ...")
self.writer = self.build_writer()
self.logger.info("=> Building train dataset & dataloader ...")
self.train_loader = self.build_train_loader()
self.logger.info("=> Building val dataset & dataloader ...")
self.val_loader = self.build_val_loader()
self.logger.info("=> Building optimize, scheduler, scaler(amp) ...")
self.optimizer = self.build_optimizer()
self.scheduler = self.build_scheduler()
self.scaler = self.build_scaler()
self.logger.info("=> Building hooks ...")
self.register_hooks(self.cfg.hooks)
def gredient_clip_params(self):
parameters_to_clip = self.cfg.gredient_clip if(hasattr(self.cfg, "gredient_clip")) else []
clip_parameters = []
clip_names = []
for n, p in self.model.named_parameters():
for i in range(len(parameters_to_clip)):
if (parameters_to_clip[i] in n):
clip_parameters.append(p)
clip_names.append(n)
if (len(clip_parameters) > 0):
self.logger.info(f"Gredient Clip - {clip_names}")
else:
self.logger.info("No using gredient clip!")
self.cfg.gredient_clip_params = clip_parameters
def train(self):
with EventStorage() as self.storage:
# => before train
self.before_train()
self.gredient_clip_params()
if(not hasattr(self.cfg, "save_freq_threshold")): self.cfg.save_freq_threshold = None
if(not hasattr(self.cfg, "skip_connection_scale_i")): self.cfg.skip_connection_scale_i = False
self.logger.info(f"Save Frequency Threshold: {self.cfg.save_freq_threshold}")
self.logger.info(f"Save Frequency : {self.cfg.hooks[4].save_freq}")
self.logger.info(f"Random Seed : {self.cfg.seed}")
self.logger.info(f"Diffusion Model : {self.cfg.dm}")
self.logger.info(f"DM Input : {self.cfg.dm_input}")
self.logger.info(f"DM Target : {self.cfg.dm_target}")
self.logger.info(f"DM Min SNR : {self.cfg.dm_min_snr}")
self.logger.info(f"Loss Type : {self.cfg.loss_type}")
self.logger.info(f"Skip Connection Mode : {self.cfg.skip_connection_mode}")
self.logger.info(f"Skip Connection Scale : {self.cfg.skip_connection_scale}")
self.logger.info(f"Skip Connection SegNet : {self.cfg.skip_connection_scale_i}")
self.logger.info(f"TM Bidirectional : {self.cfg.tm_bidirectional}")
self.logger.info(f"TM Feat : {self.cfg.tm_feat}")
self.logger.info(f"TM Restomer : {self.cfg.tm_restomer}")
self.logger.info(f"FreeU ==> backbone factor : {self.cfg.b_factor}, skip_connection factor : {self.cfg.s_factor}")
self.logger.info(">>>>>>>>>>>>>>>> Start Training >>>>>>>>>>>>>>>>")
for self.epoch in range(self.start_epoch, self.max_epoch):
if(self.cfg.save_freq_threshold is not None):
if(self.epoch < self.cfg.save_freq_threshold):
self.hooks[4].save_freq = None
else:
self.hooks[4].save_freq = self.cfg.hooks[4].save_freq
# => before epoch
# TODO: optimize to iteration based
if comm.get_world_size() > 1:
self.train_loader.sampler.set_epoch(self.epoch)
self.model.train()
self.data_iterator = enumerate(self.train_loader)
self.before_epoch()
# => run_epoch
for (
self.comm_info["iter"],
self.comm_info["input_dict"],
) in self.data_iterator:
# => before_step
self.before_step()
# => run_step
self.run_step()
# => after_step
self.after_step()
# => after epoch
self.after_epoch()
# => after train
self.after_train()
def run_step(self):
input_dict = self.comm_info["input_dict"]
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
'''
self.cfg.enable_amp = True : using mixed prediction training
self.cfg.enable_amp = False : no using mixed prediction training
'''
with torch.cuda.amp.autocast(enabled=self.cfg.enable_amp):
output_dict = self.model(input_dict)
loss = output_dict["loss"]
# set gradient to 0
self.optimizer.zero_grad()
if self.cfg.enable_amp:
'''
scaling the 'loss', and backwarding.
==> loss.backward()
'''
self.scaler.scale(loss).backward()
# ---- gredient clip ----
if(len(self.cfg.gredient_clip_params) > 0):
torch.nn.utils.clip_grad_norm_(self.cfg.gredient_clip_params, max_norm=0.1)
# ---- gredient clip ----
'''
checking overflowing, and update params.
==> optmizer.step()
'''
self.scaler.step(self.optimizer)
'''
getting the scale factor, and updating.
'''
scaler = self.scaler.get_scale()
self.scaler.update()
# When enable amp, optimizer.step call are skipped if the loss scaling factor is too large.
# Fix torch warning scheduler step before optimizer step.
if scaler <= self.scaler.get_scale():
self.scheduler.step()
else:
loss.backward()
# ---- gredient clip ----
if(len(self.cfg.gredient_clip_params) > 0):
torch.nn.utils.clip_grad_norm_(self.cfg.gredient_clip_params, max_norm=0.1)
# ---- gredient clip ----
self.optimizer.step()
self.scheduler.step()
if self.cfg.empty_cache:
torch.cuda.empty_cache()
self.comm_info["model_output_dict"] = output_dict
def build_model(self):
model = build_model(self.cfg.model)
if self.cfg.sync_bn:
model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
# logger.info(f"Model: \n{self.model}")
self.logger.info(f"Num params: {n_parameters}")
model = create_ddp_model(
model.cuda(),
broadcast_buffers=False,
find_unused_parameters=self.cfg.find_unused_parameters,
)
return model
def build_writer(self):
writer = SummaryWriter(self.cfg.save_path) if comm.is_main_process() else None
self.logger.info(f"Tensorboard writer logging dir: {self.cfg.save_path}")
return writer
def build_train_loader(self):
train_data = build_dataset(self.cfg.data.train)
if comm.get_world_size() > 1:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_data)
else:
train_sampler = None
init_fn = (
partial(
worker_init_fn,
num_workers=self.cfg.num_worker_per_gpu,
rank=comm.get_rank(),
seed=self.cfg.seed
)
if self.cfg.seed is not None
else None
)
train_loader = torch.utils.data.DataLoader(
train_data,
batch_size=self.cfg.batch_size_per_gpu,
shuffle=(train_sampler is None),
num_workers=self.cfg.num_worker_per_gpu,
sampler=train_sampler,
collate_fn=partial(point_collate_fn, mix_prob=self.cfg.mix_prob),
pin_memory=True,
worker_init_fn=init_fn,
drop_last=True,
persistent_workers=True,
)
return train_loader
def build_val_loader(self):
val_loader = None
if self.cfg.evaluate:
val_data = build_dataset(self.cfg.data.val)
if comm.get_world_size() > 1:
val_sampler = torch.utils.data.distributed.DistributedSampler(val_data)
else:
val_sampler = None
val_loader = torch.utils.data.DataLoader(
val_data,
batch_size=self.cfg.batch_size_val_per_gpu,
shuffle=False,
num_workers=self.cfg.num_worker_per_gpu,
pin_memory=True,
sampler=val_sampler,
collate_fn=collate_fn,
)
return val_loader
def build_optimizer(self):
return build_optimizer(self.cfg.optimizer, self.model, self.cfg.param_dicts)
def build_scheduler(self):
assert hasattr(self, "optimizer")
assert hasattr(self, "train_loader")
self.cfg.scheduler.total_steps = len(self.train_loader) * self.cfg.eval_epoch
return build_scheduler(self.cfg.scheduler, self.optimizer)
def build_scaler(self):
scaler = torch.cuda.amp.GradScaler() if self.cfg.enable_amp else None
return scaler
@TRAINERS.register_module("MultiDatasetTrainer")
class MultiDatasetTrainer(Trainer):
def build_train_loader(self):
from pointcept.datasets import MultiDatasetDataloader
train_data = build_dataset(self.cfg.data.train)
train_loader = MultiDatasetDataloader(
train_data,
self.cfg.batch_size_per_gpu,
self.cfg.num_worker_per_gpu,
self.cfg.mix_prob,
self.cfg.seed,
)
self.comm_info["iter_per_epoch"] = len(train_loader)
return train_loader
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/defaults.py | pointcept/engines/defaults.py | """
Default training/testing logic
modified from detectron2(https://github.com/facebookresearch/detectron2)
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import sys
import argparse
import multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
import pointcept.utils.comm as comm
from pointcept.utils.env import get_random_seed, set_seed
from pointcept.utils.config import Config, DictAction
def create_ddp_model(model, *, fp16_compression=False, **kwargs):
"""
Create a DistributedDataParallel model if there are >1 processes.
Args:
model: a torch.nn.Module
fp16_compression: add fp16 compression hooks to the ddp object.
See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook
kwargs: other arguments of :module:`torch.nn.parallel.DistributedDataParallel`.
"""
if comm.get_world_size() == 1:
return model
# kwargs['find_unused_parameters'] = True
if "device_ids" not in kwargs:
kwargs["device_ids"] = [comm.get_local_rank()]
if "output_device" not in kwargs:
kwargs["output_device"] = [comm.get_local_rank()]
ddp = DistributedDataParallel(model, **kwargs)
if fp16_compression:
from torch.distributed.algorithms.ddp_comm_hooks import default as comm_hooks
ddp.register_comm_hook(state=None, hook=comm_hooks.fp16_compress_hook)
return ddp
def worker_init_fn(worker_id, num_workers, rank, seed):
"""Worker init func for dataloader.
The seed of each worker equals to num_worker * rank + worker_id + user_seed
Args:
worker_id (int): Worker id.
num_workers (int): Number of workers.
rank (int): The rank of current process.
seed (int): The random seed to use.
"""
worker_seed = num_workers * rank + worker_id + seed
set_seed(worker_seed)
def default_argument_parser(epilog=None):
parser = argparse.ArgumentParser(
epilog=epilog
or f"""
Examples:
Run on single machine:
$ {sys.argv[0]} --num-gpus 8 --config-file cfg.yaml
Change some config options:
$ {sys.argv[0]} --config-file cfg.yaml MODEL.WEIGHTS /path/to/weight.pth SOLVER.BASE_LR 0.001
Run on multiple machines:
(machine0)$ {sys.argv[0]} --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags]
(machine1)$ {sys.argv[0]} --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags]
""",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--config-file", default="", metavar="FILE", help="path to config file"
)
parser.add_argument(
"--num-gpus", type=int, default=1, help="number of gpus *per machine*"
)
parser.add_argument(
"--num-machines", type=int, default=1, help="total number of machines"
)
parser.add_argument(
"--machine-rank",
type=int,
default=0,
help="the rank of this machine (unique per machine)",
)
# PyTorch still may leave orphan processes in multi-gpu training.
# Therefore we use a deterministic way to obtain port,
# so that users are aware of orphan processes by seeing the port occupied.
# port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14
parser.add_argument(
"--dist-url",
# default="tcp://127.0.0.1:{}".format(port),
default="auto",
help="initialization URL for pytorch distributed backend. See "
"https://pytorch.org/docs/stable/distributed.html for details.",
)
parser.add_argument(
"--options", nargs="+", action=DictAction, help="custom options"
)
return parser
def default_config_parser(file_path, options):
# config name protocol: dataset_name/model_name-exp_name
if os.path.isfile(file_path):
cfg = Config.fromfile(file_path)
else:
sep = file_path.find("-")
cfg = Config.fromfile(os.path.join(file_path[:sep], file_path[sep + 1 :]))
if options is not None:
cfg.merge_from_dict(options)
if cfg.seed is None:
cfg.seed = get_random_seed()
cfg.data.train.loop = cfg.epoch // cfg.eval_epoch
os.makedirs(os.path.join(cfg.save_path, "model"), exist_ok=True)
if not cfg.resume:
cfg.dump(os.path.join(cfg.save_path, "config.py"))
return cfg
def default_setup(cfg):
# scalar by world size
world_size = comm.get_world_size()
cfg.num_worker = cfg.num_worker if cfg.num_worker is not None else mp.cpu_count()
cfg.num_worker_per_gpu = cfg.num_worker // world_size
assert cfg.batch_size % world_size == 0
assert cfg.batch_size_val is None or cfg.batch_size_val % world_size == 0
assert cfg.batch_size_test is None or cfg.batch_size_test % world_size == 0
cfg.batch_size_per_gpu = cfg.batch_size // world_size
cfg.batch_size_val_per_gpu = (
cfg.batch_size_val // world_size if cfg.batch_size_val is not None else 1
)
cfg.batch_size_test_per_gpu = (
cfg.batch_size_test // world_size if cfg.batch_size_test is not None else 1
)
# update data loop
assert cfg.epoch % cfg.eval_epoch == 0
# settle random seed
rank = comm.get_rank()
# seed = None if cfg.seed is None else cfg.seed * cfg.num_worker_per_gpu + rank
seed = None if cfg.seed is None else cfg.seed
set_seed(seed)
return cfg
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/__init__.py | pointcept/engines/__init__.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/launch.py | pointcept/engines/launch.py | """
Launcher
modified from detectron2(https://github.com/facebookresearch/detectron2)
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import logging
from datetime import timedelta
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from pointcept.utils import comm
__all__ = ["DEFAULT_TIMEOUT", "launch"]
DEFAULT_TIMEOUT = timedelta(minutes=60)
def _find_free_port():
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Binding to port 0 will cause the OS to find an available port for us
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
# NOTE: there is still a chance the port could be taken by other processes.
return port
def launch(
main_func,
num_gpus_per_machine,
num_machines=1,
machine_rank=0,
dist_url=None,
cfg=(),
timeout=DEFAULT_TIMEOUT,
):
"""
Launch multi-gpu or distributed training.
This function must be called on all machines involved in the training.
It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine.
Args:
main_func: a function that will be called by `main_func(*args)`
num_gpus_per_machine (int): number of GPUs per machine
num_machines (int): the total number of machines
machine_rank (int): the rank of this machine
dist_url (str): url to connect to for distributed jobs, including protocol
e.g. "tcp://127.0.0.1:8686".
Can be set to "auto" to automatically select a free port on localhost
timeout (timedelta): timeout of the distributed workers
args (tuple): arguments passed to main_func
"""
world_size = num_machines * num_gpus_per_machine
if world_size > 1:
if dist_url == "auto":
assert (
num_machines == 1
), "dist_url=auto not supported in multi-machine jobs."
port = _find_free_port()
dist_url = f"tcp://127.0.0.1:{port}"
if num_machines > 1 and dist_url.startswith("file://"):
logger = logging.getLogger(__name__)
logger.warning(
"file:// is not a reliable init_method in multi-machine jobs. Prefer tcp://"
)
mp.spawn(
_distributed_worker,
nprocs=num_gpus_per_machine,
args=(
main_func,
world_size,
num_gpus_per_machine,
machine_rank,
dist_url,
cfg,
timeout,
),
daemon=False,
)
else:
main_func(*cfg)
def _distributed_worker(
local_rank,
main_func,
world_size,
num_gpus_per_machine,
machine_rank,
dist_url,
cfg,
timeout=DEFAULT_TIMEOUT,
):
assert (
torch.cuda.is_available()
), "cuda is not available. Please check your installation."
global_rank = machine_rank * num_gpus_per_machine + local_rank
try:
dist.init_process_group(
backend="NCCL",
init_method=dist_url,
world_size=world_size,
rank=global_rank,
timeout=timeout,
)
except Exception as e:
logger = logging.getLogger(__name__)
logger.error("Process group URL: {}".format(dist_url))
raise e
# Setup the local process group (which contains ranks within the same machine)
assert comm._LOCAL_PROCESS_GROUP is None
num_machines = world_size // num_gpus_per_machine
for i in range(num_machines):
ranks_on_i = list(
range(i * num_gpus_per_machine, (i + 1) * num_gpus_per_machine)
)
pg = dist.new_group(ranks_on_i)
if i == machine_rank:
comm._LOCAL_PROCESS_GROUP = pg
assert num_gpus_per_machine <= torch.cuda.device_count()
torch.cuda.set_device(local_rank)
# synchronize is needed here to prevent a possible timeout after calling init_process_group
# See: https://github.com/facebookresearch/maskrcnn-benchmark/issues/172
comm.synchronize()
main_func(*cfg)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/test.py | pointcept/engines/test.py | """
Tester
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import os
import time
import numpy as np
from collections import OrderedDict
import torch
import torch.distributed as dist
import torch.nn.functional as F
import torch.utils.data
from .defaults import create_ddp_model
import pointcept.utils.comm as comm
from pointcept.datasets import build_dataset, collate_fn
from pointcept.models import build_model
from pointcept.utils.logger import get_root_logger
from pointcept.utils.registry import Registry
from pointcept.utils.misc import (
AverageMeter,
intersection_and_union,
intersection_and_union_gpu,
make_dirs,
)
TESTERS = Registry("testers")
class TesterBase:
def __init__(self, cfg, model=None, test_loader=None, verbose=False) -> None:
torch.multiprocessing.set_sharing_strategy("file_system")
self.logger = get_root_logger(
log_file=os.path.join(cfg.save_path, "test.log"),
file_mode="a" if cfg.resume else "w",
)
self.logger.info("=> Loading config ...")
self.cfg = cfg
self.verbose = verbose
if self.verbose:
self.logger.info(f"Save path: {cfg.save_path}")
self.logger.info(f"Config:\n{cfg.pretty_text}")
if model is None:
self.logger.info("=> Building model ...")
self.model = self.build_model()
else:
self.model = model
if test_loader is None:
self.logger.info("=> Building test dataset & dataloader ...")
self.test_loader = self.build_test_loader()
else:
self.test_loader = test_loader
def build_model(self):
model = build_model(self.cfg.model)
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
self.logger.info(f"Num params: {n_parameters}")
model = create_ddp_model(
model.cuda(),
broadcast_buffers=False,
find_unused_parameters=self.cfg.find_unused_parameters,
)
if os.path.isfile(self.cfg.weight):
self.logger.info(f"Loading weight at: {self.cfg.weight}")
checkpoint = torch.load(self.cfg.weight)
weight = OrderedDict()
for key, value in checkpoint["state_dict"].items():
if key.startswith("module."):
if comm.get_world_size() == 1:
key = key[7:] # module.xxx.xxx -> xxx.xxx
else:
if comm.get_world_size() > 1:
key = "module." + key # xxx.xxx -> module.xxx.xxx
weight[key] = value
model.load_state_dict(weight, strict=True)
self.logger.info(
"=> Loaded weight '{}' (epoch {})".format(
self.cfg.weight, checkpoint["epoch"]
)
)
else:
raise RuntimeError("=> No checkpoint found at '{}'".format(self.cfg.weight))
return model
def build_test_loader(self):
test_dataset = build_dataset(self.cfg.data.test)
if comm.get_world_size() > 1:
test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset)
else:
test_sampler = None
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=self.cfg.batch_size_test_per_gpu,
shuffle=False,
num_workers=self.cfg.batch_size_test_per_gpu,
pin_memory=True,
sampler=test_sampler,
collate_fn=self.__class__.collate_fn,
)
return test_loader
def test(self):
raise NotImplementedError
@staticmethod
def collate_fn(batch):
raise collate_fn(batch)
@TESTERS.register_module()
class SemSegTester(TesterBase):
def test(self):
assert self.test_loader.batch_size == 1
logger = get_root_logger()
if(not hasattr(self.cfg, "noise_level")): self.cfg.noise_level = None
if(not hasattr(self.cfg, "skip_connection_scale_i")): self.cfg.skip_connection_scale_i = False
if(not hasattr(self.cfg, "inference_mode")): self.cfg.inference_mode = "SSI"
if(not hasattr(self.cfg, "step")): self.cfg.step = 1
self.logger.info(f"Noise Level : {self.cfg.noise_level}")
self.logger.info(f"Random Seed : {self.cfg.seed}")
self.logger.info(f"Diffusion Model : {self.cfg.dm}")
self.logger.info(f"DM Input : {self.cfg.dm_input}")
self.logger.info(f"DM Target : {self.cfg.dm_target}")
self.logger.info(f"DM Min SNR : {self.cfg.dm_min_snr}")
self.logger.info(f"Loss Type : {self.cfg.loss_type}")
self.logger.info(f"Skip Connection Mode : {self.cfg.skip_connection_mode}")
self.logger.info(f"Skip Connection Scale : {self.cfg.skip_connection_scale}")
self.logger.info(f"Skip Connection Scale SegNet: {self.cfg.skip_connection_scale_i}")
self.logger.info(f"TM Bidirectional : {self.cfg.tm_bidirectional}")
self.logger.info(f"TM Feat : {self.cfg.tm_feat}")
self.logger.info(f"TM Restomer : {self.cfg.tm_restomer}")
self.logger.info(f"inference_mode : {self.cfg.inference_mode}")
self.logger.info(f"step : {self.cfg.step}")
self.logger.info(
f"FreeU ==> backbone factor : {self.cfg.b_factor}, skip_connection factor : {self.cfg.s_factor}")
logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
batch_time = AverageMeter()
intersection_meter = AverageMeter()
union_meter = AverageMeter()
target_meter = AverageMeter()
self.model.eval()
save_path = os.path.join(self.cfg.save_path, "result")
make_dirs(save_path)
# create submit folder only on main process
if (
self.cfg.data.test.type == "ScanNetDataset"
or self.cfg.data.test.type == "ScanNet200Dataset"
) and comm.is_main_process():
make_dirs(os.path.join(save_path, "submit"))
elif (
self.cfg.data.test.type == "SemanticKITTIDataset" and comm.is_main_process()
):
make_dirs(os.path.join(save_path, "submit"))
elif self.cfg.data.test.type == "NuScenesDataset" and comm.is_main_process():
import json
make_dirs(os.path.join(save_path, "submit", "lidarseg", "test"))
make_dirs(os.path.join(save_path, "submit", "test"))
submission = dict(
meta=dict(
use_camera=False,
use_lidar=True,
use_radar=False,
use_map=False,
use_external=False,
)
)
with open(
os.path.join(save_path, "submit", "test", "submission.json"), "w"
) as f:
json.dump(submission, f, indent=4)
comm.synchronize()
record = {}
# fragment inference
for idx, data_dict in enumerate(self.test_loader):
end = time.time()
data_dict = data_dict[0] # current assume batch size is 1
fragment_list = data_dict.pop("fragment_list")
segment = data_dict.pop("segment")
data_name = data_dict.pop("name")
# coord = data_dict.pop("coord")
pred_save_path = os.path.join(save_path, "{}_pred.npy".format(data_name))
if os.path.isfile(pred_save_path):
logger.info(
"{}/{}: {}, loaded pred and label.".format(
idx + 1, len(self.test_loader), data_name
)
)
pred = np.load(pred_save_path)
else:
pred = torch.zeros((segment.size, self.cfg.data.num_classes)).cuda()
for i in range(len(fragment_list)):
fragment_batch_size = 1
s_i, e_i = i * fragment_batch_size, min(
(i + 1) * fragment_batch_size, len(fragment_list)
)
input_dict = collate_fn(fragment_list[s_i:e_i])
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
idx_part = input_dict["index"]
with torch.no_grad():
# ---- 网络输入 ----
# pred_part = self.model(input_dict)["seg_logits"] # (n, k)
if(self.cfg.inference_mode == "SSI"):
if (self.cfg.num_gpus == 1):
pred_part = self.model.inference( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level
)["seg_logits"]
else:
pred_part = self.model.module.inference( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level
)["seg_logits"]
elif(self.cfg.inference_mode == "MSAI"):
if (self.cfg.num_gpus == 1):
pred_part = self.model.inference_ddim( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level,
mode="avg",
step=self.cfg.step
)["seg_logits"]
else:
pred_part = self.model.module.inference_ddim( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level,
mode="avg",
step=self.cfg.step
)["seg_logits"]
elif(self.cfg.inference_mode == "MSFI"):
if (self.cfg.num_gpus == 1):
pred_part = self.model.inference_ddim( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level,
mode="final",
step=self.cfg.step
)["seg_logits"]
else:
pred_part = self.model.module.inference_ddim( # inference_ddim, inference
input_dict,
eval=False,
noise_level=self.cfg.noise_level,
mode="final",
step=self.cfg.step
)["seg_logits"]
# ---- 网络输入 ----
pred_part = F.softmax(pred_part, -1)
if self.cfg.empty_cache:
torch.cuda.empty_cache()
bs = 0
for be in input_dict["offset"]:
pred[idx_part[bs:be], :] += pred_part[bs:be]
bs = be
logger.info(
"Test: {}/{}-{data_name}, Batch: {batch_idx}/{batch_num}".format(
idx + 1,
len(self.test_loader),
data_name=data_name,
batch_idx=i,
batch_num=len(fragment_list),
)
)
pred = pred.max(1)[1].data.cpu().numpy()
np.save(pred_save_path, pred)
# # ---- save point cloud, segmentation, pre ---- #
# pred_save_path_data = os.path.join(save_path, "{}.pth".format(data_name))
# data={
# "coord" : coord,
# "gt":segment,
# "pred":pred
# }
# torch.save(data, pred_save_path_data)
# # ---- save point cloud, segmentation, pre ---- #
if "origin_segment" in data_dict.keys():
assert "inverse" in data_dict.keys()
pred = pred[data_dict["inverse"]]
segment = data_dict["origin_segment"]
intersection, union, target = intersection_and_union(
pred, segment, self.cfg.data.num_classes, self.cfg.data.ignore_index
)
intersection_meter.update(intersection)
union_meter.update(union)
target_meter.update(target)
record[data_name] = dict(
intersection=intersection, union=union, target=target
)
mask = union != 0
iou_class = intersection / (union + 1e-10)
iou = np.mean(iou_class[mask])
acc = sum(intersection) / (sum(target) + 1e-10)
m_iou = np.mean(intersection_meter.sum / (union_meter.sum + 1e-10))
m_acc = np.mean(intersection_meter.sum / (target_meter.sum + 1e-10))
batch_time.update(time.time() - end)
logger.info(
"Test: {} [{}/{}]-{} "
"Batch {batch_time.val:.3f} ({batch_time.avg:.3f}) "
"Accuracy {acc:.4f} ({m_acc:.4f}) "
"mIoU {iou:.4f} ({m_iou:.4f})".format(
data_name,
idx + 1,
len(self.test_loader),
segment.size,
batch_time=batch_time,
acc=acc,
m_acc=m_acc,
iou=iou,
m_iou=m_iou,
)
)
if (
self.cfg.data.test.type == "ScanNetDataset"
or self.cfg.data.test.type == "ScanNet200Dataset"
):
np.savetxt(
os.path.join(save_path, "submit", "{}.txt".format(data_name)),
self.test_loader.dataset.class2id[pred].reshape([-1, 1]),
fmt="%d",
)
elif self.cfg.data.test.type == "SemanticKITTIDataset":
# 00_000000 -> 00, 000000
sequence_name, frame_name = data_name.split("_")
os.makedirs(
os.path.join(
save_path, "submit", "sequences", sequence_name, "predictions"
),
exist_ok=True,
)
pred = pred.astype(np.uint32)
pred = np.vectorize(
self.test_loader.dataset.learning_map_inv.__getitem__
)(pred).astype(np.uint32)
pred.tofile(
os.path.join(
save_path,
"submit",
"sequences",
sequence_name,
"predictions",
f"{frame_name}.label",
)
)
elif self.cfg.data.test.type == "NuScenesDataset":
np.array(pred + 1).astype(np.uint8).tofile(
os.path.join(
save_path,
"submit",
"lidarseg",
"test",
"{}_lidarseg.bin".format(data_name),
)
)
self.cfg.inference_mode = "SSI"
logger.info("Syncing ...")
comm.synchronize()
record_sync = comm.gather(record, dst=0)
if comm.is_main_process():
record = {}
for _ in range(len(record_sync)):
r = record_sync.pop()
record.update(r)
del r
intersection = np.sum(
[meters["intersection"] for _, meters in record.items()], axis=0
)
union = np.sum([meters["union"] for _, meters in record.items()], axis=0)
target = np.sum([meters["target"] for _, meters in record.items()], axis=0)
if self.cfg.data.test.type == "S3DISDataset":
torch.save(
dict(intersection=intersection, union=union, target=target),
os.path.join(save_path, f"{self.test_loader.dataset.split}.pth"),
)
iou_class = intersection / (union + 1e-10)
accuracy_class = intersection / (target + 1e-10)
mIoU = np.mean(iou_class)
mAcc = np.mean(accuracy_class)
allAcc = sum(intersection) / (sum(target) + 1e-10)
logger.info(
"Val result: mIoU/mAcc/allAcc {:.4f}/{:.4f}/{:.4f}".format(
mIoU, mAcc, allAcc
)
)
for i in range(self.cfg.data.num_classes):
logger.info(
"Class_{idx} - {name} Result: iou/accuracy {iou:.4f}/{accuracy:.4f}".format(
idx=i,
name=self.cfg.data.names[i],
iou=iou_class[i],
accuracy=accuracy_class[i],
)
)
logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
@staticmethod
def collate_fn(batch):
return batch
@TESTERS.register_module()
class ClsTester(TesterBase):
def test(self):
logger = get_root_logger()
logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
batch_time = AverageMeter()
intersection_meter = AverageMeter()
union_meter = AverageMeter()
target_meter = AverageMeter()
self.model.eval()
for i, input_dict in enumerate(self.test_loader):
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
end = time.time()
with torch.no_grad():
output_dict = self.model(input_dict)
output = output_dict["cls_logits"]
pred = output.max(1)[1]
label = input_dict["category"]
intersection, union, target = intersection_and_union_gpu(
pred, label, self.cfg.data.num_classes, self.cfg.data.ignore_index
)
if comm.get_world_size() > 1:
dist.all_reduce(intersection), dist.all_reduce(union), dist.all_reduce(
target
)
intersection, union, target = (
intersection.cpu().numpy(),
union.cpu().numpy(),
target.cpu().numpy(),
)
intersection_meter.update(intersection), union_meter.update(
union
), target_meter.update(target)
accuracy = sum(intersection_meter.val) / (sum(target_meter.val) + 1e-10)
batch_time.update(time.time() - end)
logger.info(
"Test: [{}/{}] "
"Batch {batch_time.val:.3f} ({batch_time.avg:.3f}) "
"Accuracy {accuracy:.4f} ".format(
i + 1,
len(self.test_loader),
batch_time=batch_time,
accuracy=accuracy,
)
)
iou_class = intersection_meter.sum / (union_meter.sum + 1e-10)
accuracy_class = intersection_meter.sum / (target_meter.sum + 1e-10)
mIoU = np.mean(iou_class)
mAcc = np.mean(accuracy_class)
allAcc = sum(intersection_meter.sum) / (sum(target_meter.sum) + 1e-10)
logger.info(
"Val result: mIoU/mAcc/allAcc {:.4f}/{:.4f}/{:.4f}.".format(
mIoU, mAcc, allAcc
)
)
for i in range(self.cfg.data.num_classes):
logger.info(
"Class_{idx} - {name} Result: iou/accuracy {iou:.4f}/{accuracy:.4f}".format(
idx=i,
name=self.cfg.data.names[i],
iou=iou_class[i],
accuracy=accuracy_class[i],
)
)
logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
@staticmethod
def collate_fn(batch):
return collate_fn(batch)
@TESTERS.register_module()
class PartSegTester(TesterBase):
def test(self):
test_dataset = self.test_loader.dataset
logger = get_root_logger()
logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
batch_time = AverageMeter()
num_categories = len(self.test_loader.dataset.categories)
iou_category, iou_count = np.zeros(num_categories), np.zeros(num_categories)
self.model.eval()
save_path = os.path.join(
self.cfg.save_path, "result", "test_epoch{}".format(self.cfg.test_epoch)
)
make_dirs(save_path)
for idx in range(len(test_dataset)):
end = time.time()
data_name = test_dataset.get_data_name(idx)
data_dict_list, label = test_dataset[idx]
pred = torch.zeros((label.size, self.cfg.data.num_classes)).cuda()
batch_num = int(np.ceil(len(data_dict_list) / self.cfg.batch_size_test))
for i in range(batch_num):
s_i, e_i = i * self.cfg.batch_size_test, min(
(i + 1) * self.cfg.batch_size_test, len(data_dict_list)
)
input_dict = collate_fn(data_dict_list[s_i:e_i])
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
with torch.no_grad():
pred_part = self.model(input_dict)["cls_logits"]
pred_part = F.softmax(pred_part, -1)
if self.cfg.empty_cache:
torch.cuda.empty_cache()
pred_part = pred_part.reshape(-1, label.size, self.cfg.data.num_classes)
pred = pred + pred_part.total(dim=0)
logger.info(
"Test: {} {}/{}, Batch: {batch_idx}/{batch_num}".format(
data_name,
idx + 1,
len(test_dataset),
batch_idx=i,
batch_num=batch_num,
)
)
pred = pred.max(1)[1].data.cpu().numpy()
category_index = data_dict_list[0]["cls_token"]
category = self.test_loader.dataset.categories[category_index]
parts_idx = self.test_loader.dataset.category2part[category]
parts_iou = np.zeros(len(parts_idx))
for j, part in enumerate(parts_idx):
if (np.sum(label == part) == 0) and (np.sum(pred == part) == 0):
parts_iou[j] = 1.0
else:
i = (label == part) & (pred == part)
u = (label == part) | (pred == part)
parts_iou[j] = np.sum(i) / (np.sum(u) + 1e-10)
iou_category[category_index] += parts_iou.mean()
iou_count[category_index] += 1
batch_time.update(time.time() - end)
logger.info(
"Test: {} [{}/{}] "
"Batch {batch_time.val:.3f} "
"({batch_time.avg:.3f}) ".format(
data_name, idx + 1, len(self.test_loader), batch_time=batch_time
)
)
ins_mIoU = iou_category.sum() / (iou_count.sum() + 1e-10)
cat_mIoU = (iou_category / (iou_count + 1e-10)).mean()
logger.info(
"Val result: ins.mIoU/cat.mIoU {:.4f}/{:.4f}.".format(ins_mIoU, cat_mIoU)
)
for i in range(num_categories):
logger.info(
"Class_{idx}-{name} Result: iou_cat/num_sample {iou_cat:.4f}/{iou_count:.4f}".format(
idx=i,
name=self.test_loader.dataset.categories[i],
iou_cat=iou_category[i] / (iou_count[i] + 1e-10),
iou_count=int(iou_count[i]),
)
)
logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
@staticmethod
def collate_fn(batch):
return collate_fn(batch)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/hooks/default.py | pointcept/engines/hooks/default.py | """
Default Hook
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
class HookBase:
"""
Base class for hooks that can be registered with :class:`TrainerBase`.
"""
trainer = None # A weak reference to the trainer object.
def before_train(self):
pass
def before_epoch(self):
pass
def before_step(self):
pass
def after_step(self):
pass
def after_epoch(self):
pass
def after_train(self):
pass
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/hooks/evaluator.py | pointcept/engines/hooks/evaluator.py | """
Evaluate Hook
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import numpy as np
import torch
import torch.distributed as dist
import pointops
from uuid import uuid4
import pointcept.utils.comm as comm
from pointcept.utils.misc import intersection_and_union_gpu
from .default import HookBase
from .builder import HOOKS
@HOOKS.register_module()
class ClsEvaluator(HookBase):
def after_epoch(self):
if self.trainer.cfg.evaluate:
self.eval()
def eval(self):
self.trainer.logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
self.trainer.model.eval()
for i, input_dict in enumerate(self.trainer.val_loader):
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
with torch.no_grad():
output_dict = self.trainer.model(input_dict)
output = output_dict["cls_logits"]
loss = output_dict["loss"]
pred = output.max(1)[1]
label = input_dict["category"]
intersection, union, target = intersection_and_union_gpu(
pred,
label,
self.trainer.cfg.data.num_classes,
self.trainer.cfg.data.ignore_index,
)
if comm.get_world_size() > 1:
dist.all_reduce(intersection), dist.all_reduce(union), dist.all_reduce(
target
)
intersection, union, target = (
intersection.cpu().numpy(),
union.cpu().numpy(),
target.cpu().numpy(),
)
# Here there is no need to sync since sync happened in dist.all_reduce
self.trainer.storage.put_scalar("val_intersection", intersection)
self.trainer.storage.put_scalar("val_union", union)
self.trainer.storage.put_scalar("val_target", target)
self.trainer.storage.put_scalar("val_loss", loss.item())
self.trainer.logger.info(
"Test: [{iter}/{max_iter}] "
"Loss {loss:.4f} ".format(
iter=i + 1, max_iter=len(self.trainer.val_loader), loss=loss.item()
)
)
loss_avg = self.trainer.storage.history("val_loss").avg
intersection = self.trainer.storage.history("val_intersection").total
union = self.trainer.storage.history("val_union").total
target = self.trainer.storage.history("val_target").total
iou_class = intersection / (union + 1e-10)
acc_class = intersection / (target + 1e-10)
m_iou = np.mean(iou_class)
m_acc = np.mean(acc_class)
all_acc = sum(intersection) / (sum(target) + 1e-10)
self.trainer.logger.info(
"Val result: mIoU/mAcc/allAcc {:.4f}/{:.4f}/{:.4f}.".format(
m_iou, m_acc, all_acc
)
)
for i in range(self.trainer.cfg.data.num_classes):
self.trainer.logger.info(
"Class_{idx}-{name} Result: iou/accuracy {iou:.4f}/{accuracy:.4f}".format(
idx=i,
name=self.trainer.cfg.data.names[i],
iou=iou_class[i],
accuracy=acc_class[i],
)
)
current_epoch = self.trainer.epoch + 1
if self.trainer.writer is not None:
self.trainer.writer.add_scalar("val/loss", loss_avg, current_epoch)
self.trainer.writer.add_scalar("val/mIoU", m_iou, current_epoch)
self.trainer.writer.add_scalar("val/mAcc", m_acc, current_epoch)
self.trainer.writer.add_scalar("val/allAcc", all_acc, current_epoch)
self.trainer.logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
self.trainer.comm_info["current_metric_value"] = all_acc # save for saver
self.trainer.comm_info["current_metric_name"] = "allAcc" # save for saver
def after_train(self):
self.trainer.logger.info(
"Best {}: {:.4f}".format("allAcc", self.trainer.best_metric_value)
)
@HOOKS.register_module()
class SemSegEvaluator(HookBase):
def after_epoch(self):
if self.trainer.cfg.evaluate:
self.eval()
def eval(self):
self.trainer.logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
self.trainer.model.eval()
for i, input_dict in enumerate(self.trainer.val_loader):
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
with torch.no_grad():
# ---- 在这里验证 ----
# output_dict = self.trainer.model(input_dict)
if (self.trainer.cfg.num_gpus == 1):
output_dict = self.trainer.model.inference(input_dict) # inference_ddim, inference
else:
output_dict = self.trainer.model.module.inference(input_dict) # inference_ddim, inference
# ---- 在这里验证 ----
output = output_dict["seg_logits"]
loss = output_dict["loss"]
pred = output.max(1)[1]
segment = input_dict["segment"]
if "origin_coord" in input_dict.keys():
idx, _ = pointops.knn_query(
1,
input_dict["coord"].float(),
input_dict["offset"].int(),
input_dict["origin_coord"].float(),
input_dict["origin_offset"].int(),
)
pred = pred[idx.flatten().long()]
segment = input_dict["origin_segment"]
intersection, union, target = intersection_and_union_gpu(
pred,
segment,
self.trainer.cfg.data.num_classes,
self.trainer.cfg.data.ignore_index,
)
if comm.get_world_size() > 1:
dist.all_reduce(intersection), dist.all_reduce(union), dist.all_reduce(
target
)
intersection, union, target = (
intersection.cpu().numpy(),
union.cpu().numpy(),
target.cpu().numpy(),
)
# Here there is no need to sync since sync happened in dist.all_reduce
self.trainer.storage.put_scalar("val_intersection", intersection)
self.trainer.storage.put_scalar("val_union", union)
self.trainer.storage.put_scalar("val_target", target)
self.trainer.storage.put_scalar("val_loss", loss.item())
info = "Test: [{iter}/{max_iter}] ".format(
iter=i + 1, max_iter=len(self.trainer.val_loader)
)
if "origin_coord" in input_dict.keys():
info = "Interp. " + info
self.trainer.logger.info(
info
+ "Loss {loss:.4f} ".format(
iter=i + 1, max_iter=len(self.trainer.val_loader), loss=loss.item()
)
)
loss_avg = self.trainer.storage.history("val_loss").avg
intersection = self.trainer.storage.history("val_intersection").total
union = self.trainer.storage.history("val_union").total
target = self.trainer.storage.history("val_target").total
iou_class = intersection / (union + 1e-10)
acc_class = intersection / (target + 1e-10)
m_iou = np.mean(iou_class)
m_acc = np.mean(acc_class)
all_acc = sum(intersection) / (sum(target) + 1e-10)
self.trainer.logger.info(
"Val result: mIoU/mAcc/allAcc {:.4f}/{:.4f}/{:.4f}.".format(
m_iou, m_acc, all_acc
)
)
for i in range(self.trainer.cfg.data.num_classes):
self.trainer.logger.info(
"Class_{idx}-{name} Result: iou/accuracy {iou:.4f}/{accuracy:.4f}".format(
idx=i,
name=self.trainer.cfg.data.names[i],
iou=iou_class[i],
accuracy=acc_class[i],
)
)
current_epoch = self.trainer.epoch + 1
if self.trainer.writer is not None:
self.trainer.writer.add_scalar("val/loss", loss_avg, current_epoch)
self.trainer.writer.add_scalar("val/mIoU", m_iou, current_epoch)
self.trainer.writer.add_scalar("val/mAcc", m_acc, current_epoch)
self.trainer.writer.add_scalar("val/allAcc", all_acc, current_epoch)
self.trainer.logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
self.trainer.comm_info["current_metric_value"] = m_iou # save for saver
self.trainer.comm_info["current_metric_name"] = "mIoU" # save for saver
def after_train(self):
self.trainer.logger.info(
"Best {}: {:.4f}".format("mIoU", self.trainer.best_metric_value)
)
@HOOKS.register_module()
class InsSegEvaluator(HookBase):
def __init__(self, segment_ignore_index=(-1,), instance_ignore_index=-1):
self.segment_ignore_index = segment_ignore_index
self.instance_ignore_index = instance_ignore_index
self.valid_class_names = None # update in before train
self.overlaps = np.append(np.arange(0.5, 0.95, 0.05), 0.25)
self.min_region_sizes = 100
self.distance_threshes = float("inf")
self.distance_confs = -float("inf")
def before_train(self):
self.valid_class_names = [
self.trainer.cfg.data.names[i]
for i in range(self.trainer.cfg.data.num_classes)
if i not in self.segment_ignore_index
]
def after_epoch(self):
if self.trainer.cfg.evaluate:
self.eval()
def associate_instances(self, pred, segment, instance):
segment = segment.cpu().numpy()
instance = instance.cpu().numpy()
void_mask = np.in1d(segment, self.segment_ignore_index)
assert (
pred["pred_classes"].shape[0]
== pred["pred_scores"].shape[0]
== pred["pred_masks"].shape[0]
)
assert pred["pred_masks"].shape[1] == segment.shape[0] == instance.shape[0]
# get gt instances
gt_instances = dict()
for i in range(self.trainer.cfg.data.num_classes):
if i not in self.segment_ignore_index:
gt_instances[self.trainer.cfg.data.names[i]] = []
instance_ids, idx, counts = np.unique(
instance, return_index=True, return_counts=True
)
segment_ids = segment[idx]
for i in range(len(instance_ids)):
if instance_ids[i] == self.instance_ignore_index:
continue
if segment_ids[i] in self.segment_ignore_index:
continue
gt_inst = dict()
gt_inst["instance_id"] = instance_ids[i]
gt_inst["segment_id"] = segment_ids[i]
gt_inst["dist_conf"] = 0.0
gt_inst["med_dist"] = -1.0
gt_inst["vert_count"] = counts[i]
gt_inst["matched_pred"] = []
gt_instances[self.trainer.cfg.data.names[segment_ids[i]]].append(gt_inst)
# get pred instances and associate with gt
pred_instances = dict()
for i in range(self.trainer.cfg.data.num_classes):
if i not in self.segment_ignore_index:
pred_instances[self.trainer.cfg.data.names[i]] = []
instance_id = 0
for i in range(len(pred["pred_classes"])):
if pred["pred_classes"][i] in self.segment_ignore_index:
continue
pred_inst = dict()
pred_inst["uuid"] = uuid4()
pred_inst["instance_id"] = instance_id
pred_inst["segment_id"] = pred["pred_classes"][i]
pred_inst["confidence"] = pred["pred_scores"][i]
pred_inst["mask"] = np.not_equal(pred["pred_masks"][i], 0)
pred_inst["vert_count"] = np.count_nonzero(pred_inst["mask"])
pred_inst["void_intersection"] = np.count_nonzero(
np.logical_and(void_mask, pred_inst["mask"])
)
if pred_inst["vert_count"] < self.min_region_sizes:
continue # skip if empty
segment_name = self.trainer.cfg.data.names[pred_inst["segment_id"]]
matched_gt = []
for gt_idx, gt_inst in enumerate(gt_instances[segment_name]):
intersection = np.count_nonzero(
np.logical_and(
instance == gt_inst["instance_id"], pred_inst["mask"]
)
)
if intersection > 0:
gt_inst_ = gt_inst.copy()
pred_inst_ = pred_inst.copy()
gt_inst_["intersection"] = intersection
pred_inst_["intersection"] = intersection
matched_gt.append(gt_inst_)
gt_inst["matched_pred"].append(pred_inst_)
pred_inst["matched_gt"] = matched_gt
pred_instances[segment_name].append(pred_inst)
instance_id += 1
return gt_instances, pred_instances
def evaluate_matches(self, scenes):
overlaps = self.overlaps
min_region_sizes = [self.min_region_sizes]
dist_threshes = [self.distance_threshes]
dist_confs = [self.distance_confs]
# results: class x overlap
ap_table = np.zeros(
(len(dist_threshes), len(self.valid_class_names), len(overlaps)), float
)
for di, (min_region_size, distance_thresh, distance_conf) in enumerate(
zip(min_region_sizes, dist_threshes, dist_confs)
):
for oi, overlap_th in enumerate(overlaps):
pred_visited = {}
for scene in scenes:
for _ in scene["pred"]:
for label_name in self.valid_class_names:
for p in scene["pred"][label_name]:
if "uuid" in p:
pred_visited[p["uuid"]] = False
for li, label_name in enumerate(self.valid_class_names):
y_true = np.empty(0)
y_score = np.empty(0)
hard_false_negatives = 0
has_gt = False
has_pred = False
for scene in scenes:
pred_instances = scene["pred"][label_name]
gt_instances = scene["gt"][label_name]
# filter groups in ground truth
gt_instances = [
gt
for gt in gt_instances
if gt["vert_count"] >= min_region_size
and gt["med_dist"] <= distance_thresh
and gt["dist_conf"] >= distance_conf
]
if gt_instances:
has_gt = True
if pred_instances:
has_pred = True
cur_true = np.ones(len(gt_instances))
cur_score = np.ones(len(gt_instances)) * (-float("inf"))
cur_match = np.zeros(len(gt_instances), dtype=bool)
# collect matches
for gti, gt in enumerate(gt_instances):
found_match = False
for pred in gt["matched_pred"]:
# greedy assignments
if pred_visited[pred["uuid"]]:
continue
overlap = float(pred["intersection"]) / (
gt["vert_count"]
+ pred["vert_count"]
- pred["intersection"]
)
if overlap > overlap_th:
confidence = pred["confidence"]
# if already have a prediction for this gt,
# the prediction with the lower score is automatically a false positive
if cur_match[gti]:
max_score = max(cur_score[gti], confidence)
min_score = min(cur_score[gti], confidence)
cur_score[gti] = max_score
# append false positive
cur_true = np.append(cur_true, 0)
cur_score = np.append(cur_score, min_score)
cur_match = np.append(cur_match, True)
# otherwise set score
else:
found_match = True
cur_match[gti] = True
cur_score[gti] = confidence
pred_visited[pred["uuid"]] = True
if not found_match:
hard_false_negatives += 1
# remove non-matched ground truth instances
cur_true = cur_true[cur_match]
cur_score = cur_score[cur_match]
# collect non-matched predictions as false positive
for pred in pred_instances:
found_gt = False
for gt in pred["matched_gt"]:
overlap = float(gt["intersection"]) / (
gt["vert_count"]
+ pred["vert_count"]
- gt["intersection"]
)
if overlap > overlap_th:
found_gt = True
break
if not found_gt:
num_ignore = pred["void_intersection"]
for gt in pred["matched_gt"]:
if gt["segment_id"] in self.segment_ignore_index:
num_ignore += gt["intersection"]
# small ground truth instances
if (
gt["vert_count"] < min_region_size
or gt["med_dist"] > distance_thresh
or gt["dist_conf"] < distance_conf
):
num_ignore += gt["intersection"]
proportion_ignore = (
float(num_ignore) / pred["vert_count"]
)
# if not ignored append false positive
if proportion_ignore <= overlap_th:
cur_true = np.append(cur_true, 0)
confidence = pred["confidence"]
cur_score = np.append(cur_score, confidence)
# append to overall results
y_true = np.append(y_true, cur_true)
y_score = np.append(y_score, cur_score)
# compute average precision
if has_gt and has_pred:
# compute precision recall curve first
# sorting and cumsum
score_arg_sort = np.argsort(y_score)
y_score_sorted = y_score[score_arg_sort]
y_true_sorted = y_true[score_arg_sort]
y_true_sorted_cumsum = np.cumsum(y_true_sorted)
# unique thresholds
(thresholds, unique_indices) = np.unique(
y_score_sorted, return_index=True
)
num_prec_recall = len(unique_indices) + 1
# prepare precision recall
num_examples = len(y_score_sorted)
# https://github.com/ScanNet/ScanNet/pull/26
# all predictions are non-matched but also all of them are ignored and not counted as FP
# y_true_sorted_cumsum is empty
# num_true_examples = y_true_sorted_cumsum[-1]
num_true_examples = (
y_true_sorted_cumsum[-1]
if len(y_true_sorted_cumsum) > 0
else 0
)
precision = np.zeros(num_prec_recall)
recall = np.zeros(num_prec_recall)
# deal with the first point
y_true_sorted_cumsum = np.append(y_true_sorted_cumsum, 0)
# deal with remaining
for idx_res, idx_scores in enumerate(unique_indices):
cumsum = y_true_sorted_cumsum[idx_scores - 1]
tp = num_true_examples - cumsum
fp = num_examples - idx_scores - tp
fn = cumsum + hard_false_negatives
p = float(tp) / (tp + fp)
r = float(tp) / (tp + fn)
precision[idx_res] = p
recall[idx_res] = r
# first point in curve is artificial
precision[-1] = 1.0
recall[-1] = 0.0
# compute average of precision-recall curve
recall_for_conv = np.copy(recall)
recall_for_conv = np.append(recall_for_conv[0], recall_for_conv)
recall_for_conv = np.append(recall_for_conv, 0.0)
stepWidths = np.convolve(
recall_for_conv, [-0.5, 0, 0.5], "valid"
)
# integrate is now simply a dot product
ap_current = np.dot(precision, stepWidths)
elif has_gt:
ap_current = 0.0
else:
ap_current = float("nan")
ap_table[di, li, oi] = ap_current
d_inf = 0
o50 = np.where(np.isclose(self.overlaps, 0.5))
o25 = np.where(np.isclose(self.overlaps, 0.25))
oAllBut25 = np.where(np.logical_not(np.isclose(self.overlaps, 0.25)))
ap_scores = dict()
ap_scores["all_ap"] = np.nanmean(ap_table[d_inf, :, oAllBut25])
ap_scores["all_ap_50%"] = np.nanmean(ap_table[d_inf, :, o50])
ap_scores["all_ap_25%"] = np.nanmean(ap_table[d_inf, :, o25])
ap_scores["classes"] = {}
for li, label_name in enumerate(self.valid_class_names):
ap_scores["classes"][label_name] = {}
ap_scores["classes"][label_name]["ap"] = np.average(
ap_table[d_inf, li, oAllBut25]
)
ap_scores["classes"][label_name]["ap50%"] = np.average(
ap_table[d_inf, li, o50]
)
ap_scores["classes"][label_name]["ap25%"] = np.average(
ap_table[d_inf, li, o25]
)
return ap_scores
def eval(self):
self.trainer.logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>")
self.trainer.model.eval()
scenes = []
for i, input_dict in enumerate(self.trainer.val_loader):
assert (
len(input_dict["offset"]) == 1
) # currently only support bs 1 for each GPU
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
with torch.no_grad():
output_dict = self.trainer.model(input_dict)
loss = output_dict["loss"]
segment = input_dict["segment"]
instance = input_dict["instance"]
# map to origin
if "origin_coord" in input_dict.keys():
idx, _ = pointops.knn_query(
1,
input_dict["coord"].float(),
input_dict["offset"].int(),
input_dict["origin_coord"].float(),
input_dict["origin_offset"].int(),
)
idx = idx.cpu().flatten().long()
output_dict["pred_masks"] = output_dict["pred_masks"][:, idx]
segment = input_dict["origin_segment"]
instance = input_dict["origin_instance"]
gt_instances, pred_instance = self.associate_instances(
output_dict, segment, instance
)
scenes.append(dict(gt=gt_instances, pred=pred_instance))
self.trainer.storage.put_scalar("val_loss", loss.item())
self.trainer.logger.info(
"Test: [{iter}/{max_iter}] "
"Loss {loss:.4f} ".format(
iter=i + 1, max_iter=len(self.trainer.val_loader), loss=loss.item()
)
)
loss_avg = self.trainer.storage.history("val_loss").avg
comm.synchronize()
scenes_sync = comm.gather(scenes, dst=0)
scenes = [scene for scenes_ in scenes_sync for scene in scenes_]
ap_scores = self.evaluate_matches(scenes)
all_ap = ap_scores["all_ap"]
all_ap_50 = ap_scores["all_ap_50%"]
all_ap_25 = ap_scores["all_ap_25%"]
self.trainer.logger.info(
"Val result: mAP/AP50/AP25 {:.4f}/{:.4f}/{:.4f}.".format(
all_ap, all_ap_50, all_ap_25
)
)
for i, label_name in enumerate(self.valid_class_names):
ap = ap_scores["classes"][label_name]["ap"]
ap_50 = ap_scores["classes"][label_name]["ap50%"]
ap_25 = ap_scores["classes"][label_name]["ap25%"]
self.trainer.logger.info(
"Class_{idx}-{name} Result: AP/AP50/AP25 {AP:.4f}/{AP50:.4f}/{AP25:.4f}".format(
idx=i, name=label_name, AP=ap, AP50=ap_50, AP25=ap_25
)
)
current_epoch = self.trainer.epoch + 1
if self.trainer.writer is not None:
self.trainer.writer.add_scalar("val/loss", loss_avg, current_epoch)
self.trainer.writer.add_scalar("val/mAP", all_ap, current_epoch)
self.trainer.writer.add_scalar("val/AP50", all_ap_50, current_epoch)
self.trainer.writer.add_scalar("val/AP25", all_ap_25, current_epoch)
self.trainer.logger.info("<<<<<<<<<<<<<<<<< End Evaluation <<<<<<<<<<<<<<<<<")
self.trainer.comm_info["current_metric_value"] = all_ap_50 # save for saver
self.trainer.comm_info["current_metric_name"] = "AP50" # save for saver
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/hooks/misc.py | pointcept/engines/hooks/misc.py | """
Misc Hook
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
import sys
import glob
import os
import shutil
import time
import torch
import torch.utils.data
from collections import OrderedDict
if sys.version_info >= (3, 10):
from collections.abc import Sequence
else:
from collections import Sequence
from pointcept.utils.timer import Timer
from pointcept.utils.comm import is_main_process, synchronize, get_world_size
from pointcept.utils.cache import shared_dict
import pointcept.utils.comm as comm
from pointcept.engines.test import TESTERS
from .default import HookBase
from .builder import HOOKS
@HOOKS.register_module()
class IterationTimer(HookBase):
def __init__(self, warmup_iter=1):
self._warmup_iter = warmup_iter
self._start_time = time.perf_counter()
self._iter_timer = Timer()
self._remain_iter = 0
def before_train(self):
self._start_time = time.perf_counter()
self._remain_iter = self.trainer.max_epoch * len(self.trainer.train_loader)
def before_epoch(self):
self._iter_timer.reset()
def before_step(self):
data_time = self._iter_timer.seconds()
self.trainer.storage.put_scalar("data_time", data_time)
def after_step(self):
batch_time = self._iter_timer.seconds()
self._iter_timer.reset()
self.trainer.storage.put_scalar("batch_time", batch_time)
self._remain_iter -= 1
remain_time = self._remain_iter * self.trainer.storage.history("batch_time").avg
t_m, t_s = divmod(remain_time, 60)
t_h, t_m = divmod(t_m, 60)
remain_time = "{:02d}:{:02d}:{:02d}".format(int(t_h), int(t_m), int(t_s))
if "iter_info" in self.trainer.comm_info.keys():
info = (
"Data {data_time_val:.3f} ({data_time_avg:.3f}) "
"Batch {batch_time_val:.3f} ({batch_time_avg:.3f}) "
"Remain {remain_time} ".format(
data_time_val=self.trainer.storage.history("data_time").val,
data_time_avg=self.trainer.storage.history("data_time").avg,
batch_time_val=self.trainer.storage.history("batch_time").val,
batch_time_avg=self.trainer.storage.history("batch_time").avg,
remain_time=remain_time,
)
)
self.trainer.comm_info["iter_info"] += info
if self.trainer.comm_info["iter"] <= self._warmup_iter:
self.trainer.storage.history("data_time").reset()
self.trainer.storage.history("batch_time").reset()
@HOOKS.register_module()
class InformationWriter(HookBase):
def __init__(self):
self.curr_iter = 0
self.model_output_keys = []
def before_train(self):
self.trainer.comm_info["iter_info"] = ""
self.curr_iter = self.trainer.start_epoch * len(self.trainer.train_loader)
def before_step(self):
self.curr_iter += 1
# MSC pretrain do not have offset information. Comment the code for support MSC
# info = "Train: [{epoch}/{max_epoch}][{iter}/{max_iter}] " \
# "Scan {batch_size} ({points_num}) ".format(
# epoch=self.trainer.epoch + 1, max_epoch=self.trainer.max_epoch,
# iter=self.trainer.comm_info["iter"], max_iter=len(self.trainer.train_loader),
# batch_size=len(self.trainer.comm_info["input_dict"]["offset"]),
# points_num=self.trainer.comm_info["input_dict"]["offset"][-1]
# )
info = "Train: [{epoch}/{max_epoch}][{iter}/{max_iter}] ".format(
epoch=self.trainer.epoch + 1,
max_epoch=self.trainer.max_epoch,
iter=self.trainer.comm_info["iter"] + 1,
max_iter=len(self.trainer.train_loader),
)
self.trainer.comm_info["iter_info"] += info
def after_step(self):
if "model_output_dict" in self.trainer.comm_info.keys():
model_output_dict = self.trainer.comm_info["model_output_dict"]
self.model_output_keys = model_output_dict.keys()
for key in self.model_output_keys:
self.trainer.storage.put_scalar(key, model_output_dict[key].item())
for key in self.model_output_keys:
self.trainer.comm_info["iter_info"] += "{key}: {value:.4f} ".format(
key=key, value=self.trainer.storage.history(key).val
)
lr = self.trainer.optimizer.state_dict()["param_groups"][0]["lr"]
self.trainer.comm_info["iter_info"] += "Lr: {lr:.5f}".format(lr=lr)
self.trainer.logger.info(self.trainer.comm_info["iter_info"])
self.trainer.comm_info["iter_info"] = "" # reset iter info
if self.trainer.writer is not None:
self.trainer.writer.add_scalar("lr", lr, self.curr_iter)
for key in self.model_output_keys:
self.trainer.writer.add_scalar(
"train_batch/" + key,
self.trainer.storage.history(key).val,
self.curr_iter,
)
def after_epoch(self):
epoch_info = "Train result: "
for key in self.model_output_keys:
epoch_info += "{key}: {value:.4f} ".format(
key=key, value=self.trainer.storage.history(key).avg
)
self.trainer.logger.info(epoch_info)
if self.trainer.writer is not None:
for key in self.model_output_keys:
self.trainer.writer.add_scalar(
"train/" + key,
self.trainer.storage.history(key).avg,
self.trainer.epoch + 1,
)
@HOOKS.register_module()
class CheckpointSaver(HookBase):
def __init__(self, save_freq=None):
self.save_freq = save_freq # None or int, None indicate only save model last
def after_epoch(self):
if is_main_process():
is_best = False
if self.trainer.cfg.evaluate:
current_metric_value = self.trainer.comm_info["current_metric_value"]
current_metric_name = self.trainer.comm_info["current_metric_name"]
if current_metric_value > self.trainer.best_metric_value:
self.trainer.best_metric_value = current_metric_value
is_best = True
self.trainer.logger.info(
"Best validation {} updated to: {:.4f}".format(
current_metric_name, current_metric_value
)
)
self.trainer.logger.info(
"Currently Best {}: {:.4f}".format(
current_metric_name, self.trainer.best_metric_value
)
)
filename = os.path.join(
self.trainer.cfg.save_path, "model", "model_last.pth"
)
self.trainer.logger.info("Saving checkpoint to: " + filename)
torch.save(
{
"epoch": self.trainer.epoch + 1,
"state_dict": self.trainer.model.state_dict(),
"optimizer": self.trainer.optimizer.state_dict(),
"scheduler": self.trainer.scheduler.state_dict(),
"scaler": (
self.trainer.scaler.state_dict()
if self.trainer.cfg.enable_amp
else None
),
"best_metric_value": self.trainer.best_metric_value,
},
filename + ".tmp",
)
os.replace(filename + ".tmp", filename)
if is_best:
shutil.copyfile(
filename,
os.path.join(self.trainer.cfg.save_path, "model", "model_best.pth"),
)
if self.save_freq and (self.trainer.epoch + 1) % self.save_freq == 0:
shutil.copyfile(
filename,
os.path.join(
self.trainer.cfg.save_path,
"model",
f"epoch_{self.trainer.epoch + 1}.pth",
),
)
@HOOKS.register_module()
class CheckpointLoader(HookBase):
def __init__(self, keywords="", replacement=None, strict=False):
self.keywords = keywords
self.replacement = replacement if replacement is not None else keywords
self.strict = strict
def before_train(self):
self.trainer.logger.info("=> Loading checkpoint & weight ...")
if self.trainer.cfg.weight and os.path.isfile(self.trainer.cfg.weight):
self.trainer.logger.info(f"Loading weight at: {self.trainer.cfg.weight}")
checkpoint = torch.load(
self.trainer.cfg.weight,
map_location=lambda storage, loc: storage.cuda(),
)
self.trainer.logger.info(
f"Loading layer weights with keyword: {self.keywords}, "
f"replace keyword with: {self.replacement}"
)
weight = OrderedDict()
for key, value in checkpoint["state_dict"].items():
if not key.startswith("module."):
key = "module." + key # xxx.xxx -> module.xxx.xxx
# Now all keys contain "module." no matter DDP or not.
if self.keywords in key:
key = key.replace(self.keywords, self.replacement)
if comm.get_world_size() == 1:
key = key[7:] # module.xxx.xxx -> xxx.xxx
weight[key] = value
load_state_info = self.trainer.model.load_state_dict(
weight, strict=self.strict
)
self.trainer.logger.info(f"Missing keys: {load_state_info[0]}")
if self.trainer.cfg.resume:
self.trainer.logger.info(
f"Resuming train at eval epoch: {checkpoint['epoch']}"
)
self.trainer.start_epoch = checkpoint["epoch"]
self.trainer.best_metric_value = checkpoint["best_metric_value"]
self.trainer.optimizer.load_state_dict(checkpoint["optimizer"])
self.trainer.scheduler.load_state_dict(checkpoint["scheduler"])
if self.trainer.cfg.enable_amp:
self.trainer.scaler.load_state_dict(checkpoint["scaler"])
else:
self.trainer.logger.info(f"No weight found at: {self.trainer.cfg.weight}")
@HOOKS.register_module()
class PreciseEvaluator(HookBase):
def __init__(self, test_last=False):
self.test_last = test_last
def after_train(self):
self.trainer.logger.info(
">>>>>>>>>>>>>>>> Start Precise Evaluation >>>>>>>>>>>>>>>>"
)
torch.cuda.empty_cache()
cfg = self.trainer.cfg
tester = TESTERS.build(
dict(type=cfg.test.type, cfg=cfg, model=self.trainer.model)
)
if self.test_last:
self.trainer.logger.info("=> Testing on model_last ...")
else:
self.trainer.logger.info("=> Testing on model_best ...")
best_path = os.path.join(
self.trainer.cfg.save_path, "model", "model_best.pth"
)
checkpoint = torch.load(best_path)
state_dict = checkpoint["state_dict"]
tester.model.load_state_dict(state_dict, strict=True)
tester.test()
@HOOKS.register_module()
class DataCacheOperator(HookBase):
def __init__(self, data_root, split):
self.data_root = data_root
self.split = split
self.data_list = self.get_data_list()
def get_data_list(self):
if isinstance(self.split, str):
data_list = glob.glob(os.path.join(self.data_root, self.split, "*.pth"))
elif isinstance(self.split, Sequence):
data_list = []
for split in self.split:
data_list += glob.glob(os.path.join(self.data_root, split, "*.pth"))
else:
raise NotImplementedError
return data_list
def get_cache_name(self, data_path):
data_name = data_path.replace(os.path.dirname(self.data_root), "").split(".")[0]
return "pointcept" + data_name.replace(os.path.sep, "-")
def before_train(self):
self.trainer.logger.info(
f"=> Caching dataset: {self.data_root}, split: {self.split} ..."
)
if is_main_process():
for data_path in self.data_list:
cache_name = self.get_cache_name(data_path)
data = torch.load(data_path)
shared_dict(cache_name, data)
synchronize()
@HOOKS.register_module()
class RuntimeProfiler(HookBase):
def __init__(
self,
forward=True,
backward=True,
interrupt=False,
warm_up=2,
sort_by="cuda_time_total",
row_limit=30,
):
self.forward = forward
self.backward = backward
self.interrupt = interrupt
self.warm_up = warm_up
self.sort_by = sort_by
self.row_limit = row_limit
def before_train(self):
self.trainer.logger.info("Profiling runtime ...")
from torch.profiler import profile, record_function, ProfilerActivity
for i, input_dict in enumerate(self.trainer.train_loader):
if i == self.warm_up + 1:
break
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
if self.forward:
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
record_shapes=True,
profile_memory=True,
with_stack=True,
) as forward_prof:
with record_function("model_inference"):
output_dict = self.trainer.model(input_dict)
else:
output_dict = self.trainer.model(input_dict)
loss = output_dict["loss"]
if self.backward:
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
record_shapes=True,
profile_memory=True,
with_stack=True,
) as backward_prof:
with record_function("model_inference"):
loss.backward()
self.trainer.logger.info(f"Profile: [{i + 1}/{self.warm_up + 1}]")
if self.forward:
self.trainer.logger.info(
"Forward profile: \n"
+ str(
forward_prof.key_averages().table(
sort_by=self.sort_by, row_limit=self.row_limit
)
)
)
forward_prof.export_chrome_trace(
os.path.join(self.trainer.cfg.save_path, "forward_trace.json")
)
if self.backward:
self.trainer.logger.info(
"Backward profile: \n"
+ str(
backward_prof.key_averages().table(
sort_by=self.sort_by, row_limit=self.row_limit
)
)
)
backward_prof.export_chrome_trace(
os.path.join(self.trainer.cfg.save_path, "backward_trace.json")
)
if self.interrupt:
sys.exit(0)
@HOOKS.register_module()
class RuntimeProfilerV2(HookBase):
def __init__(
self,
interrupt=False,
wait=1,
warmup=1,
active=10,
repeat=1,
sort_by="cuda_time_total",
row_limit=30,
):
self.interrupt = interrupt
self.wait = wait
self.warmup = warmup
self.active = active
self.repeat = repeat
self.sort_by = sort_by
self.row_limit = row_limit
def before_train(self):
self.trainer.logger.info("Profiling runtime ...")
from torch.profiler import (
profile,
record_function,
ProfilerActivity,
schedule,
tensorboard_trace_handler,
)
prof = profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
schedule=schedule(
wait=self.wait,
warmup=self.warmup,
active=self.active,
repeat=self.repeat,
),
on_trace_ready=tensorboard_trace_handler(self.trainer.cfg.save_path),
record_shapes=True,
profile_memory=True,
with_stack=True,
)
prof.start()
for i, input_dict in enumerate(self.trainer.train_loader):
if i >= (self.wait + self.warmup + self.active) * self.repeat:
break
for key in input_dict.keys():
if isinstance(input_dict[key], torch.Tensor):
input_dict[key] = input_dict[key].cuda(non_blocking=True)
with record_function("model_forward"):
output_dict = self.trainer.model(input_dict)
loss = output_dict["loss"]
with record_function("model_backward"):
loss.backward()
prof.step()
self.trainer.logger.info(
f"Profile: [{i + 1}/{(self.wait + self.warmup + self.active) * self.repeat}]"
)
self.trainer.logger.info(
"Profile: \n"
+ str(
prof.key_averages().table(
sort_by=self.sort_by, row_limit=self.row_limit
)
)
)
prof.stop()
if self.interrupt:
sys.exit(0)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/hooks/__init__.py | pointcept/engines/hooks/__init__.py | from .default import HookBase
from .misc import *
from .evaluator import *
from .builder import build_hooks
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/pointcept/engines/hooks/builder.py | pointcept/engines/hooks/builder.py | """
Hook Builder
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
Please cite our work if the code is helpful to you.
"""
from pointcept.utils.registry import Registry
HOOKS = Registry("hooks")
def build_hooks(cfg):
hooks = []
for hook_cfg in cfg:
hooks.append(HOOKS.build(hook_cfg))
return hooks
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/assets/init.py | assets/init.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet200/Baseline.py | configs/scannet200/Baseline.py | from pointcept.datasets.preprocessing.scannet.meta_data.scannet200_constants import (
CLASS_LABELS_200,
)
_base_ = ["../_base_/default_runtime.py"]
# ---- common ---/data/qwt/dataset/scannet_npy
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = False
dm_input = "xt" # x0, xt
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001
beta_end = 0.005
noise_schedule = 'linear'
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 200
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.30,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNet200Dataset"
data_root = "data/scannet"
data_val_root = "data/scannet"
data_test_root = "data/scannet"
# data_root = "/root/dataset/scannet_short"
# data_root = "/root/dataset/scannet_debug"
data = dict(
num_classes=num_classes,
ignore_index=-1,
names=CLASS_LABELS_200,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_val_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_test_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[dict(type="RandomFlip", p=1)],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet200/PTv3_CNF.py | configs/scannet200/PTv3_CNF.py | from pointcept.datasets.preprocessing.scannet.meta_data.scannet200_constants import (
CLASS_LABELS_200,
)
_base_ = ["../_base_/default_runtime.py"]
# ---- common ---/data/qwt/dataset/scannet_npy
batch_size = 12 # bs=2 for 1 GPU, bs=6 for 2 GPUs, bs=12 for 4GPUs
num_worker = 24 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt" # x0, xt
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001 # 0.0001
beta_end = 0.005 # 0.02
noise_schedule = "linear"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 200
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNet200Dataset"
data_root = "data/scannet"
# data_root = "/root/dataset/scannet_short"
# data_root = "/root/dataset/scannet_debug"
data = dict(
num_classes=num_classes,
ignore_index=-1,
names=CLASS_LABELS_200,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[dict(type="RandomFlip", p=1)],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet200/PTv3.py | configs/scannet200/PTv3.py | from pointcept.datasets.preprocessing.scannet.meta_data.scannet200_constants import (
CLASS_LABELS_200,
)
_base_ = ["../_base_/default_runtime.py"]
# ---- common ---/data/qwt/dataset/scannet_npy
batch_size = 12 # bs=2 for 1 GPU, bs=6 for 2 GPUs, bs=12 for 4GPUs
num_worker = 24 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = False
dm = False
dm_input = "xt" # x0, xt
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001 # 0.0001
beta_end = 0.005 # 0.02
noise_schedule = "linear"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "EW"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 200
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "add"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.006, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.006, 0.0006],
pct_start=0.05,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0006)]
# dataset settings
dataset_type = "ScanNet200Dataset"
data_root = "data/scannet"
# data_root = "/root/dataset/scannet_short"
# data_root = "/root/dataset/scannet_debug"
data = dict(
num_classes=num_classes,
ignore_index=-1,
names=CLASS_LABELS_200,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[dict(type="RandomFlip", p=1)],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet200/CDSegNet.py | configs/scannet200/CDSegNet.py | from pointcept.datasets.preprocessing.scannet.meta_data.scannet200_constants import (
CLASS_LABELS_200,
)
_base_ = ["../_base_/default_runtime.py"]
# ---- common ---/data/qwt/dataset/scannet_npy
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt" # x0, xt
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001
beta_end = 0.005
noise_schedule = 'linear'
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 200
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.30,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNet200Dataset"
data_root = "data/scannet"
data_val_root = "data/scannet"
data_test_root = "data/scannet"
# data_root = "/root/dataset/scannet_short"
# data_root = "/root/dataset/scannet_debug"
data = dict(
num_classes=num_classes,
ignore_index=-1,
names=CLASS_LABELS_200,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_val_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_test_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[dict(type="RandomFlip", p=1)],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/_base_/default_runtime.py | configs/_base_/default_runtime.py | weight = None # path to model weight
resume = False # whether to resume training process
evaluate = True # evaluate after each epoch training process
test_only = False # test process
seed = None # train process will init a random seed and record
save_path = "exp/default"
num_worker = 16 # total worker in all gpu
batch_size = 16 # total batch size in all gpu
batch_size_val = None # auto adapt to bs 1 for each gpu
batch_size_test = None # auto adapt to bs 1 for each gpu
epoch = 100 # total epoch, data loop = epoch // eval_epoch
eval_epoch = 100 # sche total eval & checkpoint epoch
sync_bn = False
enable_amp = False
empty_cache = False
find_unused_parameters = False
mix_prob = 0
param_dicts = None # example: param_dicts = [dict(keyword="block", lr_scale=0.1)]
# hook
hooks = [
dict(type="CheckpointLoader"),
dict(type="IterationTimer", warmup_iter=2),
dict(type="InformationWriter"),
dict(type="SemSegEvaluator"),
dict(type="CheckpointSaver", save_freq=None),
dict(type="PreciseEvaluator", test_last=False),
]
# Trainer
train = dict(type="DefaultTrainer")
# Tester
test = dict(type="SemSegTester", verbose=True)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/Baseline.py | configs/scannet/Baseline.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = False
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0
beta_end = 1000
noise_schedule = "cosine"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "data/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(type="RandomFlip", p=1)
],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/PTv3_CNF.py | configs/scannet/PTv3_CNF.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 12 # bs=2 for 1 GPU, bs=6 for 2 GPUs, bs=12 for 4GPUs
num_worker = 24 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.0001
beta_end = 0.0005
noise_schedule = "linear"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "data/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(type="RandomFlip", p=1)
],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/CDSegNet_time.py | configs/scannet/CDSegNet_time.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 4
num_worker = 8
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0
beta_end = 1000
noise_schedule = "cosine"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "/root/dataset/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.0001,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(type="RandomFlip", p=1)
# ],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/PTv3_CNF_time.py | configs/scannet/PTv3_CNF_time.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 6
num_worker = 12
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.0001
beta_end = 0.0005
noise_schedule = "linear"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "/root/dataset/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.0001,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# )
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[0.95, 0.95]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[0],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[1],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(
# type="RandomRotateTargetAngle",
# angle=[3 / 2],
# axis="z",
# center=[0, 0, 0],
# p=1,
# ),
# dict(type="RandomScale", scale=[1.05, 1.05]),
# ],
# [
# dict(type="RandomFlip", p=1)
# ],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/PTv3.py | configs/scannet/PTv3.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 12 # bs=2 for 1 GPU, bs=6 for 2 GPUs, bs=12 for 4GPUs
num_worker = 24 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = False
dm = False
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.0001
beta_end = 0.0005
noise_schedule = "linear"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "EW" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "add" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.006, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.006, 0.0006],
pct_start=0.05,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0006)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "data/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(type="RandomFlip", p=1)
],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/scannet/CDSegNet.py | configs/scannet/CDSegNet.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0
beta_end = 1000
noise_schedule = "cosine"
c_in_channels = 6
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 20
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=6,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("ScanNet", "S3DIS", "Structured3D"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type = loss_type,
task_num = task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 800
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.05)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "ScanNetDataset"
data_root = "data/scannet"
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=[
"wall",
"floor",
"cabinet",
"bed",
"chair",
"sofa",
"table",
"door",
"window",
"bookshelf",
"picture",
"counter",
"desk",
"curtain",
"refridgerator",
"shower curtain",
"toilet",
"sink",
"bathtub",
"otherfurniture",
],
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2
),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="x", p=0.5),
dict(type="RandomRotate", angle=[-1 / 64, 1 / 64], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(type="ChromaticAutoContrast", p=0.2, blend_factor=None),
dict(type="ChromaticTranslation", p=0.95, ratio=0.05),
dict(type="ChromaticJitter", p=0.95, std=0.05),
# dict(type="HueSaturationTranslation", hue_max=0.2, saturation_max=0.2),
# dict(type="RandomColorDrop", p=0.2, color_augment=0.0),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="SphereCrop", point_max=102400, mode="random"),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
# dict(type="ShufflePoint"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="train",
return_grid_coord=True,
),
dict(type="CenterShift", apply_z=False),
dict(type="NormalizeColor"),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("color", "normal"),
),
],
test_mode=False,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="CenterShift", apply_z=True),
dict(type="NormalizeColor"),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.02,
hash_type="fnv",
mode="test",
keys=("coord", "color", "normal"),
return_grid_coord=True,
),
crop=None,
post_transform=[
dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("color", "normal"),
),
],
aug_transform=[
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
)
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[0.95, 0.95]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[0],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[1],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(
type="RandomRotateTargetAngle",
angle=[3 / 2],
axis="z",
center=[0, 0, 0],
p=1,
),
dict(type="RandomScale", scale=[1.05, 1.05]),
],
[
dict(type="RandomFlip", p=1)
],
],
),
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/Baseline.py | configs/nuscenes/Baseline.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = False
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001 # 0 # 0.001 0.0001
beta_end = 0.005 # 1000 # 0.005 0.002
noise_schedule = "linear" # "cosine" # "linear"
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes = 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
# optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
# scheduler = dict(
# type="OneCycleLR",
# max_lr=[0.002, 0.0002],
# pct_start=0.04,
# anneal_strategy="cos",
# div_factor=10.0,
# final_div_factor=100.0,
# )
# param_dicts = [dict(keyword="block", lr=0.0002)]
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.10,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "data/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
[dict(type="RandomScale", scale=[0.9, 0.9])],
[dict(type="RandomScale", scale=[0.95, 0.95])],
[dict(type="RandomScale", scale=[1, 1])],
[dict(type="RandomScale", scale=[1.05, 1.05])],
[dict(type="RandomScale", scale=[1.1, 1.1])],
[
dict(type="RandomScale", scale=[0.9, 0.9]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[0.95, 0.95]),
dict(type="RandomFlip", p=1),
],
[dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
[
dict(type="RandomScale", scale=[1.05, 1.05]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[1.1, 1.1]),
dict(type="RandomFlip", p=1),
],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/PTv3_CNF_testing_82.8.py | configs/nuscenes/PTv3_CNF_testing_82.8.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.002
beta_end = 0.003
noise_schedule = 'linear'
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.10,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "/root/dataset/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
[dict(type="RandomScale", scale=[0.9, 0.9])],
[dict(type="RandomScale", scale=[0.95, 0.95])],
[dict(type="RandomScale", scale=[1, 1])],
[dict(type="RandomScale", scale=[1.05, 1.05])],
[dict(type="RandomScale", scale=[1.1, 1.1])],
[
dict(type="RandomScale", scale=[0.9, 0.9]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[0.95, 0.95]),
dict(type="RandomFlip", p=1),
],
[dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
[
dict(type="RandomScale", scale=[1.05, 1.05]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[1.1, 1.1]),
dict(type="RandomFlip", p=1),
],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/PTv3_time.py | configs/nuscenes/PTv3_time.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 6
num_worker = 12
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = False
dm = False
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.002
beta_end = 0.003
noise_schedule = 'linear'
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "EW" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "add" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "/root/dataset/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.0001,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
# [dict(type="RandomScale", scale=[0.9, 0.9])],
# [dict(type="RandomScale", scale=[0.95, 0.95])],
# [dict(type="RandomScale", scale=[1, 1])],
# [dict(type="RandomScale", scale=[1.05, 1.05])],
# [dict(type="RandomScale", scale=[1.1, 1.1])],
# [
# dict(type="RandomScale", scale=[0.9, 0.9]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[0.95, 0.95]),
# dict(type="RandomFlip", p=1),
# ],
# [dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
# [
# dict(type="RandomScale", scale=[1.05, 1.05]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[1.1, 1.1]),
# dict(type="RandomFlip", p=1),
# ],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/PTv3_CNF.py | configs/nuscenes/PTv3_CNF.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.002
beta_end = 0.003
noise_schedule = 'linear'
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "data/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
[dict(type="RandomScale", scale=[0.9, 0.9])],
[dict(type="RandomScale", scale=[0.95, 0.95])],
[dict(type="RandomScale", scale=[1, 1])],
[dict(type="RandomScale", scale=[1.05, 1.05])],
[dict(type="RandomScale", scale=[1.1, 1.1])],
[
dict(type="RandomScale", scale=[0.9, 0.9]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[0.95, 0.95]),
dict(type="RandomFlip", p=1),
],
[dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
[
dict(type="RandomScale", scale=[1.05, 1.05]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[1.1, 1.1]),
dict(type="RandomFlip", p=1),
],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/CDSegNet_time.py | configs/nuscenes/CDSegNet_time.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8
num_worker = 16
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001 # 0 # 0.001 0.0001
beta_end = 0.005 # 1000 # 0.005 0.002
noise_schedule = "linear" # "cosine" # "linear"
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes = 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.10,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "/root/dataset/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.0001,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
# [dict(type="RandomScale", scale=[0.9, 0.9])],
# [dict(type="RandomScale", scale=[0.95, 0.95])],
# [dict(type="RandomScale", scale=[1, 1])],
# [dict(type="RandomScale", scale=[1.05, 1.05])],
# [dict(type="RandomScale", scale=[1.1, 1.1])],
# [
# dict(type="RandomScale", scale=[0.9, 0.9]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[0.95, 0.95]),
# dict(type="RandomFlip", p=1),
# ],
# [dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
# [
# dict(type="RandomScale", scale=[1.05, 1.05]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[1.1, 1.1]),
# dict(type="RandomFlip", p=1),
# ],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/PTv3_CNF_time.py | configs/nuscenes/PTv3_CNF_time.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 16
num_worker = 32
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.002
beta_end = 0.003
noise_schedule = 'linear'
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.50,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "/root/dataset/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.0001,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
# [dict(type="RandomScale", scale=[0.9, 0.9])],
# [dict(type="RandomScale", scale=[0.95, 0.95])],
# [dict(type="RandomScale", scale=[1, 1])],
# [dict(type="RandomScale", scale=[1.05, 1.05])],
# [dict(type="RandomScale", scale=[1.1, 1.1])],
# [
# dict(type="RandomScale", scale=[0.9, 0.9]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[0.95, 0.95]),
# dict(type="RandomFlip", p=1),
# ],
# [dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
# [
# dict(type="RandomScale", scale=[1.05, 1.05]),
# dict(type="RandomFlip", p=1),
# ],
# [
# dict(type="RandomScale", scale=[1.1, 1.1]),
# dict(type="RandomFlip", p=1),
# ],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/PTv3.py | configs/nuscenes/PTv3.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 12 # bs=2 for 1 GPU, bs=6 for 2 GPUs, bs=12 for 4GPUs
num_worker = 24 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = False
dm = False
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.002
beta_end = 0.003
noise_schedule = 'linear'
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "EW" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes= 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "add" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 2),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.04,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "data/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
[dict(type="RandomScale", scale=[0.9, 0.9])],
[dict(type="RandomScale", scale=[0.95, 0.95])],
[dict(type="RandomScale", scale=[1, 1])],
[dict(type="RandomScale", scale=[1.05, 1.05])],
[dict(type="RandomScale", scale=[1.1, 1.1])],
[
dict(type="RandomScale", scale=[0.9, 0.9]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[0.95, 0.95]),
dict(type="RandomFlip", p=1),
],
[dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
[
dict(type="RandomScale", scale=[1.05, 1.05]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[1.1, 1.1]),
dict(type="RandomFlip", p=1),
],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/configs/nuscenes/CDSegNet.py | configs/nuscenes/CDSegNet.py | _base_ = ["../_base_/default_runtime.py"]
# ---- common ---
batch_size = 8 # bs=2 for 1 GPU, bs=4 for 2 GPUs, bs=8 for 4GPUs
num_worker = 16 # the num_worker is double batch_size.
mix_prob = 0.8
empty_cache = False
enable_amp = True
seed = 54421566 # 54421566, 42
gredient_clip = []
ignore_index = -1
# ---- common ---
# ---- Seg Model ----
condition = True
dm = True
dm_input = "xt"
dm_target = "noise"
dm_min_snr = None
T = 1000
T_dim = 128
beta_start = 0.001 # 0 # 0.001 0.0001
beta_end = 0.005 # 1000 # 0.005 0.002
noise_schedule = "linear" # "cosine" # "linear"
c_in_channels = 4
n_in_channels = 4
# ---- Seg Model ----
# ---- loss ----
loss_type = "GLS" # "EW", "GLS"
task_num = 2
# ---- loss ----
# --- backbone ---
enable_rpe = False
enable_flash = True
num_classes = 16
tm_bidirectional = False
tm_feat = 1.0 # "channel_scale", "b_channel_scale", "lr_scale", "b_lr_scale", 1.0
tm_restomer = False
skip_connection_mode = "cat" # "cat", "add", "cat_all"
b_factor = [1.0, 1.0, 1.0, 1.0]
s_factor = [1.0, 1.0, 1.0, 1.0]
skip_connection_scale = True
skip_connection_scale_i = False
# --- backbone ---
# model settings
model = dict(
type="DefaultSegmentorV2",
backbone=dict(
type="PT-v3m1",
c_in_channels=c_in_channels,
n_in_channels=n_in_channels,
order=("z", "z-trans", "hilbert", "hilbert-trans"),
c_stride=(4, 4),
c_enc_depths=(2, 2, 2),
c_enc_channels=(32, 64, 128),
c_enc_num_head=(2, 4, 8),
c_enc_patch_size=(1024, 1024, 1024),
c_dec_depths=(2, 2),
c_dec_channels=(64, 64),
c_dec_num_head=(4, 4),
c_dec_patch_size=(1024, 1024),
n_stride=(2, 2, 2, 2),
n_enc_depths=(2, 2, 2, 6, 6),
n_enc_channels=(32, 64, 128, 256, 512),
n_enc_num_head=(2, 4, 8, 16, 32),
n_enc_patch_size=(1024, 1024, 1024, 1024, 1024),
n_dec_depths=(2, 2, 2, 2),
n_dec_channels=(64, 64, 128, 256),
n_dec_num_head=(4, 4, 8, 16),
n_dec_patch_size=(1024, 1024, 1024, 1024),
mlp_ratio=4,
qkv_bias=True,
qk_scale=None,
attn_drop=0.0,
proj_drop=0.0,
drop_path=0.3,
shuffle_orders=True,
pre_norm=True,
enable_rpe=enable_rpe,
enable_flash=enable_flash,
upcast_attention=False,
upcast_softmax=False,
cls_mode=False,
pdnorm_bn=False,
pdnorm_ln=False,
pdnorm_decouple=True,
pdnorm_adaptive=False,
pdnorm_affine=True,
pdnorm_conditions=("nuScenes", "SemanticKITTI", "Waymo"),
num_classes=num_classes,
T_dim=T_dim,
tm_bidirectional=tm_bidirectional,
tm_feat=tm_feat,
tm_restomer=tm_restomer,
condition=condition,
skip_connection_mode=skip_connection_mode,
b_factor=b_factor,
s_factor=s_factor,
skip_connection_scale=skip_connection_scale,
skip_connection_scale_i=skip_connection_scale_i
),
criteria=[
dict(type="MSELoss", loss_weight=1.0, ignore_index=ignore_index, batch_sample_point=-1),
dict(type="CrossEntropyLoss", loss_weight=1.0, ignore_index=ignore_index),
dict(type="LovaszLoss", mode="multiclass", loss_weight=1.0, ignore_index=ignore_index),
],
loss_type=loss_type,
task_num=task_num,
num_classes=num_classes,
T=T,
beta_start=beta_start,
beta_end=beta_end,
noise_schedule=noise_schedule,
T_dim=T_dim,
dm=dm,
dm_input=dm_input,
dm_target=dm_target,
dm_min_snr=dm_min_snr,
condition=condition,
c_in_channels=c_in_channels
)
# scheduler settings
epoch = 50
eval_epoch = 50
optimizer = dict(type="AdamW", lr=0.002, weight_decay=0.005)
scheduler = dict(
type="OneCycleLR",
max_lr=[0.002, 0.0002],
pct_start=0.10,
anneal_strategy="cos",
div_factor=10.0,
final_div_factor=1000.0,
)
param_dicts = [dict(keyword="block", lr=0.0002)]
# dataset settings
dataset_type = "NuScenesDataset"
data_root = "data/nuscenes"
ignore_index = ignore_index
names = [
"barrier",
"bicycle",
"bus",
"car",
"construction_vehicle",
"motorcycle",
"pedestrian",
"traffic_cone",
"trailer",
"truck",
"driveable_surface",
"other_flat",
"sidewalk",
"terrain",
"manmade",
"vegetation",
]
data = dict(
num_classes=num_classes,
ignore_index=ignore_index,
names=names,
train=dict(
type=dataset_type,
split="train",
data_root=data_root,
transform=[
# dict(type="RandomDropout", dropout_ratio=0.2, dropout_application_ratio=0.2),
# dict(type="RandomRotateTargetAngle", angle=(1/2, 1, 3/2), center=[0, 0, 0], axis="z", p=0.75),
dict(type="RandomRotate", angle=[-1, 1], axis="z", center=[0, 0, 0], p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="x", p=0.5),
# dict(type="RandomRotate", angle=[-1/6, 1/6], axis="y", p=0.5),
dict(type="RandomScale", scale=[0.9, 1.1]),
# dict(type="RandomShift", shift=[0.2, 0.2, 0.2]),
dict(type="RandomFlip", p=0.5),
dict(type="RandomJitter", sigma=0.005, clip=0.02),
# dict(type="ElasticDistortion", distortion_params=[[0.2, 0.4], [0.8, 1.6]]),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode="random"),
# dict(type="CenterShift", apply_z=False),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
val=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
# dict(type="PointClip", point_cloud_range=(-51.2, -51.2, -4, 51.2, 51.2, 2.4)),
dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_grid_coord=True,
),
# dict(type="SphereCrop", point_max=1000000, mode='center'),
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "segment"),
feat_keys=("coord", "strength"),
),
],
test_mode=False,
ignore_index=ignore_index,
),
test=dict(
type=dataset_type,
split="val",
data_root=data_root,
transform=[
dict(type="Copy", keys_dict={"segment": "origin_segment"}),
dict(
type="GridSample",
grid_size=0.025,
hash_type="fnv",
mode="train",
keys=("coord", "strength", "segment"),
return_inverse=True,
),
],
test_mode=True,
test_cfg=dict(
voxelize=dict(
type="GridSample",
grid_size=0.05,
hash_type="fnv",
mode="test",
return_grid_coord=True,
keys=("coord", "strength"),
),
crop=None,
post_transform=[
dict(type="ToTensor"),
dict(
type="Collect",
keys=("coord", "grid_coord", "index"),
feat_keys=("coord", "strength"),
),
],
aug_transform=[
[dict(type="RandomScale", scale=[0.9, 0.9])],
[dict(type="RandomScale", scale=[0.95, 0.95])],
[dict(type="RandomScale", scale=[1, 1])],
[dict(type="RandomScale", scale=[1.05, 1.05])],
[dict(type="RandomScale", scale=[1.1, 1.1])],
[
dict(type="RandomScale", scale=[0.9, 0.9]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[0.95, 0.95]),
dict(type="RandomFlip", p=1),
],
[dict(type="RandomScale", scale=[1, 1]), dict(type="RandomFlip", p=1)],
[
dict(type="RandomScale", scale=[1.05, 1.05]),
dict(type="RandomFlip", p=1),
],
[
dict(type="RandomScale", scale=[1.1, 1.1]),
dict(type="RandomFlip", p=1),
],
],
),
ignore_index=ignore_index,
),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointgroup_ops/setup.py | libs/pointgroup_ops/setup.py | import os
from sys import argv
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from distutils.sysconfig import get_config_vars
(opt,) = get_config_vars("OPT")
os.environ["OPT"] = " ".join(
flag for flag in opt.split() if flag != "-Wstrict-prototypes"
)
def _argparse(pattern, argv, is_flag=True, is_list=False):
if is_flag:
found = pattern in argv
if found:
argv.remove(pattern)
return found, argv
else:
arr = [arg for arg in argv if pattern == arg.split("=")[0]]
if is_list:
if len(arr) == 0: # not found
return False, argv
else:
assert "=" in arr[0], f"{arr[0]} requires a value."
argv.remove(arr[0])
val = arr[0].split("=")[1]
if "," in val:
return val.split(","), argv
else:
return [val], argv
else:
if len(arr) == 0: # not found
return False, argv
else:
assert "=" in arr[0], f"{arr[0]} requires a value."
argv.remove(arr[0])
return arr[0].split("=")[1], argv
INCLUDE_DIRS, argv = _argparse("--include_dirs", argv, False, is_list=True)
include_dirs = []
if not (INCLUDE_DIRS is False):
include_dirs += INCLUDE_DIRS
setup(
name="pointgroup_ops",
packages=["pointgroup_ops"],
package_dir={"pointgroup_ops": "functions"},
ext_modules=[
CUDAExtension(
name="pointgroup_ops_cuda",
sources=["src/bfs_cluster.cpp", "src/bfs_cluster_kernel.cu"],
extra_compile_args={"cxx": ["-g"], "nvcc": ["-O2"]},
)
],
include_dirs=[*include_dirs],
cmdclass={"build_ext": BuildExtension},
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointgroup_ops/functions/__init__.py | libs/pointgroup_ops/functions/__init__.py | from .functions import bfs_cluster, ballquery_batch_p, Clustering
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointgroup_ops/functions/functions.py | libs/pointgroup_ops/functions/functions.py | import torch
from torch.autograd import Function
import pointgroup_ops_cuda
class BallQueryBatchP(Function):
@staticmethod
def forward(ctx, coords, batch_idxs, batch_offsets, radius, meanActive):
"""
:param ctx:
:param coords: (n, 3) float
:param batch_idxs: (n) int
:param batch_offsets: (B+1) int
:param radius: float
:param meanActive: int
:return: idx (nActive), int
:return: start_len (n, 2), int
"""
n = coords.size(0)
assert coords.is_contiguous() and coords.is_cuda
assert batch_idxs.is_contiguous() and batch_idxs.is_cuda
assert batch_offsets.is_contiguous() and batch_offsets.is_cuda
while True:
idx = torch.cuda.IntTensor(n * meanActive).zero_()
start_len = torch.cuda.IntTensor(n, 2).zero_()
nActive = pointgroup_ops_cuda.ballquery_batch_p(
coords, batch_idxs, batch_offsets, idx, start_len, n, meanActive, radius
)
if nActive <= n * meanActive:
break
meanActive = int(nActive // n + 1)
idx = idx[:nActive]
return idx, start_len
@staticmethod
def backward(ctx, a=None, b=None):
return None, None, None
ballquery_batch_p = BallQueryBatchP.apply
class Clustering:
def __init__(
self,
ignored_labels,
class_mapping,
thresh=0.03,
closed_points=300,
min_points=50,
propose_points=100,
score_func=torch.max,
) -> None:
self.ignored_labels = ignored_labels
self.thresh = thresh
self.closed_points = closed_points
self.min_points = min_points
self.class_mapping = class_mapping
self.propose_points = propose_points
self.score_func = score_func
def cluster(self, vertices, scores):
labels = torch.max(scores, 1)[1] # (N) long, cuda
proposals_idx, proposals_offset = self.cluster_(vertices, labels)
## debug
# import ipdb; ipdb.set_trace()
# colors = np.array(create_color_palette())[labels.cpu()]
# write_triangle_mesh(vertices, colors, None, 'semantics.ply')
# scatter
proposals_pred = torch.zeros(
(proposals_offset.shape[0] - 1, vertices.shape[0]), dtype=torch.int
) # (nProposal, N), int, cuda
proposals_pred[proposals_idx[:, 0].long(), proposals_idx[:, 1].long()] = 1
labels = labels[proposals_idx[:, 1][proposals_offset[:-1].long()].long()]
proposals_pointnum = proposals_pred.sum(1)
npoint_mask = proposals_pointnum > self.propose_points
proposals_pred = proposals_pred[npoint_mask]
labels = labels[npoint_mask]
return proposals_pred, labels
def cluster_(self, vertices, labels):
"""
:param batch_idxs: (N), int, cuda
:labels: 0-19
"""
batch_idxs = torch.zeros_like(labels)
mask_non_ignored = torch.ones_like(labels).bool()
for ignored_label in self.ignored_labels:
mask_non_ignored = mask_non_ignored & (
self.class_mapping[labels] != ignored_label
)
object_idxs = mask_non_ignored.nonzero().view(-1)
vertices_ = vertices[object_idxs].float()
labels_ = labels[object_idxs].int()
if vertices_.numel() == 0:
return torch.zeros((0, 2)).int(), torch.zeros(1).int()
batch_idxs_ = batch_idxs[object_idxs].int()
batch_offsets_ = torch.FloatTensor([0, object_idxs.shape[0]]).int().cuda()
idx, start_len = ballquery_batch_p(
vertices_, batch_idxs_, batch_offsets_, self.thresh, self.closed_points
)
proposals_idx, proposals_offset = bfs_cluster(
labels_.cpu(), idx.cpu(), start_len.cpu(), self.min_points
)
proposals_idx[:, 1] = object_idxs[proposals_idx[:, 1].long()].int()
return proposals_idx, proposals_offset
def get_instances(self, vertices, scores):
proposals_pred, labels = self.cluster(vertices, scores)
instances = {}
for proposal_id in range(len(proposals_pred)):
clusters_i = proposals_pred[proposal_id]
score = scores[clusters_i.bool(), labels[proposal_id]]
score = self.score_func(score)
instances[proposal_id] = {}
instances[proposal_id]["conf"] = score.cpu().numpy()
instances[proposal_id]["label_id"] = self.class_mapping.cpu()[
labels[proposal_id]
]
instances[proposal_id]["pred_mask"] = clusters_i.cpu().numpy()
return instances
class BFSCluster(Function):
@staticmethod
def forward(ctx, semantic_label, ball_query_idxs, start_len, threshold):
"""
:param ctx:
:param semantic_label: (N), int
:param ball_query_idxs: (nActive), int
:param start_len: (N, 2), int
:return: cluster_idxs: int (sumNPoint, 2), dim 0 for cluster_id, dim 1 for corresponding point idxs in N
:return: cluster_offsets: int (nCluster + 1)
"""
N = start_len.size(0)
assert semantic_label.is_contiguous()
assert ball_query_idxs.is_contiguous()
assert start_len.is_contiguous()
cluster_idxs = semantic_label.new()
cluster_offsets = semantic_label.new()
pointgroup_ops_cuda.bfs_cluster(
semantic_label,
ball_query_idxs,
start_len,
cluster_idxs,
cluster_offsets,
N,
threshold,
)
return cluster_idxs, cluster_offsets
@staticmethod
def backward(ctx, a=None):
return None
bfs_cluster = BFSCluster.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/setup.py | libs/pointops2/setup.py | import os
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from distutils.sysconfig import get_config_vars
(opt,) = get_config_vars("OPT")
os.environ["OPT"] = " ".join(
flag for flag in opt.split() if flag != "-Wstrict-prototypes"
)
src = "src"
sources = [
os.path.join(root, file)
for root, dirs, files in os.walk(src)
for file in files
if file.endswith(".cpp") or file.endswith(".cu")
]
setup(
name="pointops2",
version="1.0",
install_requires=["torch", "numpy"],
packages=["pointops2"],
package_dir={"pointops2": "functions"},
ext_modules=[
CUDAExtension(
name="pointops2_cuda",
sources=sources,
extra_compile_args={"cxx": ["-g"], "nvcc": ["-O2"]},
)
],
cmdclass={"build_ext": BuildExtension},
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/__init__.py | libs/pointops2/__init__.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/src/__init__.py | libs/pointops2/src/__init__.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_attention_op_step1_v2.py | libs/pointops2/functions/test_attention_op_step1_v2.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 800000
N = 35000
C = 96
h = 6
query = torch.rand(N, h, C // h).cuda()
key = torch.rand(N, h, C // h).cuda()
index_0 = torch.rand(M)
index_0[index_0 < 0] = 0
index_0 = (index_0 * N).long().cuda()
index_1 = torch.rand(M)
index_1[index_1 < 0] = 0
index_1 = (index_1 * N).long().cuda()
query.requires_grad = True
key.requires_grad = True
attn_flat = pointops.attention_step1(
query.float(), key.float(), index_0.int(), index_1.int()
)
loss = attn_flat.sum()
loss.backward()
print(
"attn_flat.shape: {}, attn_flat[:20,:10]: {}".format(
attn_flat.shape, attn_flat[:20, :10]
)
)
print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
input()
# rearrange index for acceleration
index_0, indices = torch.sort(index_0) # [M,]
index_1 = index_1[indices] # [M,]
index_0_counts = index_0.bincount()
print("index_0_counts.shape: ", index_0_counts.shape)
n_max = index_0_counts.max()
index_0_offsets = index_0_counts.cumsum(dim=-1) # [N]
print("v1 index_0_offsets.shape: ", index_0_offsets.shape)
index_0_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_0_offsets], 0
) # [N+1]
# print("index_0[:100]: ", index_0[:100])
print("n_max: ", n_max)
print("index_0_offsets.shape: ", index_0_offsets.shape)
# input()
print("index_0_offsets[:100]: ", index_0_offsets[:100])
print("index_1[:20]: ", index_1[:20])
attn_flat = pointops.attention_step1(
query.float(), key.float(), index_0.int(), index_1.int()
)
# loss = attn_flat.sum()
# loss.backward()
# # attn_flat = pointops.attention_step1(query.float(), key.float(), index_0.int(), index_1.int())
# # loss = attn_flat.sum()
# # loss.backward()
# print("attn_flat.shape: {}, attn_flat[:20,:10]: {}".format(attn_flat.shape, attn_flat[:20,:10]))
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# input()
print("query.is_contiguous(): ", query.is_contiguous())
print("key.is_contiguous(): ", key.is_contiguous())
print("index_0.is_contiguous(): ", index_0.is_contiguous())
print("index_1.is_contiguous(): ", index_1.is_contiguous())
attn_flat_v2 = pointops.attention_step1_v2(
query.float(), key.float(), index_1.int(), index_0_offsets.int(), n_max
)
loss = attn_flat_v2.sum()
loss.backward()
# attn_flat_v2 = pointops.attention_step1_v2(query.float(), key.float(), index_1.int(), index_0_offsets.int(), n_max)
# loss = attn_flat_v2.sum()
# loss.backward()
print(
"attn_flat_v2.shape: {}, attn_flat_v2[:20,:10]: {}".format(
attn_flat_v2.shape, attn_flat_v2[:20, :10]
)
)
print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# input()
# mask = attn_flat_v2.sum(-1) != 0
# print("mask.sum(): ", mask.sum())
# print("attn_flat_v2[mask] - attn_flat[mask]: ", ((attn_flat_v2[mask] - attn_flat[mask])**2).max())
print(
"((attn_flat-attn_flat_v2)**2 < 1e-8).all(): ",
((attn_flat - attn_flat_v2) ** 2 < 1e-8).all(),
)
selected = 10000
print(
"torch.max((attn_flat[:selected]-attn_flat_v2[:selected])**2, 0): ",
torch.max((attn_flat[:selected] - attn_flat_v2[:selected]) ** 2, 0),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_relative_pos_encoding_op_step1_v3.py | libs/pointops2/functions/test_relative_pos_encoding_op_step1_v3.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 80000
N = 3500
# M = 80
# N = 5
hdim = 16
h = 6
L = 31
query = torch.rand(N, h, hdim).cuda()
table_q = torch.rand(L, h, hdim, 3).cuda()
key = torch.rand(N, h, hdim).cuda()
table_k = torch.rand(L, h, hdim, 3).cuda()
index_q = torch.rand(M)
index_q[index_q < 0] = 0
index_q = (index_q * N).long().cuda()
index_k = torch.rand(M)
index_k[index_k < 0] = 0
index_k = (index_k * N).long().cuda()
rel_index = torch.rand(M, 3)
rel_index[rel_index < 0] = 0
rel_index = (rel_index * L).long().cuda()
# rearrange index for acceleration
index_q, indices = torch.sort(index_q) # [M,]
index_k = index_k[indices] # [M,]
rel_index = rel_index[indices]
index_q_counts = index_q.bincount()
print("index_q_counts.shape: ", index_q_counts.shape)
n_max = index_q_counts.max()
index_q_offsets = index_q_counts.cumsum(dim=-1) # [N]
print("v1 index_q_offsets.shape: ", index_q_offsets.shape)
index_q_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_q_offsets], 0
) # [N+1]
# print("index_q[:100]: ", index_q[:100])
print("n_max: ", n_max)
print("index_q_offsets.shape: ", index_q_offsets.shape)
# input()
print("index_q_offsets[:100]: ", index_q_offsets[:100])
print("index_k[:20]: ", index_k[:20])
query.requires_grad = True
table_q.requires_grad = True
key.requires_grad = True
table_k.requires_grad = True
output1 = pointops.dot_prod_with_idx(query, index_q.int(), table_q, rel_index.int())
output2 = pointops.dot_prod_with_idx(key, index_k.int(), table_k, rel_index.int())
output = output1 + output2
loss = output.mean()
loss.backward()
# print("output.shape: {}, output[:5,:10]: {}".format(output.shape, output[:5,:10]))
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("table_q.grad[:5, :3, :5, :2]: ", table_q.grad[:5, :3, :5, :2])
# print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# print("table_k.grad[:5, :3, :5, :2]: ", table_k.grad[:5, :3, :5, :2])
# input()
# print("query.is_contiguous(): ", query.is_contiguous())
# print("key.is_contiguous(): ", key.is_contiguous())
# print("index_q.is_contiguous(): ", index_q.is_contiguous())
# print("index_k.is_contiguous(): ", index_k.is_contiguous())
output_v2 = pointops.dot_prod_with_idx_v3(
query,
index_q_offsets.int(),
n_max,
key,
index_k.int(),
table_q,
table_k,
rel_index.int(),
)
# loss = output_v2.mean()
# loss.backward()
# print("output_v2.shape: {}, output_v2[:5,:10]: {}".format(output_v2.shape, output_v2[:5,:10]))
# print("v2 query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("v2 table_q.grad[:5, :3, :5, :2]: ", table_q.grad[:5, :3, :5, :2])
# print("v2 key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# print("v2 table_k.grad[:5, :3, :5, :2]: ", table_k.grad[:5, :3, :5, :2])
# input()
print("((output-output_v2)**2).max(): ", ((output - output_v2) ** 2).max())
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/pointops2.py | libs/pointops2/functions/pointops2.py | from typing import Tuple
import torch
from torch.autograd import Function
import torch.nn as nn
import pointops2_cuda as pointops_cuda
class FurthestSampling(Function):
@staticmethod
def forward(ctx, xyz, offset, new_offset):
"""
input: xyz: (n, 3), offset: (b), new_offset: (b)
output: idx: (m)
"""
assert xyz.is_contiguous()
n, b, n_max = xyz.shape[0], offset.shape[0], offset[0]
for i in range(1, b):
n_max = max(offset[i] - offset[i - 1], n_max)
idx = torch.cuda.IntTensor(new_offset[b - 1].item()).zero_()
tmp = torch.cuda.FloatTensor(n).fill_(1e10)
pointops_cuda.furthestsampling_cuda(b, n_max, xyz, offset, new_offset, tmp, idx)
del tmp
return idx
furthestsampling = FurthestSampling.apply
class KNNQuery(Function):
@staticmethod
def forward(ctx, nsample, xyz, new_xyz, offset, new_offset):
"""
input: xyz: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample), dist2: (m, nsample)
"""
if new_xyz is None:
new_xyz = xyz
assert xyz.is_contiguous() and new_xyz.is_contiguous()
m = new_xyz.shape[0]
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
pointops_cuda.knnquery_cuda(
m, nsample, xyz, new_xyz, offset, new_offset, idx, dist2
)
return idx, torch.sqrt(dist2)
knnquery = KNNQuery.apply
class Grouping(Function):
@staticmethod
def forward(ctx, input, idx):
"""
input: input: (n, c), idx : (m, nsample)
output: (m, nsample, c)
"""
assert input.is_contiguous() and idx.is_contiguous()
m, nsample, n, c = idx.shape[0], idx.shape[1], input.shape[0], input.shape[1]
output = torch.cuda.FloatTensor(m, nsample, c)
pointops_cuda.grouping_forward_cuda(m, nsample, c, input, idx, output)
ctx.n = n
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (m, c, nsample)
output: (n, c), None
"""
n = ctx.n
(idx,) = ctx.saved_tensors
m, nsample, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.grouping_backward_cuda(
m, nsample, c, grad_output, idx, grad_input
)
return grad_input, None
grouping = Grouping.apply
def queryandgroup(nsample, xyz, new_xyz, feat, idx, offset, new_offset, use_xyz=True):
"""
input: xyz: (n, 3), new_xyz: (m, 3), feat: (n, c), idx: (m, nsample), offset: (b), new_offset: (b)
output: new_feat: (m, c+3, nsample), grouped_idx: (m, nsample)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
if new_xyz is None:
new_xyz = xyz
if idx is None:
idx, _ = knnquery(nsample, xyz, new_xyz, offset, new_offset) # (m, nsample)
n, m, c = xyz.shape[0], new_xyz.shape[0], feat.shape[1]
grouped_xyz = xyz[idx.view(-1).long(), :].view(m, nsample, 3) # (m, nsample, 3)
# grouped_xyz = grouping(xyz, idx) # (m, nsample, 3)
grouped_xyz -= new_xyz.unsqueeze(1) # (m, nsample, 3)
grouped_feat = feat[idx.view(-1).long(), :].view(m, nsample, c) # (m, nsample, c)
# grouped_feat = grouping(feat, idx) # (m, nsample, c)
if use_xyz:
return torch.cat((grouped_xyz, grouped_feat), -1) # (m, nsample, 3+c)
else:
return grouped_feat
class Subtraction(Function):
@staticmethod
def forward(ctx, input1, input2, idx):
"""
input: input1: (n, c), input2: (n, c), idx: (n, nsample)
output: (n, nsample, c)
"""
assert input1.is_contiguous() and input2.is_contiguous()
n, c = input1.shape
nsample = idx.shape[-1]
output = torch.cuda.FloatTensor(n, nsample, c).zero_()
pointops_cuda.subtraction_forward_cuda(
n, nsample, c, input1, input2, idx, output
)
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, nsample, c)
output: grad_input1: (n, c), grad_input2: (n, c)
"""
(idx,) = ctx.saved_tensors
n, nsample, c = grad_output.shape
grad_input1 = torch.cuda.FloatTensor(n, c).zero_()
grad_input2 = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.subtraction_backward_cuda(
n, nsample, c, idx, grad_output, grad_input1, grad_input2
)
return grad_input1, grad_input2, None
subtraction = Subtraction.apply
class Aggregation(Function):
@staticmethod
def forward(ctx, input, position, weight, idx):
"""
input: input: (n, c), position: (n, nsample, c), weight : (n, nsample, c'), idx: (n, nsample)
output: (n, c)
"""
assert (
input.is_contiguous()
and position.is_contiguous()
and weight.is_contiguous()
)
n, nsample, c = position.shape
w_c = weight.shape[-1]
output = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.aggregation_forward_cuda(
n, nsample, c, w_c, input, position, weight, idx, output
)
ctx.save_for_backward(input, position, weight, idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, c)
output: grad_input: (n, c), grad_position: (n, nsample, c), grad_weight : (n, nsample, c')
"""
input, position, weight, idx = ctx.saved_tensors
n, nsample, c = position.shape
w_c = weight.shape[-1]
grad_input = torch.cuda.FloatTensor(n, c).zero_()
grad_position = torch.cuda.FloatTensor(n, nsample, c).zero_()
grad_weight = torch.cuda.FloatTensor(n, nsample, w_c).zero_()
pointops_cuda.aggregation_backward_cuda(
n,
nsample,
c,
w_c,
input,
position,
weight,
idx,
grad_output,
grad_input,
grad_position,
grad_weight,
)
return grad_input, grad_position, grad_weight, None
aggregation = Aggregation.apply
def interpolation(xyz, new_xyz, feat, offset, new_offset, k=3):
"""
input: xyz: (m, 3), new_xyz: (n, 3), feat: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
idx, dist = knnquery(k, xyz, new_xyz, offset, new_offset) # (n, 3), (n, 3)
dist_recip = 1.0 / (dist + 1e-8) # (n, 3)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, 3)
new_feat = torch.cuda.FloatTensor(new_xyz.shape[0], feat.shape[1]).zero_()
for i in range(k):
new_feat += feat[idx[:, i].long(), :] * weight[:, i].unsqueeze(-1)
return new_feat
class Interpolation(Function):
@staticmethod
def forward(ctx, xyz, new_xyz, input, offset, new_offset, k=3):
"""
input: xyz: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and input.is_contiguous()
idx, dist = knnquery(k, xyz, new_xyz, offset, new_offset) # (n, k), (n, k)
dist_recip = 1.0 / (dist + 1e-8) # (n, k)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, k)
n, c, m = new_xyz.shape[0], input.shape[1], input.shape[0]
output = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.interpolation_forward_cuda(n, c, k, input, idx, weight, output)
ctx.m, ctx.k = m, k
ctx.save_for_backward(idx, weight)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: xyz: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
m, k = ctx.m, ctx.k
idx, weight = ctx.saved_tensors
n, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(m, c).zero_()
pointops_cuda.interpolation_backward_cuda(
n, c, k, grad_output, idx, weight, grad_input
)
return None, None, grad_input, None, None, None
interpolation2 = Interpolation.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/pointops_ablation.py | libs/pointops2/functions/pointops_ablation.py | from typing import Tuple
import torch
from torch.autograd import Function
import torch.nn as nn
import pointops2_cuda as pointops_cuda
class FurthestSampling(Function):
@staticmethod
def forward(ctx, xyz, offset, new_offset):
"""
input: xyz: (n, 3), offset: (b), new_offset: (b)
output: idx: (m)
"""
assert xyz.is_contiguous()
n, b, n_max = xyz.shape[0], offset.shape[0], offset[0]
for i in range(1, b):
n_max = max(offset[i] - offset[i - 1], n_max)
idx = torch.cuda.IntTensor(new_offset[b - 1].item()).zero_()
tmp = torch.cuda.FloatTensor(n).fill_(1e10)
pointops_cuda.furthestsampling_cuda(b, n_max, xyz, offset, new_offset, tmp, idx)
del tmp
return idx
furthestsampling = FurthestSampling.apply
class KNNQuery(Function):
@staticmethod
def forward(ctx, nsample, xyz, new_xyz, offset, new_offset):
"""
input: xyz: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample), dist2: (m, nsample)
"""
if new_xyz is None:
new_xyz = xyz
assert xyz.is_contiguous() and new_xyz.is_contiguous()
m = new_xyz.shape[0]
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
pointops_cuda.knnquery_cuda(
m, nsample, xyz, new_xyz, offset, new_offset, idx, dist2
)
return idx, torch.sqrt(dist2)
knnquery = KNNQuery.apply
class Grouping(Function):
@staticmethod
def forward(ctx, input, idx):
"""
input: input: (n, c), idx : (m, nsample)
output: (m, nsample, c)
"""
assert input.is_contiguous() and idx.is_contiguous()
m, nsample, n, c = idx.shape[0], idx.shape[1], input.shape[0], input.shape[1]
output = torch.cuda.FloatTensor(m, nsample, c)
pointops_cuda.grouping_forward_cuda(m, nsample, c, input, idx, output)
ctx.n = n
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (m, c, nsample)
output: (n, c), None
"""
n = ctx.n
(idx,) = ctx.saved_tensors
m, nsample, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.grouping_backward_cuda(
m, nsample, c, grad_output, idx, grad_input
)
return grad_input, None
grouping = Grouping.apply
def queryandgroup(
nsample, xyz, new_xyz, feat, idx, offset, new_offset, use_xyz=True, relative=True
):
"""
input: xyz: (n, 3), new_xyz: (m, 3), feat: (n, c), idx: (m, nsample), offset: (b), new_offset: (b)
output: new_feat: (m, c+3, nsample), grouped_idx: (m, nsample)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
if new_xyz is None:
new_xyz = xyz
if idx is None:
idx, _ = knnquery(nsample, xyz, new_xyz, offset, new_offset) # (m, nsample)
n, m, c = xyz.shape[0], new_xyz.shape[0], feat.shape[1]
grouped_xyz = xyz[idx.view(-1).long(), :].view(m, nsample, 3) # (m, nsample, 3)
# grouped_xyz = grouping(xyz, idx) # (m, nsample, 3)
if relative:
grouped_xyz -= new_xyz.unsqueeze(1) # (m, nsample, 3)
grouped_feat = feat[idx.view(-1).long(), :].view(m, nsample, c) # (m, nsample, c)
# grouped_feat = grouping(feat, idx) # (m, nsample, c)
if use_xyz:
return torch.cat((grouped_xyz, grouped_feat), -1) # (m, nsample, 3+c)
else:
return grouped_feat
class Subtraction(Function):
@staticmethod
def forward(ctx, input1, input2, idx):
"""
input: input1: (n, c), input2: (n, c), idx: (n, nsample)
output: (n, nsample, c)
"""
assert input1.is_contiguous() and input2.is_contiguous()
n, c = input1.shape
nsample = idx.shape[-1]
output = torch.cuda.FloatTensor(n, nsample, c).zero_()
pointops_cuda.subtraction_forward_cuda(
n, nsample, c, input1, input2, idx, output
)
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, nsample, c)
output: grad_input1: (n, c), grad_input2: (n, c)
"""
(idx,) = ctx.saved_tensors
n, nsample, c = grad_output.shape
grad_input1 = torch.cuda.FloatTensor(n, c).zero_()
grad_input2 = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.subtraction_backward_cuda(
n, nsample, c, idx, grad_output, grad_input1, grad_input2
)
return grad_input1, grad_input2, None
subtraction = Subtraction.apply
class Aggregation(Function):
@staticmethod
def forward(ctx, input, position, weight, idx):
"""
input: input: (n, c), position: (n, nsample, c), weight : (n, nsample, c'), idx: (n, nsample)
output: (n, c)
"""
assert (
input.is_contiguous()
and position.is_contiguous()
and weight.is_contiguous()
)
n, nsample, c = position.shape
w_c = weight.shape[-1]
output = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.aggregation_forward_cuda(
n, nsample, c, w_c, input, position, weight, idx, output
)
ctx.save_for_backward(input, position, weight, idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, c)
output: grad_input: (n, c), grad_position: (n, nsample, c), grad_weight : (n, nsample, c')
"""
input, position, weight, idx = ctx.saved_tensors
n, nsample, c = position.shape
w_c = weight.shape[-1]
grad_input = torch.cuda.FloatTensor(n, c).zero_()
grad_position = torch.cuda.FloatTensor(n, nsample, c).zero_()
grad_weight = torch.cuda.FloatTensor(n, nsample, w_c).zero_()
pointops_cuda.aggregation_backward_cuda(
n,
nsample,
c,
w_c,
input,
position,
weight,
idx,
grad_output,
grad_input,
grad_position,
grad_weight,
)
return grad_input, grad_position, grad_weight, None
aggregation = Aggregation.apply
def interpolation(xyz, new_xyz, feat, offset, new_offset, k=3):
"""
input: xyz: (m, 3), new_xyz: (n, 3), feat: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
idx, dist = knnquery(k, xyz, new_xyz, offset, new_offset) # (n, 3), (n, 3)
dist_recip = 1.0 / (dist + 1e-8) # (n, 3)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, 3)
new_feat = torch.cuda.FloatTensor(new_xyz.shape[0], feat.shape[1]).zero_()
for i in range(k):
new_feat += feat[idx[:, i].long(), :] * weight[:, i].unsqueeze(-1)
return new_feat
class Interpolation(Function):
@staticmethod
def forward(ctx, xyz, new_xyz, input, offset, new_offset, k=3):
"""
input: xyz: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and input.is_contiguous()
idx, dist = knnquery(k, xyz, new_xyz, offset, new_offset) # (n, k), (n, k)
dist_recip = 1.0 / (dist + 1e-8) # (n, k)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, k)
n, c, m = new_xyz.shape[0], input.shape[1], input.shape[0]
output = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.interpolation_forward_cuda(n, c, k, input, idx, weight, output)
ctx.m, ctx.k = m, k
ctx.save_for_backward(idx, weight)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: xyz: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
m, k = ctx.m, ctx.k
idx, weight = ctx.saved_tensors
n, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(m, c).zero_()
pointops_cuda.interpolation_backward_cuda(
n, c, k, grad_output, idx, weight, grad_input
)
return None, None, grad_input, None, None, None
interpolation2 = Interpolation.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_attention_op_step2.py | libs/pointops2/functions/test_attention_op_step2.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 800000
N = 35000
C = 96
h = 6
softmax_attn_flat = torch.rand(M, h).cuda()
value = torch.rand(N, h, C // h).cuda()
index_0 = torch.rand(M)
index_0[index_0 < 0] = 0
index_0 = (index_0 * N).long().cuda()
index_1 = torch.rand(M)
index_1[index_1 < 0] = 0
index_1 = (index_1 * N).long().cuda()
softmax_attn_flat.requires_grad = True
value.requires_grad = True
# value_flat = value[index_1] #[M, num_heads, C // num_heads]
# x = (softmax_attn_flat.unsqueeze(-1) * value_flat).reshape(M, C)
# x = scatter_sum(src=x, index=index_0, dim=0, dim_size=N) #[N, C]
# loss = x.sum()
# loss.backward()
# print("x.shape: {}, x[:5,:10]: {}".format(x.shape, x[:5,:10]))
# print("softmax_attn_flat.grad[:5, :10]: ", softmax_attn_flat.grad[:5, :10])
# print("value.grad[:5, :3, :5]: ", value.grad[:5, :3, :5])
# input()
print("softmax_attn_flat.is_contiguous(): ", softmax_attn_flat.is_contiguous())
print("value.is_contiguous(): ", value.is_contiguous())
print("index_0.is_contiguous(): ", index_0.is_contiguous())
print("index_1.is_contiguous(): ", index_1.is_contiguous())
x_v2 = pointops.attention_step2(
softmax_attn_flat.float(), value.float(), index_0.int(), index_1.int()
)
x_v2 = x_v2.view(N, C)
loss = x_v2.sum()
loss.backward()
print("x_v2.shape: {}, x_v2[:5,:10]: {}".format(x_v2.shape, x_v2[:5, :10]))
print("softmax_attn_flat.grad[:5, :10]: ", softmax_attn_flat.grad[:5, :10])
print("value.grad[:5, :3, :5]: ", value.grad[:5, :3, :5])
input()
print("((x-x_v2)**2 < 1e-8).all(): ", ((x - x_v2) ** 2 < 1e-8).all())
print("torch.max((x-x_v2)**2): ", torch.max((x - x_v2) ** 2))
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_relative_pos_encoding_op_step2_v2.py | libs/pointops2/functions/test_relative_pos_encoding_op_step2_v2.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 80000
N = 3500
hdim = 16
h = 6
L = 31
attn = torch.rand(M, h).cuda()
v = torch.rand(N, h, hdim).cuda()
table = torch.rand(L, h, hdim, 3).cuda()
index_0 = torch.rand(M)
index_0[index_0 < 0] = 0
index_0 = (index_0 * N).long().cuda()
index_1 = torch.rand(M)
index_1[index_1 < 0] = 0
index_1 = (index_1 * N).long().cuda()
rel_index = torch.rand(M, 3)
rel_index[rel_index < 0] = 0
rel_index = (rel_index * L).long().cuda()
# rearrange index for acceleration
index_0, indices = torch.sort(index_0) # [M,]
index_1 = index_1[indices] # [M,]
rel_index = rel_index[indices]
index_0_counts = index_0.bincount()
print("index_0_counts.shape: ", index_0_counts.shape)
n_max = index_0_counts.max()
index_0_offsets = index_0_counts.cumsum(dim=-1) # [N]
print("v1 index_0_offsets.shape: ", index_0_offsets.shape)
index_0_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_0_offsets], 0
) # [N+1]
attn.requires_grad = True
v.requires_grad = True
table.requires_grad = True
output = pointops.attention_step2_with_rel_pos_value(
attn, v, index_0.int(), index_1.int(), table, rel_index.int()
)
loss = output.mean()
loss.backward()
print(
"output.shape: {}, output[:5,:10,:5]: {}".format(output.shape, output[:5, :10, :5])
)
print("attn.grad[:5, :3]: ", attn.grad[:5, :3])
print("v.grad[:5, :3, :5]: ", v.grad[:5, :3, :5])
print("table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
# input()
attn_grad = attn.grad.clone()
v_grad = v.grad.clone()
table_grad = table.grad.clone()
attn.grad.zero_()
v.grad.zero_()
table.grad.zero_()
# print("query.is_contiguous(): ", query.is_contiguous())
# print("key.is_contiguous(): ", key.is_contiguous())
# print("index_0.is_contiguous(): ", index_0.is_contiguous())
# print("index_1.is_contiguous(): ", index_1.is_contiguous())
output_v2 = pointops.attention_step2_with_rel_pos_value_v2(
attn, v, index_0_offsets.int(), n_max, index_1.int(), table, rel_index.int()
)
loss = output_v2.mean()
loss.backward()
print(
"output_v2.shape: {}, output_v2[:5,:10,:5]: {}".format(
output_v2.shape, output_v2[:5, :10, :5]
)
)
print("v2 attn.grad[:5, :3]: ", attn.grad[:5, :3])
print("v2 v.grad[:5, :3, :5]: ", v.grad[:5, :3, :5])
print("v2 table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
# input()
print("((output-output_v2)**2).max(): ", ((output - output_v2) ** 2).max())
print("((attn_grad-attn.grad)**2).max(): ", ((attn_grad - attn.grad) ** 2).max())
print("((v_grad-v.grad)**2).max(): ", ((v_grad - v.grad) ** 2).max())
print("((table_grad-table.grad)**2).max(): ", ((table_grad - table.grad) ** 2).max())
# print("torch.max((attn_flat-attn_flat_v2)**2): ", torch.max((attn_flat-attn_flat_v2)**2))
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_attention_op_step1.py | libs/pointops2/functions/test_attention_op_step1.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 800000
N = 35000
C = 96
h = 6
query = torch.rand(N, h, C // h).cuda()
key = torch.rand(N, h, C // h).cuda()
index_0 = torch.rand(M)
index_0[index_0 < 0] = 0
index_0 = (index_0 * N).long().cuda()
index_1 = torch.rand(M)
index_1[index_1 < 0] = 0
index_1 = (index_1 * N).long().cuda()
query.requires_grad = True
key.requires_grad = True
# rearrange index for acceleration
index_0, indices = torch.sort(index_0) # [M,]
index_1 = index_1[indices] # [M,]
index_0_counts = index_0.bincount()
print("index_0_counts.shape: ", index_0_counts.shape)
n_max = index_0_counts.max()
index_0_offsets = index_0_counts.cumsum(dim=-1) # [N]
print("v1 index_0_offsets.shape: ", index_0_offsets.shape)
index_0_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), index_0_offsets], 0
) # [N+1]
# print("index_0[:100]: ", index_0[:100])
print("n_max: ", n_max)
print("index_0_offsets.shape: ", index_0_offsets.shape)
# input()
print("index_0_offsets[:100]: ", index_0_offsets[:100])
print("index_1[300:320]: ", index_1[300:320])
attn_flat = pointops.attention_step1(
query.float(), key.float(), index_0.int(), index_1.int()
)
# loss = attn_flat.sum()
# loss.backward()
print(
"attn_flat.shape: {}, attn_flat[300:320,:10]: {}".format(
attn_flat.shape, attn_flat[300:320, :10]
)
)
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# input()
print("query.is_contiguous(): ", query.is_contiguous())
print("key.is_contiguous(): ", key.is_contiguous())
print("index_0.is_contiguous(): ", index_0.is_contiguous())
print("index_1.is_contiguous(): ", index_1.is_contiguous())
attn_flat_v2 = pointops.attention_step1_v2(
query.float(), key.float(), index_1.int(), index_0_offsets.int(), n_max
)
# loss = attn_flat_v2.sum()
# loss.backward()
print(
"attn_flat_v2.shape: {}, attn_flat_v2[300:320,:10]: {}".format(
attn_flat_v2.shape, attn_flat_v2[300:320, :10]
)
)
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# input()
mask = attn_flat_v2.sum(-1) != 0
print("mask.sum(): ", mask.sum())
print(
"attn_flat_v2[mask] - attn_flat[mask]: ",
((attn_flat_v2[mask] - attn_flat[mask]) ** 2).max(),
)
print(
"((attn_flat-attn_flat_v2)**2 < 1e-8).all(): ",
((attn_flat - attn_flat_v2) ** 2 < 1e-8).all(),
)
selected = 10000
print(
"torch.max((attn_flat[:selected]-attn_flat_v2[:selected])**2, 0): ",
torch.max((attn_flat[:selected] - attn_flat_v2[:selected]) ** 2, 0),
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_relative_pos_encoding_op_step1_v2.py | libs/pointops2/functions/test_relative_pos_encoding_op_step1_v2.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 80000
N = 3500
hdim = 16
h = 6
L = 31
query = torch.rand(N, h, hdim).cuda()
table_q = torch.rand(L, h, hdim, 3).cuda()
key = torch.rand(N, h, hdim).cuda()
table_k = torch.rand(L, h, hdim, 3).cuda()
index_q = torch.rand(M)
index_q[index_q < 0] = 0
index_q = (index_q * N).long().cuda()
index_k = torch.rand(M)
index_k[index_k < 0] = 0
index_k = (index_k * N).long().cuda()
rel_index = torch.rand(M, 3)
rel_index[rel_index < 0] = 0
rel_index = (rel_index * L).long().cuda()
query.requires_grad = True
table_q.requires_grad = True
key.requires_grad = True
table_k.requires_grad = True
output1 = pointops.dot_prod_with_idx(query, index_q.int(), table_q, rel_index.int())
output2 = pointops.dot_prod_with_idx(key, index_k.int(), table_k, rel_index.int())
output = output1 + output2
# loss = output.mean()
# loss.backward()
# print("output.shape: {}, output[:5,:10]: {}".format(output.shape, output[:5,:10]))
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("table_q.grad[:5, :3, :5, :2]: ", table_q.grad[:5, :3, :5, :2])
# print("key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
# print("table_k.grad[:5, :3, :5, :2]: ", table_k.grad[:5, :3, :5, :2])
# input()
# print("query.is_contiguous(): ", query.is_contiguous())
# print("key.is_contiguous(): ", key.is_contiguous())
# print("index_0.is_contiguous(): ", index_0.is_contiguous())
# print("index_1.is_contiguous(): ", index_1.is_contiguous())
output_v2 = pointops.dot_prod_with_idx_v2(
query, index_q.int(), key, index_k.int(), table_q, table_k, rel_index.int()
)
loss = output_v2.mean()
loss.backward()
print(
"output_v2.shape: {}, output_v2[:5,:10]: {}".format(
output_v2.shape, output_v2[:5, :10]
)
)
print("v2 query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
print("v2 table_q.grad[:5, :3, :5, :2]: ", table_q.grad[:5, :3, :5, :2])
print("v2 key.grad[:5, :3, :5]: ", key.grad[:5, :3, :5])
print("v2 table_k.grad[:5, :3, :5, :2]: ", table_k.grad[:5, :3, :5, :2])
# input()
print("((output-output_v2)**2).max(): ", ((output - output_v2) ** 2).max())
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/__init__.py | libs/pointops2/functions/__init__.py | from pointops2 import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_relative_pos_encoding_op_step1.py | libs/pointops2/functions/test_relative_pos_encoding_op_step1.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 80000
N = 3500
hdim = 16
h = 6
L = 31
query = torch.rand(N, h, hdim).cuda()
table = torch.rand(L, h, hdim, 3).cuda()
index = torch.rand(M)
index[index < 0] = 0
index = (index * N).long().cuda()
rel_index = torch.rand(M, 3)
rel_index[rel_index < 0] = 0
rel_index = (rel_index * L).long().cuda()
query.requires_grad = True
table.requires_grad = True
# query_flat = query[index] #[M, h, hdim]
# table_x, table_y, table_z = table[:,:,:,0], table[:,:,:,1], table[:,:,:,2] #[L, h, hdim]
# rel_index_x, rel_index_y, rel_index_z = rel_index[:,0], rel_index[:,1], rel_index[:,2] #[M]
# rel_pos_encoding = table_x[rel_index_x] + table_y[rel_index_y] + table_z[rel_index_z] #[M, h, hdim]
# output = (query_flat * rel_pos_encoding).sum(-1) #[M, h]
# loss = output.mean()
# loss.backward()
# print("output.shape: {}, output[:5,:10]: {}".format(output.shape, output[:5,:10]))
# print("query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
# print("table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
# input()
# print("query.is_contiguous(): ", query.is_contiguous())
# print("key.is_contiguous(): ", key.is_contiguous())
# print("index_0.is_contiguous(): ", index_0.is_contiguous())
# print("index_1.is_contiguous(): ", index_1.is_contiguous())
output_v2 = pointops.dot_prod_with_idx(query, index.int(), table, rel_index.int())
loss = output_v2.mean()
loss.backward()
print(
"output_v2.shape: {}, output_v2[:5,:10]: {}".format(
output_v2.shape, output_v2[:5, :10]
)
)
print("v2: query.grad[:5, :3, :5]: ", query.grad[:5, :3, :5])
print("v2: table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
input()
# print("((output-output_v2)**2).max(): ", ((output-output_v2)**2).max())
# print("torch.max((attn_flat-attn_flat_v2)**2): ", torch.max((attn_flat-attn_flat_v2)**2))
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/test_relative_pos_encoding_op_step2.py | libs/pointops2/functions/test_relative_pos_encoding_op_step2.py | import torch
import pointops
from torch_scatter import (
scatter_max,
scatter_mean,
scatter_add,
scatter_min,
scatter_sum,
)
torch.manual_seed(1)
M = 80000
N = 3500
hdim = 16
h = 6
L = 31
attn = torch.rand(M, h).cuda()
v = torch.rand(N, h, hdim).cuda()
table = torch.rand(L, h, hdim, 3).cuda()
index_0 = torch.rand(M)
index_0[index_0 < 0] = 0
index_0 = (index_0 * N).long().cuda()
index_1 = torch.rand(M)
index_1[index_1 < 0] = 0
index_1 = (index_1 * N).long().cuda()
rel_index = torch.rand(M, 3)
rel_index[rel_index < 0] = 0
rel_index = (rel_index * L).long().cuda()
attn.requires_grad = True
v.requires_grad = True
table.requires_grad = True
v_flat = v[index_1] # [M, h, hdim]
table_x, table_y, table_z = (
table[:, :, :, 0],
table[:, :, :, 1],
table[:, :, :, 2],
) # [L, h, hdim]
rel_index_x, rel_index_y, rel_index_z = (
rel_index[:, 0],
rel_index[:, 1],
rel_index[:, 2],
) # [M]
rel_pos_encoding = (
table_x[rel_index_x] + table_y[rel_index_y] + table_z[rel_index_z]
) # [M, h, hdim]
v_flat_new = v_flat + rel_pos_encoding # [M, h, hdim]
output = attn.unsqueeze(-1) * v_flat_new # [M, h, hdim]
output = scatter_sum(src=output, index=index_0, dim=0, dim_size=N) # [N, h, hdim]
loss = output.mean()
loss.backward()
print(
"output.shape: {}, output[:5,:10,:5]: {}".format(output.shape, output[:5, :10, :5])
)
print("attn.grad[:5, :3]: ", attn.grad[:5, :3])
print("v.grad[:5, :3, :5]: ", v.grad[:5, :3, :5])
print("table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
input()
# print("query.is_contiguous(): ", query.is_contiguous())
# print("key.is_contiguous(): ", key.is_contiguous())
# print("index_0.is_contiguous(): ", index_0.is_contiguous())
# print("index_1.is_contiguous(): ", index_1.is_contiguous())
# output_v2 = pointops.attention_step2_with_rel_pos_value(attn, v, index_0.int(), index_1.int(), table, rel_index.int())
# loss = output_v2.mean()
# loss.backward()
# print("output_v2.shape: {}, output_v2[:5,:10,:5]: {}".format(output_v2.shape, output_v2[:5,:10,:5]))
# print("v2 attn.grad[:5, :3]: ", attn.grad[:5, :3])
# print("v2 v.grad[:5, :3, :5]: ", v.grad[:5, :3, :5])
# print("v2 table.grad[:5, :3, :5, :2]: ", table.grad[:5, :3, :5, :2])
# input()
# print("((output-output_v2)**2).max(): ", ((output-output_v2)**2).max())
# print("torch.max((attn_flat-attn_flat_v2)**2): ", torch.max((attn_flat-attn_flat_v2)**2))
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops2/functions/pointops.py | libs/pointops2/functions/pointops.py | """
The part of attention operations is written by Xin Lai.
Email: xinlai@cse.cuhk.edu.hk
"""
from typing import Tuple
import torch
from torch.autograd import Function
import torch.nn as nn
import pointops2_cuda as pointops_cuda
import time
class FurthestSampling(Function):
@staticmethod
def forward(ctx, xyz, offset, new_offset):
"""
input: xyz: (n, 3), offset: (b), new_offset: (b)
output: idx: (m)
"""
assert xyz.is_contiguous()
n, b, n_max = xyz.shape[0], offset.shape[0], offset[0]
for i in range(1, b):
n_max = max(offset[i] - offset[i - 1], n_max)
idx = torch.cuda.IntTensor(new_offset[b - 1].item()).zero_()
tmp = torch.cuda.FloatTensor(n).fill_(1e10)
pointops_cuda.furthestsampling_cuda(b, n_max, xyz, offset, new_offset, tmp, idx)
del tmp
return idx
furthestsampling = FurthestSampling.apply
class KNNQuery(Function):
@staticmethod
def forward(ctx, nsample, xyz, new_xyz, offset, new_offset):
"""
input: xyz: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample), dist2: (m, nsample)
"""
if new_xyz is None:
new_xyz = xyz
assert xyz.is_contiguous() and new_xyz.is_contiguous()
m = new_xyz.shape[0]
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
pointops_cuda.knnquery_cuda(
m, nsample, xyz, new_xyz, offset, new_offset, idx, dist2
)
return idx, torch.sqrt(dist2)
knnquery = KNNQuery.apply
class Grouping(Function):
@staticmethod
def forward(ctx, input, idx):
"""
input: input: (n, c), idx : (m, nsample)
output: (m, nsample, c)
"""
assert input.is_contiguous() and idx.is_contiguous()
m, nsample, n, c = idx.shape[0], idx.shape[1], input.shape[0], input.shape[1]
output = torch.cuda.FloatTensor(m, nsample, c)
pointops_cuda.grouping_forward_cuda(m, nsample, c, input, idx, output)
ctx.n = n
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (m, c, nsample)
output: (n, c), None
"""
n = ctx.n
(idx,) = ctx.saved_tensors
m, nsample, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.grouping_backward_cuda(
m, nsample, c, grad_output, idx, grad_input
)
return grad_input, None
grouping = Grouping.apply
class AttentionStep1(Function):
@staticmethod
def forward(ctx, q, k, index0, index1):
"""
input: q: (N, h, C//h), k: (N, h, C//h), index0: (M), index1: (M)
output: output: [N, h, C//h]
"""
assert (
q.is_contiguous()
and k.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
)
N_q, h, C_div_h = q.shape
N_k = k.shape[0]
M = index0.shape[0]
C = int(C_div_h * h)
output = torch.cuda.FloatTensor(M, h).zero_()
pointops_cuda.attention_step1_forward_cuda(
N_k, M, h, C, q, k, index0, index1, output
)
ctx.N_q = N_q
ctx.N_k = N_k
ctx.C = C
ctx.save_for_backward(q, k, index0, index1)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (N, h, C//h)
output: (M, h), (N, h, C//h), None, None
"""
N_q = ctx.N_q
N_k = ctx.N_k
C = ctx.C
q, k, index0, index1 = ctx.saved_tensors
M, h = grad_output.shape
grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
q.is_contiguous()
and k.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_q = torch.cuda.FloatTensor(N_q, h, C // h).zero_()
grad_k = torch.cuda.FloatTensor(N_k, h, C // h).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.attention_step1_backward_cuda(
N_q, M, h, C, grad_output, index0, index1, q, k, grad_q, grad_k
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v7: {}".format(end - start))
# # input()
return grad_q, grad_k, None, None
attention_step1 = AttentionStep1.apply
class AttentionStep1_v2(Function):
@staticmethod
def forward(ctx, q, k, index1, index0_offsets, n_max):
"""
input: q: (N, h, C//h), k: (N, h, C//h), index0: (M), index1: (M)
output: output: [N, h, C//h]
"""
assert (
q.is_contiguous()
and k.is_contiguous()
and index0_offsets.is_contiguous()
and index1.is_contiguous()
)
assert n_max <= 1024
N_q, h, C_div_h = q.shape
N_k = k.shape[0]
M = index1.shape[0]
C = int(C_div_h * h)
output = torch.cuda.FloatTensor(M, h).zero_()
pointops_cuda.attention_step1_forward_cuda_v2(
N_k, M, h, C, n_max, q, k, index0_offsets, index1, output
)
ctx.N_q = N_q
ctx.N_k = N_k
ctx.C = C
ctx.n_max = n_max
ctx.save_for_backward(q, k, index0_offsets, index1)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (N, h, C//h)
output: (M, h), (N, h, C//h), None, None
"""
N_q = ctx.N_q
N_k = ctx.N_k
C = ctx.C
n_max = ctx.n_max
q, k, index0_offsets, index1 = ctx.saved_tensors
M, h = grad_output.shape
grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
q.is_contiguous()
and k.is_contiguous()
and index0_offsets.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_q = torch.cuda.FloatTensor(N_q, h, C // h).zero_()
grad_k = torch.cuda.FloatTensor(N_k, h, C // h).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.attention_step1_backward_cuda_v2(
N_q,
M,
h,
C,
n_max,
grad_output,
index0_offsets,
index1,
q,
k,
grad_q,
grad_k,
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v7: {}".format(end - start))
# # input()
return grad_q, grad_k, None, None, None
attention_step1_v2 = AttentionStep1_v2.apply
class AttentionStep2(Function):
@staticmethod
def forward(ctx, attn, v, index0, index1):
"""
input: attn: (M, h), v: (N, h, C//h), index0: (M), index1: (M)
output: output: [N, h, C//h]
"""
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
)
M, h = attn.shape
N_q = index0.max().item() + 1
N_v, h, C_div_h = v.shape
C = int(C_div_h * h)
output = torch.cuda.FloatTensor(N_q, h, C // h).zero_()
pointops_cuda.attention_step2_forward_cuda(
N_q, M, h, C, attn, v, index0, index1, output
)
ctx.M = M
# print("attn[:5,:5]: ", attn[:5, :5])
ctx.save_for_backward(attn, v, index0, index1)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (N, h, C//h)
output: (M, h), (N, h, C//h), None, None
"""
M = ctx.M
attn, v, index0, index1 = ctx.saved_tensors
N_v = v.shape[0]
N_q, h, C_div_h = grad_output.shape
C = h * C_div_h
grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_attn = torch.cuda.FloatTensor(M, h).zero_()
grad_v = torch.cuda.FloatTensor(N_v, h, C // h).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.attention_step2_backward_cuda(
N_q, M, h, C, grad_output, index0, index1, attn, v, grad_attn, grad_v
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v8: {}".format(end - start))
# # input()
return grad_attn, grad_v, None, None
attention_step2 = AttentionStep2.apply
class AttentionStep2_v2(Function):
@staticmethod
def forward(ctx, attn, v, index0, index1):
"""
input: attn: (M, h), v: (N, h, C//h), index0: (M), index1: (M)
output: output: [L, h, C//h]
"""
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
)
L = int(index0.max().item()) + 1
M, h = attn.shape
N, h, C_div_h = v.shape
C = int(C_div_h * h)
output = torch.cuda.FloatTensor(L, h, C // h).zero_()
pointops_cuda.attention_step2_forward_cuda(
N, M, h, C, attn, v, index0, index1, output
)
ctx.M = M
# print("attn[:5,:5]: ", attn[:5, :5])
ctx.save_for_backward(attn, v, index0, index1)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (L, h, C//h)
output: (M, h), (N, h, C//h), None, None
"""
M = ctx.M
attn, v, index0, index1 = ctx.saved_tensors
L, h, C_div_h = grad_output.shape
N = v.shape[0]
C = h * C_div_h
grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_attn = torch.cuda.FloatTensor(M, h).zero_()
grad_v = torch.cuda.FloatTensor(N, h, C // h).zero_()
pointops_cuda.attention_step2_backward_cuda(
N, M, h, C, grad_output, index0, index1, attn, v, grad_attn, grad_v
)
return grad_attn, grad_v, None, None
attention_step2_v2 = AttentionStep2_v2.apply
class DotProdWithIdx(Function):
@staticmethod
def forward(ctx, q, index, table, rel_idx):
"""
input: q: (N, h, hdim), index: (M), table: (L, h, hdim, 3), rel_idx: (M, 3)
output: output: [M, h]
"""
assert (
q.is_contiguous()
and index.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
)
N, h, hdim = q.shape
M = index.shape[0]
output = torch.cuda.FloatTensor(M, h).zero_()
pointops_cuda.dot_prod_with_idx_forward_cuda(
N, M, h, hdim, q, index, table, rel_idx, output
)
ctx.save_for_backward(q, index, table, rel_idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: [M, h]
output: (N, h, hdim), None, (L, h, hdim, 3), None
"""
q, index, table, rel_idx = ctx.saved_tensors
M, h = grad_output.shape
N, _, hdim = q.shape
L = table.shape[0]
grad_output = grad_output.contiguous()
assert (
q.is_contiguous()
and index.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_q = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.dot_prod_with_idx_backward_cuda(
N, M, h, hdim, grad_output, q, index, table, rel_idx, grad_q, grad_table
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v9: {}".format(end - start))
# # input()
return grad_q, None, grad_table, None
dot_prod_with_idx = DotProdWithIdx.apply
class DotProdWithIdx_v2(Function):
@staticmethod
def forward(ctx, q, index_q, k, index_k, table_q, table_k, rel_idx):
"""
input: q: (N, h, hdim), index_q: (M), k: (N, h, hdim), index_k: (M), table_q: (L, h, hdim, 3), table_k: (L, h, hdim, 3), rel_idx: (M, 3)
output: output: [M, h]
"""
assert (
q.is_contiguous()
and index_q.is_contiguous()
and k.is_contiguous()
and index_k.is_contiguous()
and table_q.is_contiguous()
and table_k.is_contiguous()
and rel_idx.is_contiguous()
)
N, h, hdim = q.shape
M = index_q.shape[0]
L = table_q.shape[0]
assert table_k.shape[0] == L and index_k.shape[0] == M
# obtain the mapping from block_idx to m_idx
rel_idx_merge = (
rel_idx[:, 0] + rel_idx[:, 1] * L + rel_idx[:, 2] * (L**2)
) # [M, ]
sorted_values, sort_indices = torch.sort(rel_idx_merge)
_, counts = torch.unique_consecutive(sorted_values, return_counts=True)
rel_idx_offsets = torch.cumsum(counts, dim=-1) # [T,]
rel_idx_offsets = torch.cat(
[torch.zeros(1, dtype=torch.long).cuda(), rel_idx_offsets], 0
) # [T+1,]
n_max = counts.max()
T = counts.shape[0]
# print("M: {}, L: {}, n_max: {}, T: {}".format(M, L, n_max, T))
# print("rel_idx_merge.shape: {}, sorted_values.shape: {}".format(rel_idx_merge.shape, sorted_values.shape))
# print("counts.shape: {}".format(counts.shape))
output = torch.cuda.FloatTensor(M, h).zero_()
# pointops_cuda.dot_prod_with_idx_forward_cuda(N, M, h, hdim, q, index, table, rel_idx, output)
pointops_cuda.dot_prod_with_idx_forward_cuda_v2(
N,
M,
h,
hdim,
n_max,
T,
q,
index_q,
k,
index_k,
table_q,
table_k,
rel_idx,
rel_idx_offsets.int(),
sort_indices.int(),
output,
)
ctx.n_max = n_max
ctx.T = T
ctx.save_for_backward(
q,
index_q,
k,
index_k,
table_q,
table_k,
rel_idx,
rel_idx_offsets,
sort_indices,
)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: [M, h]
output: (N, h, hdim), None, (L, h, hdim, 3), None
"""
(
q,
index_q,
k,
index_k,
table_q,
table_k,
rel_idx,
rel_idx_offsets,
sort_indices,
) = ctx.saved_tensors
M, h = grad_output.shape
N, _, hdim = q.shape
L = table_q.shape[0]
T, n_max = ctx.T, ctx.n_max
grad_output = grad_output.contiguous()
assert (
q.is_contiguous()
and index_q.is_contiguous()
and k.is_contiguous()
and index_k.is_contiguous()
and table_q.is_contiguous()
and table_k.is_contiguous()
and rel_idx.is_contiguous()
and rel_idx_offsets.is_contiguous()
and sort_indices.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_q = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table_q = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
grad_k = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table_k = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.dot_prod_with_idx_backward_cuda_v2(
N,
M,
h,
hdim,
n_max,
T,
grad_output,
q,
index_q,
k,
index_k,
table_q,
table_k,
rel_idx,
rel_idx_offsets.int(),
sort_indices.int(),
grad_q,
grad_k,
grad_table_q,
grad_table_k,
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v9: {}".format(end - start))
# # input()
return grad_q, None, grad_k, None, grad_table_q, grad_table_k, None
dot_prod_with_idx_v2 = DotProdWithIdx_v2.apply
class DotProdWithIdx_v3(Function):
@staticmethod
def forward(ctx, q, index_q_offsets, n_max, k, index_k, table_q, table_k, rel_idx):
"""
input: q: (N, h, hdim), index_q: (M), k: (N, h, hdim), index_k: (M), table_q: (L, h, hdim, 3), table_k: (L, h, hdim, 3), rel_idx: (M, 3)
output: output: [M, h]
"""
assert (
q.is_contiguous()
and index_q_offsets.is_contiguous()
and k.is_contiguous()
and index_k.is_contiguous()
and table_q.is_contiguous()
and table_k.is_contiguous()
and rel_idx.is_contiguous()
)
N, h, hdim = q.shape
M = index_k.shape[0]
L = table_q.shape[0]
assert table_k.shape[0] == L
# # obtain the mapping from block_idx to m_idx
# rel_idx_merge = rel_idx[:, 0] + rel_idx[:, 1] * L + rel_idx[:, 2] * (L ** 2) #[M, ]
# sorted_values, sort_indices = torch.sort(rel_idx_merge)
# _, counts = torch.unique_consecutive(sorted_values, return_counts=True)
# rel_idx_offsets = torch.cumsum(counts, dim=-1) #[T,]
# rel_idx_offsets = torch.cat([torch.zeros(1, dtype=torch.long).cuda(), rel_idx_offsets], 0) #[T+1,]
# n_max = counts.max()
# T = counts.shape[0]
# print("M: {}, L: {}, n_max: {}, T: {}".format(M, L, n_max, T))
# print("rel_idx_merge.shape: {}, sorted_values.shape: {}".format(rel_idx_merge.shape, sorted_values.shape))
# print("counts.shape: {}".format(counts.shape))
# print("M: {}, L: {}, n_max: {}".format(M, L, n_max))
output = torch.cuda.FloatTensor(M, h).zero_()
# pointops_cuda.dot_prod_with_idx_forward_cuda(N, M, h, hdim, q, index, table, rel_idx, output)
pointops_cuda.dot_prod_with_idx_forward_cuda_v3(
N,
M,
h,
hdim,
n_max,
q,
index_q_offsets,
k,
index_k,
table_q,
table_k,
rel_idx,
output,
)
ctx.n_max = n_max
# ctx.T = T
ctx.save_for_backward(q, index_q_offsets, k, index_k, table_q, table_k, rel_idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: [M, h]
output: (N, h, hdim), None, (L, h, hdim, 3), None
"""
q, index_q_offsets, k, index_k, table_q, table_k, rel_idx = ctx.saved_tensors
M, h = grad_output.shape
N, _, hdim = q.shape
L = table_q.shape[0]
n_max = ctx.n_max
grad_output = grad_output.contiguous()
assert (
q.is_contiguous()
and index_q_offsets.is_contiguous()
and k.is_contiguous()
and index_k.is_contiguous()
and table_q.is_contiguous()
and table_k.is_contiguous()
and rel_idx.is_contiguous()
and grad_output.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_q = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table_q = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
grad_k = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table_k = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.dot_prod_with_idx_backward_cuda_v3(
N,
M,
h,
hdim,
n_max,
grad_output,
q,
index_q_offsets,
k,
index_k,
table_q,
table_k,
rel_idx,
grad_q,
grad_k,
grad_table_q,
grad_table_k,
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v9: {}".format(end - start))
# # input()
return grad_q, None, None, grad_k, None, grad_table_q, grad_table_k, None
dot_prod_with_idx_v3 = DotProdWithIdx_v3.apply
class AttentionStep2WithRelPosValue(Function):
@staticmethod
def forward(ctx, attn, v, index0, index1, table, rel_idx):
"""
input: attn: (M, h), v: (N, h, hdim), index0: (M), index1: (M), table: (L, h, hdim, 3), rel_idx: (M, 3)
output: output: [N, h, hdim]
"""
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
)
M, h = attn.shape
N_v, h, hdim = v.shape
N_q = index0.max().item() + 1
output = torch.cuda.FloatTensor(N_q, h, hdim).zero_()
pointops_cuda.attention_step2_with_rel_pos_value_forward_cuda(
N_q, M, h, hdim, attn, v, index0, index1, table, rel_idx, output
)
# print("attn[:5,:5]: ", attn[:5, :5])
ctx.save_for_backward(attn, v, index0, index1, table, rel_idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (N, h, C//h)
output: (M, h), (N, h, C//h), None, None, (L, h, hdim, 3), None
"""
attn, v, index0, index1, table, rel_idx = ctx.saved_tensors
N_q, h, hdim = grad_output.shape
N_v = v.shape[0]
M = attn.shape[0]
L = table.shape[0]
grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0.shape, index1.shape))
grad_attn = torch.cuda.FloatTensor(M, h).zero_()
grad_v = torch.cuda.FloatTensor(N_v, h, hdim).zero_()
grad_table = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
# print("attn.shape: {}, grad_attn.shape: {}".format(attn.shape, grad_attn.shape))
# print("v.shape: {}, grad_v.shape: {}".format(v.shape, grad_v.shape))
# print("table.shape: {}, grad_table.shape: {}".format(table.shape, grad_table.shape))
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.attention_step2_with_rel_pos_value_backward_cuda(
N_q,
M,
h,
hdim,
grad_output,
index0,
index1,
attn,
v,
table,
rel_idx,
grad_attn,
grad_v,
grad_table,
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v10: {}".format(end - start))
# # input()
return grad_attn, grad_v, None, None, grad_table, None
attention_step2_with_rel_pos_value = AttentionStep2WithRelPosValue.apply
class AttentionStep2WithRelPosValue_v2(Function):
@staticmethod
def forward(ctx, attn, v, index0_offsets, n_max, index1, table, rel_idx):
"""
input: attn: (M, h), v: (N, h, hdim), index0_offsets: (M), index1: (M), table: (L, h, hdim, 3), rel_idx: (M, 3)
output: output: [N, h, hdim]
"""
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0_offsets.is_contiguous()
and index1.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
)
M, h = attn.shape
N, h, hdim = v.shape
# N_q = int(index0_offsets.max().item()) + 1
output = torch.cuda.FloatTensor(N, h, hdim).zero_()
pointops_cuda.attention_step2_with_rel_pos_value_forward_cuda_v2(
N,
M,
h,
hdim,
n_max,
attn,
v,
index0_offsets,
index1,
table,
rel_idx,
output,
)
# print("attn[:5,:5]: ", attn[:5, :5])
ctx.n_max = n_max
ctx.save_for_backward(attn, v, index0_offsets, index1, table, rel_idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_output: (N, h, C//h)
output: (M, h), (N, h, C//h), None, None, (L, h, hdim, 3), None
"""
n_max = ctx.n_max
attn, v, index0_offsets, index1, table, rel_idx = ctx.saved_tensors
N, h, hdim = grad_output.shape
N = v.shape[0]
M = attn.shape[0]
L = table.shape[0]
# grad_output = grad_output.contiguous()
# print("grad_output.is_contiguous(): ", grad_output.is_contiguous())
assert (
attn.is_contiguous()
and v.is_contiguous()
and index0_offsets.is_contiguous()
and index1.is_contiguous()
and grad_output.is_contiguous()
and table.is_contiguous()
and rel_idx.is_contiguous()
)
# print("back: attn[:5,:5]: ", attn[:5, :5])
# print("attn.shape: {} v.shape: {}, index0_offsets.shape: {}, index1.shape: {}".format(attn.shape, v.shape, index0_offsets.shape, index1.shape))
grad_attn = torch.cuda.FloatTensor(M, h).zero_()
grad_v = torch.cuda.FloatTensor(N, h, hdim).zero_()
grad_table = torch.cuda.FloatTensor(L, h, hdim, 3).zero_()
# print("attn.shape: {}, grad_attn.shape: {}".format(attn.shape, grad_attn.shape))
# print("v.shape: {}, grad_v.shape: {}".format(v.shape, grad_v.shape))
# print("table.shape: {}, grad_table.shape: {}".format(table.shape, grad_table.shape))
# torch.cuda.synchronize()
# start = time.time()
pointops_cuda.attention_step2_with_rel_pos_value_backward_cuda_v2(
N,
M,
h,
hdim,
n_max,
grad_output,
index0_offsets,
index1,
attn,
v,
table,
rel_idx,
grad_attn,
grad_v,
grad_table,
)
# torch.cuda.synchronize()
# end = time.time()
# print("time v10: {}".format(end - start))
return grad_attn, grad_v, None, None, None, grad_table, None
attention_step2_with_rel_pos_value_v2 = AttentionStep2WithRelPosValue_v2.apply
def queryandgroup(
nsample,
xyz,
new_xyz,
feat,
idx,
offset,
new_offset,
use_xyz=True,
return_indx=False,
):
"""
input: xyz: (n, 3), new_xyz: (m, 3), feat: (n, c), idx: (m, nsample), offset: (b), new_offset: (b)
output: new_feat: (m, c+3, nsample), grouped_idx: (m, nsample)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
if new_xyz is None:
new_xyz = xyz
if idx is None:
idx, _ = knnquery(nsample, xyz, new_xyz, offset, new_offset) # (m, nsample)
n, m, c = xyz.shape[0], new_xyz.shape[0], feat.shape[1]
grouped_xyz = xyz[idx.view(-1).long(), :].view(m, nsample, 3) # (m, nsample, 3)
# grouped_xyz = grouping(xyz, idx) # (m, nsample, 3)
# 相对位置
grouped_xyz -= new_xyz.unsqueeze(1) # (m, nsample, 3)
grouped_feat = feat[idx.view(-1).long(), :].view(m, nsample, c) # (m, nsample, c)
# grouped_feat = grouping(feat, idx) # (m, nsample, c)
if use_xyz:
if return_indx:
return torch.cat((grouped_xyz, grouped_feat), -1), idx # (m, nsample, 3+c)
else:
return torch.cat((grouped_xyz, grouped_feat), -1)
else:
if return_indx:
return grouped_feat, idx
else:
return grouped_feat
def Divide2Patch(nsample, xyz, offset, return_offset=False, anchor_scale=None):
# nsample: 16 xyz: (n, 3) offset: (b)
downsample_scale = anchor_scale or nsample
new_offset, count = [offset[0].item() // downsample_scale], offset[
0
].item() // downsample_scale
for i in range(1, offset.shape[0]):
count += (offset[i].item() - offset[i - 1].item()) // downsample_scale
new_offset.append(count)
# print("donw sample scale:", downsample_scale,"offset:", offset, "newoffset:", new_offset)
new_offset = torch.cuda.IntTensor(new_offset)
idx = furthestsampling(xyz, offset, new_offset) # (m)
new_xyz = xyz[idx.long()]
p_idx, _ = knnquery(nsample, xyz, new_xyz, offset, new_offset) # (m, nsample)
if return_offset:
return p_idx, new_offset
else:
return p_idx
class Subtraction(Function):
@staticmethod
def forward(ctx, input1, input2, idx):
"""
input: input1: (n, c), input2: (n, c), idx: (n, nsample)
output: (n, nsample, c)
"""
assert input1.is_contiguous() and input2.is_contiguous()
n, c = input1.shape
nsample = idx.shape[-1]
output = torch.cuda.FloatTensor(n, nsample, c).zero_()
pointops_cuda.subtraction_forward_cuda(
n, nsample, c, input1, input2, idx, output
)
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, nsample, c)
output: grad_input1: (n, c), grad_input2: (n, c)
"""
(idx,) = ctx.saved_tensors
n, nsample, c = grad_output.shape
grad_input1 = torch.cuda.FloatTensor(n, c).zero_()
grad_input2 = torch.cuda.FloatTensor(n, c).zero_()
pointops_cuda.subtraction_backward_cuda(
n, nsample, c, idx, grad_output, grad_input1, grad_input2
)
return grad_input1, grad_input2, None
subtraction = Subtraction.apply
class Aggregation(Function):
@staticmethod
def forward(ctx, input, position, weight, idx):
"""
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | true |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/setup.py | libs/pointops/setup.py | import os
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from distutils.sysconfig import get_config_vars
(opt,) = get_config_vars("OPT")
os.environ["OPT"] = " ".join(
flag for flag in opt.split() if flag != "-Wstrict-prototypes"
)
src = "src"
sources = [
os.path.join(root, file)
for root, dirs, files in os.walk(src)
for file in files
if file.endswith(".cpp") or file.endswith(".cu")
]
setup(
name="pointops",
version="1.0",
install_requires=["torch", "numpy"],
packages=["pointops"],
package_dir={"pointops": "functions"},
ext_modules=[
CUDAExtension(
name="pointops._C",
sources=sources,
extra_compile_args={"cxx": ["-g"], "nvcc": ["-O2"]},
)
],
cmdclass={"build_ext": BuildExtension},
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/__init__.py | libs/pointops/__init__.py | from .functions import *
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/src/__init__.py | libs/pointops/src/__init__.py | python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false | |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/subtraction.py | libs/pointops/functions/subtraction.py | import torch
from torch.autograd import Function
from pointops._C import subtraction_forward_cuda, subtraction_backward_cuda
class Subtraction(Function):
@staticmethod
def forward(ctx, input1, input2, idx):
"""
input: input1: (n, c), input2: (n, c), idx: (n, nsample)
output: (n, nsample, c)
"""
assert input1.is_contiguous() and input2.is_contiguous()
n, c = input1.shape
nsample = idx.shape[-1]
output = torch.cuda.FloatTensor(n, nsample, c).zero_()
subtraction_forward_cuda(n, nsample, c, input1, input2, idx, output)
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (n, nsample, c)
output: grad_input1: (n, c), grad_input2: (n, c)
"""
(idx,) = ctx.saved_tensors
n, nsample, c = grad_output.shape
grad_input1 = torch.cuda.FloatTensor(n, c).zero_()
grad_input2 = torch.cuda.FloatTensor(n, c).zero_()
subtraction_backward_cuda(
n, nsample, c, idx, grad_output, grad_input1, grad_input2
)
return grad_input1, grad_input2, None
subtraction = Subtraction.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/query.py | libs/pointops/functions/query.py | import torch
from torch.autograd import Function
from pointops._C import knn_query_cuda, random_ball_query_cuda, ball_query_cuda
class KNNQuery(Function):
@staticmethod
def forward(ctx, nsample, xyz, offset, new_xyz=None, new_offset=None):
"""
input: coords: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample) -1 is placeholder, dist2: (m, nsample)
"""
if new_xyz is None or new_offset is None:
new_xyz = xyz
new_offset = offset
assert xyz.is_contiguous() and new_xyz.is_contiguous()
m = new_xyz.shape[0]
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
knn_query_cuda(
m, nsample, xyz, new_xyz, offset.int(), new_offset.int(), idx, dist2
)
return idx, torch.sqrt(dist2)
class RandomBallQuery(Function):
"""Random Ball Query.
Find nearby points in spherical space.
"""
@staticmethod
def forward(
ctx, nsample, max_radius, min_radius, xyz, offset, new_xyz=None, new_offset=None
):
"""
input: coords: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample), dist2: (m, nsample)
"""
if new_xyz is None or new_offset is None:
new_xyz = xyz
new_offset = offset
assert xyz.is_contiguous() and new_xyz.is_contiguous()
assert min_radius < max_radius
m = new_xyz.shape[0]
order = []
for k in range(offset.shape[0]):
s_k, e_k = (0, offset[0]) if k == 0 else (offset[k - 1], offset[k])
order.append(
torch.randperm(e_k - s_k, dtype=torch.int32, device=offset.device) + s_k
)
order = torch.cat(order, dim=0)
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
random_ball_query_cuda(
m,
nsample,
min_radius,
max_radius,
order,
xyz,
new_xyz,
offset.int(),
new_offset.int(),
idx,
dist2,
)
return idx, torch.sqrt(dist2)
class BallQuery(Function):
"""Ball Query.
Find nearby points in spherical space.
"""
@staticmethod
def forward(
ctx, nsample, max_radius, min_radius, xyz, offset, new_xyz=None, new_offset=None
):
"""
input: coords: (n, 3), new_xyz: (m, 3), offset: (b), new_offset: (b)
output: idx: (m, nsample), dist2: (m, nsample)
"""
if new_xyz is None or new_offset is None:
new_xyz = xyz
new_offset = offset
assert xyz.is_contiguous() and new_xyz.is_contiguous()
assert min_radius < max_radius
m = new_xyz.shape[0]
idx = torch.cuda.IntTensor(m, nsample).zero_()
dist2 = torch.cuda.FloatTensor(m, nsample).zero_()
ball_query_cuda(
m,
nsample,
min_radius,
max_radius,
xyz,
new_xyz,
offset.int(),
new_offset.int(),
idx,
dist2,
)
return idx, torch.sqrt(dist2)
knn_query = KNNQuery.apply
ball_query = BallQuery.apply
random_ball_query = RandomBallQuery.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/sampling.py | libs/pointops/functions/sampling.py | import torch
from torch.autograd import Function
from pointops._C import farthest_point_sampling_cuda
class FarthestPointSampling(Function):
@staticmethod
def forward(ctx, xyz, offset, new_offset):
"""
input: coords: (n, 3), offset: (b), new_offset: (b)
output: idx: (m)
"""
assert xyz.is_contiguous()
n, b, n_max = xyz.shape[0], offset.shape[0], offset[0]
for i in range(1, b):
n_max = max(offset[i] - offset[i - 1], n_max)
idx = torch.cuda.IntTensor(new_offset[b - 1].item()).zero_()
tmp = torch.cuda.FloatTensor(n).fill_(1e10)
farthest_point_sampling_cuda(
b, n_max, xyz, offset.int(), new_offset.int(), tmp, idx
)
del tmp
return idx
farthest_point_sampling = FarthestPointSampling.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/grouping.py | libs/pointops/functions/grouping.py | import torch
from torch.autograd import Function
from pointops._C import grouping_forward_cuda, grouping_backward_cuda
class Grouping(Function):
@staticmethod
def forward(ctx, input, idx):
"""
input: input: (n, c), idx : (m, nsample)
output: (m, nsample, c)
"""
assert input.is_contiguous() and idx.is_contiguous()
m, nsample, n, c = idx.shape[0], idx.shape[1], input.shape[0], input.shape[1]
output = torch.cuda.FloatTensor(m, nsample, c)
grouping_forward_cuda(m, nsample, c, input, idx, output)
ctx.n = n
ctx.save_for_backward(idx)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: grad_out: (m, c, nsample)
output: (n, c), None
"""
n = ctx.n
(idx,) = ctx.saved_tensors
m, nsample, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(n, c).zero_()
grouping_backward_cuda(m, nsample, c, grad_output, idx, grad_input)
return grad_input, None
def grouping(idx, feat, xyz, new_xyz=None, with_xyz=False):
if new_xyz is None:
new_xyz = xyz
assert xyz.is_contiguous() and feat.is_contiguous()
m, nsample, c = idx.shape[0], idx.shape[1], feat.shape[1]
xyz = torch.cat([xyz, torch.zeros([1, 3]).to(xyz.device)], dim=0)
feat = torch.cat([feat, torch.zeros([1, c]).to(feat.device)], dim=0)
grouped_feat = feat[idx.view(-1).long(), :].view(
m, nsample, c
) # (m, num_sample, c)
if with_xyz:
assert new_xyz.is_contiguous()
mask = torch.sign(idx + 1)
grouped_xyz = xyz[idx.view(-1).long(), :].view(
m, nsample, 3
) - new_xyz.unsqueeze(
1
) # (m, num_sample, 3)
grouped_xyz = torch.einsum(
"n s c, n s -> n s c", grouped_xyz, mask
) # (m, num_sample, 3)
return torch.cat((grouped_xyz, grouped_feat), -1)
else:
return grouped_feat
grouping2 = Grouping.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/interpolation.py | libs/pointops/functions/interpolation.py | import torch
from torch.autograd import Function
from pointops._C import interpolation_forward_cuda, interpolation_backward_cuda
from .query import knn_query
def interpolation(xyz, new_xyz, feat, offset, new_offset, k=3):
"""
input: coords: (m, 3), new_xyz: (n, 3), color: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
idx, dist = knn_query(k, xyz, offset, new_xyz, new_offset) # (n, 3), (n, 3)
dist_recip = 1.0 / (dist + 1e-8) # (n, 3)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, 3)
new_feat = torch.cuda.FloatTensor(new_xyz.shape[0], feat.shape[1]).zero_()
for i in range(k):
new_feat += feat[idx[:, i].long(), :] * weight[:, i].unsqueeze(-1)
return new_feat
class Interpolation(Function):
@staticmethod
def forward(ctx, xyz, new_xyz, input, offset, new_offset, k=3):
"""
input: coords: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and input.is_contiguous()
idx, dist = knn_query(k, xyz, offset, new_xyz, new_offset) # (n, k), (n, k)
dist_recip = 1.0 / (dist + 1e-8) # (n, k)
norm = torch.sum(dist_recip, dim=1, keepdim=True)
weight = dist_recip / norm # (n, k)
n, c, m = new_xyz.shape[0], input.shape[1], input.shape[0]
output = torch.cuda.FloatTensor(n, c).zero_()
interpolation_forward_cuda(n, c, k, input, idx, weight, output)
ctx.m, ctx.k = m, k
ctx.save_for_backward(idx, weight)
return output
@staticmethod
def backward(ctx, grad_output):
"""
input: coords: (m, 3), new_xyz: (n, 3), input: (m, c), offset: (b), new_offset: (b)
output: (n, c)
"""
m, k = ctx.m, ctx.k
idx, weight = ctx.saved_tensors
n, c = grad_output.shape
grad_input = torch.cuda.FloatTensor(m, c).zero_()
interpolation_backward_cuda(n, c, k, grad_output, idx, weight, grad_input)
return None, None, grad_input, None, None, None
interpolation2 = Interpolation.apply
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/utils.py | libs/pointops/functions/utils.py | import torch
from pointops import knn_query, ball_query, grouping
def knn_query_and_group(
feat,
xyz,
offset=None,
new_xyz=None,
new_offset=None,
idx=None,
nsample=None,
with_xyz=False,
):
if idx is None:
assert nsample is not None
idx, _ = knn_query(nsample, xyz, offset, new_xyz, new_offset)
return grouping(idx, feat, xyz, new_xyz, with_xyz), idx
def ball_query_and_group(
feat,
xyz,
offset=None,
new_xyz=None,
new_offset=None,
idx=None,
max_radio=None,
min_radio=0,
nsample=None,
with_xyz=False,
):
if idx is None:
assert nsample is not None and offset is not None
assert max_radio is not None and min_radio is not None
idx, _ = ball_query(
nsample, max_radio, min_radio, xyz, offset, new_xyz, new_offset
)
return grouping(idx, feat, xyz, new_xyz, with_xyz), idx
def query_and_group(
nsample,
xyz,
new_xyz,
feat,
idx,
offset,
new_offset,
dilation=0,
with_feat=True,
with_xyz=True,
):
"""
input: coords: (n, 3), new_xyz: (m, 3), color: (n, c), idx: (m, nsample), offset: (b), new_offset: (b)
output: new_feat: (m, nsample, c+3), grouped_idx: (m, nsample)
"""
assert xyz.is_contiguous() and new_xyz.is_contiguous() and feat.is_contiguous()
if new_xyz is None:
new_xyz = xyz
if idx is None:
num_samples_total = 1 + (nsample - 1) * (dilation + 1)
# num points in a batch might < num_samples_total => [n1, n2, ..., nk, ns, ns, ns, ...]
idx_no_dilation, _ = knn_query(
num_samples_total, xyz, offset, new_xyz, new_offset
) # (m, nsample * (d + 1))
idx = []
batch_end = offset.tolist()
batch_start = [0] + batch_end[:-1]
new_batch_end = new_offset.tolist()
new_batch_start = [0] + new_batch_end[:-1]
for i in range(offset.shape[0]):
if batch_end[i] - batch_start[i] < num_samples_total:
soft_dilation = (batch_end[i] - batch_start[i] - 1) / (nsample - 1) - 1
else:
soft_dilation = dilation
idx.append(
idx_no_dilation[
new_batch_start[i] : new_batch_end[i],
[int((soft_dilation + 1) * i) for i in range(nsample)],
]
)
idx = torch.cat(idx, dim=0)
if not with_feat:
return idx
n, m, c = xyz.shape[0], new_xyz.shape[0], feat.shape[1]
grouped_xyz = xyz[idx.view(-1).long(), :].view(m, nsample, 3) # (m, nsample, 3)
# grouped_xyz = grouping(coords, idx) # (m, nsample, 3)
grouped_xyz -= new_xyz.unsqueeze(1) # (m, nsample, 3)
grouped_feat = feat[idx.view(-1).long(), :].view(m, nsample, c) # (m, nsample, c)
# grouped_feat = grouping(color, idx) # (m, nsample, c)
if with_xyz:
return torch.cat((grouped_xyz, grouped_feat), -1), idx # (m, nsample, 3+c)
else:
return grouped_feat, idx
def offset2batch(offset):
return (
torch.cat(
[
(
torch.tensor([i] * (o - offset[i - 1]))
if i > 0
else torch.tensor([i] * o)
)
for i, o in enumerate(offset)
],
dim=0,
)
.long()
.to(offset.device)
)
def batch2offset(batch):
return torch.cumsum(batch.bincount(), dim=0).int()
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
QWTforGithub/CDSegNet | https://github.com/QWTforGithub/CDSegNet/blob/87b603dbd011c0f57fb498d70680e32d4f8cf2f0/libs/pointops/functions/__init__.py | libs/pointops/functions/__init__.py | from .query import knn_query, ball_query, random_ball_query
from .sampling import farthest_point_sampling
from .grouping import grouping, grouping2
from .interpolation import interpolation, interpolation2
from .subtraction import subtraction
from .aggregation import aggregation
from .attention import attention_relation_step, attention_fusion_step
from .utils import (
query_and_group,
knn_query_and_group,
ball_query_and_group,
batch2offset,
offset2batch,
)
| python | MIT | 87b603dbd011c0f57fb498d70680e32d4f8cf2f0 | 2026-01-05T07:13:40.759144Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.