repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/vfe_template.py
import torch.nn as nn class VFETemplate(nn.Module): def __init__(self, model_cfg, **kwargs): super().__init__() self.model_cfg = model_cfg def get_output_feature_dim(self): raise NotImplementedError def forward(self, **kwargs): """ Args: **kwargs: Returns: batch_dict: ... vfe_features: (num_voxels, C) """ raise NotImplementedError
470
19.478261
45
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/dynamic_mean_vfe.py
import torch from .vfe_template import VFETemplate try: import torch_scatter except Exception as e: # Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter pass from .vfe_template import VFETemplate class DynamicMeanVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs): super().__init__(model_cfg=model_cfg) self.num_point_features = num_point_features self.grid_size = torch.tensor(grid_size).cuda() self.voxel_size = torch.tensor(voxel_size).cuda() self.point_cloud_range = torch.tensor(point_cloud_range).cuda() self.voxel_x = voxel_size[0] self.voxel_y = voxel_size[1] self.voxel_z = voxel_size[2] self.x_offset = self.voxel_x / 2 + point_cloud_range[0] self.y_offset = self.voxel_y / 2 + point_cloud_range[1] self.z_offset = self.voxel_z / 2 + point_cloud_range[2] self.scale_xyz = grid_size[0] * grid_size[1] * grid_size[2] self.scale_yz = grid_size[1] * grid_size[2] self.scale_z = grid_size[2] def get_output_feature_dim(self): return self.num_point_features @torch.no_grad() def forward(self, batch_dict, **kwargs): """ Args: batch_dict: voxels: (num_voxels, max_points_per_voxel, C) voxel_num_points: optional (num_voxels) **kwargs: Returns: vfe_features: (num_voxels, C) """ batch_size = batch_dict['batch_size'] points = batch_dict['points'] # (batch_idx, x, y, z, i, e) # # debug point_coords = torch.floor((points[:, 1:4] - self.point_cloud_range[0:3]) / self.voxel_size).int() mask = ((point_coords >= 0) & (point_coords < self.grid_size)).all(dim=1) points = points[mask] point_coords = point_coords[mask] merge_coords = points[:, 0].int() * self.scale_xyz + \ point_coords[:, 0] * self.scale_yz + \ point_coords[:, 1] * self.scale_z + \ point_coords[:, 2] points_data = points[:, 1:].contiguous() unq_coords, unq_inv, unq_cnt = torch.unique(merge_coords, return_inverse=True, return_counts=True) points_mean = torch_scatter.scatter_mean(points_data, unq_inv, dim=0) unq_coords = unq_coords.int() voxel_coords = torch.stack((unq_coords // self.scale_xyz, (unq_coords % self.scale_xyz) // self.scale_yz, (unq_coords % self.scale_yz) // self.scale_z, unq_coords % self.scale_z), dim=1) voxel_coords = voxel_coords[:, [0, 3, 2, 1]] batch_dict['voxel_features'] = points_mean.contiguous() batch_dict['voxel_coords'] = voxel_coords.contiguous() return batch_dict
2,980
37.714286
106
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/mean_vfe.py
import torch from .vfe_template import VFETemplate class MeanVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, **kwargs): super().__init__(model_cfg=model_cfg) self.num_point_features = num_point_features def get_output_feature_dim(self): return self.num_point_features def forward(self, batch_dict, **kwargs): """ Args: batch_dict: voxels: (num_voxels, max_points_per_voxel, C) voxel_num_points: optional (num_voxels) **kwargs: Returns: vfe_features: (num_voxels, C) """ voxel_features, voxel_num_points = batch_dict['voxels'], batch_dict['voxel_num_points'] points_mean = voxel_features[:, :, :].sum(dim=1, keepdim=False) normalizer = torch.clamp_min(voxel_num_points.view(-1, 1), min=1.0).type_as(voxel_features) points_mean = points_mean / normalizer batch_dict['voxel_features'] = points_mean.contiguous() return batch_dict
1,038
31.46875
99
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/dynamic_pillar_vfe.py
import torch import torch.nn as nn import torch.nn.functional as F try: import torch_scatter except Exception as e: # Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter pass from .vfe_template import VFETemplate class PFNLayerV2(nn.Module): def __init__(self, in_channels, out_channels, use_norm=True, last_layer=False): super().__init__() self.last_vfe = last_layer self.use_norm = use_norm if not self.last_vfe: out_channels = out_channels // 2 if self.use_norm: self.linear = nn.Linear(in_channels, out_channels, bias=False) self.norm = nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01) else: self.linear = nn.Linear(in_channels, out_channels, bias=True) self.relu = nn.ReLU() def forward(self, inputs, unq_inv): x = self.linear(inputs) x = self.norm(x) if self.use_norm else x x = self.relu(x) x_max = torch_scatter.scatter_max(x, unq_inv, dim=0)[0] if self.last_vfe: return x_max else: x_concatenated = torch.cat([x, x_max[unq_inv, :]], dim=1) return x_concatenated class DynamicPillarVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs): super().__init__(model_cfg=model_cfg) self.use_norm = self.model_cfg.USE_NORM self.with_distance = self.model_cfg.WITH_DISTANCE self.use_absolute_xyz = self.model_cfg.USE_ABSLOTE_XYZ num_point_features += 6 if self.use_absolute_xyz else 3 if self.with_distance: num_point_features += 1 self.num_filters = self.model_cfg.NUM_FILTERS assert len(self.num_filters) > 0 num_filters = [num_point_features] + list(self.num_filters) pfn_layers = [] for i in range(len(num_filters) - 1): in_filters = num_filters[i] out_filters = num_filters[i + 1] pfn_layers.append( PFNLayerV2(in_filters, out_filters, self.use_norm, last_layer=(i >= len(num_filters) - 2)) ) self.pfn_layers = nn.ModuleList(pfn_layers) self.voxel_x = voxel_size[0] self.voxel_y = voxel_size[1] self.voxel_z = voxel_size[2] self.x_offset = self.voxel_x / 2 + point_cloud_range[0] self.y_offset = self.voxel_y / 2 + point_cloud_range[1] self.z_offset = self.voxel_z / 2 + point_cloud_range[2] self.scale_xy = grid_size[0] * grid_size[1] self.scale_y = grid_size[1] self.grid_size = torch.tensor(grid_size).cuda() self.voxel_size = torch.tensor(voxel_size).cuda() self.point_cloud_range = torch.tensor(point_cloud_range).cuda() def get_output_feature_dim(self): return self.num_filters[-1] def forward(self, batch_dict, **kwargs): points = batch_dict['points'] # (batch_idx, x, y, z, i, e) points_coords = torch.floor((points[:, [1,2]] - self.point_cloud_range[[0,1]]) / self.voxel_size[[0,1]]).int() mask = ((points_coords >= 0) & (points_coords < self.grid_size[[0,1]])).all(dim=1) points = points[mask] points_coords = points_coords[mask] points_xyz = points[:, [1, 2, 3]].contiguous() merge_coords = points[:, 0].int() * self.scale_xy + \ points_coords[:, 0] * self.scale_y + \ points_coords[:, 1] unq_coords, unq_inv, unq_cnt = torch.unique(merge_coords, return_inverse=True, return_counts=True, dim=0) points_mean = torch_scatter.scatter_mean(points_xyz, unq_inv, dim=0) f_cluster = points_xyz - points_mean[unq_inv, :] f_center = torch.zeros_like(points_xyz) f_center[:, 0] = points_xyz[:, 0] - (points_coords[:, 0].to(points_xyz.dtype) * self.voxel_x + self.x_offset) f_center[:, 1] = points_xyz[:, 1] - (points_coords[:, 1].to(points_xyz.dtype) * self.voxel_y + self.y_offset) f_center[:, 2] = points_xyz[:, 2] - self.z_offset if self.use_absolute_xyz: features = [points[:, 1:], f_cluster, f_center] else: features = [points[:, 4:], f_cluster, f_center] if self.with_distance: points_dist = torch.norm(points[:, 1:4], 2, dim=1, keepdim=True) features.append(points_dist) features = torch.cat(features, dim=-1) for pfn in self.pfn_layers: features = pfn(features, unq_inv) # features = self.linear1(features) # features_max = torch_scatter.scatter_max(features, unq_inv, dim=0)[0] # features = torch.cat([features, features_max[unq_inv, :]], dim=1) # features = self.linear2(features) # features = torch_scatter.scatter_max(features, unq_inv, dim=0)[0] # generate voxel coordinates unq_coords = unq_coords.int() voxel_coords = torch.stack((unq_coords // self.scale_xy, (unq_coords % self.scale_xy) // self.scale_y, unq_coords % self.scale_y, torch.zeros(unq_coords.shape[0]).to(unq_coords.device).int() ), dim=1) voxel_coords = voxel_coords[:, [0, 3, 2, 1]] batch_dict['pillar_features'] = features batch_dict['voxel_coords'] = voxel_coords return batch_dict
5,614
38.265734
118
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/pillar_vfe.py
import torch import torch.nn as nn import torch.nn.functional as F from .vfe_template import VFETemplate class PFNLayer(nn.Module): def __init__(self, in_channels, out_channels, use_norm=True, last_layer=False): super().__init__() self.last_vfe = last_layer self.use_norm = use_norm if not self.last_vfe: out_channels = out_channels // 2 if self.use_norm: self.linear = nn.Linear(in_channels, out_channels, bias=False) self.norm = nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01) else: self.linear = nn.Linear(in_channels, out_channels, bias=True) self.part = 50000 def forward(self, inputs): if inputs.shape[0] > self.part: # nn.Linear performs randomly when batch size is too large num_parts = inputs.shape[0] // self.part part_linear_out = [self.linear(inputs[num_part*self.part:(num_part+1)*self.part]) for num_part in range(num_parts+1)] x = torch.cat(part_linear_out, dim=0) else: x = self.linear(inputs) torch.backends.cudnn.enabled = False x = self.norm(x.permute(0, 2, 1)).permute(0, 2, 1) if self.use_norm else x torch.backends.cudnn.enabled = True x = F.relu(x) x_max = torch.max(x, dim=1, keepdim=True)[0] if self.last_vfe: return x_max else: x_repeat = x_max.repeat(1, inputs.shape[1], 1) x_concatenated = torch.cat([x, x_repeat], dim=2) return x_concatenated class PillarVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, point_cloud_range, **kwargs): super().__init__(model_cfg=model_cfg) self.use_norm = self.model_cfg.USE_NORM self.with_distance = self.model_cfg.WITH_DISTANCE self.use_absolute_xyz = self.model_cfg.USE_ABSLOTE_XYZ num_point_features += 6 if self.use_absolute_xyz else 3 if self.with_distance: num_point_features += 1 self.num_filters = self.model_cfg.NUM_FILTERS assert len(self.num_filters) > 0 num_filters = [num_point_features] + list(self.num_filters) pfn_layers = [] for i in range(len(num_filters) - 1): in_filters = num_filters[i] out_filters = num_filters[i + 1] pfn_layers.append( PFNLayer(in_filters, out_filters, self.use_norm, last_layer=(i >= len(num_filters) - 2)) ) self.pfn_layers = nn.ModuleList(pfn_layers) self.voxel_x = voxel_size[0] self.voxel_y = voxel_size[1] self.voxel_z = voxel_size[2] self.x_offset = self.voxel_x / 2 + point_cloud_range[0] self.y_offset = self.voxel_y / 2 + point_cloud_range[1] self.z_offset = self.voxel_z / 2 + point_cloud_range[2] def get_output_feature_dim(self): return self.num_filters[-1] def get_paddings_indicator(self, actual_num, max_num, axis=0): actual_num = torch.unsqueeze(actual_num, axis + 1) max_num_shape = [1] * len(actual_num.shape) max_num_shape[axis + 1] = -1 max_num = torch.arange(max_num, dtype=torch.int, device=actual_num.device).view(max_num_shape) paddings_indicator = actual_num.int() > max_num return paddings_indicator def forward(self, batch_dict, **kwargs): voxel_features, voxel_num_points, coords = batch_dict['voxels'], batch_dict['voxel_num_points'], batch_dict['voxel_coords'] points_mean = voxel_features[:, :, :3].sum(dim=1, keepdim=True) / voxel_num_points.type_as(voxel_features).view(-1, 1, 1) f_cluster = voxel_features[:, :, :3] - points_mean f_center = torch.zeros_like(voxel_features[:, :, :3]) f_center[:, :, 0] = voxel_features[:, :, 0] - (coords[:, 3].to(voxel_features.dtype).unsqueeze(1) * self.voxel_x + self.x_offset) f_center[:, :, 1] = voxel_features[:, :, 1] - (coords[:, 2].to(voxel_features.dtype).unsqueeze(1) * self.voxel_y + self.y_offset) f_center[:, :, 2] = voxel_features[:, :, 2] - (coords[:, 1].to(voxel_features.dtype).unsqueeze(1) * self.voxel_z + self.z_offset) if self.use_absolute_xyz: features = [voxel_features, f_cluster, f_center] else: features = [voxel_features[..., 3:], f_cluster, f_center] if self.with_distance: points_dist = torch.norm(voxel_features[:, :, :3], 2, 2, keepdim=True) features.append(points_dist) features = torch.cat(features, dim=-1) voxel_count = features.shape[1] mask = self.get_paddings_indicator(voxel_num_points, voxel_count, axis=0) mask = torch.unsqueeze(mask, -1).type_as(voxel_features) features *= mask for pfn in self.pfn_layers: features = pfn(features) features = features.squeeze() batch_dict['pillar_features'] = features return batch_dict
5,099
40.129032
137
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe.py
import torch from .vfe_template import VFETemplate from .image_vfe_modules import ffn, f2v class ImageVFE(VFETemplate): def __init__(self, model_cfg, grid_size, point_cloud_range, depth_downsample_factor, **kwargs): super().__init__(model_cfg=model_cfg) self.grid_size = grid_size self.pc_range = point_cloud_range self.downsample_factor = depth_downsample_factor self.module_topology = [ 'ffn', 'f2v' ] self.build_modules() def build_modules(self): """ Builds modules """ for module_name in self.module_topology: module = getattr(self, 'build_%s' % module_name)() self.add_module(module_name, module) def build_ffn(self): """ Builds frustum feature network Returns: ffn_module: nn.Module, Frustum feature network """ ffn_module = ffn.__all__[self.model_cfg.FFN.NAME]( model_cfg=self.model_cfg.FFN, downsample_factor=self.downsample_factor ) self.disc_cfg = ffn_module.disc_cfg return ffn_module def build_f2v(self): """ Builds frustum to voxel transformation Returns: f2v_module: nn.Module, Frustum to voxel transformation """ f2v_module = f2v.__all__[self.model_cfg.F2V.NAME]( model_cfg=self.model_cfg.F2V, grid_size=self.grid_size, pc_range=self.pc_range, disc_cfg=self.disc_cfg ) return f2v_module def get_output_feature_dim(self): """ Gets number of output channels Returns: out_feature_dim: int, Number of output channels """ out_feature_dim = self.ffn.get_output_feature_dim() return out_feature_dim def forward(self, batch_dict, **kwargs): """ Args: batch_dict: images: (N, 3, H_in, W_in), Input images **kwargs: Returns: batch_dict: voxel_features: (B, C, Z, Y, X), Image voxel features """ batch_dict = self.ffn(batch_dict) batch_dict = self.f2v(batch_dict) return batch_dict def get_loss(self): """ Gets DDN loss Returns: loss: (1), Depth distribution network loss tb_dict: dict[float], All losses to log in tensorboard """ loss, tb_dict = self.ffn.get_loss() return loss, tb_dict
2,526
28.383721
99
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/ffn/depth_ffn.py
import torch.nn as nn import torch.nn.functional as F from . import ddn, ddn_loss from pcdet.models.model_utils.basic_block_2d import BasicBlock2D class DepthFFN(nn.Module): def __init__(self, model_cfg, downsample_factor): """ Initialize frustum feature network via depth distribution estimation Args: model_cfg: EasyDict, Depth classification network config downsample_factor: int, Depth map downsample factor """ super().__init__() self.model_cfg = model_cfg self.disc_cfg = model_cfg.DISCRETIZE self.downsample_factor = downsample_factor # Create modules self.ddn = ddn.__all__[model_cfg.DDN.NAME]( num_classes=self.disc_cfg["num_bins"] + 1, backbone_name=model_cfg.DDN.BACKBONE_NAME, **model_cfg.DDN.ARGS ) self.channel_reduce = BasicBlock2D(**model_cfg.CHANNEL_REDUCE) self.ddn_loss = ddn_loss.__all__[model_cfg.LOSS.NAME]( disc_cfg=self.disc_cfg, downsample_factor=downsample_factor, **model_cfg.LOSS.ARGS ) self.forward_ret_dict = {} def get_output_feature_dim(self): return self.channel_reduce.out_channels def forward(self, batch_dict): """ Predicts depths and creates image depth feature volume using depth distributions Args: batch_dict: images: (N, 3, H_in, W_in), Input images Returns: batch_dict: frustum_features: (N, C, D, H_out, W_out), Image depth features """ # Pixel-wise depth classification images = batch_dict["images"] ddn_result = self.ddn(images) image_features = ddn_result["features"] depth_logits = ddn_result["logits"] # Channel reduce if self.channel_reduce is not None: image_features = self.channel_reduce(image_features) # Create image feature plane-sweep volume frustum_features = self.create_frustum_features(image_features=image_features, depth_logits=depth_logits) batch_dict["frustum_features"] = frustum_features if self.training: self.forward_ret_dict["depth_maps"] = batch_dict["depth_maps"] self.forward_ret_dict["gt_boxes2d"] = batch_dict["gt_boxes2d"] self.forward_ret_dict["depth_logits"] = depth_logits return batch_dict def create_frustum_features(self, image_features, depth_logits): """ Create image depth feature volume by multiplying image features with depth distributions Args: image_features: (N, C, H, W), Image features depth_logits: (N, D+1, H, W), Depth classification logits Returns: frustum_features: (N, C, D, H, W), Image features """ channel_dim = 1 depth_dim = 2 # Resize to match dimensions image_features = image_features.unsqueeze(depth_dim) depth_logits = depth_logits.unsqueeze(channel_dim) # Apply softmax along depth axis and remove last depth category (> Max Range) depth_probs = F.softmax(depth_logits, dim=depth_dim) depth_probs = depth_probs[:, :, :-1] # Multiply to form image depth feature volume frustum_features = depth_probs * image_features return frustum_features def get_loss(self): """ Gets DDN loss Args: Returns: loss: (1), Depth distribution network loss tb_dict: dict[float], All losses to log in tensorboard """ loss, tb_dict = self.ddn_loss(**self.forward_ret_dict) return loss, tb_dict
3,778
35.336538
96
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/ffn/ddn/ddn_deeplabv3.py
from .ddn_template import DDNTemplate try: import torchvision except: pass class DDNDeepLabV3(DDNTemplate): def __init__(self, backbone_name, **kwargs): """ Initializes DDNDeepLabV3 model Args: backbone_name: string, ResNet Backbone Name [ResNet50/ResNet101] """ if backbone_name == "ResNet50": constructor = torchvision.models.segmentation.deeplabv3_resnet50 elif backbone_name == "ResNet101": constructor = torchvision.models.segmentation.deeplabv3_resnet101 else: raise NotImplementedError super().__init__(constructor=constructor, **kwargs)
674
26
77
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/ffn/ddn/ddn_template.py
from collections import OrderedDict from pathlib import Path from torch import hub import torch import torch.nn as nn import torch.nn.functional as F try: from kornia.enhance.normalize import normalize except: pass # print('Warning: kornia is not installed. This package is only required by CaDDN') class DDNTemplate(nn.Module): def __init__(self, constructor, feat_extract_layer, num_classes, pretrained_path=None, aux_loss=None): """ Initializes depth distribution network. Args: constructor: function, Model constructor feat_extract_layer: string, Layer to extract features from num_classes: int, Number of classes pretrained_path: string, (Optional) Path of the model to load weights from aux_loss: bool, Flag to include auxillary loss """ super().__init__() self.num_classes = num_classes self.pretrained_path = pretrained_path self.pretrained = pretrained_path is not None self.aux_loss = aux_loss if self.pretrained: # Preprocess Module self.norm_mean = torch.Tensor([0.485, 0.456, 0.406]) self.norm_std = torch.Tensor([0.229, 0.224, 0.225]) # Model self.model = self.get_model(constructor=constructor) self.feat_extract_layer = feat_extract_layer self.model.backbone.return_layers = { feat_extract_layer: 'features', **self.model.backbone.return_layers } def get_model(self, constructor): """ Get model Args: constructor: function, Model constructor Returns: model: nn.Module, Model """ # Get model model = constructor(pretrained=False, pretrained_backbone=False, num_classes=self.num_classes, aux_loss=self.aux_loss) # Update weights if self.pretrained_path is not None: model_dict = model.state_dict() # Download pretrained model if not available yet checkpoint_path = Path(self.pretrained_path) if not checkpoint_path.exists(): checkpoint = checkpoint_path.name save_dir = checkpoint_path.parent save_dir.mkdir(parents=True) url = f'https://download.pytorch.org/models/{checkpoint}' hub.load_state_dict_from_url(url, save_dir) # Get pretrained state dict pretrained_dict = torch.load(self.pretrained_path) pretrained_dict = self.filter_pretrained_dict(model_dict=model_dict, pretrained_dict=pretrained_dict) # Update current model state dict model_dict.update(pretrained_dict) model.load_state_dict(model_dict) return model def filter_pretrained_dict(self, model_dict, pretrained_dict): """ Removes layers from pretrained state dict that are not used or changed in model Args: model_dict: dict, Default model state dictionary pretrained_dict: dict, Pretrained model state dictionary Returns: pretrained_dict: dict, Pretrained model state dictionary with removed weights """ # Removes aux classifier weights if not used if "aux_classifier.0.weight" in pretrained_dict and "aux_classifier.0.weight" not in model_dict: pretrained_dict = {key: value for key, value in pretrained_dict.items() if "aux_classifier" not in key} # Removes final conv layer from weights if number of classes are different model_num_classes = model_dict["classifier.4.weight"].shape[0] pretrained_num_classes = pretrained_dict["classifier.4.weight"].shape[0] if model_num_classes != pretrained_num_classes: pretrained_dict.pop("classifier.4.weight") pretrained_dict.pop("classifier.4.bias") return pretrained_dict def forward(self, images): """ Forward pass Args: images: (N, 3, H_in, W_in), Input images Returns result: dict[torch.Tensor], Depth distribution result features: (N, C, H_out, W_out), Image features logits: (N, num_classes, H_out, W_out), Classification logits aux: (N, num_classes, H_out, W_out), Auxillary classification logits """ # Preprocess images x = self.preprocess(images) # Extract features result = OrderedDict() features = self.model.backbone(x) result['features'] = features['features'] feat_shape = features['features'].shape[-2:] # Prediction classification logits x = features["out"] x = self.model.classifier(x) x = F.interpolate(x, size=feat_shape, mode='bilinear', align_corners=False) result["logits"] = x # Prediction auxillary classification logits if self.model.aux_classifier is not None: x = features["aux"] x = self.model.aux_classifier(x) x = F.interpolate(x, size=feat_shape, mode='bilinear', align_corners=False) result["aux"] = x return result def preprocess(self, images): """ Preprocess images Args: images: (N, 3, H, W), Input images Return x: (N, 3, H, W), Preprocessed images """ x = images if self.pretrained: # Create a mask for padded pixels mask = torch.isnan(x) # Match ResNet pretrained preprocessing x = normalize(x, mean=self.norm_mean, std=self.norm_std) # Make padded pixels = 0 x[mask] = 0 return x
5,941
35.453988
106
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/ffn/ddn_loss/balancer.py
import torch import torch.nn as nn from pcdet.utils import loss_utils class Balancer(nn.Module): def __init__(self, fg_weight, bg_weight, downsample_factor=1): """ Initialize fixed foreground/background loss balancer Args: fg_weight: float, Foreground loss weight bg_weight: float, Background loss weight downsample_factor: int, Depth map downsample factor """ super().__init__() self.fg_weight = fg_weight self.bg_weight = bg_weight self.downsample_factor = downsample_factor def forward(self, loss, gt_boxes2d): """ Forward pass Args: loss: (B, H, W), Pixel-wise loss gt_boxes2d: (B, N, 4), 2D box labels for foreground/background balancing Returns: loss: (1), Total loss after foreground/background balancing tb_dict: dict[float], All losses to log in tensorboard """ # Compute masks fg_mask = loss_utils.compute_fg_mask(gt_boxes2d=gt_boxes2d, shape=loss.shape, downsample_factor=self.downsample_factor, device=loss.device) bg_mask = ~fg_mask # Compute balancing weights weights = self.fg_weight * fg_mask + self.bg_weight * bg_mask num_pixels = fg_mask.sum() + bg_mask.sum() # Compute losses loss *= weights fg_loss = loss[fg_mask].sum() / num_pixels bg_loss = loss[bg_mask].sum() / num_pixels # Get total loss loss = fg_loss + bg_loss tb_dict = {"balancer_loss": loss.item(), "fg_loss": fg_loss.item(), "bg_loss": bg_loss.item()} return loss, tb_dict
1,806
34.431373
102
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/ffn/ddn_loss/ddn_loss.py
import torch import torch.nn as nn from .balancer import Balancer from pcdet.utils import transform_utils try: from kornia.losses.focal import FocalLoss except: pass # print('Warning: kornia is not installed. This package is only required by CaDDN') class DDNLoss(nn.Module): def __init__(self, weight, alpha, gamma, disc_cfg, fg_weight, bg_weight, downsample_factor): """ Initializes DDNLoss module Args: weight: float, Loss function weight alpha: float, Alpha value for Focal Loss gamma: float, Gamma value for Focal Loss disc_cfg: dict, Depth discretiziation configuration fg_weight: float, Foreground loss weight bg_weight: float, Background loss weight downsample_factor: int, Depth map downsample factor """ super().__init__() self.device = torch.cuda.current_device() self.disc_cfg = disc_cfg self.balancer = Balancer(downsample_factor=downsample_factor, fg_weight=fg_weight, bg_weight=bg_weight) # Set loss function self.alpha = alpha self.gamma = gamma self.loss_func = FocalLoss(alpha=self.alpha, gamma=self.gamma, reduction="none") self.weight = weight def forward(self, depth_logits, depth_maps, gt_boxes2d): """ Gets DDN loss Args: depth_logits: (B, D+1, H, W), Predicted depth logits depth_maps: (B, H, W), Depth map [m] gt_boxes2d: torch.Tensor (B, N, 4), 2D box labels for foreground/background balancing Returns: loss: (1), Depth distribution network loss tb_dict: dict[float], All losses to log in tensorboard """ tb_dict = {} # Bin depth map to create target depth_target = transform_utils.bin_depths(depth_maps, **self.disc_cfg, target=True) # Compute loss loss = self.loss_func(depth_logits, depth_target) # Compute foreground/background balancing loss, tb_dict = self.balancer(loss=loss, gt_boxes2d=gt_boxes2d) # Final loss loss *= self.weight tb_dict.update({"ddn_loss": loss.item()}) return loss, tb_dict
2,428
30.960526
97
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/f2v/frustum_to_voxel.py
import torch import torch.nn as nn from .frustum_grid_generator import FrustumGridGenerator from .sampler import Sampler class FrustumToVoxel(nn.Module): def __init__(self, model_cfg, grid_size, pc_range, disc_cfg): """ Initializes module to transform frustum features to voxel features via 3D transformation and sampling Args: model_cfg: EasyDict, Module configuration grid_size: [X, Y, Z], Voxel grid size pc_range: [x_min, y_min, z_min, x_max, y_max, z_max], Voxelization point cloud range (m) disc_cfg: EasyDict, Depth discretiziation configuration """ super().__init__() self.model_cfg = model_cfg self.grid_size = grid_size self.pc_range = pc_range self.disc_cfg = disc_cfg self.grid_generator = FrustumGridGenerator(grid_size=grid_size, pc_range=pc_range, disc_cfg=disc_cfg) self.sampler = Sampler(**model_cfg.SAMPLER) def forward(self, batch_dict): """ Generates voxel features via 3D transformation and sampling Args: batch_dict: frustum_features: (B, C, D, H_image, W_image), Image frustum features lidar_to_cam: (B, 4, 4), LiDAR to camera frame transformation cam_to_img: (B, 3, 4), Camera projection matrix image_shape: (B, 2), Image shape [H, W] Returns: batch_dict: voxel_features: (B, C, Z, Y, X), Image voxel features """ # Generate sampling grid for frustum volume grid = self.grid_generator(lidar_to_cam=batch_dict["trans_lidar_to_cam"], cam_to_img=batch_dict["trans_cam_to_img"], image_shape=batch_dict["image_shape"]) # (B, X, Y, Z, 3) # Sample frustum volume to generate voxel volume voxel_features = self.sampler(input_features=batch_dict["frustum_features"], grid=grid) # (B, C, X, Y, Z) # (B, C, X, Y, Z) -> (B, C, Z, Y, X) voxel_features = voxel_features.permute(0, 1, 4, 3, 2) batch_dict["voxel_features"] = voxel_features return batch_dict
2,338
41.527273
109
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/f2v/frustum_grid_generator.py
import torch import torch.nn as nn try: from kornia.utils.grid import create_meshgrid3d from kornia.geometry.linalg import transform_points except Exception as e: # Note: Kornia team will fix this import issue to try to allow the usage of lower torch versions. # print('Warning: kornia is not installed correctly, please ignore this warning if you do not use CaDDN. Otherwise, it is recommended to use torch version greater than 1.2 to use kornia properly.') pass from pcdet.utils import transform_utils class FrustumGridGenerator(nn.Module): def __init__(self, grid_size, pc_range, disc_cfg): """ Initializes Grid Generator for frustum features Args: grid_size: [X, Y, Z], Voxel grid size pc_range: [x_min, y_min, z_min, x_max, y_max, z_max], Voxelization point cloud range (m) disc_cfg: EasyDict, Depth discretiziation configuration """ super().__init__() try: import kornia except Exception as e: # Note: Kornia team will fix this import issue to try to allow the usage of lower torch versions. print('Error: kornia is not installed correctly, please ignore this warning if you do not use CaDDN. ' 'Otherwise, it is recommended to use torch version greater than 1.2 to use kornia properly.') exit(-1) self.dtype = torch.float32 self.grid_size = torch.as_tensor(grid_size, dtype=self.dtype) self.pc_range = pc_range self.out_of_bounds_val = -2 self.disc_cfg = disc_cfg # Calculate voxel size pc_range = torch.as_tensor(pc_range).reshape(2, 3) self.pc_min = pc_range[0] self.pc_max = pc_range[1] self.voxel_size = (self.pc_max - self.pc_min) / self.grid_size # Create voxel grid self.depth, self.width, self.height = self.grid_size.int() self.voxel_grid = create_meshgrid3d(depth=self.depth, height=self.height, width=self.width, normalized_coordinates=False) self.voxel_grid = self.voxel_grid.permute(0, 1, 3, 2, 4) # XZY-> XYZ # Add offsets to center of voxel self.voxel_grid += 0.5 self.grid_to_lidar = self.grid_to_lidar_unproject(pc_min=self.pc_min, voxel_size=self.voxel_size) def grid_to_lidar_unproject(self, pc_min, voxel_size): """ Calculate grid to LiDAR unprojection for each plane Args: pc_min: [x_min, y_min, z_min], Minimum of point cloud range (m) voxel_size: [x, y, z], Size of each voxel (m) Returns: unproject: (4, 4), Voxel grid to LiDAR unprojection matrix """ x_size, y_size, z_size = voxel_size x_min, y_min, z_min = pc_min unproject = torch.tensor([[x_size, 0, 0, x_min], [0, y_size, 0, y_min], [0, 0, z_size, z_min], [0, 0, 0, 1]], dtype=self.dtype) # (4, 4) return unproject def transform_grid(self, voxel_grid, grid_to_lidar, lidar_to_cam, cam_to_img): """ Transforms voxel sampling grid into frustum sampling grid Args: grid: (B, X, Y, Z, 3), Voxel sampling grid grid_to_lidar: (4, 4), Voxel grid to LiDAR unprojection matrix lidar_to_cam: (B, 4, 4), LiDAR to camera frame transformation cam_to_img: (B, 3, 4), Camera projection matrix Returns: frustum_grid: (B, X, Y, Z, 3), Frustum sampling grid """ B = lidar_to_cam.shape[0] # Create transformation matricies V_G = grid_to_lidar # Voxel Grid -> LiDAR (4, 4) C_V = lidar_to_cam # LiDAR -> Camera (B, 4, 4) I_C = cam_to_img # Camera -> Image (B, 3, 4) trans = C_V @ V_G # Reshape to match dimensions trans = trans.reshape(B, 1, 1, 4, 4) voxel_grid = voxel_grid.repeat_interleave(repeats=B, dim=0) # Transform to camera frame camera_grid = transform_points(trans_01=trans, points_1=voxel_grid) # Project to image I_C = I_C.reshape(B, 1, 1, 3, 4) image_grid, image_depths = transform_utils.project_to_image(project=I_C, points=camera_grid) # Convert depths to depth bins image_depths = transform_utils.bin_depths(depth_map=image_depths, **self.disc_cfg) # Stack to form frustum grid image_depths = image_depths.unsqueeze(-1) frustum_grid = torch.cat((image_grid, image_depths), dim=-1) return frustum_grid def forward(self, lidar_to_cam, cam_to_img, image_shape): """ Generates sampling grid for frustum features Args: lidar_to_cam: (B, 4, 4), LiDAR to camera frame transformation cam_to_img: (B, 3, 4), Camera projection matrix image_shape: (B, 2), Image shape [H, W] Returns: frustum_grid (B, X, Y, Z, 3), Sampling grids for frustum features """ frustum_grid = self.transform_grid(voxel_grid=self.voxel_grid.to(lidar_to_cam.device), grid_to_lidar=self.grid_to_lidar.to(lidar_to_cam.device), lidar_to_cam=lidar_to_cam, cam_to_img=cam_to_img) # Normalize grid image_shape, _ = torch.max(image_shape, dim=0) image_depth = torch.tensor([self.disc_cfg["num_bins"]], device=image_shape.device, dtype=image_shape.dtype) frustum_shape = torch.cat((image_depth, image_shape)) frustum_grid = transform_utils.normalize_coords(coords=frustum_grid, shape=frustum_shape) # Replace any NaNs or infinites with out of bounds mask = ~torch.isfinite(frustum_grid) frustum_grid[mask] = self.out_of_bounds_val return frustum_grid
6,249
41.808219
201
py
3DTrans
3DTrans-master/pcdet/models/backbones_3d/vfe/image_vfe_modules/f2v/sampler.py
import torch import torch.nn as nn import torch.nn.functional as F class Sampler(nn.Module): def __init__(self, mode="bilinear", padding_mode="zeros"): """ Initializes module Args: mode: string, Sampling mode [bilinear/nearest] padding_mode: string, Padding mode for outside grid values [zeros/border/reflection] """ super().__init__() self.mode = mode self.padding_mode = padding_mode def forward(self, input_features, grid): """ Samples input using sampling grid Args: input_features: (B, C, D, H, W), Input frustum features grid: (B, X, Y, Z, 3), Sampling grids for input features Returns output_features: (B, C, X, Y, Z) Output voxel features """ # Sample from grid output = F.grid_sample(input=input_features, grid=grid, mode=self.mode, padding_mode=self.padding_mode) return output
980
30.645161
111
py
3DTrans
3DTrans-master/pcdet/models/active_models/discriminator.py
from xml.dom.minidom import DOMImplementation import torch import torch.nn as nn import torch.nn.functional as F import math class ActiveDiscriminator(nn.Module): def __init__(self, model_cfg): super().__init__() self.model_cfg = model_cfg self.fc = nn.Linear(model_cfg['FEATURE_DIM'], 1) self.sigmoid = nn.Sigmoid() nn.init.kaiming_uniform_(self.fc.weight) def get_discriminator_loss(self, batch_dict, source=True): domainness = batch_dict['domainness'] if source: discri_loss = F.binary_cross_entropy(domainness, torch.zeros_like(domainness)) else: discri_loss = F.binary_cross_entropy(domainness, torch.ones_like(domainness)) return discri_loss def get_accuracy(self, batch_dict, source=True): batch_size = batch_dict['batch_size'] domainness = batch_dict['domainness'] zero = torch.zeros_like(domainness) one = torch.ones_like(domainness) domainness = torch.where(domainness > 0.5, one, domainness) domainness = torch.where(domainness <= 0.5, zero, domainness) if source: acc = (domainness == zero).sum() / batch_size else: acc = (domainness == one).sum() / batch_size return acc def domainness_evaluate(self, batch_dict, source=False): domainness = batch_dict['domainness'] if source == False else 1 - batch_dict['domainness'] # domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / 2 * (self.model_cfg.SIGMA ** 2)) # batch_dict['domainness_evaluate'] = domainness_value batch_dict['domainness_evaluate'] = domainness return batch_dict def forward(self, batch_dict): point_feature = batch_dict['point_features'] point_feature_score = batch_dict['point_cls_scores'] point_coords = batch_dict['point_coords'] point_feature = point_feature * point_feature_score.view(-1, 1) batch_size = batch_dict['batch_size'] scene_feature = point_feature.new_zeros((batch_size, point_feature.shape[-1])) for i in range(batch_size): mask = point_coords[:, 0] == i scene_feature[i] = torch.mean(point_feature[mask], dim=0) domainness = self.fc(scene_feature) domainness = self.sigmoid(domainness) batch_dict['domainness'] = domainness return batch_dict
2,477
41.724138
163
py
3DTrans
3DTrans-master/pcdet/models/active_models/discriminator_from_bev.py
import math import torch import torch.nn as nn import torch.nn.functional as F class BEVDiscriminator_Conv(nn.Module): def __init__(self, model_cfg): super().__init__() c_in = model_cfg['FEATURE_DIM'] c_out = model_cfg['FEATURE_DIM'] // 4 self.c_out = c_out self.block = nn.Sequential( nn.Conv2d(c_in, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True) ) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.mlp = nn.Linear(c_out, 1) def forward(self, batch_dict): x = batch_dict['spatial_features_2d'] score = batch_dict['bev_score'] bev_map = batch_dict['bev_map'] bev_map = F.sigmoid(bev_map).clamp_(1e-6) entropy_map = -bev_map * torch.log(bev_map) entropy_map = entropy_map.max(dim=1)[0].view(-1, 1, *entropy_map.shape[2:]) score = F.sigmoid(score) score = torch.cat([score, entropy_map], dim=1).mean(dim=1).view(-1, 1, *score.shape[2:]) x = x * (1 + score) x = self.block(x) x = self.gap(x).view(-1, self.c_out) batch_dict['bev_pooled_feature'] = x x = self.mlp(x) batch_dict['domainness'] = x return batch_dict def get_discriminator_loss(self, batch_dict, source=True, loss='bce'): domainness = batch_dict['domainness'] if source: if loss == 'bce': discri_loss = bce_loss(domainness, 0) else: discri_loss = ls_loss(domainness, 0) else: if loss == 'bce': discri_loss = bce_loss(domainness, 1) else: discri_loss = ls_loss(domainness, 1) return discri_loss def domainness_evaluate(self, batch_dict, source=False): domainness = batch_dict['domainness'] # domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / 2 * (self.model_cfg.SIGMA ** 2)) # batch_dict['domainness_evaluate'] = domainness_value batch_dict['domainness_evaluate'] = domainness batch_dict['domainness_evaluate_sigmoid'] = F.sigmoid(domainness) return batch_dict class BEVDiscriminator_Conv_2(nn.Module): def __init__(self, model_cfg): super().__init__() c_in = model_cfg['FEATURE_DIM'] c_out = model_cfg['FEATURE_DIM'] // 4 self.c_out = c_out self.block = nn.Sequential( nn.Conv2d(c_in, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True) ) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.mlp = nn.Linear(c_out, 1) def forward(self, batch_dict): x = batch_dict['spatial_features_2d'] score = batch_dict['bev_score'] bev_map = batch_dict['bev_map'] bev_map = F.sigmoid(bev_map).clamp_(1e-6) entropy_map = -bev_map * torch.log2(bev_map) - (1 - bev_map) * torch.log2(1 - bev_map) entropy_map = entropy_map.max(dim=1)[0].view(-1, 1, *entropy_map.shape[2:]) score = F.sigmoid(score) score = (torch.cat([score, entropy_map], dim=1).mean(dim=1).view(-1, 1, *score.shape[2:])) / 2 x = x * (1 + score) x = self.block(x) x = self.gap(x).view(-1, self.c_out) x = self.mlp(x) batch_dict['domainness'] = x return batch_dict def get_discriminator_loss(self, batch_dict, source=True, loss='bce'): domainness = batch_dict['domainness'] if source: if loss == 'bce': discri_loss = bce_loss(domainness, 0) else: discri_loss = ls_loss(domainness, 0) else: if loss == 'bce': discri_loss = bce_loss(domainness, 1) else: discri_loss = ls_loss(domainness, 1) return discri_loss def domainness_evaluate(self, batch_dict, source=False): domainness = batch_dict['domainness'] # domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / 2 * (self.model_cfg.SIGMA ** 2)) # batch_dict['domainness_evaluate'] = domainness_value batch_dict['domainness_evaluate'] = domainness batch_dict['domainness_evaluate_sigmoid'] = F.sigmoid(domainness) return batch_dict class BEVDiscriminator_Center(nn.Module): def __init__(self, model_cfg): super().__init__() c_in = model_cfg['FEATURE_DIM'] c_out = model_cfg['FEATURE_DIM'] // 4 self.c_out = c_out self.block = nn.Sequential( nn.Conv2d(c_in, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True) ) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.mlp = nn.Linear(c_out, 1) def forward(self, batch_dict): x = batch_dict['spatial_features_2d'] score = batch_dict['bev_score'] # bev_map = batch_dict['bev_map'] bev_map = F.sigmoid(score).clamp_(1e-6) entropy_map = (-bev_map * torch.log2(bev_map) - (1-bev_map) * torch.log2(1-bev_map)) / 2 # entropy_map = entropy_map.max(dim=1)[0].view(-1, 1, *entropy_map.shape[2:]) score = F.sigmoid(score) score = torch.cat([score, entropy_map], dim=1).mean(dim=1).view(-1, 1, *score.shape[2:]) x = x * (1 + score) x = self.block(x) x = self.gap(x).view(-1, self.c_out) batch_dict['bev_pooled_feature'] = x x = self.mlp(x) batch_dict['domainness'] = x return batch_dict def get_discriminator_loss(self, batch_dict, source=True, loss='bce'): domainness = batch_dict['domainness'] if source: if loss == 'bce': discri_loss = bce_loss(domainness, 0) else: discri_loss = ls_loss(domainness, 0) else: if loss == 'bce': discri_loss = bce_loss(domainness, 1) else: discri_loss = ls_loss(domainness, 1) return discri_loss def domainness_evaluate(self, batch_dict, source=False): domainness = batch_dict['domainness'] # domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / 2 * (self.model_cfg.SIGMA ** 2)) # batch_dict['domainness_evaluate'] = domainness_value batch_dict['domainness_evaluate'] = domainness batch_dict['domainness_evaluate_sigmoid'] = F.sigmoid(domainness) return batch_dict def bce_loss(y_pred, y_label): y_truth_tensor = torch.FloatTensor(y_pred.size()) y_truth_tensor.fill_(y_label) y_truth_tensor = y_truth_tensor.to(y_pred.get_device()) return nn.BCEWithLogitsLoss()(y_pred, y_truth_tensor) def ls_loss(y_pred, y_label): y_truth_tensor = torch.FloatTensor(y_pred.size()) y_truth_tensor.fill_(y_label) y_truth_tensor = y_truth_tensor.to(y_pred.get_device()) return nn.MSELoss()(y_pred, y_truth_tensor) class BEVDiscriminator_TQS(nn.Module): def __init__(self, model_cfg): super().__init__() self.model_cfg = model_cfg c_in = model_cfg['FEATURE_DIM'] c_out = model_cfg['FEATURE_DIM'] // 4 self.c_out = c_out self.block = nn.Sequential( nn.Conv2d(c_in, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True) ) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.mlp = nn.Linear(c_out, 1) def forward(self, batch_dict): x = batch_dict['spatial_features_2d'] x = self.block(x) x = self.gap(x).view(-1, self.c_out) x = self.mlp(x) batch_dict['domainness'] = x return batch_dict def get_discriminator_loss(self, batch_dict, source=True, loss='bce'): domainness = batch_dict['domainness'] if source: if loss == 'bce': discri_loss = bce_loss(domainness, 0) else: discri_loss = ls_loss(domainness, 0) else: if loss == 'bce': discri_loss = bce_loss(domainness, 1) else: discri_loss = ls_loss(domainness, 1) return discri_loss def domainness_evaluate(self, batch_dict): domainness = batch_dict['domainness'] domainness = F.sigmoid(domainness) domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / (2 * (self.model_cfg.SIGMA ** 2))) batch_dict['domainness_evaluate'] = domainness_value return batch_dict class BEVDiscriminator_Center_TQS(nn.Module): def __init__(self, model_cfg): super().__init__() c_in = model_cfg['FEATURE_DIM'] c_out = model_cfg['FEATURE_DIM'] // 4 self.model_cfg = model_cfg self.c_out = c_out self.block = nn.Sequential( nn.Conv2d(c_in, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(c_out, c_out, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True) ) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.mlp = nn.Linear(c_out, 1) def forward(self, batch_dict): x = batch_dict['spatial_features_2d'] x = self.block(x) x = self.gap(x).view(-1, self.c_out) batch_dict['bev_pooled_feature'] = x x = self.mlp(x) batch_dict['domainness'] = x return batch_dict def get_discriminator_loss(self, batch_dict, source=True, loss='bce'): domainness = batch_dict['domainness'] if source: if loss == 'bce': discri_loss = bce_loss(domainness, 0) else: discri_loss = ls_loss(domainness, 0) else: if loss == 'bce': discri_loss = bce_loss(domainness, 1) else: discri_loss = ls_loss(domainness, 1) return discri_loss def domainness_evaluate(self, batch_dict, source=False): domainness = batch_dict['domainness'] domainness = F.sigmoid(domainness) domainness_value = 1 / (math.sqrt(2*3.14) * self.model_cfg.SIGMA) * torch.exp(-(domainness - self.model_cfg.MU).pow(2) / (2 * (self.model_cfg.SIGMA ** 2))) batch_dict['domainness_evaluate'] = domainness_value return batch_dict
13,106
42.115132
163
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/anchor_head_single.py
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from .anchor_head_template import AnchorHeadTemplate class AnchorHeadSingle(AnchorHeadTemplate): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, predict_boxes_when_training=True, **kwargs): super().__init__( model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_range=point_cloud_range, predict_boxes_when_training=predict_boxes_when_training ) self.num_anchors_per_location = sum(self.num_anchors_per_location) self.conv_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_box = nn.Conv2d( input_channels, self.num_anchors_per_location * self.box_coder.code_size, kernel_size=1 ) if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', None) is not None: self.conv_dir_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.model_cfg.NUM_DIR_BINS, kernel_size=1 ) else: self.conv_dir_cls = None self.init_weights() def init_weights(self): pi = 0.01 nn.init.constant_(self.conv_cls.bias, -np.log((1 - pi) / pi)) nn.init.normal_(self.conv_box.weight, mean=0, std=0.001) def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] cls_preds = self.conv_cls(spatial_features_2d) box_preds = self.conv_box(spatial_features_2d) cls_preds = cls_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] box_preds = box_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] self.forward_ret_dict['cls_preds'] = cls_preds self.forward_ret_dict['box_preds'] = box_preds if self.conv_dir_cls is not None: dir_cls_preds = self.conv_dir_cls(spatial_features_2d) dir_cls_preds = dir_cls_preds.permute(0, 2, 3, 1).contiguous() self.forward_ret_dict['dir_cls_preds'] = dir_cls_preds else: dir_cls_preds = None if self.training: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False return data_dict class ActiveAnchorHeadSingle1(AnchorHeadTemplate): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, predict_boxes_when_training=True, **kwargs): super().__init__( model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_range=point_cloud_range, predict_boxes_when_training=predict_boxes_when_training ) self.num_anchors_per_location = sum(self.num_anchors_per_location) self.conv_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_box = nn.Conv2d( input_channels, self.num_anchors_per_location * self.box_coder.code_size, kernel_size=1 ) if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', None) is not None: self.conv_dir_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.model_cfg.NUM_DIR_BINS, kernel_size=1 ) else: self.conv_dir_cls = None self.init_weights() def init_weights(self): pi = 0.01 nn.init.constant_(self.conv_cls.bias, -np.log((1 - pi) / pi)) nn.init.normal_(self.conv_box.weight, mean=0, std=0.001) def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] cls_preds = self.conv_cls(spatial_features_2d) box_preds = self.conv_box(spatial_features_2d) data_dict['bev_score'] = cls_preds.max(dim=1)[0].view(-1, 1, *cls_preds.shape[2:]) data_dict['bev_map'] = cls_preds cls_preds = cls_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] box_preds = box_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] self.forward_ret_dict['cls_preds'] = cls_preds self.forward_ret_dict['box_preds'] = box_preds if self.conv_dir_cls is not None: dir_cls_preds = self.conv_dir_cls(spatial_features_2d) dir_cls_preds = dir_cls_preds.permute(0, 2, 3, 1).contiguous() self.forward_ret_dict['dir_cls_preds'] = dir_cls_preds else: dir_cls_preds = None if self.training: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False return data_dict class AnchorHeadSingle_TQS(AnchorHeadTemplate): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, predict_boxes_when_training=True, **kwargs): super().__init__( model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_range=point_cloud_range, predict_boxes_when_training=predict_boxes_when_training ) self.num_anchors_per_location = sum(self.num_anchors_per_location) self.input_channels = input_channels self.margin_scale = self.model_cfg.get('MARGIN_SCALE', None) self._init_cls_layers() self.conv_box = nn.Conv2d( input_channels, self.num_anchors_per_location * self.box_coder.code_size, kernel_size=1 ) if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', None) is not None: self.conv_dir_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.model_cfg.NUM_DIR_BINS, kernel_size=1 ) else: self.conv_dir_cls = None self.init_weights() def _init_cls_layers(self): self.conv_cls = nn.Conv2d( self.input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_cls1 = nn.Conv2d( self.input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_cls2 = nn.Conv2d( self.input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) def init_weights(self): pi = 0.01 nn.init.constant_(self.conv_cls.bias, -np.log((1 - pi) / pi)) nn.init.xavier_normal_(self.conv_cls1.weight) nn.init.xavier_uniform_(self.conv_cls2.weight) nn.init.normal_(self.conv_box.weight, mean=0, std=0.001) def get_active_loss(self, mode=None): cls_loss, tb_dict = self.get_multi_cls_layer_loss() cls_loss_1, tb_dict_1 = self.get_multi_cls_layer_loss(head='cls_preds_1') tb_dict.update(tb_dict_1) cls_loss_2, tb_dict_2 = self.get_multi_cls_layer_loss(head='cls_preds_2') tb_dict.update(tb_dict_2) box_loss, tb_dict_box = self.get_box_reg_layer_loss() tb_dict.update(tb_dict_box) if mode is 'train_detector': rpn_loss = cls_loss + box_loss + cls_loss_1 + cls_loss_2 elif mode == 'train_mul_cls': rpn_loss = cls_loss_1 + cls_loss_2 return rpn_loss, tb_dict def get_multi_cls_layer_loss(self, head=None): head = 'cls_preds' if head is None else head cls_preds = self.forward_ret_dict[head] box_cls_labels = self.forward_ret_dict['box_cls_labels'] batch_size = int(cls_preds.shape[0]) cared = box_cls_labels >= 0 # [N, num_anchors] positives = box_cls_labels > 0 negatives = box_cls_labels == 0 negative_cls_weights = negatives * 1.0 cls_weights = (negative_cls_weights + 1.0 * positives).float() reg_weights = positives.float() if self.num_class == 1: # class agnostic box_cls_labels[positives] = 1 pos_normalizer = positives.sum(1, keepdim=True).float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) cls_weights /= torch.clamp(pos_normalizer, min=1.0) cls_targets = box_cls_labels * cared.type_as(box_cls_labels) cls_targets = cls_targets.unsqueeze(dim=-1) cls_targets = cls_targets.squeeze(dim=-1) one_hot_targets = torch.zeros( *list(cls_targets.shape), self.num_class + 1, dtype=cls_preds.dtype, device=cls_targets.device ) one_hot_targets.scatter_(-1, cls_targets.unsqueeze(dim=-1).long(), 1.0) cls_preds = cls_preds.view(batch_size, -1, self.num_class) one_hot_targets = one_hot_targets[..., 1:] cls_loss_src = self.cls_loss_func(cls_preds, one_hot_targets, weights=cls_weights) # [N, M] cls_loss = cls_loss_src.sum() / batch_size cls_loss = cls_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['cls_weight'] loss_name = 'rpn_loss_cls' + head.split('_')[-1] if head is not None else 'rpn_loss_cls' tb_dict = { loss_name: cls_loss.item() } return cls_loss, tb_dict def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] cls_preds = self.conv_cls(spatial_features_2d) box_preds = self.conv_box(spatial_features_2d) # multi-classifier cls_preds_1 = self.conv_cls1(spatial_features_2d) cls_preds_2 = self.conv_cls2(spatial_features_2d) cls_preds = cls_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] box_preds = box_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] # multi-classifier cls_preds_1 = cls_preds_1.permute(0, 2, 3, 1).contiguous() cls_preds_2 = cls_preds_2.permute(0, 2, 3, 1).contiguous() self.forward_ret_dict['cls_preds'] = cls_preds self.forward_ret_dict['box_preds'] = box_preds self.forward_ret_dict['cls_preds_1'] = cls_preds_1 self.forward_ret_dict['cls_preds_2'] = cls_preds_2 if self.conv_dir_cls is not None: dir_cls_preds = self.conv_dir_cls(spatial_features_2d) dir_cls_preds = dir_cls_preds.permute(0, 2, 3, 1).contiguous() self.forward_ret_dict['dir_cls_preds'] = dir_cls_preds else: dir_cls_preds = None if self.training: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False return data_dict def committee_evaluate(self, data_dict): batch_size = self.forward_ret_dict['cls_preds_1'].shape[0] cls_preds_1 = self.forward_ret_dict['cls_preds_1'] cls_preds_2 = self.forward_ret_dict['cls_preds_2'] cls_preds_1 = cls_preds_1.view(batch_size, -1, self.num_class) # (B, num_anchor, num_class) cls_preds_2 = cls_preds_2.view(batch_size, -1, self.num_class) # (B, num_anchor, num_class) distances = torch.zeros((batch_size, 1)) for i in range(batch_size): reweight_cls_1 = cls_preds_1[i] reweight_cls_2 = cls_preds_2[i] dis = (F.sigmoid(reweight_cls_1) - F.sigmoid(reweight_cls_2)).pow(2) # (num_pos_anchor, num_class) dis = dis.mean(dim=-1).mean() distances[i] = dis self.forward_ret_dict['committee_evaluate'] = distances data_dict['committee_evaluate'] = distances return data_dict def uncertainty_evaluate(self, data_dict): batch_size = self.forward_ret_dict['cls_preds_1'].shape[0] cls_preds_1 = self.forward_ret_dict['cls_preds_1'].view(batch_size, -1, self.num_class) cls_preds_2 = self.forward_ret_dict['cls_preds_2'].view(batch_size, -1, self.num_class) uncertainty = torch.zeros((batch_size, 1)) for i in range(batch_size): reweight_cls_1 = cls_preds_1[i].view(-1, 1) reweight_cls_2 = cls_preds_2[i].view(-1, 1) reweight_cls_1 = F.sigmoid(reweight_cls_1) reweight_cls_2 = F.sigmoid(reweight_cls_2) uncertainty_cls_1 = torch.min(torch.cat([torch.ones_like(reweight_cls_1) - reweight_cls_1, reweight_cls_1 - torch.zeros_like(reweight_cls_1)], dim=1)).view(-1).mean() uncertainty_cls_2 = torch.min(torch.cat([torch.ones_like(reweight_cls_2) - reweight_cls_2, reweight_cls_2 - torch.zeros_like(reweight_cls_2)], dim=1)).view(-1).mean() uncertainty[i] = (uncertainty_cls_1 + uncertainty_cls_2) / 2 data_dict['uncertainty_evaluate'] = uncertainty return data_dict
14,330
41.907186
178
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/point_head_template.py
import torch import torch.nn as nn import torch.nn.functional as F from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import common_utils, loss_utils class PointHeadTemplate(nn.Module): def __init__(self, model_cfg, num_class): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.build_losses(self.model_cfg.LOSS_CONFIG) self.forward_ret_dict = None def build_losses(self, losses_cfg): self.add_module( 'cls_loss_func', loss_utils.SigmoidFocalClassificationLoss(alpha=0.25, gamma=2.0) ) reg_loss_type = losses_cfg.get('LOSS_REG', None) if reg_loss_type == 'smooth-l1': self.reg_loss_func = F.smooth_l1_loss elif reg_loss_type == 'l1': self.reg_loss_func = F.l1_loss elif reg_loss_type == 'WeightedSmoothL1Loss': self.reg_loss_func = loss_utils.WeightedSmoothL1Loss( code_weights=losses_cfg.LOSS_WEIGHTS.get('code_weights', None) ) else: self.reg_loss_func = F.smooth_l1_loss @staticmethod def make_fc_layers(fc_cfg, input_channels, output_channels): fc_layers = [] c_in = input_channels for k in range(0, fc_cfg.__len__()): fc_layers.extend([ nn.Linear(c_in, fc_cfg[k], bias=False), nn.BatchNorm1d(fc_cfg[k]), nn.ReLU(), ]) c_in = fc_cfg[k] fc_layers.append(nn.Linear(c_in, output_channels, bias=True)) return nn.Sequential(*fc_layers) def assign_stack_targets(self, points, gt_boxes, extend_gt_boxes=None, ret_box_labels=False, ret_part_labels=False, set_ignore_flag=True, use_ball_constraint=False, central_radius=2.0): """ Args: points: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes: (B, M, 8) extend_gt_boxes: [B, M, 8] ret_box_labels: ret_part_labels: set_ignore_flag: use_ball_constraint: central_radius: Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_box_labels: (N1 + N2 + N3 + ..., code_size) """ assert len(points.shape) == 2 and points.shape[1] == 4, 'points.shape=%s' % str(points.shape) assert len(gt_boxes.shape) == 3 and gt_boxes.shape[2] == 8, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert extend_gt_boxes is None or len(extend_gt_boxes.shape) == 3 and extend_gt_boxes.shape[2] == 8, \ 'extend_gt_boxes.shape=%s' % str(extend_gt_boxes.shape) assert set_ignore_flag != use_ball_constraint, 'Choose one only!' batch_size = gt_boxes.shape[0] bs_idx = points[:, 0] point_cls_labels = points.new_zeros(points.shape[0]).long() point_box_labels = gt_boxes.new_zeros((points.shape[0], 8)) if ret_box_labels else None point_part_labels = gt_boxes.new_zeros((points.shape[0], 3)) if ret_part_labels else None for k in range(batch_size): bs_mask = (bs_idx == k) points_single = points[bs_mask][:, 1:4] point_cls_labels_single = point_cls_labels.new_zeros(bs_mask.sum()) box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points_single.unsqueeze(dim=0), gt_boxes[k:k + 1, :, 0:7].contiguous() ).long().squeeze(dim=0) box_fg_flag = (box_idxs_of_pts >= 0) if set_ignore_flag: extend_box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points_single.unsqueeze(dim=0), extend_gt_boxes[k:k+1, :, 0:7].contiguous() ).long().squeeze(dim=0) fg_flag = box_fg_flag ignore_flag = fg_flag ^ (extend_box_idxs_of_pts >= 0) point_cls_labels_single[ignore_flag] = -1 elif use_ball_constraint: box_centers = gt_boxes[k][box_idxs_of_pts][:, 0:3].clone() box_centers[:, 2] += gt_boxes[k][box_idxs_of_pts][:, 5] / 2 ball_flag = ((box_centers - points_single).norm(dim=1) < central_radius) fg_flag = box_fg_flag & ball_flag else: raise NotImplementedError gt_box_of_fg_points = gt_boxes[k][box_idxs_of_pts[fg_flag]] point_cls_labels_single[fg_flag] = 1 if self.num_class == 1 else gt_box_of_fg_points[:, -1].long() point_cls_labels[bs_mask] = point_cls_labels_single if ret_box_labels and gt_box_of_fg_points.shape[0] > 0: point_box_labels_single = point_box_labels.new_zeros((bs_mask.sum(), 8)) fg_point_box_labels = self.box_coder.encode_torch( gt_boxes=gt_box_of_fg_points[:, :-1], points=points_single[fg_flag], gt_classes=gt_box_of_fg_points[:, -1].long() ) point_box_labels_single[fg_flag] = fg_point_box_labels point_box_labels[bs_mask] = point_box_labels_single if ret_part_labels: point_part_labels_single = point_part_labels.new_zeros((bs_mask.sum(), 3)) transformed_points = points_single[fg_flag] - gt_box_of_fg_points[:, 0:3] transformed_points = common_utils.rotate_points_along_z( transformed_points.view(-1, 1, 3), -gt_box_of_fg_points[:, 6] ).view(-1, 3) offset = torch.tensor([0.5, 0.5, 0.5]).view(1, 3).type_as(transformed_points) point_part_labels_single[fg_flag] = (transformed_points / gt_box_of_fg_points[:, 3:6]) + offset point_part_labels[bs_mask] = point_part_labels_single targets_dict = { 'point_cls_labels': point_cls_labels, 'point_box_labels': point_box_labels, 'point_part_labels': point_part_labels } return targets_dict def get_cls_layer_loss(self, tb_dict=None): point_cls_labels = self.forward_ret_dict['point_cls_labels'].view(-1) point_cls_preds = self.forward_ret_dict['point_cls_preds'].view(-1, self.num_class) positives = (point_cls_labels > 0) negative_cls_weights = (point_cls_labels == 0) * 1.0 cls_weights = (negative_cls_weights + 1.0 * positives).float() pos_normalizer = positives.sum(dim=0).float() cls_weights /= torch.clamp(pos_normalizer, min=1.0) one_hot_targets = point_cls_preds.new_zeros(*list(point_cls_labels.shape), self.num_class + 1) one_hot_targets.scatter_(-1, (point_cls_labels * (point_cls_labels >= 0).long()).unsqueeze(dim=-1).long(), 1.0) one_hot_targets = one_hot_targets[..., 1:] cls_loss_src = self.cls_loss_func(point_cls_preds, one_hot_targets, weights=cls_weights) point_loss_cls = cls_loss_src.sum() loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_cls = point_loss_cls * loss_weights_dict['point_cls_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({ 'point_loss_cls': point_loss_cls.item(), 'point_pos_num': pos_normalizer.item() }) return point_loss_cls, tb_dict def get_part_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['point_cls_labels'] > 0 pos_normalizer = max(1, (pos_mask > 0).sum().item()) point_part_labels = self.forward_ret_dict['point_part_labels'] point_part_preds = self.forward_ret_dict['point_part_preds'] point_loss_part = F.binary_cross_entropy(torch.sigmoid(point_part_preds), point_part_labels, reduction='none') point_loss_part = (point_loss_part.sum(dim=-1) * pos_mask.float()).sum() / (3 * pos_normalizer) loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_part = point_loss_part * loss_weights_dict['point_part_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'point_loss_part': point_loss_part.item()}) return point_loss_part, tb_dict def get_box_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['point_cls_labels'] > 0 point_box_labels = self.forward_ret_dict['point_box_labels'] point_box_preds = self.forward_ret_dict['point_box_preds'] reg_weights = pos_mask.float() pos_normalizer = pos_mask.sum().float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) point_loss_box_src = self.reg_loss_func( point_box_preds[None, ...], point_box_labels[None, ...], weights=reg_weights[None, ...] ) point_loss_box = point_loss_box_src.sum() loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_box = point_loss_box * loss_weights_dict['point_box_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'point_loss_box': point_loss_box.item()}) return point_loss_box, tb_dict def generate_predicted_boxes(self, points, point_cls_preds, point_box_preds): """ Args: points: (N, 3) point_cls_preds: (N, num_class) point_box_preds: (N, box_code_size) Returns: point_cls_preds: (N, num_class) point_box_preds: (N, box_code_size) """ _, pred_classes = point_cls_preds.max(dim=-1) point_box_preds = self.box_coder.decode_torch(point_box_preds, points, pred_classes + 1) return point_cls_preds, point_box_preds def forward(self, **kwargs): raise NotImplementedError
9,776
45.336493
119
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/anchor_head_template.py
import numpy as np import torch import torch.nn as nn from ...utils import box_coder_utils, common_utils, loss_utils from .target_assigner.anchor_generator import AnchorGenerator from .target_assigner.atss_target_assigner import ATSSTargetAssigner from .target_assigner.axis_aligned_target_assigner import AxisAlignedTargetAssigner class AnchorHeadTemplate(nn.Module): def __init__(self, model_cfg, num_class, class_names, grid_size, point_cloud_range, predict_boxes_when_training): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.class_names = class_names self.predict_boxes_when_training = predict_boxes_when_training self.use_multihead = self.model_cfg.get('USE_MULTIHEAD', False) anchor_target_cfg = self.model_cfg.TARGET_ASSIGNER_CONFIG self.box_coder = getattr(box_coder_utils, anchor_target_cfg.BOX_CODER)( num_dir_bins=anchor_target_cfg.get('NUM_DIR_BINS', 6), **anchor_target_cfg.get('BOX_CODER_CONFIG', {}) ) anchor_generator_cfg = self.model_cfg.ANCHOR_GENERATOR_CONFIG anchors, self.num_anchors_per_location = self.generate_anchors( anchor_generator_cfg, grid_size=grid_size, point_cloud_range=point_cloud_range, anchor_ndim=self.box_coder.code_size ) self.anchors = [x.cuda() for x in anchors] self.target_assigner = self.get_target_assigner(anchor_target_cfg) self.forward_ret_dict = {} self.build_losses(self.model_cfg.LOSS_CONFIG) @staticmethod def generate_anchors(anchor_generator_cfg, grid_size, point_cloud_range, anchor_ndim=7): anchor_generator = AnchorGenerator( anchor_range=point_cloud_range, anchor_generator_config=anchor_generator_cfg ) feature_map_size = [grid_size[:2] // config['feature_map_stride'] for config in anchor_generator_cfg] anchors_list, num_anchors_per_location_list = anchor_generator.generate_anchors(feature_map_size) if anchor_ndim != 7: for idx, anchors in enumerate(anchors_list): pad_zeros = anchors.new_zeros([*anchors.shape[0:-1], anchor_ndim - 7]) new_anchors = torch.cat((anchors, pad_zeros), dim=-1) anchors_list[idx] = new_anchors return anchors_list, num_anchors_per_location_list def get_target_assigner(self, anchor_target_cfg): if anchor_target_cfg.NAME == 'ATSS': target_assigner = ATSSTargetAssigner( topk=anchor_target_cfg.TOPK, box_coder=self.box_coder, use_multihead=self.use_multihead, match_height=anchor_target_cfg.MATCH_HEIGHT ) elif anchor_target_cfg.NAME == 'AxisAlignedTargetAssigner': target_assigner = AxisAlignedTargetAssigner( model_cfg=self.model_cfg, class_names=self.class_names, box_coder=self.box_coder, match_height=anchor_target_cfg.MATCH_HEIGHT ) else: raise NotImplementedError return target_assigner def build_losses(self, losses_cfg): self.add_module( 'cls_loss_func', loss_utils.SigmoidFocalClassificationLoss(alpha=0.25, gamma=2.0) ) reg_loss_name = 'WeightedSmoothL1Loss' if losses_cfg.get('REG_LOSS_TYPE', None) is None \ else losses_cfg.REG_LOSS_TYPE self.add_module( 'reg_loss_func', getattr(loss_utils, reg_loss_name)(code_weights=losses_cfg.LOSS_WEIGHTS['code_weights']) ) self.add_module( 'dir_loss_func', loss_utils.WeightedCrossEntropyLoss() ) def assign_targets(self, gt_boxes): """ Args: gt_boxes: (B, M, 8) Returns: """ targets_dict = self.target_assigner.assign_targets( self.anchors, gt_boxes ) return targets_dict def get_cls_layer_loss(self): cls_preds = self.forward_ret_dict['cls_preds'] box_cls_labels = self.forward_ret_dict['box_cls_labels'] batch_size = int(cls_preds.shape[0]) cared = box_cls_labels >= 0 # [N, num_anchors] positives = box_cls_labels > 0 negatives = box_cls_labels == 0 negative_cls_weights = negatives * 1.0 cls_weights = (negative_cls_weights + 1.0 * positives).float() reg_weights = positives.float() if self.num_class == 1: # class agnostic box_cls_labels[positives] = 1 pos_normalizer = positives.sum(1, keepdim=True).float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) cls_weights /= torch.clamp(pos_normalizer, min=1.0) cls_targets = box_cls_labels * cared.type_as(box_cls_labels) cls_targets = cls_targets.unsqueeze(dim=-1) cls_targets = cls_targets.squeeze(dim=-1) one_hot_targets = torch.zeros( *list(cls_targets.shape), self.num_class + 1, dtype=cls_preds.dtype, device=cls_targets.device ) one_hot_targets.scatter_(-1, cls_targets.unsqueeze(dim=-1).long(), 1.0) cls_preds = cls_preds.view(batch_size, -1, self.num_class) one_hot_targets = one_hot_targets[..., 1:] cls_loss_src = self.cls_loss_func(cls_preds, one_hot_targets, weights=cls_weights) # [N, M] cls_loss = cls_loss_src.sum() / batch_size cls_loss = cls_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['cls_weight'] tb_dict = { 'rpn_loss_cls': cls_loss.item() } return cls_loss, tb_dict @staticmethod def add_sin_difference(boxes1, boxes2, dim=6): assert dim != -1 rad_pred_encoding = torch.sin(boxes1[..., dim:dim + 1]) * torch.cos(boxes2[..., dim:dim + 1]) rad_tg_encoding = torch.cos(boxes1[..., dim:dim + 1]) * torch.sin(boxes2[..., dim:dim + 1]) boxes1 = torch.cat([boxes1[..., :dim], rad_pred_encoding, boxes1[..., dim + 1:]], dim=-1) boxes2 = torch.cat([boxes2[..., :dim], rad_tg_encoding, boxes2[..., dim + 1:]], dim=-1) return boxes1, boxes2 @staticmethod def get_direction_target(anchors, reg_targets, one_hot=True, dir_offset=0, num_bins=2): batch_size = reg_targets.shape[0] anchors = anchors.view(batch_size, -1, anchors.shape[-1]) rot_gt = reg_targets[..., 6] + anchors[..., 6] offset_rot = common_utils.limit_period(rot_gt - dir_offset, 0, 2 * np.pi) dir_cls_targets = torch.floor(offset_rot / (2 * np.pi / num_bins)).long() dir_cls_targets = torch.clamp(dir_cls_targets, min=0, max=num_bins - 1) if one_hot: dir_targets = torch.zeros(*list(dir_cls_targets.shape), num_bins, dtype=anchors.dtype, device=dir_cls_targets.device) dir_targets.scatter_(-1, dir_cls_targets.unsqueeze(dim=-1).long(), 1.0) dir_cls_targets = dir_targets return dir_cls_targets def get_box_reg_layer_loss(self): box_preds = self.forward_ret_dict['box_preds'] box_dir_cls_preds = self.forward_ret_dict.get('dir_cls_preds', None) box_reg_targets = self.forward_ret_dict['box_reg_targets'] box_cls_labels = self.forward_ret_dict['box_cls_labels'] batch_size = int(box_preds.shape[0]) positives = box_cls_labels > 0 reg_weights = positives.float() pos_normalizer = positives.sum(1, keepdim=True).float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) if isinstance(self.anchors, list): if self.use_multihead: anchors = torch.cat( [anchor.permute(3, 4, 0, 1, 2, 5).contiguous().view(-1, anchor.shape[-1]) for anchor in self.anchors], dim=0) else: anchors = torch.cat(self.anchors, dim=-3) else: anchors = self.anchors anchors = anchors.view(1, -1, anchors.shape[-1]).repeat(batch_size, 1, 1) box_preds = box_preds.view(batch_size, -1, box_preds.shape[-1] // self.num_anchors_per_location if not self.use_multihead else box_preds.shape[-1]) # sin(a - b) = sinacosb-cosasinb box_preds_sin, reg_targets_sin = self.add_sin_difference(box_preds, box_reg_targets) loc_loss_src = self.reg_loss_func(box_preds_sin, reg_targets_sin, weights=reg_weights) # [N, M] loc_loss = loc_loss_src.sum() / batch_size loc_loss = loc_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['loc_weight'] box_loss = loc_loss tb_dict = { 'rpn_loss_loc': loc_loss.item() } if box_dir_cls_preds is not None: dir_targets = self.get_direction_target( anchors, box_reg_targets, dir_offset=self.model_cfg.DIR_OFFSET, num_bins=self.model_cfg.NUM_DIR_BINS ) dir_logits = box_dir_cls_preds.view(batch_size, -1, self.model_cfg.NUM_DIR_BINS) weights = positives.type_as(dir_logits) weights /= torch.clamp(weights.sum(-1, keepdim=True), min=1.0) dir_loss = self.dir_loss_func(dir_logits, dir_targets, weights=weights) dir_loss = dir_loss.sum() / batch_size dir_loss = dir_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['dir_weight'] box_loss += dir_loss tb_dict['rpn_loss_dir'] = dir_loss.item() return box_loss, tb_dict def get_loss(self): cls_loss, tb_dict = self.get_cls_layer_loss() box_loss, tb_dict_box = self.get_box_reg_layer_loss() tb_dict.update(tb_dict_box) rpn_loss = cls_loss + box_loss tb_dict['rpn_loss'] = rpn_loss.item() return rpn_loss, tb_dict def generate_predicted_boxes(self, batch_size, cls_preds, box_preds, dir_cls_preds=None): """ Args: batch_size: cls_preds: (N, H, W, C1) box_preds: (N, H, W, C2) dir_cls_preds: (N, H, W, C3) Returns: batch_cls_preds: (B, num_boxes, num_classes) batch_box_preds: (B, num_boxes, 7+C) """ if isinstance(self.anchors, list): if self.use_multihead: anchors = torch.cat([anchor.permute(3, 4, 0, 1, 2, 5).contiguous().view(-1, anchor.shape[-1]) for anchor in self.anchors], dim=0) else: anchors = torch.cat(self.anchors, dim=-3) else: anchors = self.anchors num_anchors = anchors.view(-1, anchors.shape[-1]).shape[0] batch_anchors = anchors.view(1, -1, anchors.shape[-1]).repeat(batch_size, 1, 1) batch_cls_preds = cls_preds.view(batch_size, num_anchors, -1).float() \ if not isinstance(cls_preds, list) else cls_preds batch_box_preds = box_preds.view(batch_size, num_anchors, -1) if not isinstance(box_preds, list) \ else torch.cat(box_preds, dim=1).view(batch_size, num_anchors, -1) batch_box_preds = self.box_coder.decode_torch(batch_box_preds, batch_anchors) if dir_cls_preds is not None: dir_offset = self.model_cfg.DIR_OFFSET dir_limit_offset = self.model_cfg.DIR_LIMIT_OFFSET dir_cls_preds = dir_cls_preds.view(batch_size, num_anchors, -1) if not isinstance(dir_cls_preds, list) \ else torch.cat(dir_cls_preds, dim=1).view(batch_size, num_anchors, -1) dir_labels = torch.max(dir_cls_preds, dim=-1)[1] period = (2 * np.pi / self.model_cfg.NUM_DIR_BINS) dir_rot = common_utils.limit_period( batch_box_preds[..., 6] - dir_offset, dir_limit_offset, period ) batch_box_preds[..., 6] = dir_rot + dir_offset + period * dir_labels.to(batch_box_preds.dtype) if isinstance(self.box_coder, box_coder_utils.PreviousResidualDecoder): batch_box_preds[..., 6] = common_utils.limit_period( -(batch_box_preds[..., 6] + np.pi / 2), offset=0.5, period=np.pi * 2 ) return batch_cls_preds, batch_box_preds def forward(self, **kwargs): raise NotImplementedError
12,364
43.800725
118
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/center_head_semi.py
import copy import numpy as np import torch import torch.nn as nn from torch.nn.init import kaiming_normal_ from ..model_utils import model_nms_utils from ..model_utils import centernet_utils from ...utils import loss_utils class SeparateHead(nn.Module): def __init__(self, input_channels, sep_head_dict, init_bias=-2.19, use_bias=False): super().__init__() self.sep_head_dict = sep_head_dict for cur_name in self.sep_head_dict: output_channels = self.sep_head_dict[cur_name]['out_channels'] num_conv = self.sep_head_dict[cur_name]['num_conv'] fc_list = [] for k in range(num_conv - 1): fc_list.append(nn.Sequential( nn.Conv2d(input_channels, input_channels, kernel_size=3, stride=1, padding=1, bias=use_bias), nn.BatchNorm2d(input_channels), nn.ReLU() )) fc_list.append(nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=1, padding=1, bias=True)) fc = nn.Sequential(*fc_list) if 'hm' in cur_name: fc[-1].bias.data.fill_(init_bias) else: for m in fc.modules(): if isinstance(m, nn.Conv2d): kaiming_normal_(m.weight.data) if hasattr(m, "bias") and m.bias is not None: nn.init.constant_(m.bias, 0) self.__setattr__(cur_name, fc) def forward(self, x): ret_dict = {} for cur_name in self.sep_head_dict: ret_dict[cur_name] = self.__getattr__(cur_name)(x) return ret_dict class CenterHeadSemi(nn.Module): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, voxel_size, predict_boxes_when_training=True): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.grid_size = grid_size self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size self.feature_map_stride = self.model_cfg.TARGET_ASSIGNER_CONFIG.get('FEATURE_MAP_STRIDE', None) self.class_names = class_names self.class_names_each_head = [] self.class_id_mapping_each_head = [] for cur_class_names in self.model_cfg.CLASS_NAMES_EACH_HEAD: self.class_names_each_head.append([x for x in cur_class_names if x in class_names]) cur_class_id_mapping = torch.from_numpy(np.array( [self.class_names.index(x) for x in cur_class_names if x in class_names] )).cuda() self.class_id_mapping_each_head.append(cur_class_id_mapping) total_classes = sum([len(x) for x in self.class_names_each_head]) assert total_classes == len(self.class_names), f'class_names_each_head={self.class_names_each_head}' self.shared_conv = nn.Sequential( nn.Conv2d( input_channels, self.model_cfg.SHARED_CONV_CHANNEL, 3, stride=1, padding=1, bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ), nn.BatchNorm2d(self.model_cfg.SHARED_CONV_CHANNEL), nn.ReLU(), ) self.heads_list = nn.ModuleList() self.separate_head_cfg = self.model_cfg.SEPARATE_HEAD_CFG for idx, cur_class_names in enumerate(self.class_names_each_head): cur_head_dict = copy.deepcopy(self.separate_head_cfg.HEAD_DICT) cur_head_dict['hm'] = dict(out_channels=len(cur_class_names), num_conv=self.model_cfg.NUM_HM_CONV) self.heads_list.append( SeparateHead( input_channels=self.model_cfg.SHARED_CONV_CHANNEL, sep_head_dict=cur_head_dict, init_bias=-2.19, use_bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ) ) self.predict_boxes_when_training = predict_boxes_when_training self.forward_ret_dict = {} self.build_losses() self.model_type = None def build_losses(self): self.add_module('hm_loss_func', loss_utils.FocalLossCenterNet()) self.add_module('reg_loss_func', loss_utils.RegLossCenterNet()) def assign_target_of_single_head( self, num_classes, gt_boxes, feature_map_size, feature_map_stride, num_max_objs=500, gaussian_overlap=0.1, min_radius=2 ): """ Args: gt_boxes: (N, 8) feature_map_size: (2), [x, y] Returns: """ heatmap = gt_boxes.new_zeros(num_classes, feature_map_size[1], feature_map_size[0]) ret_boxes = gt_boxes.new_zeros((num_max_objs, gt_boxes.shape[-1] - 1 + 1)) inds = gt_boxes.new_zeros(num_max_objs).long() mask = gt_boxes.new_zeros(num_max_objs).long() x, y, z = gt_boxes[:, 0], gt_boxes[:, 1], gt_boxes[:, 2] coord_x = (x - self.point_cloud_range[0]) / self.voxel_size[0] / feature_map_stride coord_y = (y - self.point_cloud_range[1]) / self.voxel_size[1] / feature_map_stride coord_x = torch.clamp(coord_x, min=0, max=feature_map_size[0] - 0.5) # bugfixed: 1e-6 does not work for center.int() coord_y = torch.clamp(coord_y, min=0, max=feature_map_size[1] - 0.5) # center = torch.cat((coord_x[:, None], coord_y[:, None]), dim=-1) center_int = center.int() center_int_float = center_int.float() dx, dy, dz = gt_boxes[:, 3], gt_boxes[:, 4], gt_boxes[:, 5] dx = dx / self.voxel_size[0] / feature_map_stride dy = dy / self.voxel_size[1] / feature_map_stride radius = centernet_utils.gaussian_radius(dx, dy, min_overlap=gaussian_overlap) radius = torch.clamp_min(radius.int(), min=min_radius) for k in range(min(num_max_objs, gt_boxes.shape[0])): if dx[k] <= 0 or dy[k] <= 0: continue if not (0 <= center_int[k][0] <= feature_map_size[0] and 0 <= center_int[k][1] <= feature_map_size[1]): continue cur_class_id = (gt_boxes[k, -1] - 1).long() centernet_utils.draw_gaussian_to_heatmap(heatmap[cur_class_id], center[k], radius[k].item()) inds[k] = center_int[k, 1] * feature_map_size[0] + center_int[k, 0] mask[k] = 1 ret_boxes[k, 0:2] = center[k] - center_int_float[k].float() ret_boxes[k, 2] = z[k] ret_boxes[k, 3:6] = gt_boxes[k, 3:6].log() ret_boxes[k, 6] = torch.cos(gt_boxes[k, 6]) ret_boxes[k, 7] = torch.sin(gt_boxes[k, 6]) if gt_boxes.shape[1] > 8: ret_boxes[k, 8:] = gt_boxes[k, 7:-1] return heatmap, ret_boxes, inds, mask def assign_targets(self, gt_boxes, feature_map_size=None, **kwargs): """ Args: gt_boxes: (B, M, 8) range_image_polar: (B, 3, H, W) feature_map_size: (2) [H, W] spatial_cartesian: (B, 4, H, W) Returns: """ feature_map_size = feature_map_size[::-1] # [H, W] ==> [x, y] target_assigner_cfg = self.model_cfg.TARGET_ASSIGNER_CONFIG # feature_map_size = self.grid_size[:2] // target_assigner_cfg.FEATURE_MAP_STRIDE batch_size = gt_boxes.shape[0] ret_dict = { 'heatmaps': [], 'target_boxes': [], 'inds': [], 'masks': [], 'heatmap_masks': [] } all_names = np.array(['bg', *self.class_names]) for idx, cur_class_names in enumerate(self.class_names_each_head): heatmap_list, target_boxes_list, inds_list, masks_list = [], [], [], [] for bs_idx in range(batch_size): cur_gt_boxes = gt_boxes[bs_idx] gt_class_names = all_names[cur_gt_boxes[:, -1].cpu().long().numpy()] gt_boxes_single_head = [] for idx, name in enumerate(gt_class_names): if name not in cur_class_names: continue temp_box = cur_gt_boxes[idx] temp_box[-1] = cur_class_names.index(name) + 1 gt_boxes_single_head.append(temp_box[None, :]) if len(gt_boxes_single_head) == 0: gt_boxes_single_head = cur_gt_boxes[:0, :] else: gt_boxes_single_head = torch.cat(gt_boxes_single_head, dim=0) heatmap, ret_boxes, inds, mask = self.assign_target_of_single_head( num_classes=len(cur_class_names), gt_boxes=gt_boxes_single_head.cpu(), feature_map_size=feature_map_size, feature_map_stride=target_assigner_cfg.FEATURE_MAP_STRIDE, num_max_objs=target_assigner_cfg.NUM_MAX_OBJS, gaussian_overlap=target_assigner_cfg.GAUSSIAN_OVERLAP, min_radius=target_assigner_cfg.MIN_RADIUS, ) heatmap_list.append(heatmap.to(gt_boxes_single_head.device)) target_boxes_list.append(ret_boxes.to(gt_boxes_single_head.device)) inds_list.append(inds.to(gt_boxes_single_head.device)) masks_list.append(mask.to(gt_boxes_single_head.device)) ret_dict['heatmaps'].append(torch.stack(heatmap_list, dim=0)) ret_dict['target_boxes'].append(torch.stack(target_boxes_list, dim=0)) ret_dict['inds'].append(torch.stack(inds_list, dim=0)) ret_dict['masks'].append(torch.stack(masks_list, dim=0)) return ret_dict def sigmoid(self, x): y = torch.clamp(x.sigmoid(), min=1e-4, max=1 - 1e-4) return y def get_loss(self): pred_dicts = self.forward_ret_dict['pred_dicts'] target_dicts = self.forward_ret_dict['target_dicts'] tb_dict = {} loss = 0 for idx, pred_dict in enumerate(pred_dicts): pred_dict['hm'] = self.sigmoid(pred_dict['hm']) hm_loss = self.hm_loss_func(pred_dict['hm'], target_dicts['heatmaps'][idx]) hm_loss *= self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['cls_weight'] target_boxes = target_dicts['target_boxes'][idx] pred_boxes = torch.cat([pred_dict[head_name] for head_name in self.separate_head_cfg.HEAD_ORDER], dim=1) reg_loss = self.reg_loss_func( pred_boxes, target_dicts['masks'][idx], target_dicts['inds'][idx], target_boxes ) loc_loss = (reg_loss * reg_loss.new_tensor(self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['code_weights'])).sum() loc_loss = loc_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['loc_weight'] loss += hm_loss + loc_loss tb_dict['hm_loss_head_%d' % idx] = hm_loss.item() tb_dict['loc_loss_head_%d' % idx] = loc_loss.item() tb_dict['rpn_loss'] = loss.item() return loss, tb_dict def generate_predicted_boxes(self, batch_size, pred_dicts): post_process_cfg = self.model_cfg.POST_PROCESSING post_center_limit_range = torch.tensor(post_process_cfg.POST_CENTER_LIMIT_RANGE).cuda().float() ret_dict = [{ 'pred_boxes': [], 'pred_scores': [], 'pred_labels': [], } for k in range(batch_size)] for idx, pred_dict in enumerate(pred_dicts): batch_hm = pred_dict['hm'].sigmoid() batch_center = pred_dict['center'] batch_center_z = pred_dict['center_z'] batch_dim = pred_dict['dim'].exp() batch_rot_cos = pred_dict['rot'][:, 0].unsqueeze(dim=1) batch_rot_sin = pred_dict['rot'][:, 1].unsqueeze(dim=1) batch_vel = pred_dict['vel'] if 'vel' in self.separate_head_cfg.HEAD_ORDER else None final_pred_dicts = centernet_utils.decode_bbox_from_heatmap( heatmap=batch_hm, rot_cos=batch_rot_cos, rot_sin=batch_rot_sin, center=batch_center, center_z=batch_center_z, dim=batch_dim, vel=batch_vel, point_cloud_range=self.point_cloud_range, voxel_size=self.voxel_size, feature_map_stride=self.feature_map_stride, K=post_process_cfg.MAX_OBJ_PER_SAMPLE, circle_nms=(post_process_cfg.NMS_CONFIG.NMS_TYPE == 'circle_nms'), score_thresh=post_process_cfg.SCORE_THRESH, post_center_limit_range=post_center_limit_range ) for k, final_dict in enumerate(final_pred_dicts): final_dict['pred_labels'] = self.class_id_mapping_each_head[idx][final_dict['pred_labels'].long()] if post_process_cfg.NMS_CONFIG.NMS_TYPE != 'circle_nms': selected, selected_scores = model_nms_utils.class_agnostic_nms( box_scores=final_dict['pred_scores'], box_preds=final_dict['pred_boxes'], nms_config=post_process_cfg.NMS_CONFIG, score_thresh=None ) final_dict['pred_boxes'] = final_dict['pred_boxes'][selected] final_dict['pred_scores'] = selected_scores final_dict['pred_labels'] = final_dict['pred_labels'][selected] ret_dict[k]['pred_boxes'].append(final_dict['pred_boxes']) ret_dict[k]['pred_scores'].append(final_dict['pred_scores']) ret_dict[k]['pred_labels'].append(final_dict['pred_labels']) for k in range(batch_size): ret_dict[k]['pred_boxes'] = torch.cat(ret_dict[k]['pred_boxes'], dim=0) ret_dict[k]['pred_scores'] = torch.cat(ret_dict[k]['pred_scores'], dim=0) ret_dict[k]['pred_labels'] = torch.cat(ret_dict[k]['pred_labels'], dim=0) + 1 return ret_dict @staticmethod def reorder_rois_for_refining(batch_size, pred_dicts): num_max_rois = max([len(cur_dict['pred_boxes']) for cur_dict in pred_dicts]) num_max_rois = max(1, num_max_rois) # at least one faked rois to avoid error pred_boxes = pred_dicts[0]['pred_boxes'] rois = pred_boxes.new_zeros((batch_size, num_max_rois, pred_boxes.shape[-1])) roi_scores = pred_boxes.new_zeros((batch_size, num_max_rois)) roi_labels = pred_boxes.new_zeros((batch_size, num_max_rois)).long() for bs_idx in range(batch_size): num_boxes = len(pred_dicts[bs_idx]['pred_boxes']) rois[bs_idx, :num_boxes, :] = pred_dicts[bs_idx]['pred_boxes'] roi_scores[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_scores'] roi_labels[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_labels'] return rois, roi_scores, roi_labels def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] x = self.shared_conv(spatial_features_2d) pred_dicts = [] for head in self.heads_list: pred_dicts.append(head(x)) if self.model_type == 'origin': if self.training: target_dict = self.assign_targets( data_dict['gt_boxes'], feature_map_size=spatial_features_2d.size()[2:], feature_map_stride=data_dict.get('spatial_features_2d_strides', None) ) self.forward_ret_dict['target_dicts'] = target_dict self.forward_ret_dict['pred_dicts'] = pred_dicts if not self.training or self.predict_boxes_when_training: pred_dicts = self.generate_predicted_boxes( data_dict['batch_size'], pred_dicts ) if self.predict_boxes_when_training: rois, roi_scores, roi_labels = self.reorder_rois_for_refining(data_dict['batch_size'], pred_dicts) data_dict['rois'] = rois data_dict['roi_scores'] = roi_scores data_dict['roi_labels'] = roi_labels data_dict['has_class_labels'] = True else: data_dict['final_box_dicts'] = pred_dicts elif self.model_type == 'teacher': self.forward_ret_dict['pred_dicts'] = pred_dicts pred_dicts = self.generate_predicted_boxes( data_dict['batch_size'], pred_dicts ) if self.predict_boxes_when_training: rois, roi_scores, roi_labels = self.reorder_rois_for_refining(data_dict['batch_size'], pred_dicts) data_dict['rois'] = rois data_dict['roi_scores'] = roi_scores data_dict['roi_labels'] = roi_labels data_dict['has_class_labels'] = True else: data_dict['final_box_dicts'] = pred_dicts elif self.model_type == 'student': if self.training: if 'gt_boxes' in data_dict: target_dict = self.assign_targets( data_dict['gt_boxes'], feature_map_size=spatial_features_2d.size()[2:], feature_map_stride=data_dict.get('spatial_features_2d_strides', None) ) self.forward_ret_dict['target_dicts'] = target_dict self.forward_ret_dict['pred_dicts'] = pred_dicts if not self.training or self.predict_boxes_when_training: pred_dicts = self.generate_predicted_boxes( data_dict['batch_size'], pred_dicts ) if self.predict_boxes_when_training: rois, roi_scores, roi_labels = self.reorder_rois_for_refining(data_dict['batch_size'], pred_dicts) data_dict['rois'] = rois data_dict['roi_scores'] = roi_scores data_dict['roi_labels'] = roi_labels data_dict['has_class_labels'] = True else: data_dict['final_box_dicts'] = pred_dicts else: raise Exception('Unsupprted model type') return data_dict
18,189
44.588972
125
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/anchor_head_multi.py
import numpy as np import torch import torch.nn as nn from ..backbones_2d import BaseBEVBackbone from .anchor_head_template import AnchorHeadTemplate class SingleHead(BaseBEVBackbone): def __init__(self, model_cfg, input_channels, num_class, num_anchors_per_location, code_size, rpn_head_cfg=None, head_label_indices=None, separate_reg_config=None): super().__init__(rpn_head_cfg, input_channels) self.num_anchors_per_location = num_anchors_per_location self.num_class = num_class self.code_size = code_size self.model_cfg = model_cfg self.separate_reg_config = separate_reg_config self.register_buffer('head_label_indices', head_label_indices) if self.separate_reg_config is not None: code_size_cnt = 0 self.conv_box = nn.ModuleDict() self.conv_box_names = [] num_middle_conv = self.separate_reg_config.NUM_MIDDLE_CONV num_middle_filter = self.separate_reg_config.NUM_MIDDLE_FILTER conv_cls_list = [] c_in = input_channels for k in range(num_middle_conv): conv_cls_list.extend([ nn.Conv2d( c_in, num_middle_filter, kernel_size=3, stride=1, padding=1, bias=False ), nn.BatchNorm2d(num_middle_filter), nn.ReLU() ]) c_in = num_middle_filter conv_cls_list.append(nn.Conv2d( c_in, self.num_anchors_per_location * self.num_class, kernel_size=3, stride=1, padding=1 )) self.conv_cls = nn.Sequential(*conv_cls_list) for reg_config in self.separate_reg_config.REG_LIST: reg_name, reg_channel = reg_config.split(':') reg_channel = int(reg_channel) cur_conv_list = [] c_in = input_channels for k in range(num_middle_conv): cur_conv_list.extend([ nn.Conv2d( c_in, num_middle_filter, kernel_size=3, stride=1, padding=1, bias=False ), nn.BatchNorm2d(num_middle_filter), nn.ReLU() ]) c_in = num_middle_filter cur_conv_list.append(nn.Conv2d( c_in, self.num_anchors_per_location * int(reg_channel), kernel_size=3, stride=1, padding=1, bias=True )) code_size_cnt += reg_channel self.conv_box[f'conv_{reg_name}'] = nn.Sequential(*cur_conv_list) self.conv_box_names.append(f'conv_{reg_name}') for m in self.conv_box.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') if m.bias is not None: nn.init.constant_(m.bias, 0) assert code_size_cnt == code_size, f'Code size does not match: {code_size_cnt}:{code_size}' else: self.conv_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_box = nn.Conv2d( input_channels, self.num_anchors_per_location * self.code_size, kernel_size=1 ) if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', None) is not None: self.conv_dir_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.model_cfg.NUM_DIR_BINS, kernel_size=1 ) else: self.conv_dir_cls = None self.use_multihead = self.model_cfg.get('USE_MULTIHEAD', False) self.init_weights() def init_weights(self): pi = 0.01 if isinstance(self.conv_cls, nn.Conv2d): nn.init.constant_(self.conv_cls.bias, -np.log((1 - pi) / pi)) else: nn.init.constant_(self.conv_cls[-1].bias, -np.log((1 - pi) / pi)) def forward(self, spatial_features_2d): ret_dict = {} spatial_features_2d = super().forward({'spatial_features': spatial_features_2d})['spatial_features_2d'] cls_preds = self.conv_cls(spatial_features_2d) if self.separate_reg_config is None: box_preds = self.conv_box(spatial_features_2d) else: box_preds_list = [] for reg_name in self.conv_box_names: box_preds_list.append(self.conv_box[reg_name](spatial_features_2d)) box_preds = torch.cat(box_preds_list, dim=1) if not self.use_multihead: box_preds = box_preds.permute(0, 2, 3, 1).contiguous() cls_preds = cls_preds.permute(0, 2, 3, 1).contiguous() else: H, W = box_preds.shape[2:] batch_size = box_preds.shape[0] box_preds = box_preds.view(-1, self.num_anchors_per_location, self.code_size, H, W).permute(0, 1, 3, 4, 2).contiguous() cls_preds = cls_preds.view(-1, self.num_anchors_per_location, self.num_class, H, W).permute(0, 1, 3, 4, 2).contiguous() box_preds = box_preds.view(batch_size, -1, self.code_size) cls_preds = cls_preds.view(batch_size, -1, self.num_class) if self.conv_dir_cls is not None: dir_cls_preds = self.conv_dir_cls(spatial_features_2d) if self.use_multihead: dir_cls_preds = dir_cls_preds.view( -1, self.num_anchors_per_location, self.model_cfg.NUM_DIR_BINS, H, W).permute(0, 1, 3, 4, 2).contiguous() dir_cls_preds = dir_cls_preds.view(batch_size, -1, self.model_cfg.NUM_DIR_BINS) else: dir_cls_preds = dir_cls_preds.permute(0, 2, 3, 1).contiguous() else: dir_cls_preds = None ret_dict['cls_preds'] = cls_preds ret_dict['box_preds'] = box_preds ret_dict['dir_cls_preds'] = dir_cls_preds return ret_dict class AnchorHeadMulti(AnchorHeadTemplate): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, predict_boxes_when_training=True, **kwargs): super().__init__( model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_range=point_cloud_range, predict_boxes_when_training=predict_boxes_when_training ) self.model_cfg = model_cfg self.separate_multihead = self.model_cfg.get('SEPARATE_MULTIHEAD', False) if self.model_cfg.get('SHARED_CONV_NUM_FILTER', None) is not None: shared_conv_num_filter = self.model_cfg.SHARED_CONV_NUM_FILTER self.shared_conv = nn.Sequential( nn.Conv2d(input_channels, shared_conv_num_filter, 3, stride=1, padding=1, bias=False), nn.BatchNorm2d(shared_conv_num_filter, eps=1e-3, momentum=0.01), nn.ReLU(), ) else: self.shared_conv = None shared_conv_num_filter = input_channels self.rpn_heads = None self.make_multihead(shared_conv_num_filter) def make_multihead(self, input_channels): rpn_head_cfgs = self.model_cfg.RPN_HEAD_CFGS rpn_heads = [] class_names = [] for rpn_head_cfg in rpn_head_cfgs: class_names.extend(rpn_head_cfg['HEAD_CLS_NAME']) for rpn_head_cfg in rpn_head_cfgs: num_anchors_per_location = sum([self.num_anchors_per_location[class_names.index(head_cls)] for head_cls in rpn_head_cfg['HEAD_CLS_NAME']]) head_label_indices = torch.from_numpy(np.array([ self.class_names.index(cur_name) + 1 for cur_name in rpn_head_cfg['HEAD_CLS_NAME'] ])) rpn_head = SingleHead( self.model_cfg, input_channels, len(rpn_head_cfg['HEAD_CLS_NAME']) if self.separate_multihead else self.num_class, num_anchors_per_location, self.box_coder.code_size, rpn_head_cfg, head_label_indices=head_label_indices, separate_reg_config=self.model_cfg.get('SEPARATE_REG_CONFIG', None) ) rpn_heads.append(rpn_head) self.rpn_heads = nn.ModuleList(rpn_heads) def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] if self.shared_conv is not None: spatial_features_2d = self.shared_conv(spatial_features_2d) ret_dicts = [] for rpn_head in self.rpn_heads: ret_dicts.append(rpn_head(spatial_features_2d)) cls_preds = [ret_dict['cls_preds'] for ret_dict in ret_dicts] box_preds = [ret_dict['box_preds'] for ret_dict in ret_dicts] ret = { 'cls_preds': cls_preds if self.separate_multihead else torch.cat(cls_preds, dim=1), 'box_preds': box_preds if self.separate_multihead else torch.cat(box_preds, dim=1), } if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', False): dir_cls_preds = [ret_dict['dir_cls_preds'] for ret_dict in ret_dicts] ret['dir_cls_preds'] = dir_cls_preds if self.separate_multihead else torch.cat(dir_cls_preds, dim=1) self.forward_ret_dict.update(ret) if self.training: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=ret['cls_preds'], box_preds=ret['box_preds'], dir_cls_preds=ret.get('dir_cls_preds', None) ) if isinstance(batch_cls_preds, list): multihead_label_mapping = [] for idx in range(len(batch_cls_preds)): multihead_label_mapping.append(self.rpn_heads[idx].head_label_indices) data_dict['multihead_label_mapping'] = multihead_label_mapping data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False return data_dict def get_cls_layer_loss(self): loss_weights = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS if 'pos_cls_weight' in loss_weights: pos_cls_weight = loss_weights['pos_cls_weight'] neg_cls_weight = loss_weights['neg_cls_weight'] else: pos_cls_weight = neg_cls_weight = 1.0 cls_preds = self.forward_ret_dict['cls_preds'] box_cls_labels = self.forward_ret_dict['box_cls_labels'] if not isinstance(cls_preds, list): cls_preds = [cls_preds] batch_size = int(cls_preds[0].shape[0]) cared = box_cls_labels >= 0 # [N, num_anchors] positives = box_cls_labels > 0 negatives = box_cls_labels == 0 negative_cls_weights = negatives * 1.0 * neg_cls_weight cls_weights = (negative_cls_weights + pos_cls_weight * positives).float() reg_weights = positives.float() if self.num_class == 1: # class agnostic box_cls_labels[positives] = 1 pos_normalizer = positives.sum(1, keepdim=True).float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) cls_weights /= torch.clamp(pos_normalizer, min=1.0) cls_targets = box_cls_labels * cared.type_as(box_cls_labels) one_hot_targets = torch.zeros( *list(cls_targets.shape), self.num_class + 1, dtype=cls_preds[0].dtype, device=cls_targets.device ) one_hot_targets.scatter_(-1, cls_targets.unsqueeze(dim=-1).long(), 1.0) one_hot_targets = one_hot_targets[..., 1:] start_idx = c_idx = 0 cls_losses = 0 for idx, cls_pred in enumerate(cls_preds): cur_num_class = self.rpn_heads[idx].num_class cls_pred = cls_pred.view(batch_size, -1, cur_num_class) if self.separate_multihead: one_hot_target = one_hot_targets[:, start_idx:start_idx + cls_pred.shape[1], c_idx:c_idx + cur_num_class] c_idx += cur_num_class else: one_hot_target = one_hot_targets[:, start_idx:start_idx + cls_pred.shape[1]] cls_weight = cls_weights[:, start_idx:start_idx + cls_pred.shape[1]] cls_loss_src = self.cls_loss_func(cls_pred, one_hot_target, weights=cls_weight) # [N, M] cls_loss = cls_loss_src.sum() / batch_size cls_loss = cls_loss * loss_weights['cls_weight'] cls_losses += cls_loss start_idx += cls_pred.shape[1] assert start_idx == one_hot_targets.shape[1] tb_dict = { 'rpn_loss_cls': cls_losses.item() } return cls_losses, tb_dict def get_box_reg_layer_loss(self): box_preds = self.forward_ret_dict['box_preds'] box_dir_cls_preds = self.forward_ret_dict.get('dir_cls_preds', None) box_reg_targets = self.forward_ret_dict['box_reg_targets'] box_cls_labels = self.forward_ret_dict['box_cls_labels'] positives = box_cls_labels > 0 reg_weights = positives.float() pos_normalizer = positives.sum(1, keepdim=True).float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) if not isinstance(box_preds, list): box_preds = [box_preds] batch_size = int(box_preds[0].shape[0]) if isinstance(self.anchors, list): if self.use_multihead: anchors = torch.cat( [anchor.permute(3, 4, 0, 1, 2, 5).contiguous().view(-1, anchor.shape[-1]) for anchor in self.anchors], dim=0 ) else: anchors = torch.cat(self.anchors, dim=-3) else: anchors = self.anchors anchors = anchors.view(1, -1, anchors.shape[-1]).repeat(batch_size, 1, 1) start_idx = 0 box_losses = 0 tb_dict = {} for idx, box_pred in enumerate(box_preds): box_pred = box_pred.view( batch_size, -1, box_pred.shape[-1] // self.num_anchors_per_location if not self.use_multihead else box_pred.shape[-1] ) box_reg_target = box_reg_targets[:, start_idx:start_idx + box_pred.shape[1]] reg_weight = reg_weights[:, start_idx:start_idx + box_pred.shape[1]] # sin(a - b) = sinacosb-cosasinb if box_dir_cls_preds is not None: box_pred_sin, reg_target_sin = self.add_sin_difference(box_pred, box_reg_target) loc_loss_src = self.reg_loss_func(box_pred_sin, reg_target_sin, weights=reg_weight) # [N, M] else: loc_loss_src = self.reg_loss_func(box_pred, box_reg_target, weights=reg_weight) # [N, M] loc_loss = loc_loss_src.sum() / batch_size loc_loss = loc_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['loc_weight'] box_losses += loc_loss tb_dict['rpn_loss_loc'] = tb_dict.get('rpn_loss_loc', 0) + loc_loss.item() if box_dir_cls_preds is not None: if not isinstance(box_dir_cls_preds, list): box_dir_cls_preds = [box_dir_cls_preds] dir_targets = self.get_direction_target( anchors, box_reg_targets, dir_offset=self.model_cfg.DIR_OFFSET, num_bins=self.model_cfg.NUM_DIR_BINS ) box_dir_cls_pred = box_dir_cls_preds[idx] dir_logit = box_dir_cls_pred.view(batch_size, -1, self.model_cfg.NUM_DIR_BINS) weights = positives.type_as(dir_logit) weights /= torch.clamp(weights.sum(-1, keepdim=True), min=1.0) weight = weights[:, start_idx:start_idx + box_pred.shape[1]] dir_target = dir_targets[:, start_idx:start_idx + box_pred.shape[1]] dir_loss = self.dir_loss_func(dir_logit, dir_target, weights=weight) dir_loss = dir_loss.sum() / batch_size dir_loss = dir_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['dir_weight'] box_losses += dir_loss tb_dict['rpn_loss_dir'] = tb_dict.get('rpn_loss_dir', 0) + dir_loss.item() start_idx += box_pred.shape[1] return box_losses, tb_dict
17,041
44.566845
117
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/center_head.py
import copy import numpy as np import torch import torch.nn as nn from torch.nn.init import kaiming_normal_ from ..model_utils import model_nms_utils from ..model_utils import centernet_utils from ...utils import loss_utils class SeparateHead(nn.Module): def __init__(self, input_channels, sep_head_dict, init_bias=-2.19, use_bias=False): super().__init__() self.sep_head_dict = sep_head_dict for cur_name in self.sep_head_dict: output_channels = self.sep_head_dict[cur_name]['out_channels'] num_conv = self.sep_head_dict[cur_name]['num_conv'] fc_list = [] for k in range(num_conv - 1): fc_list.append(nn.Sequential( nn.Conv2d(input_channels, input_channels, kernel_size=3, stride=1, padding=1, bias=use_bias), nn.BatchNorm2d(input_channels), nn.ReLU() )) fc_list.append(nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=1, padding=1, bias=True)) fc = nn.Sequential(*fc_list) if 'hm' in cur_name: fc[-1].bias.data.fill_(init_bias) else: for m in fc.modules(): if isinstance(m, nn.Conv2d): kaiming_normal_(m.weight.data) if hasattr(m, "bias") and m.bias is not None: nn.init.constant_(m.bias, 0) self.__setattr__(cur_name, fc) def forward(self, x): ret_dict = {} for cur_name in self.sep_head_dict: ret_dict[cur_name] = self.__getattr__(cur_name)(x) return ret_dict class CenterHead(nn.Module): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, voxel_size, predict_boxes_when_training=True): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.grid_size = grid_size self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size self.feature_map_stride = self.model_cfg.TARGET_ASSIGNER_CONFIG.get('FEATURE_MAP_STRIDE', None) self.class_names = class_names self.class_names_each_head = [] self.class_id_mapping_each_head = [] for cur_class_names in self.model_cfg.CLASS_NAMES_EACH_HEAD: self.class_names_each_head.append([x for x in cur_class_names if x in class_names]) cur_class_id_mapping = torch.from_numpy(np.array( [self.class_names.index(x) for x in cur_class_names if x in class_names] )).cuda() self.class_id_mapping_each_head.append(cur_class_id_mapping) total_classes = sum([len(x) for x in self.class_names_each_head]) assert total_classes == len(self.class_names), f'class_names_each_head={self.class_names_each_head}' self.shared_conv = nn.Sequential( nn.Conv2d( input_channels, self.model_cfg.SHARED_CONV_CHANNEL, 3, stride=1, padding=1, bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ), nn.BatchNorm2d(self.model_cfg.SHARED_CONV_CHANNEL), nn.ReLU(), ) self.heads_list = nn.ModuleList() self.separate_head_cfg = self.model_cfg.SEPARATE_HEAD_CFG for idx, cur_class_names in enumerate(self.class_names_each_head): cur_head_dict = copy.deepcopy(self.separate_head_cfg.HEAD_DICT) cur_head_dict['hm'] = dict(out_channels=len(cur_class_names), num_conv=self.model_cfg.NUM_HM_CONV) self.heads_list.append( SeparateHead( input_channels=self.model_cfg.SHARED_CONV_CHANNEL, sep_head_dict=cur_head_dict, init_bias=-2.19, use_bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ) ) self.predict_boxes_when_training = predict_boxes_when_training self.forward_ret_dict = {} self.build_losses() def build_losses(self): self.add_module('hm_loss_func', loss_utils.FocalLossCenterNet()) self.add_module('reg_loss_func', loss_utils.RegLossCenterNet()) def assign_target_of_single_head( self, num_classes, gt_boxes, feature_map_size, feature_map_stride, num_max_objs=500, gaussian_overlap=0.1, min_radius=2 ): """ Args: gt_boxes: (N, 8) feature_map_size: (2), [x, y] Returns: """ heatmap = gt_boxes.new_zeros(num_classes, feature_map_size[1], feature_map_size[0]) ret_boxes = gt_boxes.new_zeros((num_max_objs, gt_boxes.shape[-1] - 1 + 1)) inds = gt_boxes.new_zeros(num_max_objs).long() mask = gt_boxes.new_zeros(num_max_objs).long() x, y, z = gt_boxes[:, 0], gt_boxes[:, 1], gt_boxes[:, 2] coord_x = (x - self.point_cloud_range[0]) / self.voxel_size[0] / feature_map_stride coord_y = (y - self.point_cloud_range[1]) / self.voxel_size[1] / feature_map_stride coord_x = torch.clamp(coord_x, min=0, max=feature_map_size[0] - 0.5) # bugfixed: 1e-6 does not work for center.int() coord_y = torch.clamp(coord_y, min=0, max=feature_map_size[1] - 0.5) # center = torch.cat((coord_x[:, None], coord_y[:, None]), dim=-1) center_int = center.int() center_int_float = center_int.float() dx, dy, dz = gt_boxes[:, 3], gt_boxes[:, 4], gt_boxes[:, 5] dx = dx / self.voxel_size[0] / feature_map_stride dy = dy / self.voxel_size[1] / feature_map_stride radius = centernet_utils.gaussian_radius(dx, dy, min_overlap=gaussian_overlap) radius = torch.clamp_min(radius.int(), min=min_radius) for k in range(min(num_max_objs, gt_boxes.shape[0])): if dx[k] <= 0 or dy[k] <= 0: continue if not (0 <= center_int[k][0] <= feature_map_size[0] and 0 <= center_int[k][1] <= feature_map_size[1]): continue cur_class_id = (gt_boxes[k, -1] - 1).long() centernet_utils.draw_gaussian_to_heatmap(heatmap[cur_class_id], center[k], radius[k].item()) inds[k] = center_int[k, 1] * feature_map_size[0] + center_int[k, 0] mask[k] = 1 ret_boxes[k, 0:2] = center[k] - center_int_float[k].float() ret_boxes[k, 2] = z[k] ret_boxes[k, 3:6] = gt_boxes[k, 3:6].log() ret_boxes[k, 6] = torch.cos(gt_boxes[k, 6]) ret_boxes[k, 7] = torch.sin(gt_boxes[k, 6]) if gt_boxes.shape[1] > 8: ret_boxes[k, 8:] = gt_boxes[k, 7:-1] return heatmap, ret_boxes, inds, mask def assign_targets(self, gt_boxes, feature_map_size=None, **kwargs): """ Args: gt_boxes: (B, M, 8) range_image_polar: (B, 3, H, W) feature_map_size: (2) [H, W] spatial_cartesian: (B, 4, H, W) Returns: """ feature_map_size = feature_map_size[::-1] # [H, W] ==> [x, y] target_assigner_cfg = self.model_cfg.TARGET_ASSIGNER_CONFIG # feature_map_size = self.grid_size[:2] // target_assigner_cfg.FEATURE_MAP_STRIDE batch_size = gt_boxes.shape[0] ret_dict = { 'heatmaps': [], 'target_boxes': [], 'inds': [], 'masks': [], 'heatmap_masks': [] } all_names = np.array(['bg', *self.class_names]) for idx, cur_class_names in enumerate(self.class_names_each_head): heatmap_list, target_boxes_list, inds_list, masks_list = [], [], [], [] for bs_idx in range(batch_size): cur_gt_boxes = gt_boxes[bs_idx] gt_class_names = all_names[cur_gt_boxes[:, -1].cpu().long().numpy()] gt_boxes_single_head = [] for idx, name in enumerate(gt_class_names): if name not in cur_class_names: continue temp_box = cur_gt_boxes[idx] temp_box[-1] = cur_class_names.index(name) + 1 gt_boxes_single_head.append(temp_box[None, :]) if len(gt_boxes_single_head) == 0: gt_boxes_single_head = cur_gt_boxes[:0, :] else: gt_boxes_single_head = torch.cat(gt_boxes_single_head, dim=0) heatmap, ret_boxes, inds, mask = self.assign_target_of_single_head( num_classes=len(cur_class_names), gt_boxes=gt_boxes_single_head.cpu(), feature_map_size=feature_map_size, feature_map_stride=target_assigner_cfg.FEATURE_MAP_STRIDE, num_max_objs=target_assigner_cfg.NUM_MAX_OBJS, gaussian_overlap=target_assigner_cfg.GAUSSIAN_OVERLAP, min_radius=target_assigner_cfg.MIN_RADIUS, ) heatmap_list.append(heatmap.to(gt_boxes_single_head.device)) target_boxes_list.append(ret_boxes.to(gt_boxes_single_head.device)) inds_list.append(inds.to(gt_boxes_single_head.device)) masks_list.append(mask.to(gt_boxes_single_head.device)) ret_dict['heatmaps'].append(torch.stack(heatmap_list, dim=0)) ret_dict['target_boxes'].append(torch.stack(target_boxes_list, dim=0)) ret_dict['inds'].append(torch.stack(inds_list, dim=0)) ret_dict['masks'].append(torch.stack(masks_list, dim=0)) return ret_dict def sigmoid(self, x): y = torch.clamp(x.sigmoid(), min=1e-4, max=1 - 1e-4) return y def get_loss(self): pred_dicts = self.forward_ret_dict['pred_dicts'] target_dicts = self.forward_ret_dict['target_dicts'] tb_dict = {} loss = 0 for idx, pred_dict in enumerate(pred_dicts): pred_dict['hm'] = self.sigmoid(pred_dict['hm']) hm_loss = self.hm_loss_func(pred_dict['hm'], target_dicts['heatmaps'][idx]) hm_loss *= self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['cls_weight'] target_boxes = target_dicts['target_boxes'][idx] pred_boxes = torch.cat([pred_dict[head_name] for head_name in self.separate_head_cfg.HEAD_ORDER], dim=1) reg_loss = self.reg_loss_func( pred_boxes, target_dicts['masks'][idx], target_dicts['inds'][idx], target_boxes ) loc_loss = (reg_loss * reg_loss.new_tensor(self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['code_weights'])).sum() loc_loss = loc_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['loc_weight'] loss += hm_loss + loc_loss tb_dict['hm_loss_head_%d' % idx] = hm_loss.item() tb_dict['loc_loss_head_%d' % idx] = loc_loss.item() tb_dict['rpn_loss'] = loss.item() return loss, tb_dict def generate_predicted_boxes(self, batch_size, pred_dicts): post_process_cfg = self.model_cfg.POST_PROCESSING post_center_limit_range = torch.tensor(post_process_cfg.POST_CENTER_LIMIT_RANGE).cuda().float() ret_dict = [{ 'pred_boxes': [], 'pred_scores': [], 'pred_labels': [], } for k in range(batch_size)] for idx, pred_dict in enumerate(pred_dicts): batch_hm = pred_dict['hm'].sigmoid() batch_center = pred_dict['center'] batch_center_z = pred_dict['center_z'] batch_dim = pred_dict['dim'].exp() batch_rot_cos = pred_dict['rot'][:, 0].unsqueeze(dim=1) batch_rot_sin = pred_dict['rot'][:, 1].unsqueeze(dim=1) batch_vel = pred_dict['vel'] if 'vel' in self.separate_head_cfg.HEAD_ORDER else None final_pred_dicts = centernet_utils.decode_bbox_from_heatmap( heatmap=batch_hm, rot_cos=batch_rot_cos, rot_sin=batch_rot_sin, center=batch_center, center_z=batch_center_z, dim=batch_dim, vel=batch_vel, point_cloud_range=self.point_cloud_range, voxel_size=self.voxel_size, feature_map_stride=self.feature_map_stride, K=post_process_cfg.MAX_OBJ_PER_SAMPLE, circle_nms=(post_process_cfg.NMS_CONFIG.NMS_TYPE == 'circle_nms'), score_thresh=post_process_cfg.SCORE_THRESH, post_center_limit_range=post_center_limit_range ) for k, final_dict in enumerate(final_pred_dicts): final_dict['pred_labels'] = self.class_id_mapping_each_head[idx][final_dict['pred_labels'].long()] if post_process_cfg.NMS_CONFIG.NMS_TYPE != 'circle_nms': selected, selected_scores = model_nms_utils.class_agnostic_nms( box_scores=final_dict['pred_scores'], box_preds=final_dict['pred_boxes'], nms_config=post_process_cfg.NMS_CONFIG, score_thresh=None ) final_dict['pred_boxes'] = final_dict['pred_boxes'][selected] final_dict['pred_scores'] = selected_scores final_dict['pred_labels'] = final_dict['pred_labels'][selected] ret_dict[k]['pred_boxes'].append(final_dict['pred_boxes']) ret_dict[k]['pred_scores'].append(final_dict['pred_scores']) ret_dict[k]['pred_labels'].append(final_dict['pred_labels']) for k in range(batch_size): ret_dict[k]['pred_boxes'] = torch.cat(ret_dict[k]['pred_boxes'], dim=0) ret_dict[k]['pred_scores'] = torch.cat(ret_dict[k]['pred_scores'], dim=0) ret_dict[k]['pred_labels'] = torch.cat(ret_dict[k]['pred_labels'], dim=0) + 1 return ret_dict @staticmethod def reorder_rois_for_refining(batch_size, pred_dicts): num_max_rois = max([len(cur_dict['pred_boxes']) for cur_dict in pred_dicts]) num_max_rois = max(1, num_max_rois) # at least one faked rois to avoid error pred_boxes = pred_dicts[0]['pred_boxes'] rois = pred_boxes.new_zeros((batch_size, num_max_rois, pred_boxes.shape[-1])) roi_scores = pred_boxes.new_zeros((batch_size, num_max_rois)) roi_labels = pred_boxes.new_zeros((batch_size, num_max_rois)).long() for bs_idx in range(batch_size): num_boxes = len(pred_dicts[bs_idx]['pred_boxes']) rois[bs_idx, :num_boxes, :] = pred_dicts[bs_idx]['pred_boxes'] roi_scores[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_scores'] roi_labels[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_labels'] return rois, roi_scores, roi_labels def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] x = self.shared_conv(spatial_features_2d) pred_dicts = [] for head in self.heads_list: pred_dicts.append(head(x)) if self.training: target_dict = self.assign_targets( data_dict['gt_boxes'], feature_map_size=spatial_features_2d.size()[2:], feature_map_stride=data_dict.get('spatial_features_2d_strides', None) ) self.forward_ret_dict['target_dicts'] = target_dict self.forward_ret_dict['pred_dicts'] = pred_dicts if not self.training or self.predict_boxes_when_training: pred_dicts = self.generate_predicted_boxes( data_dict['batch_size'], pred_dicts ) if self.predict_boxes_when_training: rois, roi_scores, roi_labels = self.reorder_rois_for_refining(data_dict['batch_size'], pred_dicts) data_dict['rois'] = rois data_dict['roi_scores'] = roi_scores data_dict['roi_labels'] = roi_labels data_dict['has_class_labels'] = True else: data_dict['final_box_dicts'] = pred_dicts return data_dict class ActiveCenterHead(nn.Module): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, point_cloud_range, voxel_size, predict_boxes_when_training=True): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.grid_size = grid_size self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size self.feature_map_stride = self.model_cfg.TARGET_ASSIGNER_CONFIG.get('FEATURE_MAP_STRIDE', None) self.class_names = class_names self.class_names_each_head = [] self.class_id_mapping_each_head = [] for cur_class_names in self.model_cfg.CLASS_NAMES_EACH_HEAD: self.class_names_each_head.append([x for x in cur_class_names if x in class_names]) cur_class_id_mapping = torch.from_numpy(np.array( [self.class_names.index(x) for x in cur_class_names if x in class_names] )).cuda() self.class_id_mapping_each_head.append(cur_class_id_mapping) total_classes = sum([len(x) for x in self.class_names_each_head]) assert total_classes == len(self.class_names), f'class_names_each_head={self.class_names_each_head}' self.shared_conv = nn.Sequential( nn.Conv2d( input_channels, self.model_cfg.SHARED_CONV_CHANNEL, 3, stride=1, padding=1, bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ), nn.BatchNorm2d(self.model_cfg.SHARED_CONV_CHANNEL), nn.ReLU(), ) self.heads_list = nn.ModuleList() self.separate_head_cfg = self.model_cfg.SEPARATE_HEAD_CFG for idx, cur_class_names in enumerate(self.class_names_each_head): cur_head_dict = copy.deepcopy(self.separate_head_cfg.HEAD_DICT) cur_head_dict['hm'] = dict(out_channels=len(cur_class_names), num_conv=self.model_cfg.NUM_HM_CONV) self.heads_list.append( SeparateHead( input_channels=self.model_cfg.SHARED_CONV_CHANNEL, sep_head_dict=cur_head_dict, init_bias=-2.19, use_bias=self.model_cfg.get('USE_BIAS_BEFORE_NORM', False) ) ) self.predict_boxes_when_training = predict_boxes_when_training self.forward_ret_dict = {} self.build_losses() def build_losses(self): self.add_module('hm_loss_func', loss_utils.FocalLossCenterNet()) self.add_module('reg_loss_func', loss_utils.RegLossCenterNet()) def assign_target_of_single_head( self, num_classes, gt_boxes, feature_map_size, feature_map_stride, num_max_objs=500, gaussian_overlap=0.1, min_radius=2 ): """ Args: gt_boxes: (N, 8) feature_map_size: (2), [x, y] Returns: """ heatmap = gt_boxes.new_zeros(num_classes, feature_map_size[1], feature_map_size[0]) ret_boxes = gt_boxes.new_zeros((num_max_objs, gt_boxes.shape[-1] - 1 + 1)) inds = gt_boxes.new_zeros(num_max_objs).long() mask = gt_boxes.new_zeros(num_max_objs).long() x, y, z = gt_boxes[:, 0], gt_boxes[:, 1], gt_boxes[:, 2] coord_x = (x - self.point_cloud_range[0]) / self.voxel_size[0] / feature_map_stride coord_y = (y - self.point_cloud_range[1]) / self.voxel_size[1] / feature_map_stride coord_x = torch.clamp(coord_x, min=0, max=feature_map_size[0] - 0.5) # bugfixed: 1e-6 does not work for center.int() coord_y = torch.clamp(coord_y, min=0, max=feature_map_size[1] - 0.5) # center = torch.cat((coord_x[:, None], coord_y[:, None]), dim=-1) center_int = center.int() center_int_float = center_int.float() dx, dy, dz = gt_boxes[:, 3], gt_boxes[:, 4], gt_boxes[:, 5] dx = dx / self.voxel_size[0] / feature_map_stride dy = dy / self.voxel_size[1] / feature_map_stride radius = centernet_utils.gaussian_radius(dx, dy, min_overlap=gaussian_overlap) radius = torch.clamp_min(radius.int(), min=min_radius) for k in range(min(num_max_objs, gt_boxes.shape[0])): if dx[k] <= 0 or dy[k] <= 0: continue if not (0 <= center_int[k][0] <= feature_map_size[0] and 0 <= center_int[k][1] <= feature_map_size[1]): continue cur_class_id = (gt_boxes[k, -1] - 1).long() centernet_utils.draw_gaussian_to_heatmap(heatmap[cur_class_id], center[k], radius[k].item()) inds[k] = center_int[k, 1] * feature_map_size[0] + center_int[k, 0] mask[k] = 1 ret_boxes[k, 0:2] = center[k] - center_int_float[k].float() ret_boxes[k, 2] = z[k] ret_boxes[k, 3:6] = gt_boxes[k, 3:6].log() ret_boxes[k, 6] = torch.cos(gt_boxes[k, 6]) ret_boxes[k, 7] = torch.sin(gt_boxes[k, 6]) if gt_boxes.shape[1] > 8: ret_boxes[k, 8:] = gt_boxes[k, 7:-1] return heatmap, ret_boxes, inds, mask def assign_targets(self, gt_boxes, feature_map_size=None, **kwargs): """ Args: gt_boxes: (B, M, 8) range_image_polar: (B, 3, H, W) feature_map_size: (2) [H, W] spatial_cartesian: (B, 4, H, W) Returns: """ feature_map_size = feature_map_size[::-1] # [H, W] ==> [x, y] target_assigner_cfg = self.model_cfg.TARGET_ASSIGNER_CONFIG # feature_map_size = self.grid_size[:2] // target_assigner_cfg.FEATURE_MAP_STRIDE batch_size = gt_boxes.shape[0] ret_dict = { 'heatmaps': [], 'target_boxes': [], 'inds': [], 'masks': [], 'heatmap_masks': [] } all_names = np.array(['bg', *self.class_names]) for idx, cur_class_names in enumerate(self.class_names_each_head): heatmap_list, target_boxes_list, inds_list, masks_list = [], [], [], [] for bs_idx in range(batch_size): cur_gt_boxes = gt_boxes[bs_idx] gt_class_names = all_names[cur_gt_boxes[:, -1].cpu().long().numpy()] gt_boxes_single_head = [] for idx, name in enumerate(gt_class_names): if name not in cur_class_names: continue temp_box = cur_gt_boxes[idx] temp_box[-1] = cur_class_names.index(name) + 1 gt_boxes_single_head.append(temp_box[None, :]) if len(gt_boxes_single_head) == 0: gt_boxes_single_head = cur_gt_boxes[:0, :] else: gt_boxes_single_head = torch.cat(gt_boxes_single_head, dim=0) heatmap, ret_boxes, inds, mask = self.assign_target_of_single_head( num_classes=len(cur_class_names), gt_boxes=gt_boxes_single_head.cpu(), feature_map_size=feature_map_size, feature_map_stride=target_assigner_cfg.FEATURE_MAP_STRIDE, num_max_objs=target_assigner_cfg.NUM_MAX_OBJS, gaussian_overlap=target_assigner_cfg.GAUSSIAN_OVERLAP, min_radius=target_assigner_cfg.MIN_RADIUS, ) heatmap_list.append(heatmap.to(gt_boxes_single_head.device)) target_boxes_list.append(ret_boxes.to(gt_boxes_single_head.device)) inds_list.append(inds.to(gt_boxes_single_head.device)) masks_list.append(mask.to(gt_boxes_single_head.device)) ret_dict['heatmaps'].append(torch.stack(heatmap_list, dim=0)) ret_dict['target_boxes'].append(torch.stack(target_boxes_list, dim=0)) ret_dict['inds'].append(torch.stack(inds_list, dim=0)) ret_dict['masks'].append(torch.stack(masks_list, dim=0)) return ret_dict def sigmoid(self, x): y = torch.clamp(x.sigmoid(), min=1e-4, max=1 - 1e-4) return y def get_loss(self): pred_dicts = self.forward_ret_dict['pred_dicts'] target_dicts = self.forward_ret_dict['target_dicts'] tb_dict = {} loss = 0 for idx, pred_dict in enumerate(pred_dicts): pred_dict['hm'] = self.sigmoid(pred_dict['hm']) hm_loss = self.hm_loss_func(pred_dict['hm'], target_dicts['heatmaps'][idx]) hm_loss *= self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['cls_weight'] target_boxes = target_dicts['target_boxes'][idx] pred_boxes = torch.cat([pred_dict[head_name] for head_name in self.separate_head_cfg.HEAD_ORDER], dim=1) reg_loss = self.reg_loss_func( pred_boxes, target_dicts['masks'][idx], target_dicts['inds'][idx], target_boxes ) loc_loss = (reg_loss * reg_loss.new_tensor(self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['code_weights'])).sum() loc_loss = loc_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['loc_weight'] loss += hm_loss + loc_loss tb_dict['hm_loss_head_%d' % idx] = hm_loss.item() tb_dict['loc_loss_head_%d' % idx] = loc_loss.item() tb_dict['rpn_loss'] = loss.item() return loss, tb_dict def generate_predicted_boxes(self, batch_size, pred_dicts): post_process_cfg = self.model_cfg.POST_PROCESSING post_center_limit_range = torch.tensor(post_process_cfg.POST_CENTER_LIMIT_RANGE).cuda().float() ret_dict = [{ 'pred_boxes': [], 'pred_scores': [], 'pred_labels': [], } for k in range(batch_size)] for idx, pred_dict in enumerate(pred_dicts): batch_hm = pred_dict['hm'].sigmoid() batch_center = pred_dict['center'] batch_center_z = pred_dict['center_z'] batch_dim = pred_dict['dim'].exp() batch_rot_cos = pred_dict['rot'][:, 0].unsqueeze(dim=1) batch_rot_sin = pred_dict['rot'][:, 1].unsqueeze(dim=1) batch_vel = pred_dict['vel'] if 'vel' in self.separate_head_cfg.HEAD_ORDER else None final_pred_dicts = centernet_utils.decode_bbox_from_heatmap( heatmap=batch_hm, rot_cos=batch_rot_cos, rot_sin=batch_rot_sin, center=batch_center, center_z=batch_center_z, dim=batch_dim, vel=batch_vel, point_cloud_range=self.point_cloud_range, voxel_size=self.voxel_size, feature_map_stride=self.feature_map_stride, K=post_process_cfg.MAX_OBJ_PER_SAMPLE, circle_nms=(post_process_cfg.NMS_CONFIG.NMS_TYPE == 'circle_nms'), score_thresh=post_process_cfg.SCORE_THRESH, post_center_limit_range=post_center_limit_range ) for k, final_dict in enumerate(final_pred_dicts): final_dict['pred_labels'] = self.class_id_mapping_each_head[idx][final_dict['pred_labels'].long()] if post_process_cfg.NMS_CONFIG.NMS_TYPE != 'circle_nms': selected, selected_scores = model_nms_utils.class_agnostic_nms( box_scores=final_dict['pred_scores'], box_preds=final_dict['pred_boxes'], nms_config=post_process_cfg.NMS_CONFIG, score_thresh=None ) final_dict['pred_boxes'] = final_dict['pred_boxes'][selected] final_dict['pred_scores'] = selected_scores final_dict['pred_labels'] = final_dict['pred_labels'][selected] ret_dict[k]['pred_boxes'].append(final_dict['pred_boxes']) ret_dict[k]['pred_scores'].append(final_dict['pred_scores']) ret_dict[k]['pred_labels'].append(final_dict['pred_labels']) for k in range(batch_size): ret_dict[k]['pred_boxes'] = torch.cat(ret_dict[k]['pred_boxes'], dim=0) ret_dict[k]['pred_scores'] = torch.cat(ret_dict[k]['pred_scores'], dim=0) ret_dict[k]['pred_labels'] = torch.cat(ret_dict[k]['pred_labels'], dim=0) + 1 return ret_dict @staticmethod def reorder_rois_for_refining(batch_size, pred_dicts): num_max_rois = max([len(cur_dict['pred_boxes']) for cur_dict in pred_dicts]) num_max_rois = max(1, num_max_rois) # at least one faked rois to avoid error pred_boxes = pred_dicts[0]['pred_boxes'] rois = pred_boxes.new_zeros((batch_size, num_max_rois, pred_boxes.shape[-1])) roi_scores = pred_boxes.new_zeros((batch_size, num_max_rois)) roi_labels = pred_boxes.new_zeros((batch_size, num_max_rois)).long() for bs_idx in range(batch_size): num_boxes = len(pred_dicts[bs_idx]['pred_boxes']) rois[bs_idx, :num_boxes, :] = pred_dicts[bs_idx]['pred_boxes'] roi_scores[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_scores'] roi_labels[bs_idx, :num_boxes] = pred_dicts[bs_idx]['pred_labels'] return rois, roi_scores, roi_labels def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] x = self.shared_conv(spatial_features_2d) pred_dicts = [] for head in self.heads_list: pred_dicts.append(head(x)) data_dict['bev_score'] = pred_dicts[0]['hm'] if self.training: target_dict = self.assign_targets( data_dict['gt_boxes'], feature_map_size=spatial_features_2d.size()[2:], feature_map_stride=data_dict.get('spatial_features_2d_strides', None) ) self.forward_ret_dict['target_dicts'] = target_dict self.forward_ret_dict['pred_dicts'] = pred_dicts if not self.training or self.predict_boxes_when_training: pred_dicts = self.generate_predicted_boxes( data_dict['batch_size'], pred_dicts ) if self.predict_boxes_when_training: rois, roi_scores, roi_labels = self.reorder_rois_for_refining(data_dict['batch_size'], pred_dicts) data_dict['rois'] = rois data_dict['roi_scores'] = roi_scores data_dict['roi_labels'] = roi_labels data_dict['has_class_labels'] = True else: data_dict['final_box_dicts'] = pred_dicts return data_dict
30,472
45.101362
125
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/anchor_head_semi.py
import numpy as np import torch.nn as nn from .anchor_head_template import AnchorHeadTemplate class AnchorHeadSemi(AnchorHeadTemplate): def __init__(self, model_cfg, input_channels, num_class, class_names, grid_size, voxel_size, point_cloud_range, predict_boxes_when_training=True): super().__init__( model_cfg=model_cfg, num_class=num_class, class_names=class_names, grid_size=grid_size, point_cloud_range=point_cloud_range, predict_boxes_when_training=predict_boxes_when_training ) self.num_anchors_per_location = sum(self.num_anchors_per_location) self.conv_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.num_class, kernel_size=1 ) self.conv_box = nn.Conv2d( input_channels, self.num_anchors_per_location * self.box_coder.code_size, kernel_size=1 ) if self.model_cfg.get('USE_DIRECTION_CLASSIFIER', None) is not None: self.conv_dir_cls = nn.Conv2d( input_channels, self.num_anchors_per_location * self.model_cfg.NUM_DIR_BINS, kernel_size=1 ) else: self.conv_dir_cls = None self.init_weights() self.model_type = None def init_weights(self): pi = 0.01 nn.init.constant_(self.conv_cls.bias, -np.log((1 - pi) / pi)) nn.init.normal_(self.conv_box.weight, mean=0, std=0.001) def forward(self, data_dict): spatial_features_2d = data_dict['spatial_features_2d'] cls_preds = self.conv_cls(spatial_features_2d) box_preds = self.conv_box(spatial_features_2d) cls_preds = cls_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] box_preds = box_preds.permute(0, 2, 3, 1).contiguous() # [N, H, W, C] self.forward_ret_dict['cls_preds'] = cls_preds self.forward_ret_dict['box_preds'] = box_preds if self.conv_dir_cls is not None: dir_cls_preds = self.conv_dir_cls(spatial_features_2d) dir_cls_preds = dir_cls_preds.permute(0, 2, 3, 1).contiguous() self.forward_ret_dict['dir_cls_preds'] = dir_cls_preds else: dir_cls_preds = None if self.model_type == 'origin': if self.training: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False elif self.model_type == 'teacher': #assert not self.training batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False elif self.model_type == 'student': if self.training: if 'gt_boxes' in data_dict: targets_dict = self.assign_targets( gt_boxes=data_dict['gt_boxes'] ) self.forward_ret_dict.update(targets_dict) batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=data_dict['batch_size'], cls_preds=cls_preds, box_preds=box_preds, dir_cls_preds=dir_cls_preds ) data_dict['batch_cls_preds'] = batch_cls_preds data_dict['batch_box_preds'] = batch_box_preds data_dict['cls_preds_normalized'] = False else: raise Exception('Unsupprted model type') return data_dict
4,321
39.018519
136
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/point_head_box.py
import torch from ...utils import box_coder_utils, box_utils from .point_head_template import PointHeadTemplate class PointHeadBox(PointHeadTemplate): """ A simple point-based segmentation head, which are used for PointRCNN. Reference Paper: https://arxiv.org/abs/1812.04244 PointRCNN: 3D Object Proposal Generation and Detection from Point Cloud """ def __init__(self, num_class, input_channels, model_cfg, predict_boxes_when_training=False, **kwargs): super().__init__(model_cfg=model_cfg, num_class=num_class) self.predict_boxes_when_training = predict_boxes_when_training self.cls_layers = self.make_fc_layers( fc_cfg=self.model_cfg.CLS_FC, input_channels=input_channels, output_channels=num_class ) target_cfg = self.model_cfg.TARGET_CONFIG self.box_coder = getattr(box_coder_utils, target_cfg.BOX_CODER)( **target_cfg.BOX_CODER_CONFIG ) self.box_layers = self.make_fc_layers( fc_cfg=self.model_cfg.REG_FC, input_channels=input_channels, output_channels=self.box_coder.code_size ) def assign_targets(self, input_dict): """ Args: input_dict: point_features: (N1 + N2 + N3 + ..., C) batch_size: point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes (optional): (B, M, 8) Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_part_labels: (N1 + N2 + N3 + ..., 3) """ point_coords = input_dict['point_coords'] gt_boxes = input_dict['gt_boxes'] assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert point_coords.shape.__len__() in [2], 'points.shape=%s' % str(point_coords.shape) batch_size = gt_boxes.shape[0] extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=self.model_cfg.TARGET_CONFIG.GT_EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) targets_dict = self.assign_stack_targets( points=point_coords, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_part_labels=False, ret_box_labels=True ) return targets_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict point_loss_cls, tb_dict_1 = self.get_cls_layer_loss() point_loss_box, tb_dict_2 = self.get_box_layer_loss() point_loss = point_loss_cls + point_loss_box tb_dict.update(tb_dict_1) tb_dict.update(tb_dict_2) return point_loss, tb_dict def forward(self, batch_dict): """ Args: batch_dict: batch_size: point_features: (N1 + N2 + N3 + ..., C) or (B, N, C) point_features_before_fusion: (N1 + N2 + N3 + ..., C) point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] point_labels (optional): (N1 + N2 + N3 + ...) gt_boxes (optional): (B, M, 8) Returns: batch_dict: point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) """ if self.model_cfg.get('USE_POINT_FEATURES_BEFORE_FUSION', False): point_features = batch_dict['point_features_before_fusion'] else: point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) point_box_preds = self.box_layers(point_features) # (total_points, box_code_size) point_cls_preds_max, _ = point_cls_preds.max(dim=-1) batch_dict['point_cls_scores'] = torch.sigmoid(point_cls_preds_max) ret_dict = {'point_cls_preds': point_cls_preds, 'point_box_preds': point_box_preds} if self.training: targets_dict = self.assign_targets(batch_dict) ret_dict['point_cls_labels'] = targets_dict['point_cls_labels'] ret_dict['point_box_labels'] = targets_dict['point_box_labels'] if not self.training or self.predict_boxes_when_training: point_cls_preds, point_box_preds = self.generate_predicted_boxes( points=batch_dict['point_coords'][:, 1:4], point_cls_preds=point_cls_preds, point_box_preds=point_box_preds ) batch_dict['batch_cls_preds'] = point_cls_preds batch_dict['batch_box_preds'] = point_box_preds batch_dict['batch_index'] = batch_dict['point_coords'][:, 0] batch_dict['cls_preds_normalized'] = False self.forward_ret_dict = ret_dict return batch_dict
4,930
41.508621
106
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/point_head_simple.py
import torch from ...utils import box_utils from .point_head_template import PointHeadTemplate class PointHeadSimple(PointHeadTemplate): """ A simple point-based segmentation head, which are used for PV-RCNN keypoint segmentaion. Reference Paper: https://arxiv.org/abs/1912.13192 PV-RCNN: Point-Voxel Feature Set Abstraction for 3D Object Detection """ def __init__(self, num_class, input_channels, model_cfg, **kwargs): super().__init__(model_cfg=model_cfg, num_class=num_class) self.cls_layers = self.make_fc_layers( fc_cfg=self.model_cfg.CLS_FC, input_channels=input_channels, output_channels=num_class ) def assign_targets(self, input_dict): """ Args: input_dict: point_features: (N1 + N2 + N3 + ..., C) batch_size: point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes (optional): (B, M, 8) Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_part_labels: (N1 + N2 + N3 + ..., 3) """ point_coords = input_dict['point_coords'] gt_boxes = input_dict['gt_boxes'] assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert point_coords.shape.__len__() in [2], 'points.shape=%s' % str(point_coords.shape) batch_size = gt_boxes.shape[0] extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=self.model_cfg.TARGET_CONFIG.GT_EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) targets_dict = self.assign_stack_targets( points=point_coords, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, #modified: gt_boxex -> gt_boxes[:, :, 0:8] set_ignore_flag=True, use_ball_constraint=False, #modified: extend_gt_boxes -> extend_gt_boxes[:, :, 0:8] ret_part_labels=False ) return targets_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict point_loss_cls, tb_dict_1 = self.get_cls_layer_loss() point_loss = point_loss_cls tb_dict.update(tb_dict_1) return point_loss, tb_dict def forward(self, batch_dict): """ Args: batch_dict: batch_size: point_features: (N1 + N2 + N3 + ..., C) or (B, N, C) point_features_before_fusion: (N1 + N2 + N3 + ..., C) point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] point_labels (optional): (N1 + N2 + N3 + ...) gt_boxes (optional): (B, M, 8) Returns: batch_dict: point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) """ if self.model_cfg.get('USE_POINT_FEATURES_BEFORE_FUSION', False): point_features = batch_dict['point_features_before_fusion'] else: point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) ret_dict = { 'point_cls_preds': point_cls_preds, } point_cls_scores = torch.sigmoid(point_cls_preds) batch_dict['point_cls_scores'], _ = point_cls_scores.max(dim=-1) if self.training: targets_dict = self.assign_targets(batch_dict) ret_dict['point_cls_labels'] = targets_dict['point_cls_labels'] self.forward_ret_dict = ret_dict return batch_dict def get_point_score(self, batch_dict): if self.model_cfg.get('USE_POINT_FEATURES_BEFORE_FUSION', False): point_features = batch_dict['point_features_before_fusion'] else: point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) ret_dict = { 'point_cls_preds': point_cls_preds, } point_cls_scores = torch.sigmoid(point_cls_preds) batch_dict['point_cls_scores'], _ = point_cls_scores.max(dim=-1) return batch_dict
4,255
39.150943
128
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/point_head_semi.py
import torch from ...utils import box_utils from .point_head_template import PointHeadTemplate class PointHeadSemi(PointHeadTemplate): """ A simple point-based segmentation head, which are used for PV-RCNN keypoint segmentaion. Reference Paper: https://arxiv.org/abs/1912.13192 PV-RCNN: Point-Voxel Feature Set Abstraction for 3D Object Detection """ def __init__(self, num_class, input_channels, model_cfg, **kwargs): super().__init__(model_cfg=model_cfg, num_class=num_class) self.cls_layers = self.make_fc_layers( fc_cfg=self.model_cfg.CLS_FC, input_channels=input_channels, output_channels=num_class ) self.model_type = None def assign_targets(self, input_dict): """ Args: input_dict: point_features: (N1 + N2 + N3 + ..., C) batch_size: point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes (optional): (B, M, 8) Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_part_labels: (N1 + N2 + N3 + ..., 3) """ point_coords = input_dict['point_coords'] gt_boxes = input_dict['gt_boxes'] assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert point_coords.shape.__len__() in [2], 'points.shape=%s' % str(point_coords.shape) batch_size = gt_boxes.shape[0] extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=self.model_cfg.TARGET_CONFIG.GT_EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) targets_dict = self.assign_stack_targets( points=point_coords, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, #modified: gt_boxex -> gt_boxes[:, :, 0:8] set_ignore_flag=True, use_ball_constraint=False, #modified: extend_gt_boxes -> extend_gt_boxes[:, :, 0:8] ret_part_labels=False ) return targets_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict point_loss_cls, tb_dict_1 = self.get_cls_layer_loss() point_loss = point_loss_cls tb_dict.update(tb_dict_1) return point_loss, tb_dict def forward(self, batch_dict): """ Args: batch_dict: batch_size: point_features: (N1 + N2 + N3 + ..., C) or (B, N, C) point_features_before_fusion: (N1 + N2 + N3 + ..., C) point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] point_labels (optional): (N1 + N2 + N3 + ...) gt_boxes (optional): (B, M, 8) Returns: batch_dict: point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) """ if self.model_cfg.get('USE_POINT_FEATURES_BEFORE_FUSION', False): point_features = batch_dict['point_features_before_fusion'] else: point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) ret_dict = { 'point_cls_preds': point_cls_preds, } point_cls_scores = torch.sigmoid(point_cls_preds) batch_dict['point_cls_scores'], _ = point_cls_scores.max(dim=-1) if self.model_type == 'origin': if self.training: targets_dict = self.assign_targets(batch_dict) ret_dict['point_cls_labels'] = targets_dict['point_cls_labels'] self.forward_ret_dict = ret_dict elif self.model_type == 'teacher': self.forward_ret_dict = ret_dict elif self.model_type == 'student': if self.training: if 'gt_boxes' in batch_dict: targets_dict = self.assign_targets(batch_dict) ret_dict['point_cls_labels'] = targets_dict['point_cls_labels'] self.forward_ret_dict = ret_dict else: raise Exception('Unsupprted model type') return batch_dict def get_point_score(self, batch_dict): if self.model_cfg.get('USE_POINT_FEATURES_BEFORE_FUSION', False): point_features = batch_dict['point_features_before_fusion'] else: point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) ret_dict = { 'point_cls_preds': point_cls_preds, } point_cls_scores = torch.sigmoid(point_cls_preds) batch_dict['point_cls_scores'], _ = point_cls_scores.max(dim=-1) return batch_dict
4,820
38.842975
128
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/point_intra_part_head.py
import torch from ...utils import box_coder_utils, box_utils from .point_head_template import PointHeadTemplate class PointIntraPartOffsetHead(PointHeadTemplate): """ Point-based head for predicting the intra-object part locations. Reference Paper: https://arxiv.org/abs/1907.03670 From Points to Parts: 3D Object Detection from Point Cloud with Part-aware and Part-aggregation Network """ def __init__(self, num_class, input_channels, model_cfg, predict_boxes_when_training=False, **kwargs): super().__init__(model_cfg=model_cfg, num_class=num_class) self.predict_boxes_when_training = predict_boxes_when_training self.cls_layers = self.make_fc_layers( fc_cfg=self.model_cfg.CLS_FC, input_channels=input_channels, output_channels=num_class ) self.part_reg_layers = self.make_fc_layers( fc_cfg=self.model_cfg.PART_FC, input_channels=input_channels, output_channels=3 ) target_cfg = self.model_cfg.TARGET_CONFIG if target_cfg.get('BOX_CODER', None) is not None: self.box_coder = getattr(box_coder_utils, target_cfg.BOX_CODER)( **target_cfg.BOX_CODER_CONFIG ) self.box_layers = self.make_fc_layers( fc_cfg=self.model_cfg.REG_FC, input_channels=input_channels, output_channels=self.box_coder.code_size ) else: self.box_layers = None def assign_targets(self, input_dict): """ Args: input_dict: point_features: (N1 + N2 + N3 + ..., C) batch_size: point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes (optional): (B, M, 8) Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_part_labels: (N1 + N2 + N3 + ..., 3) """ point_coords = input_dict['point_coords'] gt_boxes = input_dict['gt_boxes'] assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert point_coords.shape.__len__() in [2], 'points.shape=%s' % str(point_coords.shape) batch_size = gt_boxes.shape[0] extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=self.model_cfg.TARGET_CONFIG.GT_EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) targets_dict = self.assign_stack_targets( points=point_coords, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_part_labels=True, ret_box_labels=(self.box_layers is not None) ) return targets_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict point_loss_cls, tb_dict = self.get_cls_layer_loss(tb_dict) point_loss_part, tb_dict = self.get_part_layer_loss(tb_dict) point_loss = point_loss_cls + point_loss_part if self.box_layers is not None: point_loss_box, tb_dict = self.get_box_layer_loss(tb_dict) point_loss += point_loss_box return point_loss, tb_dict def forward(self, batch_dict): """ Args: batch_dict: batch_size: point_features: (N1 + N2 + N3 + ..., C) or (B, N, C) point_coords: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] point_labels (optional): (N1 + N2 + N3 + ...) gt_boxes (optional): (B, M, 8) Returns: batch_dict: point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) """ point_features = batch_dict['point_features'] point_cls_preds = self.cls_layers(point_features) # (total_points, num_class) point_part_preds = self.part_reg_layers(point_features) ret_dict = { 'point_cls_preds': point_cls_preds, 'point_part_preds': point_part_preds, } if self.box_layers is not None: point_box_preds = self.box_layers(point_features) ret_dict['point_box_preds'] = point_box_preds point_cls_scores = torch.sigmoid(point_cls_preds) point_part_offset = torch.sigmoid(point_part_preds) batch_dict['point_cls_scores'], _ = point_cls_scores.max(dim=-1) batch_dict['point_part_offset'] = point_part_offset if self.training: targets_dict = self.assign_targets(batch_dict) ret_dict['point_cls_labels'] = targets_dict['point_cls_labels'] ret_dict['point_part_labels'] = targets_dict.get('point_part_labels') ret_dict['point_box_labels'] = targets_dict.get('point_box_labels') if self.box_layers is not None and (not self.training or self.predict_boxes_when_training): point_cls_preds, point_box_preds = self.generate_predicted_boxes( points=batch_dict['point_coords'][:, 1:4], point_cls_preds=point_cls_preds, point_box_preds=ret_dict['point_box_preds'] ) batch_dict['batch_cls_preds'] = point_cls_preds batch_dict['batch_box_preds'] = point_box_preds batch_dict['batch_index'] = batch_dict['point_coords'][:, 0] batch_dict['cls_preds_normalized'] = False self.forward_ret_dict = ret_dict return batch_dict
5,568
42.507813
107
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/IASSD_head.py
import torch import torch.nn as nn import torch.nn.functional as F from ...utils import box_coder_utils, box_utils, loss_utils, common_utils from .point_head_template import PointHeadTemplate from ...ops.roiaware_pool3d import roiaware_pool3d_utils class IASSD_Head(PointHeadTemplate): """ A simple point-based detect head, which are used for IA-SSD. """ def __init__(self, num_class, input_channels, model_cfg, predict_boxes_when_training=False, **kwargs): super().__init__(model_cfg=model_cfg, num_class=num_class) self.predict_boxes_when_training = predict_boxes_when_training target_cfg = self.model_cfg.TARGET_CONFIG self.box_coder = getattr(box_coder_utils, target_cfg.BOX_CODER)( **target_cfg.BOX_CODER_CONFIG ) detector_dim = self.model_cfg.get('INPUT_DIM', input_channels) # for spec input_channel self.cls_center_layers = self.make_fc_layers( fc_cfg=self.model_cfg.CLS_FC, input_channels=detector_dim, output_channels=num_class ) self.box_center_layers = self.make_fc_layers( fc_cfg=self.model_cfg.REG_FC, input_channels=detector_dim, output_channels=self.box_coder.code_size ) self.box_iou3d_layers = self.make_fc_layers( fc_cfg=self.model_cfg.IOU_FC, input_channels=detector_dim, output_channels=1 ) if self.model_cfg.get('IOU_FC', None) is not None else None # self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) def build_losses(self, losses_cfg): # classification loss if losses_cfg.LOSS_CLS.startswith('WeightedBinaryCrossEntropy'): self.add_module( 'cls_loss_func', loss_utils.WeightedBinaryCrossEntropyLoss() ) elif losses_cfg.LOSS_CLS.startswith('WeightedCrossEntropy'): self.add_module( 'cls_loss_func', loss_utils.WeightedClassificationLoss() ) elif losses_cfg.LOSS_CLS.startswith('FocalLoss'): self.add_module( 'cls_loss_func', loss_utils.SigmoidFocalClassificationLoss( **losses_cfg.get('LOSS_CLS_CONFIG', {}) ) ) else: raise NotImplementedError # regression loss if losses_cfg.LOSS_REG == 'WeightedSmoothL1Loss': self.add_module( 'reg_loss_func', loss_utils.WeightedSmoothL1Loss( code_weights=losses_cfg.LOSS_WEIGHTS.get('code_weights', None), **losses_cfg.get('LOSS_REG_CONFIG', {}) ) ) elif losses_cfg.LOSS_REG == 'WeightedL1Loss': self.add_module( 'reg_loss_func', loss_utils.WeightedL1Loss( code_weights=losses_cfg.LOSS_WEIGHTS.get('code_weights', None) ) ) else: raise NotImplementedError # instance-aware loss if losses_cfg.get('LOSS_INS', None) is not None: if losses_cfg.LOSS_INS.startswith('WeightedBinaryCrossEntropy'): self.add_module( 'ins_loss_func', loss_utils.WeightedBinaryCrossEntropyLoss() ) elif losses_cfg.LOSS_INS.startswith('WeightedCrossEntropy'): self.add_module( 'ins_loss_func', loss_utils.WeightedClassificationLoss() ) elif losses_cfg.LOSS_INS.startswith('FocalLoss'): self.add_module( 'ins_loss_func', loss_utils.SigmoidFocalClassificationLoss( **losses_cfg.get('LOSS_CLS_CONFIG', {}) ) ) else: raise NotImplementedError def assign_stack_targets_IASSD(self, points, gt_boxes, extend_gt_boxes=None, weighted_labels=False, ret_box_labels=False, ret_offset_labels=True, set_ignore_flag=True, use_ball_constraint=False, central_radius=2.0, use_query_assign=False, central_radii=2.0, use_ex_gt_assign=False, fg_pc_ignore=False, binary_label=False): """ Args: points: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] gt_boxes: (B, M, 8) extend_gt_boxes: [B, M, 8] Returns: point_cls_labels: (N1 + N2 + N3 + ...), long type, 0:background, -1:ignored point_box_labels: (N1 + N2 + N3 + ..., code_size) """ assert len(points.shape) == 2 and points.shape[1] == 4, 'points.shape=%s' % str(points.shape) assert len(gt_boxes.shape) == 3 and gt_boxes.shape[2] == 8, 'gt_boxes.shape=%s' % str(gt_boxes.shape) assert extend_gt_boxes is None or len(extend_gt_boxes.shape) == 3 and extend_gt_boxes.shape[2] == 8, \ 'extend_gt_boxes.shape=%s' % str(extend_gt_boxes.shape) batch_size = gt_boxes.shape[0] bs_idx = points[:, 0] point_cls_labels = points.new_zeros(points.shape[0]).long() point_box_labels = gt_boxes.new_zeros((points.shape[0], 8)) if ret_box_labels else None box_idxs_labels = points.new_zeros(points.shape[0]).long() gt_boxes_of_fg_points = [] gt_box_of_points = gt_boxes.new_zeros((points.shape[0], 8)) for k in range(batch_size): bs_mask = (bs_idx == k) points_single = points[bs_mask][:, 1:4] point_cls_labels_single = point_cls_labels.new_zeros(bs_mask.sum()) box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points_single.unsqueeze(dim=0), gt_boxes[k:k + 1, :, 0:7].contiguous() ).long().squeeze(dim=0) box_fg_flag = (box_idxs_of_pts >= 0) if use_query_assign: ## centers = gt_boxes[k:k + 1, :, 0:3] query_idxs_of_pts = roiaware_pool3d_utils.points_in_ball_query_gpu( points_single.unsqueeze(dim=0), centers.contiguous(), central_radii ).long().squeeze(dim=0) query_fg_flag = (query_idxs_of_pts >= 0) if fg_pc_ignore: fg_flag = query_fg_flag ^ box_fg_flag extend_box_idxs_of_pts[box_idxs_of_pts!=-1] = -1 box_idxs_of_pts = extend_box_idxs_of_pts else: fg_flag = query_fg_flag box_idxs_of_pts = query_idxs_of_pts elif use_ex_gt_assign: ## extend_box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points_single.unsqueeze(dim=0), extend_gt_boxes[k:k+1, :, 0:7].contiguous() ).long().squeeze(dim=0) extend_fg_flag = (extend_box_idxs_of_pts >= 0) extend_box_idxs_of_pts[box_fg_flag] = box_idxs_of_pts[box_fg_flag] #instance points should keep unchanged if fg_pc_ignore: fg_flag = extend_fg_flag ^ box_fg_flag extend_box_idxs_of_pts[box_idxs_of_pts!=-1] = -1 box_idxs_of_pts = extend_box_idxs_of_pts else: fg_flag = extend_fg_flag box_idxs_of_pts = extend_box_idxs_of_pts elif set_ignore_flag: extend_box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( points_single.unsqueeze(dim=0), extend_gt_boxes[k:k+1, :, 0:7].contiguous() ).long().squeeze(dim=0) fg_flag = box_fg_flag ignore_flag = fg_flag ^ (extend_box_idxs_of_pts >= 0) point_cls_labels_single[ignore_flag] = -1 elif use_ball_constraint: box_centers = gt_boxes[k][box_idxs_of_pts][:, 0:3].clone() box_centers[:, 2] += gt_boxes[k][box_idxs_of_pts][:, 5] / 2 ball_flag = ((box_centers - points_single).norm(dim=1) < central_radius) fg_flag = box_fg_flag & ball_flag else: raise NotImplementedError gt_box_of_fg_points = gt_boxes[k][box_idxs_of_pts[fg_flag]] point_cls_labels_single[fg_flag] = 1 if self.num_class == 1 or binary_label else gt_box_of_fg_points[:, -1].long() point_cls_labels[bs_mask] = point_cls_labels_single bg_flag = (point_cls_labels_single == 0) # except ignore_id # box_bg_flag fg_flag = fg_flag ^ (fg_flag & bg_flag) gt_box_of_fg_points = gt_boxes[k][box_idxs_of_pts[fg_flag]] gt_boxes_of_fg_points.append(gt_box_of_fg_points) box_idxs_labels[bs_mask] = box_idxs_of_pts gt_box_of_points[bs_mask] = gt_boxes[k][box_idxs_of_pts] if ret_box_labels and gt_box_of_fg_points.shape[0] > 0: point_box_labels_single = point_box_labels.new_zeros((bs_mask.sum(), 8)) fg_point_box_labels = self.box_coder.encode_torch( gt_boxes=gt_box_of_fg_points[:, :-1], points=points_single[fg_flag], gt_classes=gt_box_of_fg_points[:, -1].long() ) point_box_labels_single[fg_flag] = fg_point_box_labels point_box_labels[bs_mask] = point_box_labels_single gt_boxes_of_fg_points = torch.cat(gt_boxes_of_fg_points, dim=0) targets_dict = { 'point_cls_labels': point_cls_labels, 'point_box_labels': point_box_labels, 'gt_box_of_fg_points': gt_boxes_of_fg_points, 'box_idxs_labels': box_idxs_labels, 'gt_box_of_points': gt_box_of_points, } return targets_dict def assign_targets(self, input_dict): """ Args: input_dict: batch_size: int centers: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] centers_origin: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] encoder_coords: List of point_coords in SA gt_boxes (optional): (B, M, 8) Returns: target_dict: ... """ target_cfg = self.model_cfg.TARGET_CONFIG gt_boxes = input_dict['gt_boxes'] if gt_boxes.shape[-1] == 10: #nscence gt_boxes = torch.cat((gt_boxes[..., 0:7], gt_boxes[..., -1:]), dim=-1) targets_dict_center = {} # assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) # assert point_coords.shape.__len__() in [2], 'points.shape=%s' % str(point_coords.shape) batch_size = input_dict['batch_size'] if target_cfg.get('EXTRA_WIDTH', False): # multi class extension extend_gt = box_utils.enlarge_box3d_for_class( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=target_cfg.EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) else: extend_gt = gt_boxes extend_gt_boxes = box_utils.enlarge_box3d( extend_gt.view(-1, extend_gt.shape[-1]), extra_width=target_cfg.GT_EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) assert gt_boxes.shape.__len__() == 3, 'gt_boxes.shape=%s' % str(gt_boxes.shape) center_targets_dict = self.assign_stack_targets_IASSD( points=input_dict['centers'].detach(), gt_boxes=extend_gt, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_box_labels=True ) targets_dict_center['center_gt_box_of_fg_points'] = center_targets_dict['gt_box_of_fg_points'] targets_dict_center['center_cls_labels'] = center_targets_dict['point_cls_labels'] targets_dict_center['center_box_labels'] = center_targets_dict['point_box_labels'] #only center assign targets_dict_center['center_gt_box_of_points'] = center_targets_dict['gt_box_of_points'] if target_cfg.get('INS_AWARE_ASSIGN', False): sa_ins_labels, sa_gt_box_of_fg_points, sa_xyz_coords, sa_gt_box_of_points, sa_box_idxs_labels = [],[],[],[],[] sa_ins_preds = input_dict['sa_ins_preds'] for i in range(1, len(sa_ins_preds)): # valid when i = 1,2 for IA-SSD # if sa_ins_preds[i].__len__() == 0: # continue sa_xyz = input_dict['encoder_coords'][i] if i == 1: extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=[0.5, 0.5, 0.5] #[0.2, 0.2, 0.2] ).view(batch_size, -1, gt_boxes.shape[-1]) sa_targets_dict = self.assign_stack_targets_IASSD( points=sa_xyz.view(-1,sa_xyz.shape[-1]).detach(), gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ex_gt_assign= False ) if i >= 2: # if False: extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=[0.5, 0.5, 0.5] ).view(batch_size, -1, gt_boxes.shape[-1]) sa_targets_dict = self.assign_stack_targets_IASSD( points=sa_xyz.view(-1,sa_xyz.shape[-1]).detach(), gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=False, use_ex_gt_assign= True ) # else: # extend_gt_boxes = box_utils.enlarge_box3d( # gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=[0.5, 0.5, 0.5] # ).view(batch_size, -1, gt_boxes.shape[-1]) # sa_targets_dict = self.assign_stack_targets_IASSD( # points=sa_xyz.view(-1,sa_xyz.shape[-1]).detach(), gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, # set_ignore_flag=False, use_ex_gt_assign= True # ) sa_xyz_coords.append(sa_xyz) sa_ins_labels.append(sa_targets_dict['point_cls_labels']) sa_gt_box_of_fg_points.append(sa_targets_dict['gt_box_of_fg_points']) sa_gt_box_of_points.append(sa_targets_dict['gt_box_of_points']) sa_box_idxs_labels.append(sa_targets_dict['box_idxs_labels']) targets_dict_center['sa_ins_labels'] = sa_ins_labels targets_dict_center['sa_gt_box_of_fg_points'] = sa_gt_box_of_fg_points targets_dict_center['sa_xyz_coords'] = sa_xyz_coords targets_dict_center['sa_gt_box_of_points'] = sa_gt_box_of_points targets_dict_center['sa_box_idxs_labels'] = sa_box_idxs_labels extra_method = target_cfg.get('ASSIGN_METHOD', None) if extra_method is not None and extra_method.NAME == 'extend_gt': extend_gt_boxes = box_utils.enlarge_box3d( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=extra_method.EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) if extra_method.get('ASSIGN_TYPE', 'centers') == 'centers_origin': points = input_dict['centers_origin'].detach() else: points = input_dict['centers'].detach() #default setting targets_dict = self.assign_stack_targets_IASSD( points=points, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_box_labels=True, use_ex_gt_assign=True, fg_pc_ignore=extra_method.FG_PC_IGNORE, ) targets_dict_center['center_origin_gt_box_of_fg_points'] = targets_dict['gt_box_of_fg_points'] targets_dict_center['center_origin_cls_labels'] = targets_dict['point_cls_labels'] targets_dict_center['center_origin_box_idxs_of_pts'] = targets_dict['box_idxs_labels'] targets_dict_center['gt_box_of_center_origin'] = targets_dict['gt_box_of_points'] elif extra_method is not None and extra_method.NAME == 'extend_gt_factor': extend_gt_boxes = box_utils.enlarge_box3d_with_factor( gt_boxes.view(-1, gt_boxes.shape[-1]), factor=extra_method.EXTRA_FACTOR).view(batch_size, -1, gt_boxes.shape[-1]) if extra_method.get('ASSIGN_TYPE', 'centers') == 'centers_origin': points = input_dict['centers_origin'].detach() else: points = input_dict['centers'].detach() targets_dict = self.assign_stack_targets_IASSD( points=points, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_box_labels=False, use_ex_gt_assign=True, fg_pc_ignore=extra_method.FG_PC_IGNORE, ) targets_dict_center['center_origin_gt_box_of_fg_points'] = targets_dict['gt_box_of_fg_points'] targets_dict_center['center_origin_cls_labels'] = targets_dict['point_cls_labels'] elif extra_method is not None and extra_method.NAME == 'extend_gt_for_class': extend_gt_boxes = box_utils.enlarge_box3d_for_class( gt_boxes.view(-1, gt_boxes.shape[-1]), extra_width=extra_method.EXTRA_WIDTH ).view(batch_size, -1, gt_boxes.shape[-1]) if extra_method.get('ASSIGN_TYPE', 'centers') == 'centers_origin': points = input_dict['centers_origin'].detach() else: points = input_dict['centers'].detach() targets_dict = self.assign_stack_targets_IASSD( points=points, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_box_labels=False, use_ex_gt_assign=True, fg_pc_ignore=extra_method.FG_PC_IGNORE, ) targets_dict_center['center_origin_gt_box_of_fg_points'] = targets_dict['gt_box_of_fg_points'] targets_dict_center['center_origin_cls_labels'] = targets_dict['point_cls_labels'] elif extra_method is not None and extra_method.NAME == 'extend_query': extend_gt_boxes = None if extra_method.get('ASSIGN_TYPE', 'centers') == 'centers_origin': points = input_dict['centers_origin'].detach() elif extra_method.get('ASSIGN_TYPE', 'centers') == 'centers': points = input_dict['centers'].detach() targets_dict = self.assign_stack_targets_IASSD( points=points, gt_boxes=gt_boxes, extend_gt_boxes=extend_gt_boxes, set_ignore_flag=True, use_ball_constraint=False, ret_box_labels=False, use_query_assign=True, central_radii=extra_method.RADII, fg_pc_ignore=extra_method.FG_PC_IGNORE, ) targets_dict_center['center_origin_gt_box_of_fg_points'] = targets_dict['gt_box_of_fg_points'] targets_dict_center['center_origin_cls_labels'] = targets_dict['point_cls_labels'] return targets_dict_center def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict # vote loss if self.model_cfg.TARGET_CONFIG.get('ASSIGN_METHOD') is not None and \ self.model_cfg.TARGET_CONFIG.ASSIGN_METHOD.get('ASSIGN_TYPE')== 'centers_origin': if self.model_cfg.LOSS_CONFIG.get('LOSS_VOTE_TYPE', 'none') == 'ver1': center_loss_reg, tb_dict_3 = self.get_contextual_vote_loss_ver1() elif self.model_cfg.LOSS_CONFIG.get('LOSS_VOTE_TYPE', 'none') == 'ver2': center_loss_reg, tb_dict_3 = self.get_contextual_vote_loss_ver2() else: # 'none' center_loss_reg, tb_dict_3 = self.get_contextual_vote_loss() else: center_loss_reg, tb_dict_3 = self.get_vote_loss_loss() # center assign tb_dict.update(tb_dict_3) # semantic loss in SA layers if self.model_cfg.LOSS_CONFIG.get('LOSS_INS', None) is not None: assert ('sa_ins_preds' in self.forward_ret_dict) and ('sa_ins_labels' in self.forward_ret_dict) sa_loss_cls, tb_dict_0 = self.get_sa_ins_layer_loss() tb_dict.update(tb_dict_0) else: sa_loss_cls = 0 # cls loss center_loss_cls, tb_dict_4 = self.get_center_cls_layer_loss() tb_dict.update(tb_dict_4) # reg loss if self.model_cfg.TARGET_CONFIG.BOX_CODER == 'PointResidualCoder': center_loss_box, tb_dict_5 = self.get_box_layer_loss() else: center_loss_box, tb_dict_5 = self.get_center_box_binori_layer_loss() tb_dict.update(tb_dict_5) # corner loss if self.model_cfg.LOSS_CONFIG.get('CORNER_LOSS_REGULARIZATION', False): corner_loss, tb_dict_6 = self.get_corner_layer_loss() tb_dict.update(tb_dict_6) # iou loss iou3d_loss = 0 if self.model_cfg.LOSS_CONFIG.get('IOU3D_REGULARIZATION', False): iou3d_loss, tb_dict_7 = self.get_iou3d_layer_loss() tb_dict.update(tb_dict_7) point_loss = center_loss_reg + center_loss_cls + center_loss_box + corner_loss + sa_loss_cls + iou3d_loss return point_loss, tb_dict def get_contextual_vote_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_origin_cls_labels'] > 0 center_origin_loss_box = [] for i in self.forward_ret_dict['center_origin_cls_labels'].unique(): if i <= 0: continue simple_pos_mask = self.forward_ret_dict['center_origin_cls_labels'] == i center_box_labels = self.forward_ret_dict['center_origin_gt_box_of_fg_points'][:, 0:3][(pos_mask & simple_pos_mask)[pos_mask==1]] centers_origin = self.forward_ret_dict['centers_origin'] ctr_offsets = self.forward_ret_dict['ctr_offsets'] centers_pred = centers_origin + ctr_offsets centers_pred = centers_pred[simple_pos_mask][:, 1:4] simple_center_origin_loss_box = F.smooth_l1_loss(centers_pred, center_box_labels) center_origin_loss_box.append(simple_center_origin_loss_box.unsqueeze(-1)) center_origin_loss_box = torch.cat(center_origin_loss_box, dim=-1).mean() center_origin_loss_box = center_origin_loss_box * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS.get('vote_weight') if tb_dict is None: tb_dict = {} tb_dict.update({'center_origin_loss_reg': center_origin_loss_box.item()}) return center_origin_loss_box, tb_dict def get_contextual_vote_loss_ver1(self, tb_dict=None): box_idxs_of_pts = self.forward_ret_dict['center_origin_box_idxs_of_pts'] center_box_labels = self.forward_ret_dict['gt_box_of_center_origin'] centers_origin = self.forward_ret_dict['centers_origin'] ctr_offsets = self.forward_ret_dict['ctr_offsets'] centers_pred = centers_origin[:, 1:] + ctr_offsets[:, 1:] centers_pred = torch.cat([centers_origin[:, :1], centers_pred], dim=-1) batch_idx = self.forward_ret_dict['centers'][:,0] ins_num, ins_vote_loss = [],[] for cur_id in batch_idx.unique(): batch_mask = (batch_idx == cur_id) for ins_idx in box_idxs_of_pts[batch_mask].unique(): if ins_idx < 0: continue ins_mask = (box_idxs_of_pts[batch_mask] == ins_idx) ins_num.append(ins_mask.sum().long().unsqueeze(-1)) ins_vote_loss.append(F.smooth_l1_loss(centers_pred[batch_mask][ins_mask, 1:4], center_box_labels[batch_mask][ins_mask, 0:3], reduction='sum').unsqueeze(-1)) ins_num = torch.cat(ins_num, dim=-1).float() ins_vote_loss = torch.cat(ins_vote_loss, dim=-1) ins_vote_loss = ins_vote_loss / ins_num.float().clamp(min=1.0) vote_loss = ins_vote_loss.mean() vote_loss_ver1 = vote_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['vote_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'vote_loss_ver1': vote_loss_ver1.item()}) return vote_loss_ver1, tb_dict def get_contextual_vote_loss_ver2(self, tb_dict=None): box_idxs_of_pts = self.forward_ret_dict['center_origin_box_idxs_of_pts'] center_box_labels = self.forward_ret_dict['gt_box_of_center_origin'] centers_origin = self.forward_ret_dict['centers_origin'] ctr_offsets = self.forward_ret_dict['ctr_offsets'] centers_pred = centers_origin[:, 1:] + ctr_offsets[:, 1:] centers_pred = torch.cat([centers_origin[:, :1], centers_pred], dim=-1) batch_idx = self.forward_ret_dict['centers'][:,0] ins_num, ins_vote_loss, ins_mean_vote_loss = [],[],[] for cur_id in batch_idx.unique(): batch_mask = (batch_idx == cur_id) for ins_idx in box_idxs_of_pts[batch_mask].unique(): if ins_idx < 0: continue ins_mask = (box_idxs_of_pts[batch_mask] == ins_idx) # box_idxs_of_pts[batch_mask][ins_mask] ins_num.append(ins_mask.sum().unsqueeze(-1)) ins_vote_loss.append(F.smooth_l1_loss(centers_pred[batch_mask][ins_mask, 1:4], center_box_labels[batch_mask][ins_mask, 0:3], reduction='sum').unsqueeze(-1)) ins_mean_vote_loss.append(F.smooth_l1_loss(centers_pred[batch_mask][ins_mask, 1:4], centers_pred[batch_mask][ins_mask, 1:4].mean(dim=0).repeat(centers_pred[batch_mask][ins_mask, 1:4].shape[0],1), reduction='sum').unsqueeze(-1)) ins_num = torch.cat(ins_num, dim=-1).float() ins_vote_loss = torch.cat(ins_vote_loss, dim=-1) ins_mean_vote_loss = torch.cat(ins_mean_vote_loss, dim=-1) vote_loss = ins_vote_loss + ins_mean_vote_loss * 0.5 vote_loss = vote_loss / ins_num.clamp(min=1.0) vote_loss = vote_loss.mean() vote_loss_ver2 = vote_loss * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['vote_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'vote_loss_ver2': vote_loss_ver2.item()}) return vote_loss_ver2, tb_dict def get_vote_loss_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 center_box_labels = self.forward_ret_dict['center_gt_box_of_fg_points'][:, 0:3] centers_origin = self.forward_ret_dict['centers_origin'] ctr_offsets = self.forward_ret_dict['ctr_offsets'] centers_pred = centers_origin + ctr_offsets centers_pred = centers_pred[pos_mask][:, 1:4] vote_loss = F.smooth_l1_loss(centers_pred, center_box_labels, reduction='mean') if tb_dict is None: tb_dict = {} tb_dict.update({'vote_loss': vote_loss.item()}) return vote_loss, tb_dict def get_center_cls_layer_loss(self, tb_dict=None): point_cls_labels = self.forward_ret_dict['center_cls_labels'].view(-1) point_cls_preds = self.forward_ret_dict['center_cls_preds'].view(-1, self.num_class) positives = (point_cls_labels > 0) negative_cls_weights = (point_cls_labels == 0) * 1.0 cls_weights = (1.0 *negative_cls_weights + 1.0 * positives).float() pos_normalizer = positives.sum(dim=0).float() cls_weights /= torch.clamp(pos_normalizer, min=1.0) one_hot_targets = point_cls_preds.new_zeros(*list(point_cls_labels.shape), self.num_class + 1) one_hot_targets.scatter_(-1, (point_cls_labels * (point_cls_labels >= 0).long()).unsqueeze(dim=-1).long(), 1.0) one_hot_targets = one_hot_targets[..., 1:] if self.model_cfg.LOSS_CONFIG.CENTERNESS_REGULARIZATION: centerness_mask = self.generate_center_ness_mask() one_hot_targets = one_hot_targets * centerness_mask.unsqueeze(-1).repeat(1, one_hot_targets.shape[1]) point_loss_cls = self.cls_loss_func(point_cls_preds, one_hot_targets, weights=cls_weights).mean(dim=-1).sum() loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_cls = point_loss_cls * loss_weights_dict['point_cls_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({ 'center_loss_cls': point_loss_cls.item(), 'center_pos_num': pos_normalizer.item() }) return point_loss_cls, tb_dict def get_sa_ins_layer_loss(self, tb_dict=None): sa_ins_labels = self.forward_ret_dict['sa_ins_labels'] sa_ins_preds = self.forward_ret_dict['sa_ins_preds'] sa_centerness_mask = self.generate_sa_center_ness_mask() sa_ins_loss, ignore = 0, 0 for i in range(len(sa_ins_labels)): # valid when i =1, 2 if len(sa_ins_preds[i]) != 0: try: point_cls_preds = sa_ins_preds[i][...,1:].view(-1, self.num_class) except: point_cls_preds = sa_ins_preds[i][...,1:].view(-1, 1) else: ignore += 1 continue point_cls_labels = sa_ins_labels[i].view(-1) positives = (point_cls_labels > 0) negative_cls_weights = (point_cls_labels == 0) * 1.0 cls_weights = (negative_cls_weights + 1.0 * positives).float() pos_normalizer = positives.sum(dim=0).float() cls_weights /= torch.clamp(pos_normalizer, min=1.0) one_hot_targets = point_cls_preds.new_zeros(*list(point_cls_labels.shape), self.num_class + 1) one_hot_targets.scatter_(-1, (point_cls_labels * (point_cls_labels >= 0).long()).unsqueeze(dim=-1).long(), 1.0) one_hot_targets = one_hot_targets[..., 1:] if ('ctr' in self.model_cfg.LOSS_CONFIG.SAMPLE_METHOD_LIST[i+1][0]): centerness_mask = sa_centerness_mask[i] one_hot_targets = one_hot_targets * centerness_mask.unsqueeze(-1).repeat(1, one_hot_targets.shape[1]) point_loss_ins = self.ins_loss_func(point_cls_preds, one_hot_targets, weights=cls_weights).mean(dim=-1).sum() loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_ins = point_loss_ins * loss_weights_dict.get('ins_aware_weight',[1]*len(sa_ins_labels))[i] sa_ins_loss += point_loss_ins if tb_dict is None: tb_dict = {} tb_dict.update({ 'sa%s_loss_ins' % str(i): point_loss_ins.item(), 'sa%s_pos_num' % str(i): pos_normalizer.item() }) sa_ins_loss = sa_ins_loss / (len(sa_ins_labels) - ignore) tb_dict.update({ 'sa_loss_ins': sa_ins_loss.item(), }) return sa_ins_loss, tb_dict def generate_center_ness_mask(self): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 gt_boxes = self.forward_ret_dict['center_gt_box_of_fg_points'] centers = self.forward_ret_dict['centers'][:,1:] centers = centers[pos_mask].clone().detach() offset_xyz = centers[:, 0:3] - gt_boxes[:, 0:3] offset_xyz_canical = common_utils.rotate_points_along_z(offset_xyz.unsqueeze(dim=1), -gt_boxes[:, 6]).squeeze(dim=1) template = gt_boxes.new_tensor(([1, 1, 1], [-1, -1, -1])) / 2 margin = gt_boxes[:, None, 3:6].repeat(1, 2, 1) * template[None, :, :] distance = margin - offset_xyz_canical[:, None, :].repeat(1, 2, 1) distance[:, 1, :] = -1 * distance[:, 1, :] distance_min = torch.where(distance[:, 0, :] < distance[:, 1, :], distance[:, 0, :], distance[:, 1, :]) distance_max = torch.where(distance[:, 0, :] > distance[:, 1, :], distance[:, 0, :], distance[:, 1, :]) centerness = distance_min / distance_max centerness = centerness[:, 0] * centerness[:, 1] * centerness[:, 2] centerness = torch.clamp(centerness, min=1e-6) centerness = torch.pow(centerness, 1/3) centerness_mask = pos_mask.new_zeros(pos_mask.shape).float() centerness_mask[pos_mask] = centerness return centerness_mask def generate_sa_center_ness_mask(self): sa_pos_mask = self.forward_ret_dict['sa_ins_labels'] sa_gt_boxes = self.forward_ret_dict['sa_gt_box_of_fg_points'] sa_xyz_coords = self.forward_ret_dict['sa_xyz_coords'] sa_centerness_mask = [] for i in range(len(sa_pos_mask)): pos_mask = sa_pos_mask[i] > 0 gt_boxes = sa_gt_boxes[i] xyz_coords = sa_xyz_coords[i].view(-1,sa_xyz_coords[i].shape[-1])[:,1:] xyz_coords = xyz_coords[pos_mask].clone().detach() offset_xyz = xyz_coords[:, 0:3] - gt_boxes[:, 0:3] offset_xyz_canical = common_utils.rotate_points_along_z(offset_xyz.unsqueeze(dim=1), -gt_boxes[:, 6]).squeeze(dim=1) template = gt_boxes.new_tensor(([1, 1, 1], [-1, -1, -1])) / 2 margin = gt_boxes[:, None, 3:6].repeat(1, 2, 1) * template[None, :, :] distance = margin - offset_xyz_canical[:, None, :].repeat(1, 2, 1) distance[:, 1, :] = -1 * distance[:, 1, :] distance_min = torch.where(distance[:, 0, :] < distance[:, 1, :], distance[:, 0, :], distance[:, 1, :]) distance_max = torch.where(distance[:, 0, :] > distance[:, 1, :], distance[:, 0, :], distance[:, 1, :]) centerness = distance_min / distance_max centerness = centerness[:, 0] * centerness[:, 1] * centerness[:, 2] centerness = torch.clamp(centerness, min=1e-6) centerness = torch.pow(centerness, 1/3) centerness_mask = pos_mask.new_zeros(pos_mask.shape).float() centerness_mask[pos_mask] = centerness sa_centerness_mask.append(centerness_mask) return sa_centerness_mask def get_center_box_binori_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 point_box_labels = self.forward_ret_dict['center_box_labels'] point_box_preds = self.forward_ret_dict['center_box_preds'] reg_weights = pos_mask.float() pos_normalizer = pos_mask.sum().float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) pred_box_xyzwhl = point_box_preds[:, :6] label_box_xyzwhl = point_box_labels[:, :6] point_loss_box_src = self.reg_loss_func( pred_box_xyzwhl[None, ...], label_box_xyzwhl[None, ...], weights=reg_weights[None, ...] ) point_loss_xyzwhl = point_loss_box_src.sum() pred_ori_bin_id = point_box_preds[:, 6:6+self.box_coder.bin_size] pred_ori_bin_res = point_box_preds[:, 6+self.box_coder.bin_size:] label_ori_bin_id = point_box_labels[:, 6] label_ori_bin_res = point_box_labels[:, 7] criterion = torch.nn.CrossEntropyLoss(reduction='none') loss_ori_cls = criterion(pred_ori_bin_id.contiguous(), label_ori_bin_id.long().contiguous()) loss_ori_cls = torch.sum(loss_ori_cls * reg_weights) label_id_one_hot = F.one_hot(label_ori_bin_id.long().contiguous(), self.box_coder.bin_size) pred_ori_bin_res = torch.sum(pred_ori_bin_res * label_id_one_hot.float(), dim=-1) loss_ori_reg = F.smooth_l1_loss(pred_ori_bin_res, label_ori_bin_res) loss_ori_reg = torch.sum(loss_ori_reg * reg_weights) loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS loss_ori_cls = loss_ori_cls * loss_weights_dict.get('dir_weight', 1.0) point_loss_box = point_loss_xyzwhl + loss_ori_reg + loss_ori_cls point_loss_box = point_loss_box * loss_weights_dict['point_box_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'center_loss_box': point_loss_box.item()}) tb_dict.update({'center_loss_box_xyzwhl': point_loss_xyzwhl.item()}) tb_dict.update({'center_loss_box_ori_bin': loss_ori_cls.item()}) tb_dict.update({'center_loss_box_ori_res': loss_ori_reg.item()}) return point_loss_box, tb_dict def get_center_box_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 point_box_labels = self.forward_ret_dict['center_box_labels'] point_box_preds = self.forward_ret_dict['center_box_preds'] reg_weights = pos_mask.float() pos_normalizer = pos_mask.sum().float() reg_weights /= torch.clamp(pos_normalizer, min=1.0) point_loss_box_src = self.reg_loss_func( point_box_preds[None, ...], point_box_labels[None, ...], weights=reg_weights[None, ...] ) point_loss = point_loss_box_src.sum() point_loss_box = point_loss loss_weights_dict = self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS point_loss_box = point_loss_box * loss_weights_dict['point_box_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'center_loss_box': point_loss_box.item()}) return point_loss_box, tb_dict def get_corner_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 gt_boxes = self.forward_ret_dict['center_gt_box_of_fg_points'] pred_boxes = self.forward_ret_dict['point_box_preds'] pred_boxes = pred_boxes[pos_mask] loss_corner = loss_utils.get_corner_loss_lidar( pred_boxes[:, 0:7], gt_boxes[:, 0:7] ) loss_corner = loss_corner.mean() loss_corner = loss_corner * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['corner_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'corner_loss_reg': loss_corner.item()}) return loss_corner, tb_dict def get_iou3d_layer_loss(self, tb_dict=None): pos_mask = self.forward_ret_dict['center_cls_labels'] > 0 gt_boxes = self.forward_ret_dict['center_gt_box_of_fg_points'] pred_boxes = self.forward_ret_dict['point_box_preds'].clone().detach() pred_boxes = pred_boxes[pos_mask] iou3d_targets, _ = loss_utils.generate_iou3d(pred_boxes[:, 0:7], gt_boxes[:, 0:7]) iou3d_preds = self.forward_ret_dict['box_iou3d_preds'].squeeze(-1) iou3d_preds = iou3d_preds[pos_mask] loss_iou3d = F.smooth_l1_loss(iou3d_preds, iou3d_targets) loss_iou3d = loss_iou3d * self.model_cfg.LOSS_CONFIG.LOSS_WEIGHTS['iou3d_weight'] if tb_dict is None: tb_dict = {} tb_dict.update({'iou3d_loss_reg': loss_iou3d.item()}) return loss_iou3d, tb_dict def forward(self, batch_dict): """ Args: batch_dict: batch_size: centers_features: (N1 + N2 + N3 + ..., C) or (B, N, C) centers: (N1 + N2 + N3 + ..., 4) [bs_idx, x, y, z] encoder_xyz: List of points_coords in SA gt_boxes (optional): (B, M, 8) Returns: batch_dict: batch_cls_preds: (N1 + N2 + N3 + ..., num_class) point_box_preds: (N1 + N2 + N3 + ..., 7) """ center_features = batch_dict['centers_features'] center_coords = batch_dict['centers'] center_cls_preds = self.cls_center_layers(center_features) # (total_centers, num_class) center_box_preds = self.box_center_layers(center_features) # (total_centers, box_code_size) box_iou3d_preds = self.box_iou3d_layers(center_features) if self.box_iou3d_layers is not None else None ret_dict = {'center_cls_preds': center_cls_preds, 'center_box_preds': center_box_preds, 'ctr_offsets': batch_dict['ctr_offsets'], 'centers': batch_dict['centers'], 'centers_origin': batch_dict['centers_origin'], 'sa_ins_preds': batch_dict['sa_ins_preds'], 'box_iou3d_preds': box_iou3d_preds, } if self.training: targets_dict = self.assign_targets(batch_dict) ret_dict.update(targets_dict) if not self.training or self.predict_boxes_when_training or \ self.model_cfg.LOSS_CONFIG.CORNER_LOSS_REGULARIZATION or \ self.model_cfg.LOSS_CONFIG.CENTERNESS_REGULARIZATION or \ self.model_cfg.LOSS_CONFIG.IOU3D_REGULARIZATION: point_cls_preds, point_box_preds = self.generate_predicted_boxes( points=center_coords[:, 1:4], point_cls_preds=center_cls_preds, point_box_preds=center_box_preds ) batch_dict['batch_cls_preds'] = point_cls_preds batch_dict['batch_box_preds'] = point_box_preds batch_dict['box_iou3d_preds'] = box_iou3d_preds batch_dict['batch_index'] = center_coords[:,0] batch_dict['cls_preds_normalized'] = False ret_dict['point_box_preds'] = point_box_preds self.forward_ret_dict = ret_dict return batch_dict
42,278
49.212589
259
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/target_assigner/anchor_generator.py
import torch class AnchorGenerator(object): def __init__(self, anchor_range, anchor_generator_config): super().__init__() self.anchor_generator_cfg = anchor_generator_config self.anchor_range = anchor_range self.anchor_sizes = [config['anchor_sizes'] for config in anchor_generator_config] self.anchor_rotations = [config['anchor_rotations'] for config in anchor_generator_config] self.anchor_heights = [config['anchor_bottom_heights'] for config in anchor_generator_config] self.align_center = [config.get('align_center', False) for config in anchor_generator_config] assert len(self.anchor_sizes) == len(self.anchor_rotations) == len(self.anchor_heights) self.num_of_anchor_sets = len(self.anchor_sizes) def generate_anchors(self, grid_sizes): assert len(grid_sizes) == self.num_of_anchor_sets all_anchors = [] num_anchors_per_location = [] for grid_size, anchor_size, anchor_rotation, anchor_height, align_center in zip( grid_sizes, self.anchor_sizes, self.anchor_rotations, self.anchor_heights, self.align_center): num_anchors_per_location.append(len(anchor_rotation) * len(anchor_size) * len(anchor_height)) if align_center: x_stride = (self.anchor_range[3] - self.anchor_range[0]) / grid_size[0] y_stride = (self.anchor_range[4] - self.anchor_range[1]) / grid_size[1] x_offset, y_offset = x_stride / 2, y_stride / 2 else: x_stride = (self.anchor_range[3] - self.anchor_range[0]) / (grid_size[0] - 1) y_stride = (self.anchor_range[4] - self.anchor_range[1]) / (grid_size[1] - 1) x_offset, y_offset = 0, 0 x_shifts = torch.arange( self.anchor_range[0] + x_offset, self.anchor_range[3] + 1e-5, step=x_stride, dtype=torch.float32, ).cuda() y_shifts = torch.arange( self.anchor_range[1] + y_offset, self.anchor_range[4] + 1e-5, step=y_stride, dtype=torch.float32, ).cuda() z_shifts = x_shifts.new_tensor(anchor_height) num_anchor_size, num_anchor_rotation = anchor_size.__len__(), anchor_rotation.__len__() anchor_rotation = x_shifts.new_tensor(anchor_rotation) anchor_size = x_shifts.new_tensor(anchor_size) x_shifts, y_shifts, z_shifts = torch.meshgrid([ x_shifts, y_shifts, z_shifts ]) # [x_grid, y_grid, z_grid] anchors = torch.stack((x_shifts, y_shifts, z_shifts), dim=-1) # [x, y, z, 3] anchors = anchors[:, :, :, None, :].repeat(1, 1, 1, anchor_size.shape[0], 1) anchor_size = anchor_size.view(1, 1, 1, -1, 3).repeat([*anchors.shape[0:3], 1, 1]) anchors = torch.cat((anchors, anchor_size), dim=-1) anchors = anchors[:, :, :, :, None, :].repeat(1, 1, 1, 1, num_anchor_rotation, 1) anchor_rotation = anchor_rotation.view(1, 1, 1, 1, -1, 1).repeat([*anchors.shape[0:3], num_anchor_size, 1, 1]) anchors = torch.cat((anchors, anchor_rotation), dim=-1) # [x, y, z, num_size, num_rot, 7] anchors = anchors.permute(2, 1, 0, 3, 4, 5).contiguous() #anchors = anchors.view(-1, anchors.shape[-1]) anchors[..., 2] += anchors[..., 5] / 2 # shift to box centers all_anchors.append(anchors) return all_anchors, num_anchors_per_location if __name__ == '__main__': from easydict import EasyDict config = [ EasyDict({ 'anchor_sizes': [[2.1, 4.7, 1.7], [0.86, 0.91, 1.73], [0.84, 1.78, 1.78]], 'anchor_rotations': [0, 1.57], 'anchor_heights': [0, 0.5] }) ] A = AnchorGenerator( anchor_range=[-75.2, -75.2, -2, 75.2, 75.2, 4], anchor_generator_config=config ) import pdb pdb.set_trace() A.generate_anchors([[188, 188]])
3,990
48.8875
122
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/target_assigner/axis_aligned_target_assigner.py
import numpy as np import torch from ....ops.iou3d_nms import iou3d_nms_utils from ....utils import box_utils class AxisAlignedTargetAssigner(object): def __init__(self, model_cfg, class_names, box_coder, match_height=False): super().__init__() anchor_generator_cfg = model_cfg.ANCHOR_GENERATOR_CONFIG anchor_target_cfg = model_cfg.TARGET_ASSIGNER_CONFIG self.box_coder = box_coder self.match_height = match_height self.class_names = np.array(class_names) self.anchor_class_names = [config['class_name'] for config in anchor_generator_cfg] self.pos_fraction = anchor_target_cfg.POS_FRACTION if anchor_target_cfg.POS_FRACTION >= 0 else None self.sample_size = anchor_target_cfg.SAMPLE_SIZE self.norm_by_num_examples = anchor_target_cfg.NORM_BY_NUM_EXAMPLES self.matched_thresholds = {} self.unmatched_thresholds = {} for config in anchor_generator_cfg: self.matched_thresholds[config['class_name']] = config['matched_threshold'] self.unmatched_thresholds[config['class_name']] = config['unmatched_threshold'] self.use_multihead = model_cfg.get('USE_MULTIHEAD', False) # self.separate_multihead = model_cfg.get('SEPARATE_MULTIHEAD', False) # if self.seperate_multihead: # rpn_head_cfgs = model_cfg.RPN_HEAD_CFGS # self.gt_remapping = {} # for rpn_head_cfg in rpn_head_cfgs: # for idx, name in enumerate(rpn_head_cfg['HEAD_CLS_NAME']): # self.gt_remapping[name] = idx + 1 def assign_targets(self, all_anchors, gt_boxes_with_classes): """ Args: all_anchors: [(N, 7), ...] gt_boxes: (B, M, 8) Returns: """ bbox_targets = [] cls_labels = [] reg_weights = [] batch_size = gt_boxes_with_classes.shape[0] gt_classes = gt_boxes_with_classes[:, :, -1] gt_boxes = gt_boxes_with_classes[:, :, :-1] for k in range(batch_size): cur_gt = gt_boxes[k] cnt = cur_gt.__len__() - 1 while cnt > 0 and cur_gt[cnt].sum() == 0: cnt -= 1 cur_gt = cur_gt[:cnt + 1] cur_gt_classes = gt_classes[k][:cnt + 1].int() target_list = [] for anchor_class_name, anchors in zip(self.anchor_class_names, all_anchors): if cur_gt_classes.shape[0] > 1: # mask = torch.from_numpy(self.class_names[cur_gt_classes.cpu() - 1] == anchor_class_name) # old version mask = torch.from_numpy(self.class_names[cur_gt_classes.cpu().abs() - 1] == anchor_class_name) # pseudo-labeling version else: # old version # mask = torch.tensor([self.class_names[c - 1] == anchor_class_name # for c in cur_gt_classes], dtype=torch.bool) # pseudo-labeling version mask = torch.tensor([self.class_names[torch.abs(c) - 1] == anchor_class_name for c in cur_gt_classes], dtype=torch.bool) if self.use_multihead: anchors = anchors.permute(3, 4, 0, 1, 2, 5).contiguous().view(-1, anchors.shape[-1]) # if self.seperate_multihead: # selected_classes = cur_gt_classes[mask].clone() # if len(selected_classes) > 0: # new_cls_id = self.gt_remapping[anchor_class_name] # selected_classes[:] = new_cls_id # else: # selected_classes = cur_gt_classes[mask] selected_classes = cur_gt_classes[mask] else: feature_map_size = anchors.shape[:3] anchors = anchors.view(-1, anchors.shape[-1]) selected_classes = cur_gt_classes[mask] single_target = self.assign_targets_single( anchors, cur_gt[mask], gt_classes=selected_classes, matched_threshold=self.matched_thresholds[anchor_class_name], unmatched_threshold=self.unmatched_thresholds[anchor_class_name] ) target_list.append(single_target) if self.use_multihead: target_dict = { 'box_cls_labels': [t['box_cls_labels'].view(-1) for t in target_list], 'box_reg_targets': [t['box_reg_targets'].view(-1, self.box_coder.code_size) for t in target_list], 'reg_weights': [t['reg_weights'].view(-1) for t in target_list] } target_dict['box_reg_targets'] = torch.cat(target_dict['box_reg_targets'], dim=0) target_dict['box_cls_labels'] = torch.cat(target_dict['box_cls_labels'], dim=0).view(-1) target_dict['reg_weights'] = torch.cat(target_dict['reg_weights'], dim=0).view(-1) else: target_dict = { 'box_cls_labels': [t['box_cls_labels'].view(*feature_map_size, -1) for t in target_list], 'box_reg_targets': [t['box_reg_targets'].view(*feature_map_size, -1, self.box_coder.code_size) for t in target_list], 'reg_weights': [t['reg_weights'].view(*feature_map_size, -1) for t in target_list] } target_dict['box_reg_targets'] = torch.cat( target_dict['box_reg_targets'], dim=-2 ).view(-1, self.box_coder.code_size) target_dict['box_cls_labels'] = torch.cat(target_dict['box_cls_labels'], dim=-1).view(-1) target_dict['reg_weights'] = torch.cat(target_dict['reg_weights'], dim=-1).view(-1) bbox_targets.append(target_dict['box_reg_targets']) cls_labels.append(target_dict['box_cls_labels']) reg_weights.append(target_dict['reg_weights']) bbox_targets = torch.stack(bbox_targets, dim=0) cls_labels = torch.stack(cls_labels, dim=0) reg_weights = torch.stack(reg_weights, dim=0) all_targets_dict = { 'box_cls_labels': cls_labels, 'box_reg_targets': bbox_targets, 'reg_weights': reg_weights } return all_targets_dict def assign_targets_single(self, anchors, gt_boxes, gt_classes, matched_threshold=0.6, unmatched_threshold=0.45): num_anchors = anchors.shape[0] num_gt = gt_boxes.shape[0] labels = torch.ones((num_anchors,), dtype=torch.int32, device=anchors.device) * -1 gt_ids = torch.ones((num_anchors,), dtype=torch.int32, device=anchors.device) * -1 if len(gt_boxes) > 0 and anchors.shape[0] > 0: anchor_by_gt_overlap = iou3d_nms_utils.boxes_iou3d_gpu(anchors[:, 0:7], gt_boxes[:, 0:7]) \ if self.match_height else box_utils.boxes3d_nearest_bev_iou(anchors[:, 0:7], gt_boxes[:, 0:7]) # NOTE: The speed of these two versions depends the environment and the number of anchors # anchor_to_gt_argmax = torch.from_numpy(anchor_by_gt_overlap.cpu().numpy().argmax(axis=1)).cuda() anchor_to_gt_argmax = anchor_by_gt_overlap.argmax(dim=1) anchor_to_gt_max = anchor_by_gt_overlap[torch.arange(num_anchors, device=anchors.device), anchor_to_gt_argmax] # gt_to_anchor_argmax = torch.from_numpy(anchor_by_gt_overlap.cpu().numpy().argmax(axis=0)).cuda() gt_to_anchor_argmax = anchor_by_gt_overlap.argmax(dim=0) gt_to_anchor_max = anchor_by_gt_overlap[gt_to_anchor_argmax, torch.arange(num_gt, device=anchors.device)] empty_gt_mask = gt_to_anchor_max == 0 gt_to_anchor_max[empty_gt_mask] = -1 anchors_with_max_overlap = (anchor_by_gt_overlap == gt_to_anchor_max).nonzero()[:, 0] gt_inds_force = anchor_to_gt_argmax[anchors_with_max_overlap] labels[anchors_with_max_overlap] = gt_classes[gt_inds_force] gt_ids[anchors_with_max_overlap] = gt_inds_force.int() pos_inds = anchor_to_gt_max >= matched_threshold gt_inds_over_thresh = anchor_to_gt_argmax[pos_inds] labels[pos_inds] = gt_classes[gt_inds_over_thresh] gt_ids[pos_inds] = gt_inds_over_thresh.int() bg_inds = (anchor_to_gt_max < unmatched_threshold).nonzero()[:, 0] else: bg_inds = torch.arange(num_anchors, device=anchors.device) fg_inds = (labels > 0).nonzero()[:, 0] if self.pos_fraction is not None: num_fg = int(self.pos_fraction * self.sample_size) if len(fg_inds) > num_fg: num_disabled = len(fg_inds) - num_fg disable_inds = torch.randperm(len(fg_inds))[:num_disabled] labels[disable_inds] = -1 fg_inds = (labels > 0).nonzero()[:, 0] num_bg = self.sample_size - (labels > 0).sum() if len(bg_inds) > num_bg: enable_inds = bg_inds[torch.randint(0, len(bg_inds), size=(num_bg,))] labels[enable_inds] = 0 # bg_inds = torch.nonzero(labels == 0)[:, 0] else: if len(gt_boxes) == 0 or anchors.shape[0] == 0: labels[:] = 0 else: labels[bg_inds] = 0 labels[anchors_with_max_overlap] = gt_classes[gt_inds_force] bbox_targets = anchors.new_zeros((num_anchors, self.box_coder.code_size)) if len(gt_boxes) > 0 and anchors.shape[0] > 0: fg_gt_boxes = gt_boxes[anchor_to_gt_argmax[fg_inds], :] fg_anchors = anchors[fg_inds, :] bbox_targets[fg_inds, :] = self.box_coder.encode_torch(fg_gt_boxes, fg_anchors) reg_weights = anchors.new_zeros((num_anchors,)) if self.norm_by_num_examples: num_examples = (labels >= 0).sum() num_examples = num_examples if num_examples > 1.0 else 1.0 reg_weights[labels > 0] = 1.0 / num_examples else: reg_weights[labels > 0] = 1.0 ret_dict = { 'box_cls_labels': labels, 'box_reg_targets': bbox_targets, 'reg_weights': reg_weights, } return ret_dict
10,465
47.453704
140
py
3DTrans
3DTrans-master/pcdet/models/dense_heads/target_assigner/atss_target_assigner.py
import torch from ....ops.iou3d_nms import iou3d_nms_utils from ....utils import common_utils class ATSSTargetAssigner(object): """ Reference: https://arxiv.org/abs/1912.02424 """ def __init__(self, topk, box_coder, match_height=False): self.topk = topk self.box_coder = box_coder self.match_height = match_height def assign_targets(self, anchors_list, gt_boxes_with_classes, use_multihead=False): """ Args: anchors: [(N, 7), ...] gt_boxes: (B, M, 8) Returns: """ if not isinstance(anchors_list, list): anchors_list = [anchors_list] single_set_of_anchor = True else: single_set_of_anchor = len(anchors_list) == 1 cls_labels_list, reg_targets_list, reg_weights_list = [], [], [] for anchors in anchors_list: batch_size = gt_boxes_with_classes.shape[0] gt_classes = gt_boxes_with_classes[:, :, -1] gt_boxes = gt_boxes_with_classes[:, :, :-1] if use_multihead: anchors = anchors.permute(3, 4, 0, 1, 2, 5).contiguous().view(-1, anchors.shape[-1]) else: anchors = anchors.view(-1, anchors.shape[-1]) cls_labels, reg_targets, reg_weights = [], [], [] for k in range(batch_size): cur_gt = gt_boxes[k] cnt = cur_gt.__len__() - 1 while cnt > 0 and cur_gt[cnt].sum() == 0: cnt -= 1 cur_gt = cur_gt[:cnt + 1] cur_gt_classes = gt_classes[k][:cnt + 1] cur_cls_labels, cur_reg_targets, cur_reg_weights = self.assign_targets_single( anchors, cur_gt, cur_gt_classes ) cls_labels.append(cur_cls_labels) reg_targets.append(cur_reg_targets) reg_weights.append(cur_reg_weights) cls_labels = torch.stack(cls_labels, dim=0) reg_targets = torch.stack(reg_targets, dim=0) reg_weights = torch.stack(reg_weights, dim=0) cls_labels_list.append(cls_labels) reg_targets_list.append(reg_targets) reg_weights_list.append(reg_weights) if single_set_of_anchor: ret_dict = { 'box_cls_labels': cls_labels_list[0], 'box_reg_targets': reg_targets_list[0], 'reg_weights': reg_weights_list[0] } else: ret_dict = { 'box_cls_labels': torch.cat(cls_labels_list, dim=1), 'box_reg_targets': torch.cat(reg_targets_list, dim=1), 'reg_weights': torch.cat(reg_weights_list, dim=1) } return ret_dict def assign_targets_single(self, anchors, gt_boxes, gt_classes): """ Args: anchors: (N, 7) [x, y, z, dx, dy, dz, heading] gt_boxes: (M, 7) [x, y, z, dx, dy, dz, heading] gt_classes: (M) Returns: """ num_anchor = anchors.shape[0] num_gt = gt_boxes.shape[0] # select topk anchors for each gt_boxes if self.match_height: ious = iou3d_nms_utils.boxes_iou3d_gpu(anchors[:, 0:7], gt_boxes[:, 0:7]) # (N, M) else: ious = iou3d_nms_utils.boxes_iou_bev(anchors[:, 0:7], gt_boxes[:, 0:7]) distance = (anchors[:, None, 0:3] - gt_boxes[None, :, 0:3]).norm(dim=-1) # (N, M) _, topk_idxs = distance.topk(self.topk, dim=0, largest=False) # (K, M) candidate_ious = ious[topk_idxs, torch.arange(num_gt)] # (K, M) iou_mean_per_gt = candidate_ious.mean(dim=0) iou_std_per_gt = candidate_ious.std(dim=0) iou_thresh_per_gt = iou_mean_per_gt + iou_std_per_gt + 1e-6 is_pos = candidate_ious >= iou_thresh_per_gt[None, :] # (K, M) # check whether anchor_center in gt_boxes, only check BEV x-y axes candidate_anchors = anchors[topk_idxs.view(-1)] # (KxM, 7) gt_boxes_of_each_anchor = gt_boxes[:, :].repeat(self.topk, 1) # (KxM, 7) xyz_local = candidate_anchors[:, 0:3] - gt_boxes_of_each_anchor[:, 0:3] xyz_local = common_utils.rotate_points_along_z( xyz_local[:, None, :], -gt_boxes_of_each_anchor[:, 6] ).squeeze(dim=1) xy_local = xyz_local[:, 0:2] lw = gt_boxes_of_each_anchor[:, 3:5][:, [1, 0]] # bugfixed: w ==> y, l ==> x in local coords is_in_gt = ((xy_local <= lw / 2) & (xy_local >= -lw / 2)).all(dim=-1).view(-1, num_gt) # (K, M) is_pos = is_pos & is_in_gt # (K, M) for ng in range(num_gt): topk_idxs[:, ng] += ng * num_anchor # select the highest IoU if an anchor box is assigned with multiple gt_boxes INF = -0x7FFFFFFF ious_inf = torch.full_like(ious, INF).t().contiguous().view(-1) # (MxN) index = topk_idxs.view(-1)[is_pos.view(-1)] ious_inf[index] = ious.t().contiguous().view(-1)[index] ious_inf = ious_inf.view(num_gt, -1).t() # (N, M) anchors_to_gt_values, anchors_to_gt_indexs = ious_inf.max(dim=1) # match the gt_boxes to the anchors which have maximum iou with them max_iou_of_each_gt, argmax_iou_of_each_gt = ious.max(dim=0) anchors_to_gt_indexs[argmax_iou_of_each_gt] = torch.arange(0, num_gt, device=ious.device) anchors_to_gt_values[argmax_iou_of_each_gt] = max_iou_of_each_gt cls_labels = gt_classes[anchors_to_gt_indexs] cls_labels[anchors_to_gt_values == INF] = 0 matched_gts = gt_boxes[anchors_to_gt_indexs] pos_mask = cls_labels > 0 reg_targets = matched_gts.new_zeros((num_anchor, self.box_coder.code_size)) reg_weights = matched_gts.new_zeros(num_anchor) if pos_mask.sum() > 0: reg_targets[pos_mask > 0] = self.box_coder.encode_torch(matched_gts[pos_mask > 0], anchors[pos_mask > 0]) reg_weights[pos_mask] = 1.0 return cls_labels, reg_targets, reg_weights
6,050
41.612676
117
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/roi_head_template.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from ...utils import box_coder_utils, common_utils, loss_utils from ..model_utils.model_nms_utils import class_agnostic_nms from .target_assigner.proposal_target_layer import ProposalTargetLayer class RoIHeadTemplate(nn.Module): def __init__(self, num_class, model_cfg, **kwargs): super().__init__() self.model_cfg = model_cfg self.num_class = num_class self.box_coder = getattr(box_coder_utils, self.model_cfg.TARGET_CONFIG.BOX_CODER)( **self.model_cfg.TARGET_CONFIG.get('BOX_CODER_CONFIG', {}) ) self.proposal_target_layer = ProposalTargetLayer(roi_sampler_cfg=self.model_cfg.TARGET_CONFIG) self.build_losses(self.model_cfg.LOSS_CONFIG) self.forward_ret_dict = None def build_losses(self, losses_cfg): self.add_module( 'reg_loss_func', loss_utils.WeightedSmoothL1Loss(code_weights=losses_cfg.LOSS_WEIGHTS['code_weights']) ) def make_fc_layers(self, input_channels, output_channels, fc_list): fc_layers = [] pre_channel = input_channels for k in range(0, fc_list.__len__()): fc_layers.extend([ nn.Conv1d(pre_channel, fc_list[k], kernel_size=1, bias=False), nn.BatchNorm1d(fc_list[k]), nn.ReLU() ]) pre_channel = fc_list[k] if self.model_cfg.DP_RATIO >= 0 and k == 0: fc_layers.append(nn.Dropout(self.model_cfg.DP_RATIO)) fc_layers.append(nn.Conv1d(pre_channel, output_channels, kernel_size=1, bias=True)) fc_layers = nn.Sequential(*fc_layers) return fc_layers @torch.no_grad() def proposal_layer(self, batch_dict, nms_config): """ Args: batch_dict: batch_size: batch_cls_preds: (B, num_boxes, num_classes | 1) or (N1+N2+..., num_classes | 1) batch_box_preds: (B, num_boxes, 7+C) or (N1+N2+..., 7+C) cls_preds_normalized: indicate whether batch_cls_preds is normalized batch_index: optional (N1+N2+...) nms_config: Returns: batch_dict: rois: (B, num_rois, 7+C) roi_scores: (B, num_rois) roi_labels: (B, num_rois) """ if batch_dict.get('rois', None) is not None: return batch_dict batch_size = batch_dict['batch_size'] batch_box_preds = batch_dict['batch_box_preds'] batch_cls_preds = batch_dict['batch_cls_preds'] rois = batch_box_preds.new_zeros((batch_size, nms_config.NMS_POST_MAXSIZE, batch_box_preds.shape[-1])) roi_scores = batch_box_preds.new_zeros((batch_size, nms_config.NMS_POST_MAXSIZE)) roi_labels = batch_box_preds.new_zeros((batch_size, nms_config.NMS_POST_MAXSIZE), dtype=torch.long) for index in range(batch_size): if batch_dict.get('batch_index', None) is not None: assert batch_cls_preds.shape.__len__() == 2 batch_mask = (batch_dict['batch_index'] == index) else: assert batch_dict['batch_cls_preds'].shape.__len__() == 3 batch_mask = index box_preds = batch_box_preds[batch_mask] cls_preds = batch_cls_preds[batch_mask] cur_roi_scores, cur_roi_labels = torch.max(cls_preds, dim=1) if nms_config.MULTI_CLASSES_NMS: raise NotImplementedError else: selected, selected_scores = class_agnostic_nms( box_scores=cur_roi_scores, box_preds=box_preds, nms_config=nms_config ) rois[index, :len(selected), :] = box_preds[selected] roi_scores[index, :len(selected)] = cur_roi_scores[selected] roi_labels[index, :len(selected)] = cur_roi_labels[selected] batch_dict['rois'] = rois batch_dict['roi_scores'] = roi_scores batch_dict['roi_labels'] = roi_labels + 1 batch_dict['has_class_labels'] = True if batch_cls_preds.shape[-1] > 1 else False batch_dict.pop('batch_index', None) return batch_dict def assign_targets(self, batch_dict): batch_size = batch_dict['batch_size'] with torch.no_grad(): targets_dict = self.proposal_target_layer.forward(batch_dict) rois = targets_dict['rois'] # (B, N, 7 + C) gt_of_rois = targets_dict['gt_of_rois'] # (B, N, 7 + C + 1) targets_dict['gt_of_rois_src'] = gt_of_rois.clone().detach() # canonical transformation roi_center = rois[:, :, 0:3] roi_ry = rois[:, :, 6] % (2 * np.pi) gt_of_rois[:, :, 0:3] = gt_of_rois[:, :, 0:3] - roi_center gt_of_rois[:, :, 6] = gt_of_rois[:, :, 6] - roi_ry # transfer LiDAR coords to local coords gt_of_rois = common_utils.rotate_points_along_z( points=gt_of_rois.view(-1, 1, gt_of_rois.shape[-1]), angle=-roi_ry.view(-1) ).view(batch_size, -1, gt_of_rois.shape[-1]) # flip orientation if rois have opposite orientation heading_label = gt_of_rois[:, :, 6] % (2 * np.pi) # 0 ~ 2pi opposite_flag = (heading_label > np.pi * 0.5) & (heading_label < np.pi * 1.5) heading_label[opposite_flag] = (heading_label[opposite_flag] + np.pi) % (2 * np.pi) # (0 ~ pi/2, 3pi/2 ~ 2pi) flag = heading_label > np.pi heading_label[flag] = heading_label[flag] - np.pi * 2 # (-pi/2, pi/2) heading_label = torch.clamp(heading_label, min=-np.pi / 2, max=np.pi / 2) gt_of_rois[:, :, 6] = heading_label targets_dict['gt_of_rois'] = gt_of_rois return targets_dict def get_box_reg_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG code_size = self.box_coder.code_size reg_valid_mask = forward_ret_dict['reg_valid_mask'].view(-1) gt_boxes3d_ct = forward_ret_dict['gt_of_rois'][..., 0:code_size] gt_of_rois_src = forward_ret_dict['gt_of_rois_src'][..., 0:code_size].view(-1, code_size) rcnn_reg = forward_ret_dict['rcnn_reg'] # (rcnn_batch_size, C) roi_boxes3d = forward_ret_dict['rois'] rcnn_batch_size = gt_boxes3d_ct.view(-1, code_size).shape[0] fg_mask = (reg_valid_mask > 0) fg_sum = fg_mask.long().sum().item() tb_dict = {} if loss_cfgs.REG_LOSS == 'smooth-l1': rois_anchor = roi_boxes3d.clone().detach().view(-1, code_size) rois_anchor[:, 0:3] = 0 rois_anchor[:, 6] = 0 reg_targets = self.box_coder.encode_torch( gt_boxes3d_ct.view(rcnn_batch_size, code_size), rois_anchor ) rcnn_loss_reg = self.reg_loss_func( rcnn_reg.view(rcnn_batch_size, -1).unsqueeze(dim=0), reg_targets.unsqueeze(dim=0), ) # [B, M, 7] rcnn_loss_reg = (rcnn_loss_reg.view(rcnn_batch_size, -1) * fg_mask.unsqueeze(dim=-1).float()).sum() / max(fg_sum, 1) rcnn_loss_reg = rcnn_loss_reg * loss_cfgs.LOSS_WEIGHTS['rcnn_reg_weight'] tb_dict['rcnn_loss_reg'] = rcnn_loss_reg.item() if loss_cfgs.CORNER_LOSS_REGULARIZATION and fg_sum > 0: # TODO: NEED to BE CHECK fg_rcnn_reg = rcnn_reg.view(rcnn_batch_size, -1)[fg_mask] fg_roi_boxes3d = roi_boxes3d.view(-1, code_size)[fg_mask] fg_roi_boxes3d = fg_roi_boxes3d.view(1, -1, code_size) batch_anchors = fg_roi_boxes3d.clone().detach() roi_ry = fg_roi_boxes3d[:, :, 6].view(-1) roi_xyz = fg_roi_boxes3d[:, :, 0:3].view(-1, 3) batch_anchors[:, :, 0:3] = 0 rcnn_boxes3d = self.box_coder.decode_torch( fg_rcnn_reg.view(batch_anchors.shape[0], -1, code_size), batch_anchors ).view(-1, code_size) rcnn_boxes3d = common_utils.rotate_points_along_z( rcnn_boxes3d.unsqueeze(dim=1), roi_ry ).squeeze(dim=1) rcnn_boxes3d[:, 0:3] += roi_xyz loss_corner = loss_utils.get_corner_loss_lidar( rcnn_boxes3d[:, 0:7], gt_of_rois_src[fg_mask][:, 0:7] ) loss_corner = loss_corner.mean() loss_corner = loss_corner * loss_cfgs.LOSS_WEIGHTS['rcnn_corner_weight'] rcnn_loss_reg += loss_corner tb_dict['rcnn_loss_corner'] = loss_corner.item() else: raise NotImplementedError return rcnn_loss_reg, tb_dict def get_box_cls_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG rcnn_cls = forward_ret_dict['rcnn_cls'] rcnn_cls_labels = forward_ret_dict['rcnn_cls_labels'].view(-1) if loss_cfgs.CLS_LOSS == 'BinaryCrossEntropy': rcnn_cls_flat = rcnn_cls.view(-1) batch_loss_cls = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat), rcnn_cls_labels.float(), reduction='none') cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) elif loss_cfgs.CLS_LOSS == 'CrossEntropy': batch_loss_cls = F.cross_entropy(rcnn_cls, rcnn_cls_labels, reduction='none', ignore_index=-1) cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) else: raise NotImplementedError rcnn_loss_cls = rcnn_loss_cls * loss_cfgs.LOSS_WEIGHTS['rcnn_cls_weight'] tb_dict = {'rcnn_loss_cls': rcnn_loss_cls.item()} return rcnn_loss_cls, tb_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict rcnn_loss = 0 rcnn_loss_cls, cls_tb_dict = self.get_box_cls_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_cls tb_dict.update(cls_tb_dict) rcnn_loss_reg, reg_tb_dict = self.get_box_reg_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_reg tb_dict.update(reg_tb_dict) tb_dict['rcnn_loss'] = rcnn_loss.item() return rcnn_loss, tb_dict def generate_predicted_boxes(self, batch_size, rois, cls_preds, box_preds): """ Args: batch_size: rois: (B, N, 7) cls_preds: (BN, num_class) box_preds: (BN, code_size) Returns: """ code_size = self.box_coder.code_size # batch_cls_preds: (B, N, num_class or 1) batch_cls_preds = cls_preds.view(batch_size, -1, cls_preds.shape[-1]) batch_box_preds = box_preds.view(batch_size, -1, code_size) roi_ry = rois[:, :, 6].view(-1) roi_xyz = rois[:, :, 0:3].view(-1, 3) local_rois = rois.clone().detach() local_rois[:, :, 0:3] = 0 batch_box_preds = self.box_coder.decode_torch(batch_box_preds, local_rois).view(-1, code_size) batch_box_preds = common_utils.rotate_points_along_z( batch_box_preds.unsqueeze(dim=1), roi_ry ).squeeze(dim=1) batch_box_preds[:, 0:3] += roi_xyz batch_box_preds = batch_box_preds.view(batch_size, -1, code_size) return batch_cls_preds, batch_box_preds
11,557
43.114504
128
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/voxelrcnn_head.py
import torch import torch.nn as nn from ...ops.pointnet2.pointnet2_stack import voxel_pool_modules as voxelpool_stack_modules from ...utils import common_utils from .roi_head_template import RoIHeadTemplate class VoxelRCNNHead(RoIHeadTemplate): def __init__(self, backbone_channels, model_cfg, point_cloud_range, voxel_size, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.pool_cfg = model_cfg.ROI_GRID_POOL LAYER_cfg = self.pool_cfg.POOL_LAYERS self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size c_out = 0 self.roi_grid_pool_layers = nn.ModuleList() for src_name in self.pool_cfg.FEATURES_SOURCE: mlps = LAYER_cfg[src_name].MLPS for k in range(len(mlps)): mlps[k] = [backbone_channels[src_name]] + mlps[k] pool_layer = voxelpool_stack_modules.NeighborVoxelSAModuleMSG( query_ranges=LAYER_cfg[src_name].QUERY_RANGES, nsamples=LAYER_cfg[src_name].NSAMPLE, radii=LAYER_cfg[src_name].POOL_RADIUS, mlps=mlps, pool_method=LAYER_cfg[src_name].POOL_METHOD, ) self.roi_grid_pool_layers.append(pool_layer) c_out += sum([x[-1] for x in mlps]) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # c_out = sum([x[-1] for x in mlps]) pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.SHARED_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU(inplace=True) ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) cls_fc_list = [] for k in range(0, self.model_cfg.CLS_FC.__len__()): cls_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.CLS_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.CLS_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.CLS_FC[k] if k != self.model_cfg.CLS_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: cls_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.cls_fc_layers = nn.Sequential(*cls_fc_list) self.cls_pred_layer = nn.Linear(pre_channel, self.num_class, bias=True) reg_fc_list = [] for k in range(0, self.model_cfg.REG_FC.__len__()): reg_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.REG_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.REG_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.REG_FC[k] if k != self.model_cfg.REG_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: reg_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.reg_fc_layers = nn.Sequential(*reg_fc_list) self.reg_pred_layer = nn.Linear(pre_channel, self.box_coder.code_size * self.num_class, bias=True) self.init_weights() def init_weights(self): init_func = nn.init.xavier_normal_ for module_list in [self.shared_fc_layer, self.cls_fc_layers, self.reg_fc_layers]: for m in module_list.modules(): if isinstance(m, nn.Linear): init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.cls_pred_layer.weight, 0, 0.01) nn.init.constant_(self.cls_pred_layer.bias, 0) nn.init.normal_(self.reg_pred_layer.weight, mean=0, std=0.001) nn.init.constant_(self.reg_pred_layer.bias, 0) # def _init_weights(self): # init_func = nn.init.xavier_normal_ # for m in self.modules(): # if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear): # init_func(m.weight) # if m.bias is not None: # nn.init.constant_(m.bias, 0) # nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ rois = batch_dict['rois'] batch_size = batch_dict['batch_size'] with_vf_transform = batch_dict.get('with_voxel_feature_transform', False) roi_grid_xyz, _ = self.get_global_grid_points_of_roi( rois, grid_size=self.pool_cfg.GRID_SIZE ) # (BxN, 6x6x6, 3) # roi_grid_xyz: (B, Nx6x6x6, 3) roi_grid_xyz = roi_grid_xyz.view(batch_size, -1, 3) # compute the voxel coordinates of grid points roi_grid_coords_x = (roi_grid_xyz[:, :, 0:1] - self.point_cloud_range[0]) // self.voxel_size[0] roi_grid_coords_y = (roi_grid_xyz[:, :, 1:2] - self.point_cloud_range[1]) // self.voxel_size[1] roi_grid_coords_z = (roi_grid_xyz[:, :, 2:3] - self.point_cloud_range[2]) // self.voxel_size[2] # roi_grid_coords: (B, Nx6x6x6, 3) roi_grid_coords = torch.cat([roi_grid_coords_x, roi_grid_coords_y, roi_grid_coords_z], dim=-1) batch_idx = rois.new_zeros(batch_size, roi_grid_coords.shape[1], 1) for bs_idx in range(batch_size): batch_idx[bs_idx, :, 0] = bs_idx # roi_grid_coords: (B, Nx6x6x6, 4) # roi_grid_coords = torch.cat([batch_idx, roi_grid_coords], dim=-1) # roi_grid_coords = roi_grid_coords.int() roi_grid_batch_cnt = rois.new_zeros(batch_size).int().fill_(roi_grid_coords.shape[1]) pooled_features_list = [] for k, src_name in enumerate(self.pool_cfg.FEATURES_SOURCE): pool_layer = self.roi_grid_pool_layers[k] cur_stride = batch_dict['multi_scale_3d_strides'][src_name] cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] if with_vf_transform: cur_sp_tensors = batch_dict['multi_scale_3d_features_post'][src_name] else: cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] # compute voxel center xyz and batch_cnt cur_coords = cur_sp_tensors.indices cur_voxel_xyz = common_utils.get_voxel_centers( cur_coords[:, 1:4], downsample_times=cur_stride, voxel_size=self.voxel_size, point_cloud_range=self.point_cloud_range ) cur_voxel_xyz_batch_cnt = cur_voxel_xyz.new_zeros(batch_size).int() for bs_idx in range(batch_size): cur_voxel_xyz_batch_cnt[bs_idx] = (cur_coords[:, 0] == bs_idx).sum() # get voxel2point tensor v2p_ind_tensor = common_utils.generate_voxel2pinds(cur_sp_tensors) # compute the grid coordinates in this scale, in [batch_idx, x y z] order cur_roi_grid_coords = roi_grid_coords // cur_stride cur_roi_grid_coords = torch.cat([batch_idx, cur_roi_grid_coords], dim=-1) cur_roi_grid_coords = cur_roi_grid_coords.int() # voxel neighbor aggregation pooled_features = pool_layer( xyz=cur_voxel_xyz.contiguous(), xyz_batch_cnt=cur_voxel_xyz_batch_cnt, new_xyz=roi_grid_xyz.contiguous().view(-1, 3), new_xyz_batch_cnt=roi_grid_batch_cnt, new_coords=cur_roi_grid_coords.contiguous().view(-1, 4), features=cur_sp_tensors.features.contiguous(), voxel2point_indices=v2p_ind_tensor ) pooled_features = pooled_features.view( -1, self.pool_cfg.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) pooled_features_list.append(pooled_features) ms_pooled_features = torch.cat(pooled_features_list, dim=-1) return ms_pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) # Box Refinement pooled_features = pooled_features.view(pooled_features.size(0), -1) shared_features = self.shared_fc_layer(pooled_features) rcnn_cls = self.cls_pred_layer(self.cls_fc_layers(shared_features)) rcnn_reg = self.reg_pred_layer(self.reg_fc_layers(shared_features)) # grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # batch_size_rcnn = pooled_features.shape[0] # pooled_features = pooled_features.permute(0, 2, 1).\ # contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) # shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) # rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) # rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict class ActiveVoxelRCNNHead(RoIHeadTemplate): def __init__(self, backbone_channels, model_cfg, point_cloud_range, voxel_size, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.pool_cfg = model_cfg.ROI_GRID_POOL LAYER_cfg = self.pool_cfg.POOL_LAYERS self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size c_out = 0 self.roi_grid_pool_layers = nn.ModuleList() for src_name in self.pool_cfg.FEATURES_SOURCE: mlps = LAYER_cfg[src_name].MLPS for k in range(len(mlps)): mlps[k] = [backbone_channels[src_name]] + mlps[k] pool_layer = voxelpool_stack_modules.NeighborVoxelSAModuleMSG( query_ranges=LAYER_cfg[src_name].QUERY_RANGES, nsamples=LAYER_cfg[src_name].NSAMPLE, radii=LAYER_cfg[src_name].POOL_RADIUS, mlps=mlps, pool_method=LAYER_cfg[src_name].POOL_METHOD, ) self.roi_grid_pool_layers.append(pool_layer) c_out += sum([x[-1] for x in mlps]) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # c_out = sum([x[-1] for x in mlps]) pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.SHARED_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU(inplace=True) ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) cls_fc_list = [] for k in range(0, self.model_cfg.CLS_FC.__len__()): cls_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.CLS_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.CLS_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.CLS_FC[k] if k != self.model_cfg.CLS_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: cls_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.cls_fc_layers = nn.Sequential(*cls_fc_list) self.cls_pred_layer = nn.Linear(pre_channel, self.num_class, bias=True) reg_fc_list = [] for k in range(0, self.model_cfg.REG_FC.__len__()): reg_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.REG_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.REG_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.REG_FC[k] if k != self.model_cfg.REG_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: reg_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.reg_fc_layers = nn.Sequential(*reg_fc_list) self.reg_pred_layer = nn.Linear(pre_channel, self.box_coder.code_size * self.num_class, bias=True) self.init_weights() def init_weights(self): init_func = nn.init.xavier_normal_ for module_list in [self.shared_fc_layer, self.cls_fc_layers, self.reg_fc_layers]: for m in module_list.modules(): if isinstance(m, nn.Linear): init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.cls_pred_layer.weight, 0, 0.01) nn.init.constant_(self.cls_pred_layer.bias, 0) nn.init.normal_(self.reg_pred_layer.weight, mean=0, std=0.001) nn.init.constant_(self.reg_pred_layer.bias, 0) # def _init_weights(self): # init_func = nn.init.xavier_normal_ # for m in self.modules(): # if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear): # init_func(m.weight) # if m.bias is not None: # nn.init.constant_(m.bias, 0) # nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ rois = batch_dict['rois'] batch_size = batch_dict['batch_size'] with_vf_transform = batch_dict.get('with_voxel_feature_transform', False) roi_grid_xyz, _ = self.get_global_grid_points_of_roi( rois, grid_size=self.pool_cfg.GRID_SIZE ) # (BxN, 6x6x6, 3) # roi_grid_xyz: (B, Nx6x6x6, 3) roi_grid_xyz = roi_grid_xyz.view(batch_size, -1, 3) # compute the voxel coordinates of grid points roi_grid_coords_x = (roi_grid_xyz[:, :, 0:1] - self.point_cloud_range[0]) // self.voxel_size[0] roi_grid_coords_y = (roi_grid_xyz[:, :, 1:2] - self.point_cloud_range[1]) // self.voxel_size[1] roi_grid_coords_z = (roi_grid_xyz[:, :, 2:3] - self.point_cloud_range[2]) // self.voxel_size[2] # roi_grid_coords: (B, Nx6x6x6, 3) roi_grid_coords = torch.cat([roi_grid_coords_x, roi_grid_coords_y, roi_grid_coords_z], dim=-1) batch_idx = rois.new_zeros(batch_size, roi_grid_coords.shape[1], 1) for bs_idx in range(batch_size): batch_idx[bs_idx, :, 0] = bs_idx # roi_grid_coords: (B, Nx6x6x6, 4) # roi_grid_coords = torch.cat([batch_idx, roi_grid_coords], dim=-1) # roi_grid_coords = roi_grid_coords.int() roi_grid_batch_cnt = rois.new_zeros(batch_size).int().fill_(roi_grid_coords.shape[1]) pooled_features_list = [] for k, src_name in enumerate(self.pool_cfg.FEATURES_SOURCE): pool_layer = self.roi_grid_pool_layers[k] cur_stride = batch_dict['multi_scale_3d_strides'][src_name] cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] if with_vf_transform: cur_sp_tensors = batch_dict['multi_scale_3d_features_post'][src_name] else: cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] # compute voxel center xyz and batch_cnt cur_coords = cur_sp_tensors.indices cur_voxel_xyz = common_utils.get_voxel_centers( cur_coords[:, 1:4], downsample_times=cur_stride, voxel_size=self.voxel_size, point_cloud_range=self.point_cloud_range ) cur_voxel_xyz_batch_cnt = cur_voxel_xyz.new_zeros(batch_size).int() for bs_idx in range(batch_size): cur_voxel_xyz_batch_cnt[bs_idx] = (cur_coords[:, 0] == bs_idx).sum() # get voxel2point tensor v2p_ind_tensor = common_utils.generate_voxel2pinds(cur_sp_tensors) # compute the grid coordinates in this scale, in [batch_idx, x y z] order cur_roi_grid_coords = roi_grid_coords // cur_stride cur_roi_grid_coords = torch.cat([batch_idx, cur_roi_grid_coords], dim=-1) cur_roi_grid_coords = cur_roi_grid_coords.int() # voxel neighbor aggregation pooled_features = pool_layer( xyz=cur_voxel_xyz.contiguous(), xyz_batch_cnt=cur_voxel_xyz_batch_cnt, new_xyz=roi_grid_xyz.contiguous().view(-1, 3), new_xyz_batch_cnt=roi_grid_batch_cnt, new_coords=cur_roi_grid_coords.contiguous().view(-1, 4), features=cur_sp_tensors.features.contiguous(), voxel2point_indices=v2p_ind_tensor ) pooled_features = pooled_features.view( -1, self.pool_cfg.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) pooled_features_list.append(pooled_features) ms_pooled_features = torch.cat(pooled_features_list, dim=-1) return ms_pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) # Box Refinement pooled_features = pooled_features.view(pooled_features.size(0), -1) shared_features = self.shared_fc_layer(pooled_features) if batch_dict['mode'] == 'active_evaluate': batch_size = batch_dict['batch_size'] roi_num = pooled_features.size(0) // batch_size batch_dict['roi_shared_feature'] = shared_features.view(batch_size, roi_num, -1) rcnn_cls = self.cls_pred_layer(self.cls_fc_layers(shared_features)) rcnn_reg = self.reg_pred_layer(self.reg_fc_layers(shared_features)) # grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # batch_size_rcnn = pooled_features.shape[0] # pooled_features = pooled_features.permute(0, 2, 1).\ # contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) # shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) # rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) # rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict class VoxelRCNNHead_ABL(RoIHeadTemplate): def __init__(self, backbone_channels, model_cfg, point_cloud_range, voxel_size, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.pool_cfg = model_cfg.ROI_GRID_POOL LAYER_cfg = self.pool_cfg.POOL_LAYERS self.point_cloud_range = point_cloud_range self.voxel_size = voxel_size c_out = 0 self.roi_grid_pool_layers = nn.ModuleList() for src_name in self.pool_cfg.FEATURES_SOURCE: mlps = LAYER_cfg[src_name].MLPS for k in range(len(mlps)): mlps[k] = [backbone_channels[src_name]] + mlps[k] pool_layer = voxelpool_stack_modules.NeighborVoxelSAModuleMSG( query_ranges=LAYER_cfg[src_name].QUERY_RANGES, nsamples=LAYER_cfg[src_name].NSAMPLE, radii=LAYER_cfg[src_name].POOL_RADIUS, mlps=mlps, pool_method=LAYER_cfg[src_name].POOL_METHOD, ) self.roi_grid_pool_layers.append(pool_layer) c_out += sum([x[-1] for x in mlps]) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # c_out = sum([x[-1] for x in mlps]) pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.SHARED_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU(inplace=True) ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) cls_pre_channel = pre_channel cls_fc_list = [] for k in range(0, self.model_cfg.CLS_FC.__len__()): cls_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.CLS_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.CLS_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.CLS_FC[k] if k != self.model_cfg.CLS_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: cls_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.cls_fc_layers = nn.Sequential(*cls_fc_list) self.cls_pred_layer = nn.Linear(pre_channel, self.num_class, bias=True) cls_pre_channel_1 = cls_pre_channel cls_fc_list_1 = [] for k in range(0, self.model_cfg.CLS_FC.__len__()): cls_fc_list_1.extend([ nn.Linear(cls_pre_channel_1, self.model_cfg.CLS_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.CLS_FC[k]), nn.ReLU() ]) cls_pre_channel_1 = self.model_cfg.CLS_FC[k] if k != self.model_cfg.CLS_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: cls_fc_list_1.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.cls_fc_layers_1 = nn.Sequential(*cls_fc_list_1) self.cls_pred_layer_1 = nn.Linear(pre_channel, self.num_class, bias=True) cls_pre_channel_2 = cls_pre_channel cls_fc_list_2 = [] for k in range(0, self.model_cfg.CLS_FC.__len__()): cls_fc_list_2.extend([ nn.Linear(cls_pre_channel_2, self.model_cfg.CLS_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.CLS_FC[k]), nn.ReLU() ]) cls_pre_channel_2 = self.model_cfg.CLS_FC[k] if k != self.model_cfg.CLS_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: cls_fc_list_2.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.cls_fc_layers_2 = nn.Sequential(*cls_fc_list_2) self.cls_pred_layer_2 = nn.Linear(pre_channel, self.num_class, bias=True) reg_fc_list = [] for k in range(0, self.model_cfg.REG_FC.__len__()): reg_fc_list.extend([ nn.Linear(pre_channel, self.model_cfg.REG_FC[k], bias=False), nn.BatchNorm1d(self.model_cfg.REG_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.REG_FC[k] if k != self.model_cfg.REG_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: reg_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.reg_fc_layers = nn.Sequential(*reg_fc_list) self.reg_pred_layer = nn.Linear(pre_channel, self.box_coder.code_size * self.num_class, bias=True) self.init_weights() def init_weights(self): init_func = nn.init.xavier_normal_ for module_list in [self.shared_fc_layer, self.cls_fc_layers, self.reg_fc_layers]: for m in module_list.modules(): if isinstance(m, nn.Linear): init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.cls_pred_layer.weight, 0, 0.01) nn.init.constant_(self.cls_pred_layer.bias, 0) nn.init.normal_(self.reg_pred_layer.weight, mean=0, std=0.001) nn.init.constant_(self.reg_pred_layer.bias, 0) nn.init.kaiming_normal_(self.cls_pred_layer_1.weight) nn.init.xavier_normal_(self.cls_pred_layer_2.weight) # def _init_weights(self): # init_func = nn.init.xavier_normal_ # for m in self.modules(): # if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear): # init_func(m.weight) # if m.bias is not None: # nn.init.constant_(m.bias, 0) # nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ rois = batch_dict['rois'] batch_size = batch_dict['batch_size'] with_vf_transform = batch_dict.get('with_voxel_feature_transform', False) roi_grid_xyz, _ = self.get_global_grid_points_of_roi( rois, grid_size=self.pool_cfg.GRID_SIZE ) # (BxN, 6x6x6, 3) # roi_grid_xyz: (B, Nx6x6x6, 3) roi_grid_xyz = roi_grid_xyz.view(batch_size, -1, 3) # compute the voxel coordinates of grid points roi_grid_coords_x = (roi_grid_xyz[:, :, 0:1] - self.point_cloud_range[0]) // self.voxel_size[0] roi_grid_coords_y = (roi_grid_xyz[:, :, 1:2] - self.point_cloud_range[1]) // self.voxel_size[1] roi_grid_coords_z = (roi_grid_xyz[:, :, 2:3] - self.point_cloud_range[2]) // self.voxel_size[2] # roi_grid_coords: (B, Nx6x6x6, 3) roi_grid_coords = torch.cat([roi_grid_coords_x, roi_grid_coords_y, roi_grid_coords_z], dim=-1) batch_idx = rois.new_zeros(batch_size, roi_grid_coords.shape[1], 1) for bs_idx in range(batch_size): batch_idx[bs_idx, :, 0] = bs_idx # roi_grid_coords: (B, Nx6x6x6, 4) # roi_grid_coords = torch.cat([batch_idx, roi_grid_coords], dim=-1) # roi_grid_coords = roi_grid_coords.int() roi_grid_batch_cnt = rois.new_zeros(batch_size).int().fill_(roi_grid_coords.shape[1]) pooled_features_list = [] for k, src_name in enumerate(self.pool_cfg.FEATURES_SOURCE): pool_layer = self.roi_grid_pool_layers[k] cur_stride = batch_dict['multi_scale_3d_strides'][src_name] cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] if with_vf_transform: cur_sp_tensors = batch_dict['multi_scale_3d_features_post'][src_name] else: cur_sp_tensors = batch_dict['multi_scale_3d_features'][src_name] # compute voxel center xyz and batch_cnt cur_coords = cur_sp_tensors.indices cur_voxel_xyz = common_utils.get_voxel_centers( cur_coords[:, 1:4], downsample_times=cur_stride, voxel_size=self.voxel_size, point_cloud_range=self.point_cloud_range ) cur_voxel_xyz_batch_cnt = cur_voxel_xyz.new_zeros(batch_size).int() for bs_idx in range(batch_size): cur_voxel_xyz_batch_cnt[bs_idx] = (cur_coords[:, 0] == bs_idx).sum() # get voxel2point tensor v2p_ind_tensor = common_utils.generate_voxel2pinds(cur_sp_tensors) # compute the grid coordinates in this scale, in [batch_idx, x y z] order cur_roi_grid_coords = roi_grid_coords // cur_stride cur_roi_grid_coords = torch.cat([batch_idx, cur_roi_grid_coords], dim=-1) cur_roi_grid_coords = cur_roi_grid_coords.int() # voxel neighbor aggregation pooled_features = pool_layer( xyz=cur_voxel_xyz.contiguous(), xyz_batch_cnt=cur_voxel_xyz_batch_cnt, new_xyz=roi_grid_xyz.contiguous().view(-1, 3), new_xyz_batch_cnt=roi_grid_batch_cnt, new_coords=cur_roi_grid_coords.contiguous().view(-1, 4), features=cur_sp_tensors.features.contiguous(), voxel2point_indices=v2p_ind_tensor ) pooled_features = pooled_features.view( -1, self.pool_cfg.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) pooled_features_list.append(pooled_features) ms_pooled_features = torch.cat(pooled_features_list, dim=-1) return ms_pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) # Box Refinement pooled_features = pooled_features.view(pooled_features.size(0), -1) shared_features = self.shared_fc_layer(pooled_features) if batch_dict['mode'] == 'active_evaluate': batch_size = batch_dict['batch_size'] roi_num = pooled_features.size(0) // batch_size batch_dict['roi_shared_feature'] = shared_features.view(batch_size, roi_num, -1) rcnn_cls = self.cls_pred_layer(self.cls_fc_layers(shared_features)) rcnn_cls_1 = self.cls_pred_layer_1(self.cls_fc_layers_1(shared_features)) rcnn_cls_2 = self.cls_pred_layer_2(self.cls_fc_layers_2(shared_features)) rcnn_reg = self.reg_pred_layer(self.reg_fc_layers(shared_features)) batch_dict['rcnn_cls'] = rcnn_cls batch_dict['rcnn_cls_1'] = rcnn_cls_1 batch_dict['rcnn_cls_2'] = rcnn_cls_2 # grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE # batch_size_rcnn = pooled_features.shape[0] # pooled_features = pooled_features.permute(0, 2, 1).\ # contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) # shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) # rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) # rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_cls_1'] = rcnn_cls_1 targets_dict['rcnn_cls_2'] = rcnn_cls_2 targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict def get_box_mul_cls_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG rcnn_cls = forward_ret_dict['rcnn_cls'] rcnn_cls_1 = forward_ret_dict['rcnn_cls_1'] rcnn_cls_2 = forward_ret_dict['rcnn_cls_2'] rcnn_cls_labels = forward_ret_dict['rcnn_cls_labels'].view(-1) if loss_cfgs.CLS_LOSS == 'BinaryCrossEntropy': rcnn_cls_flat = rcnn_cls.view(-1) rcnn_cls_flat_1 = rcnn_cls_1.view(-1) rcnn_cls_flat_2 = rcnn_cls_2.view(-1) batch_loss_cls = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat), rcnn_cls_labels.float(), reduction='none') batch_loss_cls_1 = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat_1), rcnn_cls_labels.float(), reduction='none') batch_loss_cls_2 = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat_2), rcnn_cls_labels.float(), reduction='none') cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) rcnn_loss_cls_1 = (batch_loss_cls_1 * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) rcnn_loss_cls_2 = (batch_loss_cls_2 * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) elif loss_cfgs.CLS_LOSS == 'CrossEntropy': batch_loss_cls = F.cross_entropy(rcnn_cls, rcnn_cls_labels, reduction='none', ignore_index=-1) batch_loss_cls_1 = F.cross_entropy(rcnn_cls_1, rcnn_cls_labels, reduction='none', ignore_index=-1) batch_loss_cls_2 = F.cross_entropy(rcnn_cls_2, rcnn_cls_labels, reduction='none', ignore_index=-1) cls_valid_mask = (rcnn_cls_labels >= 0).float() rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) rcnn_loss_cls_1 = (batch_loss_cls_1 * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) rcnn_loss_cls_2 = (batch_loss_cls_2 * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0) else: raise NotImplementedError rcnn_loss_cls = rcnn_loss_cls * loss_cfgs.LOSS_WEIGHTS['rcnn_cls_weight'] rcnn_mul_cls_loss = rcnn_loss_cls_1 + rcnn_loss_cls_2 tb_dict = {'rcnn_loss_cls': rcnn_loss_cls.item()} return rcnn_loss_cls, rcnn_mul_cls_loss, tb_dict def get_mul_cls_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict rcnn_loss = 0 rcnn_loss_cls, rcnn_mul_cls_loss, cls_tb_dict = self.get_box_mul_cls_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_cls tb_dict.update(cls_tb_dict) rcnn_loss_reg, reg_tb_dict = self.get_box_reg_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_reg tb_dict.update(reg_tb_dict) tb_dict['rcnn_loss'] = rcnn_loss.item() return rcnn_loss, rcnn_mul_cls_loss, tb_dict def committee_evaluate(self, batch_dict): batch_size = batch_dict['batch_size'] cls_1 = batch_dict['rcnn_cls_1'].view(batch_size, -1) cls_2 = batch_dict['rcnn_cls_2'].view(batch_size, -1) committee_score = torch.mean(torch.abs(cls_1 - cls_2), dim=-1) batch_dict['committee_score'] = committee_score return batch_dict def uncertainty_evaluate(self, batch_dict): batch_size = batch_dict['batch_size'] cls = batch_dict['rcnn_cls'] cls = cls.view(batch_size, -1) uncertainty = torch.mean(torch.abs(cls - (1-cls)), dim=-1) batch_dict['uncertainty'] = uncertainty return batch_dict
41,813
45.876682
128
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/pvrcnn_head_semi.py
import torch.nn as nn import torch import torch.nn.functional as F from ...ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules from ...utils import common_utils from .roi_head_template import RoIHeadTemplate class PVRCNNHeadSemi(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.roi_grid_pool_layer, num_c_out = pointnet2_stack_modules.build_local_aggregation_module( input_channels=input_channels, config=self.model_cfg.ROI_GRID_POOL ) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * num_c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.cls_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'] point_coords = batch_dict['point_coords'] point_features = batch_dict['point_features'] point_features = point_features * batch_dict['point_cls_scores'].view(-1, 1) global_roi_grid_points, local_roi_grid_points = self.get_global_grid_points_of_roi( rois, grid_size=self.model_cfg.ROI_GRID_POOL.GRID_SIZE ) # (BxN, 6x6x6, 3) global_roi_grid_points = global_roi_grid_points.view(batch_size, -1, 3) # (B, Nx6x6x6, 3) xyz = point_coords[:, 1:4] xyz_batch_cnt = xyz.new_zeros(batch_size).int() batch_idx = point_coords[:, 0] for k in range(batch_size): xyz_batch_cnt[k] = (batch_idx == k).sum() new_xyz = global_roi_grid_points.view(-1, 3) new_xyz_batch_cnt = xyz.new_zeros(batch_size).int().fill_(global_roi_grid_points.shape[1]) pooled_points, pooled_features = self.roi_grid_pool_layer( xyz=xyz.contiguous(), xyz_batch_cnt=xyz_batch_cnt, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt, features=point_features.contiguous(), ) # (M1 + M2 ..., C) pooled_features = pooled_features.view( -1, self.model_cfg.ROI_GRID_POOL.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) return pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ if self.model_type == 'origin': targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = batch_dict.get('roi_targets_dict', None) if targets_dict is None: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict elif self.model_type == 'teacher': targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TEST'] #TODO: Check if the NMS needs to open when SSL ) # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False elif self.model_type == 'student': if 'gt_boxes' in batch_dict: targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) else: targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TEST'] #TODO: Check if the NMS needs to open when SSL ) if self.training: if 'gt_boxes' in batch_dict: targets_dict = batch_dict.get('roi_targets_dict', None) if targets_dict is None: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False if 'gt_boxes' in batch_dict: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict else: raise Exception('Unsupprted model type') return batch_dict
11,809
45.679842
123
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/partA2_head.py
import numpy as np import torch import torch.nn as nn from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils.spconv_utils import spconv from .roi_head_template import RoIHeadTemplate class PartA2FCHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.SA_modules = nn.ModuleList() block = self.post_act_block c0 = self.model_cfg.ROI_AWARE_POOL.NUM_FEATURES // 2 self.conv_part = spconv.SparseSequential( block(4, 64, 3, padding=1, indice_key='rcnn_subm1'), block(64, c0, 3, padding=1, indice_key='rcnn_subm1_1'), ) self.conv_rpn = spconv.SparseSequential( block(input_channels, 64, 3, padding=1, indice_key='rcnn_subm2'), block(64, c0, 3, padding=1, indice_key='rcnn_subm1_2'), ) shared_fc_list = [] pool_size = self.model_cfg.ROI_AWARE_POOL.POOL_SIZE pre_channel = self.model_cfg.ROI_AWARE_POOL.NUM_FEATURES * pool_size * pool_size * pool_size for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.cls_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.roiaware_pool3d_layer = roiaware_pool3d_utils.RoIAwarePool3d( out_size=self.model_cfg.ROI_AWARE_POOL.POOL_SIZE, max_pts_each_voxel=self.model_cfg.ROI_AWARE_POOL.MAX_POINTS_PER_VOXEL ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def post_act_block(self, in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='subm'): if conv_type == 'subm': m = spconv.SparseSequential( spconv.SubMConv3d(in_channels, out_channels, kernel_size, bias=False, indice_key=indice_key), nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01), nn.ReLU(), ) elif conv_type == 'spconv': m = spconv.SparseSequential( spconv.SparseConv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=False, indice_key=indice_key), nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01), nn.ReLU(), ) elif conv_type == 'inverseconv': m = spconv.SparseSequential( spconv.SparseInverseConv3d(in_channels, out_channels, kernel_size, indice_key=indice_key, bias=False), nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01), nn.ReLU(), ) else: raise NotImplementedError return m def roiaware_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] batch_idx = batch_dict['point_coords'][:, 0] point_coords = batch_dict['point_coords'][:, 1:4] point_features = batch_dict['point_features'] part_features = torch.cat(( batch_dict['point_part_offset'] if not self.model_cfg.get('DISABLE_PART', False) else point_coords, batch_dict['point_cls_scores'].view(-1, 1).detach() ), dim=1) part_features[part_features[:, -1] < self.model_cfg.SEG_MASK_SCORE_THRESH, 0:3] = 0 rois = batch_dict['rois'] pooled_part_features_list, pooled_rpn_features_list = [], [] for bs_idx in range(batch_size): bs_mask = (batch_idx == bs_idx) cur_point_coords = point_coords[bs_mask] cur_part_features = part_features[bs_mask] cur_rpn_features = point_features[bs_mask] cur_roi = rois[bs_idx][:, 0:7].contiguous() # (N, 7) pooled_part_features = self.roiaware_pool3d_layer.forward( cur_roi, cur_point_coords, cur_part_features, pool_method='avg' ) # (N, out_x, out_y, out_z, 4) pooled_rpn_features = self.roiaware_pool3d_layer.forward( cur_roi, cur_point_coords, cur_rpn_features, pool_method='max' ) # (N, out_x, out_y, out_z, C) pooled_part_features_list.append(pooled_part_features) pooled_rpn_features_list.append(pooled_rpn_features) pooled_part_features = torch.cat(pooled_part_features_list, dim=0) # (B * N, out_x, out_y, out_z, 4) pooled_rpn_features = torch.cat(pooled_rpn_features_list, dim=0) # (B * N, out_x, out_y, out_z, C) return pooled_part_features, pooled_rpn_features @staticmethod def fake_sparse_idx(sparse_idx, batch_size_rcnn): print('Warning: Sparse_Idx_Shape(%s) \r' % (str(sparse_idx.shape)), end='', flush=True) # at most one sample is non-empty, then fake the first voxels of each sample(BN needs at least # two values each channel) as non-empty for the below calculation sparse_idx = sparse_idx.new_zeros((batch_size_rcnn, 3)) bs_idxs = torch.arange(batch_size_rcnn).type_as(sparse_idx).view(-1, 1) sparse_idx = torch.cat((bs_idxs, sparse_idx), dim=1) return sparse_idx def forward(self, batch_dict): """ Args: batch_dict: Returns: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_part_features, pooled_rpn_features = self.roiaware_pool(batch_dict) batch_size_rcnn = pooled_part_features.shape[0] # (B * N, out_x, out_y, out_z, 4) # transform to sparse tensors sparse_shape = np.array(pooled_part_features.shape[1:4], dtype=np.int32) sparse_idx = pooled_part_features.sum(dim=-1).nonzero() # (non_empty_num, 4) ==> [bs_idx, x_idx, y_idx, z_idx] if sparse_idx.shape[0] < 3: sparse_idx = self.fake_sparse_idx(sparse_idx, batch_size_rcnn) if self.training: # these are invalid samples targets_dict['rcnn_cls_labels'].fill_(-1) targets_dict['reg_valid_mask'].fill_(-1) part_features = pooled_part_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]] rpn_features = pooled_rpn_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]] coords = sparse_idx.int().contiguous() part_features = spconv.SparseConvTensor(part_features, coords, sparse_shape, batch_size_rcnn) rpn_features = spconv.SparseConvTensor(rpn_features, coords, sparse_shape, batch_size_rcnn) # forward rcnn network x_part = self.conv_part(part_features) x_rpn = self.conv_rpn(rpn_features) merged_feature = torch.cat((x_rpn.features, x_part.features), dim=1) # (N, C) shared_feature = spconv.SparseConvTensor(merged_feature, coords, sparse_shape, batch_size_rcnn) shared_feature = shared_feature.dense().view(batch_size_rcnn, -1, 1) shared_feature = self.shared_fc_layer(shared_feature) rcnn_cls = self.cls_layers(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict
10,089
43.844444
120
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/pvrcnn_head_MoE.py
import torch.nn as nn from ...ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules from ...utils import common_utils from .roi_head_template import RoIHeadTemplate class PVRCNNHeadMoE(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.roi_grid_pool_layer, num_c_out = pointnet2_stack_modules.build_local_aggregation_module( input_channels=input_channels, config=self.model_cfg.ROI_GRID_POOL ) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * num_c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) ## MoE Learning self.moe_fc_gate_s1 = nn.Sequential( nn.Conv1d(self.model_cfg.SHARED_FC[k], self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ) self.moe_fc_gate_s2 = nn.Sequential( nn.Conv1d(self.model_cfg.SHARED_FC[k], self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ) self.cls_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'] point_coords = batch_dict['point_coords'] point_features = batch_dict['point_features'] point_features = point_features * batch_dict['point_cls_scores'].view(-1, 1) global_roi_grid_points, local_roi_grid_points = self.get_global_grid_points_of_roi( rois, grid_size=self.model_cfg.ROI_GRID_POOL.GRID_SIZE ) # (BxN, 6x6x6, 3) global_roi_grid_points = global_roi_grid_points.view(batch_size, -1, 3) # (B, Nx6x6x6, 3) xyz = point_coords[:, 1:4] xyz_batch_cnt = xyz.new_zeros(batch_size).int() batch_idx = point_coords[:, 0] for k in range(batch_size): xyz_batch_cnt[k] = (batch_idx == k).sum() new_xyz = global_roi_grid_points.view(-1, 3) new_xyz_batch_cnt = xyz.new_zeros(batch_size).int().fill_(global_roi_grid_points.shape[1]) pooled_points, pooled_features = self.roi_grid_pool_layer( xyz=xyz.contiguous(), xyz_batch_cnt=xyz_batch_cnt, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt, features=point_features.contiguous(), ) # (M1 + M2 ..., C) pooled_features = pooled_features.view( -1, self.model_cfg.ROI_GRID_POOL.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) return pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = batch_dict.get('roi_targets_dict', None) if targets_dict is None: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) # MoE to obtain the gate weight if batch_dict['source_tag'] == 1: gate_weights_s1 = self.moe_fc_gate_s1(shared_features) gate_weights_s1 = gate_weights_s1 * shared_features shared_features = shared_features + gate_weights_s1 elif batch_dict['source_tag'] == 2: gate_weights_s2 = self.moe_fc_gate_s2(shared_features) gate_weights_s2 = gate_weights_s2 * shared_features shared_features = shared_features + gate_weights_s2 rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict
8,480
42.050761
116
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/pvrcnn_head.py
import torch.nn as nn import torch import torch.nn.functional as F from ...ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules from ...utils import common_utils from .roi_head_template import RoIHeadTemplate class PVRCNNHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.roi_grid_pool_layer, num_c_out = pointnet2_stack_modules.build_local_aggregation_module( input_channels=input_channels, config=self.model_cfg.ROI_GRID_POOL ) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * num_c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.cls_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'] point_coords = batch_dict['point_coords'] point_features = batch_dict['point_features'] point_features = point_features * batch_dict['point_cls_scores'].view(-1, 1) global_roi_grid_points, local_roi_grid_points = self.get_global_grid_points_of_roi( rois, grid_size=self.model_cfg.ROI_GRID_POOL.GRID_SIZE ) # (BxN, 6x6x6, 3) global_roi_grid_points = global_roi_grid_points.view(batch_size, -1, 3) # (B, Nx6x6x6, 3) xyz = point_coords[:, 1:4] xyz_batch_cnt = xyz.new_zeros(batch_size).int() batch_idx = point_coords[:, 0] for k in range(batch_size): xyz_batch_cnt[k] = (batch_idx == k).sum() new_xyz = global_roi_grid_points.view(-1, 3) new_xyz_batch_cnt = xyz.new_zeros(batch_size).int().fill_(global_roi_grid_points.shape[1]) pooled_points, pooled_features = self.roi_grid_pool_layer( xyz=xyz.contiguous(), xyz_batch_cnt=xyz_batch_cnt, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt, features=point_features.contiguous(), ) # (M1 + M2 ..., C) pooled_features = pooled_features.view( -1, self.model_cfg.ROI_GRID_POOL.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) return pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = batch_dict.get('roi_targets_dict', None) if targets_dict is None: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict class ActivePVRCNNHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg self.roi_grid_pool_layer, num_c_out = pointnet2_stack_modules.build_local_aggregation_module( input_channels=input_channels, config=self.model_cfg.ROI_GRID_POOL ) GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = GRID_SIZE * GRID_SIZE * GRID_SIZE * num_c_out shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.cls_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'] point_coords = batch_dict['point_coords'] point_features = batch_dict['point_features'] point_features = point_features * batch_dict['point_cls_scores'].view(-1, 1) global_roi_grid_points, local_roi_grid_points = self.get_global_grid_points_of_roi( rois, grid_size=self.model_cfg.ROI_GRID_POOL.GRID_SIZE ) # (BxN, 6x6x6, 3) global_roi_grid_points = global_roi_grid_points.view(batch_size, -1, 3) # (B, Nx6x6x6, 3) xyz = point_coords[:, 1:4] xyz_batch_cnt = xyz.new_zeros(batch_size).int() batch_idx = point_coords[:, 0] for k in range(batch_size): xyz_batch_cnt[k] = (batch_idx == k).sum() new_xyz = global_roi_grid_points.view(-1, 3) new_xyz_batch_cnt = xyz.new_zeros(batch_size).int().fill_(global_roi_grid_points.shape[1]) pooled_points, pooled_features = self.roi_grid_pool_layer( xyz=xyz.contiguous(), xyz_batch_cnt=xyz_batch_cnt, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt, features=point_features.contiguous(), ) # (M1 + M2 ..., C) pooled_features = pooled_features.view( -1, self.model_cfg.ROI_GRID_POOL.GRID_SIZE ** 3, pooled_features.shape[-1] ) # (BxN, 6x6x6, C) return pooled_features def get_global_grid_points_of_roi(self, rois, grid_size): rois = rois.view(-1, rois.shape[-1]) batch_size_rcnn = rois.shape[0] local_roi_grid_points = self.get_dense_grid_points(rois, batch_size_rcnn, grid_size) # (B, 6x6x6, 3) global_roi_grid_points = common_utils.rotate_points_along_z( local_roi_grid_points.clone(), rois[:, 6] ).squeeze(dim=1) global_center = rois[:, 0:3].clone() global_roi_grid_points += global_center.unsqueeze(dim=1) return global_roi_grid_points, local_roi_grid_points @staticmethod def get_dense_grid_points(rois, batch_size_rcnn, grid_size): faked_features = rois.new_ones((grid_size, grid_size, grid_size)) dense_idx = faked_features.nonzero() # (N, 3) [x_idx, y_idx, z_idx] dense_idx = dense_idx.repeat(batch_size_rcnn, 1, 1).float() # (B, 6x6x6, 3) local_roi_size = rois.view(batch_size_rcnn, -1)[:, 3:6] roi_grid_points = (dense_idx + 0.5) / grid_size * local_roi_size.unsqueeze(dim=1) \ - (local_roi_size.unsqueeze(dim=1) / 2) # (B, 6x6x6, 3) return roi_grid_points def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = batch_dict.get('roi_targets_dict', None) if targets_dict is None: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, 6x6x6, C) grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE batch_size_rcnn = pooled_features.shape[0] pooled_features = pooled_features.permute(0, 2, 1).\ contiguous().view(batch_size_rcnn, -1, grid_size, grid_size, grid_size) # (BxN, C, 6, 6, 6) shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) if batch_dict['mode'] == 'active_evaluate': batch_size = batch_dict['batch_size'] roi_num = batch_size_rcnn // batch_size batch_dict['roi_shared_feature'] = shared_features.view(batch_size, roi_num, -1) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict
15,017
41.543909
116
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/second_head.py
import torch import torch.nn as nn from .roi_head_template import RoIHeadTemplate from ...utils import common_utils, loss_utils class SECONDHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = self.model_cfg.ROI_GRID_POOL.IN_CHANNEL * GRID_SIZE * GRID_SIZE shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.iou_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=1, fc_list=self.model_cfg.IOU_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) spatial_features_2d: (B, C, H, W) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'].detach() spatial_features_2d = batch_dict['spatial_features_2d'].detach() height, width = spatial_features_2d.size(2), spatial_features_2d.size(3) dataset_cfg = batch_dict['dataset_cfg'] min_x = dataset_cfg.POINT_CLOUD_RANGE[0] min_y = dataset_cfg.POINT_CLOUD_RANGE[1] voxel_size_x = dataset_cfg.DATA_PROCESSOR[-1].VOXEL_SIZE[0] voxel_size_y = dataset_cfg.DATA_PROCESSOR[-1].VOXEL_SIZE[1] down_sample_ratio = self.model_cfg.ROI_GRID_POOL.DOWNSAMPLE_RATIO pooled_features_list = [] torch.backends.cudnn.enabled = False for b_id in range(batch_size): # Map global boxes coordinates to feature map coordinates x1 = (rois[b_id, :, 0] - rois[b_id, :, 3] / 2 - min_x) / (voxel_size_x * down_sample_ratio) x2 = (rois[b_id, :, 0] + rois[b_id, :, 3] / 2 - min_x) / (voxel_size_x * down_sample_ratio) y1 = (rois[b_id, :, 1] - rois[b_id, :, 4] / 2 - min_y) / (voxel_size_y * down_sample_ratio) y2 = (rois[b_id, :, 1] + rois[b_id, :, 4] / 2 - min_y) / (voxel_size_y * down_sample_ratio) angle, _ = common_utils.check_numpy_to_torch(rois[b_id, :, 6]) cosa = torch.cos(angle) sina = torch.sin(angle) theta = torch.stack(( (x2 - x1) / (width - 1) * cosa, (x2 - x1) / (width - 1) * (-sina), (x1 + x2 - width + 1) / (width - 1), (y2 - y1) / (height - 1) * sina, (y2 - y1) / (height - 1) * cosa, (y1 + y2 - height + 1) / (height - 1) ), dim=1).view(-1, 2, 3).float() grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE grid = nn.functional.affine_grid( theta, torch.Size((rois.size(1), spatial_features_2d.size(1), grid_size, grid_size)) ) pooled_features = nn.functional.grid_sample( spatial_features_2d[b_id].unsqueeze(0).expand(rois.size(1), spatial_features_2d.size(1), height, width), grid ) pooled_features_list.append(pooled_features) torch.backends.cudnn.enabled = True pooled_features = torch.cat(pooled_features_list, dim=0) return pooled_features def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, C, 7, 7) batch_size_rcnn = pooled_features.shape[0] shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) rcnn_iou = self.iou_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B*N, 1) if not self.training: batch_dict['batch_cls_preds'] = rcnn_iou.view(batch_dict['batch_size'], -1, rcnn_iou.shape[-1]) batch_dict['batch_box_preds'] = batch_dict['rois'] batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_iou'] = rcnn_iou self.forward_ret_dict = targets_dict return batch_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict rcnn_loss = 0 rcnn_loss_cls, cls_tb_dict = self.get_box_iou_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_cls tb_dict.update(cls_tb_dict) tb_dict['rcnn_loss'] = rcnn_loss.item() return rcnn_loss, tb_dict def get_box_iou_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG rcnn_iou = forward_ret_dict['rcnn_iou'] rcnn_iou_labels = forward_ret_dict['rcnn_cls_labels'].view(-1) rcnn_iou_flat = rcnn_iou.view(-1) if loss_cfgs.IOU_LOSS == 'BinaryCrossEntropy': batch_loss_iou = nn.functional.binary_cross_entropy_with_logits( rcnn_iou_flat, rcnn_iou_labels.float(), reduction='none' ) elif loss_cfgs.IOU_LOSS == 'L2': batch_loss_iou = nn.functional.mse_loss(rcnn_iou_flat, rcnn_iou_labels, reduction='none') elif loss_cfgs.IOU_LOSS == 'smoothL1': diff = rcnn_iou_flat - rcnn_iou_labels batch_loss_iou = loss_utils.WeightedSmoothL1Loss.smooth_l1_loss(diff, 1.0 / 9.0) elif loss_cfgs.IOU_LOSS == 'focalbce': batch_loss_iou = loss_utils.sigmoid_focal_cls_loss(rcnn_iou_flat, rcnn_iou_labels) else: raise NotImplementedError iou_valid_mask = (rcnn_iou_labels >= 0).float() rcnn_loss_iou = (batch_loss_iou * iou_valid_mask).sum() / torch.clamp(iou_valid_mask.sum(), min=1.0) rcnn_loss_iou = rcnn_loss_iou * loss_cfgs.LOSS_WEIGHTS['rcnn_iou_weight'] tb_dict = {'rcnn_loss_iou': rcnn_loss_iou.item()} return rcnn_loss_iou, tb_dict class ActiveSECONDHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg GRID_SIZE = self.model_cfg.ROI_GRID_POOL.GRID_SIZE pre_channel = self.model_cfg.ROI_GRID_POOL.IN_CHANNEL * GRID_SIZE * GRID_SIZE shared_fc_list = [] for k in range(0, self.model_cfg.SHARED_FC.__len__()): shared_fc_list.extend([ nn.Conv1d(pre_channel, self.model_cfg.SHARED_FC[k], kernel_size=1, bias=False), nn.BatchNorm1d(self.model_cfg.SHARED_FC[k]), nn.ReLU() ]) pre_channel = self.model_cfg.SHARED_FC[k] if k != self.model_cfg.SHARED_FC.__len__() - 1 and self.model_cfg.DP_RATIO > 0: shared_fc_list.append(nn.Dropout(self.model_cfg.DP_RATIO)) self.shared_fc_layer = nn.Sequential(*shared_fc_list) self.iou_layers = self.make_fc_layers( input_channels=pre_channel, output_channels=1, fc_list=self.model_cfg.IOU_FC ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) spatial_features_2d: (B, C, H, W) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'].detach() spatial_features_2d = batch_dict['spatial_features_2d'].detach() height, width = spatial_features_2d.size(2), spatial_features_2d.size(3) dataset_cfg = batch_dict['dataset_cfg'] min_x = dataset_cfg.POINT_CLOUD_RANGE[0] min_y = dataset_cfg.POINT_CLOUD_RANGE[1] voxel_size_x = dataset_cfg.DATA_PROCESSOR[-1].VOXEL_SIZE[0] voxel_size_y = dataset_cfg.DATA_PROCESSOR[-1].VOXEL_SIZE[1] down_sample_ratio = self.model_cfg.ROI_GRID_POOL.DOWNSAMPLE_RATIO pooled_features_list = [] torch.backends.cudnn.enabled = False for b_id in range(batch_size): # Map global boxes coordinates to feature map coordinates x1 = (rois[b_id, :, 0] - rois[b_id, :, 3] / 2 - min_x) / (voxel_size_x * down_sample_ratio) x2 = (rois[b_id, :, 0] + rois[b_id, :, 3] / 2 - min_x) / (voxel_size_x * down_sample_ratio) y1 = (rois[b_id, :, 1] - rois[b_id, :, 4] / 2 - min_y) / (voxel_size_y * down_sample_ratio) y2 = (rois[b_id, :, 1] + rois[b_id, :, 4] / 2 - min_y) / (voxel_size_y * down_sample_ratio) angle, _ = common_utils.check_numpy_to_torch(rois[b_id, :, 6]) cosa = torch.cos(angle) sina = torch.sin(angle) theta = torch.stack(( (x2 - x1) / (width - 1) * cosa, (x2 - x1) / (width - 1) * (-sina), (x1 + x2 - width + 1) / (width - 1), (y2 - y1) / (height - 1) * sina, (y2 - y1) / (height - 1) * cosa, (y1 + y2 - height + 1) / (height - 1) ), dim=1).view(-1, 2, 3).float() grid_size = self.model_cfg.ROI_GRID_POOL.GRID_SIZE grid = nn.functional.affine_grid( theta, torch.Size((rois.size(1), spatial_features_2d.size(1), grid_size, grid_size)) ) pooled_features = nn.functional.grid_sample( spatial_features_2d[b_id].unsqueeze(0).expand(rois.size(1), spatial_features_2d.size(1), height, width), grid ) pooled_features_list.append(pooled_features) torch.backends.cudnn.enabled = True pooled_features = torch.cat(pooled_features_list, dim=0) return pooled_features def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] # RoI aware pooling pooled_features = self.roi_grid_pool(batch_dict) # (BxN, C, 7, 7) batch_size_rcnn = pooled_features.shape[0] shared_features = self.shared_fc_layer(pooled_features.view(batch_size_rcnn, -1, 1)) if batch_dict['mode'] == 'active_evaluate': batch_size = batch_dict['batch_size'] roi_num = batch_size_rcnn // batch_size batch_dict['roi_shared_feature'] = shared_features.view(batch_size, roi_num, -1) rcnn_iou = self.iou_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B*N, 1) if not self.training: batch_dict['batch_cls_preds'] = rcnn_iou.view(batch_dict['batch_size'], -1, rcnn_iou.shape[-1]) batch_dict['batch_box_preds'] = batch_dict['rois'] batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_iou'] = rcnn_iou self.forward_ret_dict = targets_dict return batch_dict def get_loss(self, tb_dict=None): tb_dict = {} if tb_dict is None else tb_dict rcnn_loss = 0 rcnn_loss_cls, cls_tb_dict = self.get_box_iou_layer_loss(self.forward_ret_dict) rcnn_loss += rcnn_loss_cls tb_dict.update(cls_tb_dict) tb_dict['rcnn_loss'] = rcnn_loss.item() return rcnn_loss, tb_dict def get_box_iou_layer_loss(self, forward_ret_dict): loss_cfgs = self.model_cfg.LOSS_CONFIG rcnn_iou = forward_ret_dict['rcnn_iou'] rcnn_iou_labels = forward_ret_dict['rcnn_cls_labels'].view(-1) rcnn_iou_flat = rcnn_iou.view(-1) if loss_cfgs.IOU_LOSS == 'BinaryCrossEntropy': batch_loss_iou = nn.functional.binary_cross_entropy_with_logits( rcnn_iou_flat, rcnn_iou_labels.float(), reduction='none' ) elif loss_cfgs.IOU_LOSS == 'L2': batch_loss_iou = nn.functional.mse_loss(rcnn_iou_flat, rcnn_iou_labels, reduction='none') elif loss_cfgs.IOU_LOSS == 'smoothL1': diff = rcnn_iou_flat - rcnn_iou_labels batch_loss_iou = loss_utils.WeightedSmoothL1Loss.smooth_l1_loss(diff, 1.0 / 9.0) elif loss_cfgs.IOU_LOSS == 'focalbce': batch_loss_iou = loss_utils.sigmoid_focal_cls_loss(rcnn_iou_flat, rcnn_iou_labels) else: raise NotImplementedError iou_valid_mask = (rcnn_iou_labels >= 0).float() rcnn_loss_iou = (batch_loss_iou * iou_valid_mask).sum() / torch.clamp(iou_valid_mask.sum(), min=1.0) rcnn_loss_iou = rcnn_loss_iou * loss_cfgs.LOSS_WEIGHTS['rcnn_iou_weight'] tb_dict = {'rcnn_loss_iou': rcnn_loss_iou.item()} return rcnn_loss_iou, tb_dict
15,196
41.449721
120
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/pointrcnn_head.py
import torch import torch.nn as nn from ...ops.pointnet2.pointnet2_batch import pointnet2_modules from ...ops.roipoint_pool3d import roipoint_pool3d_utils from ...utils import common_utils from .roi_head_template import RoIHeadTemplate class PointRCNNHead(RoIHeadTemplate): def __init__(self, input_channels, model_cfg, num_class=1, **kwargs): super().__init__(num_class=num_class, model_cfg=model_cfg) self.model_cfg = model_cfg use_bn = self.model_cfg.USE_BN self.SA_modules = nn.ModuleList() channel_in = input_channels self.num_prefix_channels = 3 + 2 # xyz + point_scores + point_depth xyz_mlps = [self.num_prefix_channels] + self.model_cfg.XYZ_UP_LAYER shared_mlps = [] for k in range(len(xyz_mlps) - 1): shared_mlps.append(nn.Conv2d(xyz_mlps[k], xyz_mlps[k + 1], kernel_size=1, bias=not use_bn)) if use_bn: shared_mlps.append(nn.BatchNorm2d(xyz_mlps[k + 1])) shared_mlps.append(nn.ReLU()) self.xyz_up_layer = nn.Sequential(*shared_mlps) c_out = self.model_cfg.XYZ_UP_LAYER[-1] self.merge_down_layer = nn.Sequential( nn.Conv2d(c_out * 2, c_out, kernel_size=1, bias=not use_bn), *[nn.BatchNorm2d(c_out), nn.ReLU()] if use_bn else [nn.ReLU()] ) for k in range(self.model_cfg.SA_CONFIG.NPOINTS.__len__()): mlps = [channel_in] + self.model_cfg.SA_CONFIG.MLPS[k] npoint = self.model_cfg.SA_CONFIG.NPOINTS[k] if self.model_cfg.SA_CONFIG.NPOINTS[k] != -1 else None self.SA_modules.append( pointnet2_modules.PointnetSAModule( npoint=npoint, radius=self.model_cfg.SA_CONFIG.RADIUS[k], nsample=self.model_cfg.SA_CONFIG.NSAMPLE[k], mlp=mlps, use_xyz=True, bn=use_bn ) ) channel_in = mlps[-1] self.cls_layers = self.make_fc_layers( input_channels=channel_in, output_channels=self.num_class, fc_list=self.model_cfg.CLS_FC ) self.reg_layers = self.make_fc_layers( input_channels=channel_in, output_channels=self.box_coder.code_size * self.num_class, fc_list=self.model_cfg.REG_FC ) self.roipoint_pool3d_layer = roipoint_pool3d_utils.RoIPointPool3d( num_sampled_points=self.model_cfg.ROI_POINT_POOL.NUM_SAMPLED_POINTS, pool_extra_width=self.model_cfg.ROI_POINT_POOL.POOL_EXTRA_WIDTH ) self.init_weights(weight_init='xavier') def init_weights(self, weight_init='xavier'): if weight_init == 'kaiming': init_func = nn.init.kaiming_normal_ elif weight_init == 'xavier': init_func = nn.init.xavier_normal_ elif weight_init == 'normal': init_func = nn.init.normal_ else: raise NotImplementedError for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): if weight_init == 'normal': init_func(m.weight, mean=0, std=0.001) else: init_func(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) nn.init.normal_(self.reg_layers[-1].weight, mean=0, std=0.001) def roipool3d_gpu(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 + ..., 1) point_part_offset: (N1 + N2 + N3 + ..., 3) Returns: """ batch_size = batch_dict['batch_size'] batch_idx = batch_dict['point_coords'][:, 0] point_coords = batch_dict['point_coords'][:, 1:4] point_features = batch_dict['point_features'] rois = batch_dict['rois'] # (B, num_rois, 7 + C) batch_cnt = point_coords.new_zeros(batch_size).int() for bs_idx in range(batch_size): batch_cnt[bs_idx] = (batch_idx == bs_idx).sum() assert batch_cnt.min() == batch_cnt.max() point_scores = batch_dict['point_cls_scores'].detach() point_depths = point_coords.norm(dim=1) / self.model_cfg.ROI_POINT_POOL.DEPTH_NORMALIZER - 0.5 point_features_list = [point_scores[:, None], point_depths[:, None], point_features] point_features_all = torch.cat(point_features_list, dim=1) batch_points = point_coords.view(batch_size, -1, 3) batch_point_features = point_features_all.view(batch_size, -1, point_features_all.shape[-1]) with torch.no_grad(): pooled_features, pooled_empty_flag = self.roipoint_pool3d_layer( batch_points, batch_point_features, rois ) # pooled_features: (B, num_rois, num_sampled_points, 3 + C), pooled_empty_flag: (B, num_rois) # canonical transformation roi_center = rois[:, :, 0:3] pooled_features[:, :, :, 0:3] -= roi_center.unsqueeze(dim=2) pooled_features = pooled_features.view(-1, pooled_features.shape[-2], pooled_features.shape[-1]) pooled_features[:, :, 0:3] = common_utils.rotate_points_along_z( pooled_features[:, :, 0:3], -rois.view(-1, rois.shape[-1])[:, 6] ) pooled_features[pooled_empty_flag.view(-1) > 0] = 0 return pooled_features def forward(self, batch_dict): """ Args: batch_dict: Returns: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_dict = self.assign_targets(batch_dict) batch_dict['rois'] = targets_dict['rois'] batch_dict['roi_labels'] = targets_dict['roi_labels'] pooled_features = self.roipool3d_gpu(batch_dict) # (total_rois, num_sampled_points, 3 + C) xyz_input = pooled_features[..., 0:self.num_prefix_channels].transpose(1, 2).unsqueeze(dim=3).contiguous() xyz_features = self.xyz_up_layer(xyz_input) point_features = pooled_features[..., self.num_prefix_channels:].transpose(1, 2).unsqueeze(dim=3) merged_features = torch.cat((xyz_features, point_features), dim=1) merged_features = self.merge_down_layer(merged_features) l_xyz, l_features = [pooled_features[..., 0:3].contiguous()], [merged_features.squeeze(dim=3).contiguous()] for i in range(len(self.SA_modules)): li_xyz, li_features = self.SA_modules[i](l_xyz[i], l_features[i]) l_xyz.append(li_xyz) l_features.append(li_features) shared_features = l_features[-1] # (total_rois, num_features, 1) rcnn_cls = self.cls_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2) rcnn_reg = self.reg_layers(shared_features).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C) if not self.training: batch_cls_preds, batch_box_preds = self.generate_predicted_boxes( batch_size=batch_dict['batch_size'], rois=batch_dict['rois'], cls_preds=rcnn_cls, box_preds=rcnn_reg ) batch_dict['batch_cls_preds'] = batch_cls_preds batch_dict['batch_box_preds'] = batch_box_preds batch_dict['cls_preds_normalized'] = False else: targets_dict['rcnn_cls'] = rcnn_cls targets_dict['rcnn_reg'] = rcnn_reg self.forward_ret_dict = targets_dict return batch_dict
7,835
42.533333
116
py
3DTrans
3DTrans-master/pcdet/models/roi_heads/target_assigner/proposal_target_layer.py
import numpy as np import torch import torch.nn as nn from ....ops.iou3d_nms import iou3d_nms_utils class ProposalTargetLayer(nn.Module): def __init__(self, roi_sampler_cfg): super().__init__() self.roi_sampler_cfg = roi_sampler_cfg def forward(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) roi_scores: (B, num_rois) gt_boxes: (B, N, 7 + C + 1) roi_labels: (B, num_rois) Returns: batch_dict: rois: (B, M, 7 + C) gt_of_rois: (B, M, 7 + C) gt_iou_of_rois: (B, M) roi_scores: (B, M) roi_labels: (B, M) reg_valid_mask: (B, M) rcnn_cls_labels: (B, M) """ batch_rois, batch_gt_of_rois, batch_roi_ious, batch_roi_scores, batch_roi_labels = self.sample_rois_for_rcnn( batch_dict=batch_dict ) # regression valid mask reg_valid_mask = (batch_roi_ious > self.roi_sampler_cfg.REG_FG_THRESH).long() # classification label if self.roi_sampler_cfg.CLS_SCORE_TYPE == 'cls': batch_cls_labels = (batch_roi_ious > self.roi_sampler_cfg.CLS_FG_THRESH).long() ignore_mask = (batch_roi_ious > self.roi_sampler_cfg.CLS_BG_THRESH) & \ (batch_roi_ious < self.roi_sampler_cfg.CLS_FG_THRESH) batch_cls_labels[ignore_mask > 0] = -1 elif self.roi_sampler_cfg.CLS_SCORE_TYPE == 'roi_iou': iou_bg_thresh = self.roi_sampler_cfg.CLS_BG_THRESH iou_fg_thresh = self.roi_sampler_cfg.CLS_FG_THRESH fg_mask = batch_roi_ious > iou_fg_thresh bg_mask = batch_roi_ious < iou_bg_thresh interval_mask = (fg_mask == 0) & (bg_mask == 0) batch_cls_labels = (fg_mask > 0).float() batch_cls_labels[interval_mask] = \ (batch_roi_ious[interval_mask] - iou_bg_thresh) / (iou_fg_thresh - iou_bg_thresh) elif self.roi_sampler_cfg.CLS_SCORE_TYPE == 'raw_roi_iou': batch_cls_labels = batch_roi_ious else: raise NotImplementedError targets_dict = {'rois': batch_rois, 'gt_of_rois': batch_gt_of_rois, 'gt_iou_of_rois': batch_roi_ious, 'roi_scores': batch_roi_scores, 'roi_labels': batch_roi_labels, 'reg_valid_mask': reg_valid_mask, 'rcnn_cls_labels': batch_cls_labels} return targets_dict def sample_rois_for_rcnn(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) roi_scores: (B, num_rois) gt_boxes: (B, N, 7 + C + 1) roi_labels: (B, num_rois) Returns: """ batch_size = batch_dict['batch_size'] rois = batch_dict['rois'] roi_scores = batch_dict['roi_scores'] roi_labels = batch_dict['roi_labels'] gt_boxes = batch_dict['gt_boxes'] code_size = rois.shape[-1] batch_rois = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE, code_size) batch_gt_of_rois = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE, code_size + 1) batch_roi_ious = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE) batch_roi_scores = rois.new_zeros(batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE) batch_roi_labels = rois.new_zeros((batch_size, self.roi_sampler_cfg.ROI_PER_IMAGE), dtype=torch.long) for index in range(batch_size): cur_roi, cur_gt, cur_roi_labels, cur_roi_scores = \ rois[index], gt_boxes[index], roi_labels[index], roi_scores[index] k = cur_gt.__len__() - 1 while k >= 0 and cur_gt[k].sum() == 0: k -= 1 cur_gt = cur_gt[:k + 1] cur_gt = cur_gt.new_zeros((1, cur_gt.shape[1])) if len(cur_gt) == 0 else cur_gt if self.roi_sampler_cfg.get('SAMPLE_ROI_BY_EACH_CLASS', False): max_overlaps, gt_assignment = self.get_max_iou_with_same_class( rois=cur_roi, roi_labels=cur_roi_labels, gt_boxes=cur_gt[:, 0:7], gt_labels=cur_gt[:, -1].long() ) else: iou3d = iou3d_nms_utils.boxes_iou3d_gpu(cur_roi, cur_gt[:, 0:7]) # (M, N) #iou3d = iou3d_nms_utils.boxes_iou3d_gpu(cur_roi[:, 0:7], cur_gt[:, 0:7]) #modified: cur_roi->cur_roi[:, 0:7] max_overlaps, gt_assignment = torch.max(iou3d, dim=1) sampled_inds = self.subsample_rois(max_overlaps=max_overlaps) batch_rois[index] = cur_roi[sampled_inds] batch_roi_labels[index] = cur_roi_labels[sampled_inds] batch_roi_ious[index] = max_overlaps[sampled_inds] batch_roi_scores[index] = cur_roi_scores[sampled_inds] batch_gt_of_rois[index] = cur_gt[gt_assignment[sampled_inds]] return batch_rois, batch_gt_of_rois, batch_roi_ious, batch_roi_scores, batch_roi_labels def subsample_rois(self, max_overlaps): # sample fg, easy_bg, hard_bg fg_rois_per_image = int(np.round(self.roi_sampler_cfg.FG_RATIO * self.roi_sampler_cfg.ROI_PER_IMAGE)) fg_thresh = min(self.roi_sampler_cfg.REG_FG_THRESH, self.roi_sampler_cfg.CLS_FG_THRESH) fg_inds = ((max_overlaps >= fg_thresh)).nonzero().view(-1) easy_bg_inds = ((max_overlaps < self.roi_sampler_cfg.CLS_BG_THRESH_LO)).nonzero().view(-1) hard_bg_inds = ((max_overlaps < self.roi_sampler_cfg.REG_FG_THRESH) & (max_overlaps >= self.roi_sampler_cfg.CLS_BG_THRESH_LO)).nonzero().view(-1) fg_num_rois = fg_inds.numel() bg_num_rois = hard_bg_inds.numel() + easy_bg_inds.numel() if fg_num_rois > 0 and bg_num_rois > 0: # sampling fg fg_rois_per_this_image = min(fg_rois_per_image, fg_num_rois) rand_num = torch.from_numpy(np.random.permutation(fg_num_rois)).type_as(max_overlaps).long() fg_inds = fg_inds[rand_num[:fg_rois_per_this_image]] # sampling bg bg_rois_per_this_image = self.roi_sampler_cfg.ROI_PER_IMAGE - fg_rois_per_this_image bg_inds = self.sample_bg_inds( hard_bg_inds, easy_bg_inds, bg_rois_per_this_image, self.roi_sampler_cfg.HARD_BG_RATIO ) elif fg_num_rois > 0 and bg_num_rois == 0: # sampling fg rand_num = np.floor(np.random.rand(self.roi_sampler_cfg.ROI_PER_IMAGE) * fg_num_rois) rand_num = torch.from_numpy(rand_num).type_as(max_overlaps).long() fg_inds = fg_inds[rand_num] bg_inds = fg_inds[fg_inds < 0] # yield empty tensor elif bg_num_rois > 0 and fg_num_rois == 0: # sampling bg bg_rois_per_this_image = self.roi_sampler_cfg.ROI_PER_IMAGE bg_inds = self.sample_bg_inds( hard_bg_inds, easy_bg_inds, bg_rois_per_this_image, self.roi_sampler_cfg.HARD_BG_RATIO ) else: print('maxoverlaps:(min=%f, max=%f)' % (max_overlaps.min().item(), max_overlaps.max().item())) print('ERROR: FG=%d, BG=%d' % (fg_num_rois, bg_num_rois)) raise NotImplementedError sampled_inds = torch.cat((fg_inds, bg_inds), dim=0) return sampled_inds @staticmethod def sample_bg_inds(hard_bg_inds, easy_bg_inds, bg_rois_per_this_image, hard_bg_ratio): if hard_bg_inds.numel() > 0 and easy_bg_inds.numel() > 0: hard_bg_rois_num = min(int(bg_rois_per_this_image * hard_bg_ratio), len(hard_bg_inds)) easy_bg_rois_num = bg_rois_per_this_image - hard_bg_rois_num # sampling hard bg rand_idx = torch.randint(low=0, high=hard_bg_inds.numel(), size=(hard_bg_rois_num,)).long() hard_bg_inds = hard_bg_inds[rand_idx] # sampling easy bg rand_idx = torch.randint(low=0, high=easy_bg_inds.numel(), size=(easy_bg_rois_num,)).long() easy_bg_inds = easy_bg_inds[rand_idx] bg_inds = torch.cat([hard_bg_inds, easy_bg_inds], dim=0) elif hard_bg_inds.numel() > 0 and easy_bg_inds.numel() == 0: hard_bg_rois_num = bg_rois_per_this_image # sampling hard bg rand_idx = torch.randint(low=0, high=hard_bg_inds.numel(), size=(hard_bg_rois_num,)).long() bg_inds = hard_bg_inds[rand_idx] elif hard_bg_inds.numel() == 0 and easy_bg_inds.numel() > 0: easy_bg_rois_num = bg_rois_per_this_image # sampling easy bg rand_idx = torch.randint(low=0, high=easy_bg_inds.numel(), size=(easy_bg_rois_num,)).long() bg_inds = easy_bg_inds[rand_idx] else: raise NotImplementedError return bg_inds @staticmethod def get_max_iou_with_same_class(rois, roi_labels, gt_boxes, gt_labels): """ Args: rois: (N, 7) roi_labels: (N) gt_boxes: (N, ) gt_labels: Returns: """ """ :param rois: (N, 7) :param roi_labels: (N) :param gt_boxes: (N, 8) :return: """ max_overlaps = rois.new_zeros(rois.shape[0]) gt_assignment = roi_labels.new_zeros(roi_labels.shape[0]) for k in range(gt_labels.min().item(), gt_labels.max().item() + 1): roi_mask = (roi_labels == k) gt_mask = (gt_labels == k) if roi_mask.sum() > 0 and gt_mask.sum() > 0: cur_roi = rois[roi_mask] cur_gt = gt_boxes[gt_mask] original_gt_assignment = gt_mask.nonzero().view(-1) iou3d = iou3d_nms_utils.boxes_iou3d_gpu(cur_roi, cur_gt) # (M, N) #iou3d = iou3d_nms_utils.boxes_iou3d_gpu(cur_roi[:, 0:7], cur_gt) #modified: cur_roi->cur_roi[:, 0:7] cur_max_overlaps, cur_gt_assignment = torch.max(iou3d, dim=1) max_overlaps[roi_mask] = cur_max_overlaps gt_assignment[roi_mask] = original_gt_assignment[cur_gt_assignment] return max_overlaps, gt_assignment
10,343
43.779221
126
py
3DTrans
3DTrans-master/pcdet/models/model_utils/centernet_utils.py
# This file is modified from https://github.com/tianweiy/CenterPoint import torch import torch.nn.functional as F import numpy as np import numba def gaussian_radius(height, width, min_overlap=0.5): """ Args: height: (N) width: (N) min_overlap: Returns: """ a1 = 1 b1 = (height + width) c1 = width * height * (1 - min_overlap) / (1 + min_overlap) sq1 = (b1 ** 2 - 4 * a1 * c1).sqrt() r1 = (b1 + sq1) / 2 a2 = 4 b2 = 2 * (height + width) c2 = (1 - min_overlap) * width * height sq2 = (b2 ** 2 - 4 * a2 * c2).sqrt() r2 = (b2 + sq2) / 2 a3 = 4 * min_overlap b3 = -2 * min_overlap * (height + width) c3 = (min_overlap - 1) * width * height sq3 = (b3 ** 2 - 4 * a3 * c3).sqrt() r3 = (b3 + sq3) / 2 ret = torch.min(torch.min(r1, r2), r3) return ret def gaussian2D(shape, sigma=1): m, n = [(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x + y * y) / (2 * sigma * sigma)) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_gaussian(heatmap, center, radius, k=1): diameter = 2 * radius + 1 gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, radius), min(width - x, radius + 1) top, bottom = min(y, radius), min(height - y, radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def draw_gaussian_to_heatmap(heatmap, center, radius, k=1, valid_mask=None): diameter = 2 * radius + 1 gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, radius), min(width - x, radius + 1) top, bottom = min(y, radius), min(height - y, radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian = torch.from_numpy( gaussian[radius - top:radius + bottom, radius - left:radius + right] ).to(heatmap.device).float() if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: # TODO debug if valid_mask is not None: cur_valid_mask = valid_mask[y - top:y + bottom, x - left:x + right] masked_gaussian = masked_gaussian * cur_valid_mask.float() torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def _nms(heat, kernel=3): pad = (kernel - 1) // 2 hmax = F.max_pool2d(heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() return heat * keep @numba.jit(nopython=True) def circle_nms(dets, thresh): x1 = dets[:, 0] y1 = dets[:, 1] scores = dets[:, 2] order = scores.argsort()[::-1].astype(np.int32) # highest->lowest ndets = dets.shape[0] suppressed = np.zeros((ndets), dtype=np.int32) keep = [] for _i in range(ndets): i = order[_i] # start with highest score box if suppressed[i] == 1: # if any box have enough iou with this, remove it continue keep.append(i) for _j in range(_i + 1, ndets): j = order[_j] if suppressed[j] == 1: continue # calculate center distance between i and j box dist = (x1[i] - x1[j]) ** 2 + (y1[i] - y1[j]) ** 2 # ovr = inter / areas[j] if dist <= thresh: suppressed[j] = 1 return keep def _circle_nms(boxes, min_radius, post_max_size=83): """ NMS according to center distance """ keep = np.array(circle_nms(boxes.cpu().numpy(), thresh=min_radius))[:post_max_size] keep = torch.from_numpy(keep).long().to(boxes.device) return keep def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat def _topk(scores, K=40): batch, num_class, height, width = scores.size() topk_scores, topk_inds = torch.topk(scores.flatten(2, 3), K) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds // width).float() topk_xs = (topk_inds % width).int().float() topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), K) topk_classes = (topk_ind // K).int() topk_inds = _gather_feat(topk_inds.view(batch, -1, 1), topk_ind).view(batch, K) topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K) topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K) return topk_score, topk_inds, topk_classes, topk_ys, topk_xs def decode_bbox_from_heatmap(heatmap, rot_cos, rot_sin, center, center_z, dim, point_cloud_range=None, voxel_size=None, feature_map_stride=None, vel=None, K=100, circle_nms=False, score_thresh=None, post_center_limit_range=None): batch_size, num_class, _, _ = heatmap.size() if circle_nms: # TODO: not checked yet assert False, 'not checked yet' heatmap = _nms(heatmap) scores, inds, class_ids, ys, xs = _topk(heatmap, K=K) center = _transpose_and_gather_feat(center, inds).view(batch_size, K, 2) rot_sin = _transpose_and_gather_feat(rot_sin, inds).view(batch_size, K, 1) rot_cos = _transpose_and_gather_feat(rot_cos, inds).view(batch_size, K, 1) center_z = _transpose_and_gather_feat(center_z, inds).view(batch_size, K, 1) dim = _transpose_and_gather_feat(dim, inds).view(batch_size, K, 3) angle = torch.atan2(rot_sin, rot_cos) xs = xs.view(batch_size, K, 1) + center[:, :, 0:1] ys = ys.view(batch_size, K, 1) + center[:, :, 1:2] xs = xs * feature_map_stride * voxel_size[0] + point_cloud_range[0] ys = ys * feature_map_stride * voxel_size[1] + point_cloud_range[1] box_part_list = [xs, ys, center_z, dim, angle] if vel is not None: vel = _transpose_and_gather_feat(vel, inds).view(batch_size, K, 2) box_part_list.append(vel) final_box_preds = torch.cat((box_part_list), dim=-1) final_scores = scores.view(batch_size, K) final_class_ids = class_ids.view(batch_size, K) assert post_center_limit_range is not None mask = (final_box_preds[..., :3] >= post_center_limit_range[:3]).all(2) mask &= (final_box_preds[..., :3] <= post_center_limit_range[3:]).all(2) if score_thresh is not None: mask &= (final_scores > score_thresh) ret_pred_dicts = [] for k in range(batch_size): cur_mask = mask[k] cur_boxes = final_box_preds[k, cur_mask] cur_scores = final_scores[k, cur_mask] cur_labels = final_class_ids[k, cur_mask] if circle_nms: assert False, 'not checked yet' centers = cur_boxes[:, [0, 1]] boxes = torch.cat((centers, scores.view(-1, 1)), dim=1) keep = _circle_nms(boxes, min_radius=min_radius, post_max_size=nms_post_max_size) cur_boxes = cur_boxes[keep] cur_scores = cur_scores[keep] cur_labels = cur_labels[keep] ret_pred_dicts.append({ 'pred_boxes': cur_boxes, 'pred_scores': cur_scores, 'pred_labels': cur_labels }) return ret_pred_dicts
7,932
33.04721
111
py
3DTrans
3DTrans-master/pcdet/models/model_utils/model_nms_utils.py
import torch from ...ops.iou3d_nms import iou3d_nms_utils def class_agnostic_nms(box_scores, box_preds, nms_config, score_thresh=None): src_box_scores = box_scores if score_thresh is not None: scores_mask = (box_scores >= score_thresh) box_scores = box_scores[scores_mask] box_preds = box_preds[scores_mask] selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] if score_thresh is not None: original_idxs = scores_mask.nonzero().view(-1) selected = original_idxs[selected] return selected, src_box_scores[selected] def class_agnostic_nms_with_roi(box_scores, box_preds, roi_feature, nms_config, score_thresh=None): src_box_scores = box_scores if score_thresh is not None: scores_mask = (box_scores >= score_thresh) box_scores = box_scores[scores_mask] box_preds = box_preds[scores_mask] selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] if score_thresh is not None: original_idxs = scores_mask.nonzero().view(-1) selected = original_idxs[selected] return selected, src_box_scores[selected], roi_feature[selected] def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None): """ Args: cls_scores: (N, num_class) box_preds: (N, 7 + C) nms_config: score_thresh: Returns: """ pred_scores, pred_labels, pred_boxes = [], [], [] for k in range(cls_scores.shape[1]): if score_thresh is not None: scores_mask = (cls_scores[:, k] >= score_thresh) box_scores = cls_scores[scores_mask, k] cur_box_preds = box_preds[scores_mask] else: box_scores = cls_scores[:, k] cur_box_preds = box_preds selected = [] if box_scores.shape[0] > 0: box_scores_nms, indices = torch.topk(box_scores, k=min(nms_config.NMS_PRE_MAXSIZE, box_scores.shape[0])) boxes_for_nms = cur_box_preds[indices] keep_idx, selected_scores = getattr(iou3d_nms_utils, nms_config.NMS_TYPE)( boxes_for_nms[:, 0:7], box_scores_nms, nms_config.NMS_THRESH, **nms_config ) selected = indices[keep_idx[:nms_config.NMS_POST_MAXSIZE]] pred_scores.append(box_scores[selected]) pred_labels.append(box_scores.new_ones(len(selected)).long() * k) pred_boxes.append(cur_box_preds[selected]) pred_scores = torch.cat(pred_scores, dim=0) pred_labels = torch.cat(pred_labels, dim=0) pred_boxes = torch.cat(pred_boxes, dim=0) return pred_scores, pred_labels, pred_boxes
3,422
37.460674
116
py
3DTrans
3DTrans-master/pcdet/models/model_utils/basic_block_2d.py
import torch.nn as nn class BasicBlock2D(nn.Module): def __init__(self, in_channels, out_channels, **kwargs): """ Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d """ super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs) self.bn = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) def forward(self, features): """ Applies convolutional block Args: features: (B, C_in, H, W), Input features Returns: x: (B, C_out, H, W), Output features """ x = self.conv(features) x = self.bn(x) x = self.relu(x) return x
1,038
28.685714
60
py
3DTrans
3DTrans-master/pcdet/models/model_utils/ensemble.py
""" This file is to match with previous version of CenterPoint model """ import torch import numpy as np from .wbf_3d import weighted_boxes_fusion_3d def wbf_online(boxes, scores, labels): device = boxes.device dtype = boxes.dtype boxes_list = boxes.cpu().numpy() scores_list = scores.cpu().numpy() labels_list = labels.cpu().numpy() iou_thresh = [0.8, 0.6, 0.7] skip_box_thr = [0.1, 0.01, 0.01] boxes, scores, labels = weighted_boxes_fusion_3d( boxes_list=boxes_list, scores_list=scores_list, labels_list=labels_list, weights=None, iou_thr=iou_thresh, skip_box_thr=skip_box_thr, conf_type='avg', iou_type='3d', allows_overflow=False ) boxes = torch.from_numpy(boxes).to(device) scores = torch.from_numpy(scores).to(device) labels = torch.from_numpy(labels).to(device) return boxes, scores, labels def wbf_offline(boxes, scores, labels): raise NotImplementedError
1,000
24.025
64
py
3DTrans
3DTrans-master/pcdet/models/model_utils/wbf_3d.py
""" This file is to match with previous version of CenterPoint model """ import copy import numpy as np import torch from ...ops.iou3d_nms import iou3d_nms_utils def prefilter_boxes(boxes, scores, labels, weights, thresh): # Create dict with boxes stored by its label new_boxes = dict() for i in range(len(boxes)): if len(boxes[i]) != len(scores[i]): raise ValueError("Length of boxes not equal to length of scores.") if len(boxes[i]) != len(labels[i]): raise ValueError("Length of boxes not equal to length of labels.") for j in range(len(boxes[i])): score = scores[i][j][0] # if score < thresh: # continue label = int(labels[i][j][0]) if label == 0: continue # import pdb; pdb.set_trace() box = boxes[i][j] x = float(box[0]) y = float(box[1]) z = float(box[2]) dx = float(box[3]) dy = float(box[4]) dz = float(box[5]) yaw = float(box[6]) new_box = [int(label), float(score) * weights[i], x, y, z, dx, dy, dz, yaw] if label not in new_boxes: new_boxes[label] = [] new_boxes[label].append(new_box) # Sort each list in dict by score and transform it to numpy array for k in new_boxes: current_boxes = np.array(new_boxes[k]) new_boxes[k] = current_boxes[current_boxes[:, 1].argsort()[::-1]] current_boxes = np.array(new_boxes[k]) new_boxes[k] = current_boxes[current_boxes[:, 1] >= thresh[k - 1]] return new_boxes def get_weighted_box(boxes, conf_type='avg'): """ Create weighted box for set of boxes Param: boxes: set of boxes to fuse conf_type: type of confidence, one of 'avg' or 'max' Return: weighted box """ weighted_box = np.zeros(9, dtype=np.float32) conf = 0 conf_list = [] for box in boxes: weighted_box[2:] += (box[1] * box[2:]) conf += box[1] conf_list.append(box[1]) # assign label weighted_box[0] = boxes[0][0] # assign new score if conf_type == 'avg': weighted_box[1] = conf / len(boxes) elif conf_type == 'max': weighted_box[1] = np.array(conf_list).max() weighted_box[2:] /= conf weighted_box[-1] = boxes[conf_list.index(max(conf_list))][-1] return weighted_box def find_matching_box(boxes_list, new_box, iou_thresh, iou_type): if len(boxes_list) == 0: return -1, iou_thresh boxes_list = np.array(boxes_list) boxes_gpu = copy.deepcopy(torch.from_numpy(boxes_list[:, 2:]).float().cuda()) new_box = torch.from_numpy(new_box[2:]).unsqueeze(0).float().cuda() if iou_type == '3d': ious = iou3d_nms_utils.boxes_iou3d_gpu(new_box, boxes_gpu) elif iou_type == 'bev': ious = iou3d_nms_utils.boxes_iou_bev(new_box, boxes_gpu) best_idx = ious.argmax().item() best_iou = ious[0][best_idx].item() if best_iou <= iou_thresh: best_iou = iou_thresh best_idx = -1 return best_idx, best_iou def weighted_boxes_fusion_3d(boxes_list, scores_list, labels_list, weights=None, iou_thr=None, skip_box_thr=None, conf_type='avg', iou_type='3d', allows_overflow=False): ''' Param: boxes_list: list of boxes predictions from each model, each box is 7-dim It has 3 dimensions (models_number, model_preds, 6) Order of boxes: x,y,z,dx,dy,dz,yaw. We expect float normalized coordinates [0; 1] scores_list: list of scores of each box from each model labels_list: list of labels of each box from each model weights: list of weights for each model. Default: None, which means weight == 1 for each model iou_thr: IoU threshold for boxes to be a match skip_box_thr: exclude boxes with score lower than this threshold conf_type: confidence calculation type 'avg': average value, 'max': maximum value allows_overflow: false if we want confidence score not exceed 1.0 Return: boxes: new boxes coordinates (Order of boxes: x1, y1, z1, x2, y2, z2). scores: new confidence scores labels: boxes labels ''' if weights is None: weights = np.ones(len(boxes_list)) if len(weights) != len(boxes_list): print('Warning: incorrect number of weights {}. Must be: {}. Set weights equal to 1.'.format(len(weights), len(boxes_list))) weights = np.ones(len(boxes_list)) weights = np.array(weights) if conf_type not in ['avg', 'max']: print('Error. Unknown conf_type: {}. Must be "avg" or "max". Use "avg"'.format(conf_type)) conf_type = 'avg' filtered_boxes = prefilter_boxes(boxes_list, scores_list, labels_list, weights, skip_box_thr) if len(filtered_boxes) == 0: return np.zeros((0, 7)), np.zeros((0,)), np.zeros((0,)) overall_boxes = [] for label in filtered_boxes: boxes = filtered_boxes[label] new_boxes = [] weighted_boxes = [] # clusterize boxes for j in range(0, len(boxes)): index, best_iou = find_matching_box(weighted_boxes, boxes[j], iou_thr[label - 1], iou_type) if index != -1: new_boxes[index].append(boxes[j]) weighted_boxes[index] = get_weighted_box(new_boxes[index], conf_type) else: new_boxes.append([boxes[j].copy()]) weighted_boxes.append(boxes[j].copy()) # rescale confidence based on number of models and boxes for i in range(len(new_boxes)): if not allows_overflow: weighted_boxes[i][1] = weighted_boxes[i][1] * min(weights.sum(), len(new_boxes[i])) / weights.sum() else: weighted_boxes[i][1] = weighted_boxes[i][1] * len(new_boxes[i]) / weights.sum() if len(weighted_boxes) != 0: overall_boxes.append(np.array(weighted_boxes)) if len(overall_boxes) == 0: return np.zeros((0, 7)), np.zeros((0,)), np.zeros((0,)) overall_boxes = np.concatenate(overall_boxes, axis=0) overall_boxes = overall_boxes[overall_boxes[:, 1].argsort()[::-1]] boxes = overall_boxes[:, 2:] scores = overall_boxes[:, 1] labels = overall_boxes[:, 0].astype(int) return boxes, scores, labels
6,649
35.141304
118
py
3DTrans
3DTrans-master/pcdet/models/backbones_2d/base_bev_backbone.py
import numpy as np import torch import torch.nn as nn # from ...utils import uni3d_norm from ...utils import uni3d_norm as uni3d_norm_used # from ...utils import uni3d_norm_parallel as uni3d_norm_used class BaseBEVBackbone(nn.Module): def __init__(self, model_cfg, input_channels): super().__init__() self.model_cfg = model_cfg if self.model_cfg.get('DUAL_NORM', None): self.db_source = int(self.model_cfg.db_source) if self.model_cfg.get('LAYER_NUMS', None) is not None: assert len(self.model_cfg.LAYER_NUMS) == len(self.model_cfg.LAYER_STRIDES) == len(self.model_cfg.NUM_FILTERS) layer_nums = self.model_cfg.LAYER_NUMS layer_strides = self.model_cfg.LAYER_STRIDES num_filters = self.model_cfg.NUM_FILTERS else: layer_nums = layer_strides = num_filters = [] if self.model_cfg.get('UPSAMPLE_STRIDES', None) is not None: assert len(self.model_cfg.UPSAMPLE_STRIDES) == len(self.model_cfg.NUM_UPSAMPLE_FILTERS) num_upsample_filters = self.model_cfg.NUM_UPSAMPLE_FILTERS upsample_strides = self.model_cfg.UPSAMPLE_STRIDES else: upsample_strides = num_upsample_filters = [] num_levels = len(layer_nums) c_in_list = [input_channels, *num_filters[:-1]] self.blocks = nn.ModuleList() self.deblocks = nn.ModuleList() # using the Dual-Norm: if self.model_cfg.get('DUAL_NORM', None): for idx in range(num_levels): cur_layers = [ nn.ZeroPad2d(1), nn.Conv2d( c_in_list[idx], num_filters[idx], kernel_size=3, stride=layer_strides[idx], padding=0, bias=False ), uni3d_norm_used.UniNorm2d(num_filters[idx], dataset_from_flag=self.db_source, eps=1e-3, momentum=0.01), # using the dataset-specific norm nn.ReLU() ] for k in range(layer_nums[idx]): cur_layers.extend([ nn.Conv2d(num_filters[idx], num_filters[idx], kernel_size=3, padding=1, bias=False), uni3d_norm_used.UniNorm2d(num_filters[idx], dataset_from_flag=self.db_source, eps=1e-3, momentum=0.01), nn.ReLU() ]) self.blocks.append(nn.Sequential(*cur_layers)) if len(upsample_strides) > 0: stride = upsample_strides[idx] if stride >= 1: self.deblocks.append(nn.Sequential( nn.ConvTranspose2d( num_filters[idx], num_upsample_filters[idx], upsample_strides[idx], stride=upsample_strides[idx], bias=False ), uni3d_norm_used.UniNorm2d(num_upsample_filters[idx], dataset_from_flag=self.db_source, eps=1e-3, momentum=0.01), nn.ReLU() )) else: stride = np.round(1 / stride).astype(np.int) self.deblocks.append(nn.Sequential( nn.Conv2d( num_filters[idx], num_upsample_filters[idx], stride, stride=stride, bias=False ), uni3d_norm_used.UniNorm2d(num_upsample_filters[idx], dataset_from_flag=self.db_source, eps=1e-3, momentum=0.01), nn.ReLU() )) c_in = sum(num_upsample_filters) if len(upsample_strides) > num_levels: self.deblocks.append(nn.Sequential( nn.ConvTranspose2d(c_in, c_in, upsample_strides[-1], stride=upsample_strides[-1], bias=False), uni3d_norm_used.UniNorm2d(c_in, dataset_from_flag=self.db_source, eps=1e-3, momentum=0.01), nn.ReLU(), )) self.num_bev_features = c_in else: for idx in range(num_levels): cur_layers = [ nn.ZeroPad2d(1), nn.Conv2d( c_in_list[idx], num_filters[idx], kernel_size=3, stride=layer_strides[idx], padding=0, bias=False ), nn.BatchNorm2d(num_filters[idx], eps=1e-3, momentum=0.01), nn.ReLU() ] for k in range(layer_nums[idx]): cur_layers.extend([ nn.Conv2d(num_filters[idx], num_filters[idx], kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(num_filters[idx], eps=1e-3, momentum=0.01), nn.ReLU() ]) self.blocks.append(nn.Sequential(*cur_layers)) if len(upsample_strides) > 0: stride = upsample_strides[idx] if stride >= 1: self.deblocks.append(nn.Sequential( nn.ConvTranspose2d( num_filters[idx], num_upsample_filters[idx], upsample_strides[idx], stride=upsample_strides[idx], bias=False ), nn.BatchNorm2d(num_upsample_filters[idx], eps=1e-3, momentum=0.01), nn.ReLU() )) else: stride = np.round(1 / stride).astype(np.int) self.deblocks.append(nn.Sequential( nn.Conv2d( num_filters[idx], num_upsample_filters[idx], stride, stride=stride, bias=False ), nn.BatchNorm2d(num_upsample_filters[idx], eps=1e-3, momentum=0.01), nn.ReLU() )) c_in = sum(num_upsample_filters) if len(upsample_strides) > num_levels: self.deblocks.append(nn.Sequential( nn.ConvTranspose2d(c_in, c_in, upsample_strides[-1], stride=upsample_strides[-1], bias=False), nn.BatchNorm2d(c_in, eps=1e-3, momentum=0.01), nn.ReLU(), )) self.num_bev_features = c_in def forward(self, data_dict): """ Args: data_dict: spatial_features Returns: """ spatial_features = data_dict['spatial_features'] ups = [] ret_dict = {} x = spatial_features for i in range(len(self.blocks)): x = self.blocks[i](x) stride = int(spatial_features.shape[2] / x.shape[2]) ret_dict['spatial_features_%dx' % stride] = x if len(self.deblocks) > 0: ups.append(self.deblocks[i](x)) else: ups.append(x) if len(ups) > 1: x = torch.cat(ups, dim=1) elif len(ups) == 1: x = ups[0] if len(self.deblocks) > len(self.blocks): x = self.deblocks[-1](x) data_dict['spatial_features_2d'] = x return data_dict
7,589
43.127907
157
py
3DTrans
3DTrans-master/pcdet/models/backbones_2d/map_to_bev/conv2d_collapse.py
import torch import torch.nn as nn from pcdet.models.model_utils.basic_block_2d import BasicBlock2D class Conv2DCollapse(nn.Module): def __init__(self, model_cfg, grid_size): """ Initializes 2D convolution collapse module Args: model_cfg: EasyDict, Model configuration grid_size: (X, Y, Z) Voxel grid size """ super().__init__() self.model_cfg = model_cfg self.num_heights = grid_size[-1] self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES self.block = BasicBlock2D(in_channels=self.num_bev_features * self.num_heights, out_channels=self.num_bev_features, **self.model_cfg.ARGS) def forward(self, batch_dict): """ Collapses voxel features to BEV via concatenation and channel reduction Args: batch_dict: voxel_features: (B, C, Z, Y, X), Voxel feature representation Returns: batch_dict: spatial_features: (B, C, Y, X), BEV feature representation """ voxel_features = batch_dict["voxel_features"] bev_features = voxel_features.flatten(start_dim=1, end_dim=2) # (B, C, Z, Y, X) -> (B, C*Z, Y, X) bev_features = self.block(bev_features) # (B, C*Z, Y, X) -> (B, C, Y, X) batch_dict["spatial_features"] = bev_features return batch_dict
1,451
36.230769
106
py
3DTrans
3DTrans-master/pcdet/models/backbones_2d/map_to_bev/pointpillar_scatter.py
import torch import torch.nn as nn class PointPillarScatter(nn.Module): def __init__(self, model_cfg, grid_size, **kwargs): super().__init__() self.model_cfg = model_cfg self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES self.nx, self.ny, self.nz = grid_size assert self.nz == 1 def forward(self, batch_dict, **kwargs): pillar_features, coords = batch_dict['pillar_features'], batch_dict['voxel_coords'] batch_spatial_features = [] batch_size = coords[:, 0].max().int().item() + 1 for batch_idx in range(batch_size): spatial_feature = torch.zeros( self.num_bev_features, self.nz * self.nx * self.ny, dtype=pillar_features.dtype, device=pillar_features.device) batch_mask = coords[:, 0] == batch_idx this_coords = coords[batch_mask, :] indices = this_coords[:, 1] + this_coords[:, 2] * self.nx + this_coords[:, 3] indices = indices.type(torch.long) pillars = pillar_features[batch_mask, :] pillars = pillars.t() spatial_feature[:, indices] = pillars batch_spatial_features.append(spatial_feature) batch_spatial_features = torch.stack(batch_spatial_features, 0) batch_spatial_features = batch_spatial_features.view(batch_size, self.num_bev_features * self.nz, self.ny, self.nx) batch_dict['spatial_features'] = batch_spatial_features return batch_dict
1,545
39.684211
123
py
3DTrans
3DTrans-master/pcdet/models/backbones_2d/map_to_bev/height_compression.py
import torch.nn as nn class HeightCompression(nn.Module): def __init__(self, model_cfg, **kwargs): super().__init__() self.model_cfg = model_cfg self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES def forward(self, batch_dict): """ Args: batch_dict: encoded_spconv_tensor: sparse tensor Returns: batch_dict: spatial_features: """ encoded_spconv_tensor = batch_dict['encoded_spconv_tensor'] spatial_features = encoded_spconv_tensor.dense() N, C, D, H, W = spatial_features.shape spatial_features = spatial_features.view(N, C * D, H, W) batch_dict['spatial_features'] = spatial_features batch_dict['spatial_features_stride'] = batch_dict['encoded_spconv_tensor_stride'] return batch_dict
870
31.259259
90
py
3DTrans
3DTrans-master/pcdet/datasets/dataset.py
import torch import copy from pathlib import Path from collections import defaultdict import numpy as np import torch.utils.data as torch_data from .augmentor.data_augmentor import DataAugmentor from .processor.data_processor import DataProcessor from .processor.point_feature_encoder import PointFeatureEncoder from ..utils import common_utils, box_utils, self_training_utils from ..ops.roiaware_pool3d import roiaware_pool3d_utils class DatasetTemplate(torch_data.Dataset): def __init__(self, dataset_cfg=None, class_names=None, training=True, root_path=None, logger=None): super().__init__() self.dataset_cfg = dataset_cfg self.training = training self.class_names = class_names self.logger = logger self.root_path = root_path if root_path is not None else Path(self.dataset_cfg.DATA_PATH) self.oss_path = self.dataset_cfg.OSS_PATH if 'OSS_PATH' in self.dataset_cfg else None self.logger = logger if self.dataset_cfg is None or class_names is None: return self.point_cloud_range = np.array(self.dataset_cfg.POINT_CLOUD_RANGE, dtype=np.float32) self.point_feature_encoder = PointFeatureEncoder( self.dataset_cfg.POINT_FEATURE_ENCODING, point_cloud_range=self.point_cloud_range ) if self.oss_path is not None: self.data_augmentor = DataAugmentor( self.oss_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=True ) if self.training else None else: self.data_augmentor = DataAugmentor( self.root_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=False ) if self.training else None self.data_processor = DataProcessor( self.dataset_cfg.DATA_PROCESSOR, point_cloud_range=self.point_cloud_range, training=self.training, num_point_features=self.point_feature_encoder.num_point_features ) self.grid_size = self.data_processor.grid_size self.voxel_size = self.data_processor.voxel_size self.total_epochs = 0 self._merge_all_iters_to_one_epoch = False if hasattr(self.data_processor, "depth_downsample_factor"): self.depth_downsample_factor = self.data_processor.depth_downsample_factor else: self.depth_downsample_factor = None @property def mode(self): return 'train' if self.training else 'test' def __getstate__(self): d = dict(self.__dict__) del d['logger'] return d def __setstate__(self, d): self.__dict__.update(d) @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ To support a custom dataset, implement this function to receive the predicted results from the model, and then transform the unified normative coordinate to your required coordinate, and optionally save them to disk. Args: batch_dict: dict of original data from the dataloader pred_dicts: dict of predicted results from the model pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: if it is not None, save the results to this path Returns: """ raise NotImplementedError @staticmethod def __vis__(points, gt_boxes, ref_boxes=None, scores=None, use_fakelidar=False): import visual_utils.visualize_utils as vis import mayavi.mlab as mlab gt_boxes = copy.deepcopy(gt_boxes) if use_fakelidar: gt_boxes = box_utils.boxes3d_kitti_lidar_to_fakelidar(gt_boxes) if ref_boxes is not None: ref_boxes = copy.deepcopy(ref_boxes) if use_fakelidar: ref_boxes = box_utils.boxes3d_kitti_lidar_to_fakelidar(ref_boxes) vis.draw_scenes(points, gt_boxes, ref_boxes=ref_boxes, ref_scores=scores) mlab.show(stop=True) @staticmethod def __vis_fake__(points, gt_boxes, ref_boxes=None, scores=None, use_fakelidar=True): import visual_utils.visualize_utils as vis import mayavi.mlab as mlab gt_boxes = copy.deepcopy(gt_boxes) if use_fakelidar: gt_boxes = box_utils.boxes3d_kitti_lidar_to_fakelidar(gt_boxes) if ref_boxes is not None: ref_boxes = copy.deepcopy(ref_boxes) if use_fakelidar: ref_boxes = box_utils.boxes3d_kitti_lidar_to_fakelidar(ref_boxes) vis.draw_scenes(points, gt_boxes, ref_boxes=ref_boxes, ref_scores=scores) mlab.show(stop=True) @staticmethod def extract_fov_data(points, fov_degree, heading_angle): """ Args: points: (N, 3 + C) fov_degree: [0~180] heading_angle: [0~360] in lidar coords, 0 is the x-axis, increase clockwise Returns: """ half_fov_degree = fov_degree / 180 * np.pi / 2 heading_angle = -heading_angle / 180 * np.pi points_new = common_utils.rotate_points_along_z( points.copy()[np.newaxis, :, :], np.array([heading_angle]) )[0] angle = np.arctan2(points_new[:, 1], points_new[:, 0]) fov_mask = ((np.abs(angle) < half_fov_degree) & (points_new[:, 0] > 0)) points = points_new[fov_mask] return points @staticmethod def extract_fov_gt(gt_boxes, fov_degree, heading_angle): """ Args: anno_dict: fov_degree: [0~180] heading_angle: [0~360] in lidar coords, 0 is the x-axis, increase clockwise Returns: """ half_fov_degree = fov_degree / 180 * np.pi / 2 heading_angle = -heading_angle / 180 * np.pi gt_boxes_lidar = copy.deepcopy(gt_boxes) gt_boxes_lidar = common_utils.rotate_points_along_z( gt_boxes_lidar[np.newaxis, :, :], np.array([heading_angle]) )[0] gt_boxes_lidar[:, 6] += heading_angle gt_angle = np.arctan2(gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) fov_gt_mask = ((np.abs(gt_angle) < half_fov_degree) & (gt_boxes_lidar[:, 0] > 0)) return fov_gt_mask def fill_pseudo_labels(self, input_dict): gt_boxes = self_training_utils.load_ps_label(input_dict['frame_id']) gt_scores = gt_boxes[:, 8] gt_classes = gt_boxes[:, 7] gt_boxes = gt_boxes[:, :7] # only suitable for only one classes, generating gt_names for prepare data gt_names = np.array([self.class_names[0] for n in gt_boxes]) input_dict['gt_boxes'] = gt_boxes input_dict['gt_names'] = gt_names input_dict['gt_classes'] = gt_classes input_dict['gt_scores'] = gt_scores input_dict['pos_ps_bbox'] = (gt_classes > 0).sum() input_dict['ign_ps_bbox'] = gt_boxes.shape[0] - input_dict['pos_ps_bbox'] input_dict.pop('num_points_in_gt', None) def merge_all_iters_to_one_epoch(self, merge=True, epochs=None): if merge: self._merge_all_iters_to_one_epoch = True self.total_epochs = epochs else: self._merge_all_iters_to_one_epoch = False def __len__(self): raise NotImplementedError def __getitem__(self, index): """ To support a custom dataset, implement this function to load the raw data (and labels), then transform them to the unified normative coordinate and call the function self.prepare_data() to process the data and send them to the model. Args: index: Returns: """ raise NotImplementedError def prepare_data(self, data_dict): """ Args: data_dict: points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string ... Returns: data_dict: frame_id: string points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string use_lead_xyz: bool voxels: optional (num_voxels, max_points_per_voxel, 3 + C) voxel_coords: optional (num_voxels, 3) voxel_num_points: optional (num_voxels) ... """ if self.training: # filter gt_boxes without points num_points_in_gt = data_dict.get('num_points_in_gt', None) if num_points_in_gt is None: num_points_in_gt = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(data_dict['points'][:, :3]), torch.from_numpy(data_dict['gt_boxes'][:, :7])).numpy().sum(axis=1) mask = (num_points_in_gt >= self.dataset_cfg.get('MIN_POINTS_OF_GT', 1)) data_dict['gt_boxes'] = data_dict['gt_boxes'][mask] data_dict['gt_names'] = data_dict['gt_names'][mask] if 'gt_classes' in data_dict: data_dict['gt_classes'] = data_dict['gt_classes'][mask] data_dict['gt_scores'] = data_dict['gt_scores'][mask] assert 'gt_boxes' in data_dict, 'gt_boxes should be provided for training' gt_boxes_mask = np.array([n in self.class_names for n in data_dict['gt_names']], dtype=np.bool_) data_dict = self.data_augmentor.forward( data_dict={ **data_dict, 'gt_boxes_mask': gt_boxes_mask } ) if data_dict.get('gt_boxes', None) is not None: selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] # for pseudo label has ignore labels. if 'gt_classes' not in data_dict: gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) else: gt_classes = data_dict['gt_classes'][selected] data_dict['gt_scores'] = data_dict['gt_scores'][selected] gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes if data_dict.get('gt_boxes2d', None) is not None: data_dict['gt_boxes2d'] = data_dict['gt_boxes2d'][selected] if data_dict.get('points', None) is not None: data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) if self.training and len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) data_dict.pop('gt_names', None) data_dict.pop('gt_classes', None) return data_dict @staticmethod def collate_batch(batch_list, _unused=False): data_dict = defaultdict(list) for cur_sample in batch_list: for key, val in cur_sample.items(): data_dict[key].append(val) batch_size = len(batch_list) ret = {} for key, val in data_dict.items(): try: if key in ['voxels', 'voxel_num_points']: ret[key] = np.concatenate(val, axis=0) elif key in ['points', 'voxel_coords']: coors = [] for i, coor in enumerate(val): coor_pad = np.pad(coor, ((0, 0), (1, 0)), mode='constant', constant_values=i) coors.append(coor_pad) ret[key] = np.concatenate(coors, axis=0) elif key in ['gt_boxes']: max_gt = max([len(x) for x in val]) batch_gt_boxes3d = np.zeros((batch_size, max_gt, val[0].shape[-1]), dtype=np.float32) for k in range(batch_size): batch_gt_boxes3d[k, :val[k].__len__(), :] = val[k] ret[key] = batch_gt_boxes3d elif key in ['gt_scores']: max_gt = max([len(x) for x in val]) batch_scores = np.zeros((batch_size, max_gt), dtype=np.float32) for k in range(batch_size): batch_scores[k, :val[k].__len__()] = val[k] ret[key] = batch_scores elif key in ['gt_boxes2d']: max_boxes = 0 max_boxes = max([len(x) for x in val]) batch_boxes2d = np.zeros((batch_size, max_boxes, val[0].shape[-1]), dtype=np.float32) for k in range(batch_size): if val[k].size > 0: batch_boxes2d[k, :val[k].__len__(), :] = val[k] ret[key] = batch_boxes2d elif key in ["images", "depth_maps"]: # Get largest image size (H, W) max_h = 0 max_w = 0 for image in val: max_h = max(max_h, image.shape[0]) max_w = max(max_w, image.shape[1]) # Change size of images images = [] for image in val: pad_h = common_utils.get_pad_params(desired_size=max_h, cur_size=image.shape[0]) pad_w = common_utils.get_pad_params(desired_size=max_w, cur_size=image.shape[1]) pad_width = (pad_h, pad_w) # Pad with nan, to be replaced later in the pipeline. pad_value = np.nan if key == "images": pad_width = (pad_h, pad_w, (0, 0)) elif key == "depth_maps": pad_width = (pad_h, pad_w) image_pad = np.pad(image, pad_width=pad_width, mode='constant', constant_values=pad_value) images.append(image_pad) ret[key] = np.stack(images, axis=0) else: ret[key] = np.stack(val, axis=0) except: print('Error in collate_batch: key=%s' % key) raise TypeError ret['batch_size'] = batch_size return ret def eval(self): self.training = False self.data_processor.eval() def train(self): self.training = True self.data_processor.train()
15,032
40.527624
118
py
3DTrans
3DTrans-master/pcdet/datasets/semi_dataset.py
from collections import defaultdict from pathlib import Path import copy import numpy as np import torch.utils.data as torch_data from ..utils import common_utils from .augmentor.data_augmentor import DataAugmentor from .augmentor.ssl_data_augmentor import SSLDataAugmentor from .processor.data_processor import DataProcessor, PairDataProcessor from .processor.point_feature_encoder import PointFeatureEncoder class SemiDatasetTemplate(torch_data.Dataset): def __init__(self, dataset_cfg=None, class_names=None, training=True, root_path=None, logger=None): super().__init__() self.dataset_cfg = dataset_cfg self.training = training self.class_names = class_names self.logger = logger self.root_path = Path(root_path) if root_path is not None else Path(self.dataset_cfg.DATA_PATH) self.oss_path = self.dataset_cfg.OSS_PATH if 'OSS_PATH' in self.dataset_cfg else None self.logger = logger if self.dataset_cfg is None or class_names is None: return self.point_cloud_range = np.array(self.dataset_cfg.POINT_CLOUD_RANGE, dtype=np.float32) self.point_feature_encoder = PointFeatureEncoder( self.dataset_cfg.POINT_FEATURE_ENCODING, point_cloud_range=self.point_cloud_range ) if self.oss_path is not None: self.data_augmentor = DataAugmentor( self.oss_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=True ) if self.training else None else: self.data_augmentor = DataAugmentor( self.root_path, self.dataset_cfg.DATA_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=False ) if self.training else None if self.dataset_cfg.get('USE_PAIR_PROCESSOR', False): self.data_processor = PairDataProcessor( self.dataset_cfg.DATA_PROCESSOR, point_cloud_range=self.point_cloud_range, training=self.training, num_point_features=self.point_feature_encoder.num_point_features ) else: self.data_processor = DataProcessor( self.dataset_cfg.DATA_PROCESSOR, point_cloud_range=self.point_cloud_range, training=self.training, num_point_features=self.point_feature_encoder.num_point_features ) if self.dataset_cfg.get('USE_SHARED_AUGMENTOR', False): if self.oss_path is not None: self.share_augmentor = SSLDataAugmentor( self.oss_path, self.dataset_cfg.SHARED_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=True ) if self.training else None else: self.share_augmentor = SSLDataAugmentor( self.root_path, self.dataset_cfg.SHARED_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=False ) if self.training else None else: self.share_augmentor = None if self.oss_path is not None: self.teacher_augmentor = SSLDataAugmentor( self.oss_path, self.dataset_cfg.TEACHER_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=True ) if self.training else None self.student_augmentor = SSLDataAugmentor( self.oss_path, self.dataset_cfg.STUDENT_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=True ) if self.training else None else: self.teacher_augmentor = SSLDataAugmentor( self.root_path, self.dataset_cfg.TEACHER_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=False ) if self.training else None self.student_augmentor = SSLDataAugmentor( self.root_path, self.dataset_cfg.STUDENT_AUGMENTOR, self.class_names, logger=self.logger, oss_flag=False ) if self.training else None self.grid_size = self.data_processor.grid_size self.voxel_size = self.data_processor.voxel_size self.total_epochs = 0 self._merge_all_iters_to_one_epoch = False if hasattr(self.data_processor, "depth_downsample_factor"): self.depth_downsample_factor = self.data_processor.depth_downsample_factor else: self.depth_downsample_factor = None @property def mode(self): return 'train' if self.training else 'test' def __getstate__(self): d = dict(self.__dict__) del d['logger'] return d def __setstate__(self, d): self.__dict__.update(d) @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ To support a custom dataset, implement this function to receive the predicted results from the model, and then transform the unified normative coordinate to your required coordinate, and optionally save them to disk. Args: batch_dict: dict of original data from the dataloader pred_dicts: dict of predicted results from the model pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: if it is not None, save the results to this path Returns: """ def merge_all_iters_to_one_epoch(self, merge=True, epochs=None): if merge: self._merge_all_iters_to_one_epoch = True self.total_epochs = epochs else: self._merge_all_iters_to_one_epoch = False def __len__(self): raise NotImplementedError def __getitem__(self, index): """ To support a custom dataset, implement this function to load the raw data (and labels), then transform them to the unified normative coordinate and call the function self.prepare_data() to process the data and send them to the model. Args: index: Returns: """ raise NotImplementedError def prepare_data(self, data_dict): """ Args: data_dict: points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string ... Returns: data_dict: frame_id: string points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string use_lead_xyz: bool voxels: optional (num_voxels, max_points_per_voxel, 3 + C) voxel_coords: optional (num_voxels, 3) voxel_num_points: optional (num_voxels) ... """ if self.training: assert 'gt_boxes' in data_dict, 'gt_boxes should be provided for training' gt_boxes_mask = np.array([n in self.class_names for n in data_dict['gt_names']], dtype=np.bool_) data_dict = self.data_augmentor.forward( data_dict={ **data_dict, 'gt_boxes_mask': gt_boxes_mask } ) if len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) if data_dict.get('gt_boxes', None) is not None: selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) data_dict.pop('gt_names', None) return data_dict def prepare_data_ssl(self, data_dict, output_dicts): """ Args: data_dict: points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string ... Returns: data_dict: frame_id: string points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string use_lead_xyz: bool voxels: optional (num_voxels, max_points_per_voxel, 3 + C) voxel_coords: optional (num_voxels, 3) voxel_num_points: optional (num_voxels) ... """ if 'gt_boxes' in data_dict: gt_boxes_mask = np.array([n in self.class_names for n in data_dict['gt_names']], dtype=np.bool_) data_dict={ **data_dict, 'gt_boxes_mask': gt_boxes_mask } if self.share_augmentor is not None: data_dict = self.share_augmentor.forward(data_dict) if 'teacher' in output_dicts: teacher_data_dict = self.teacher_augmentor.forward(copy.deepcopy(data_dict)) else: teacher_data_dict = None if 'student' in output_dicts: student_data_dict = self.student_augmentor.forward(copy.deepcopy(data_dict)) else: student_data_dict = None if data_dict != None and student_data_dict == None and teacher_data_dict == None: if 'gt_boxes' in data_dict: if len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) data_dict.pop('gt_names', None) return data_dict for data_dict in [teacher_data_dict, student_data_dict]: if data_dict is None: continue if 'gt_boxes' in data_dict: if len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) data_dict.pop('gt_names', None) return teacher_data_dict, student_data_dict def prepare_data_ssl_pair(self, data_dict, output_dicts): """ Args: data_dict: points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string ... Returns: data_dict: frame_id: string points: (N, 3 + C_in) gt_boxes: optional, (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] gt_names: optional, (N), string use_lead_xyz: bool voxels: optional (num_voxels, max_points_per_voxel, 3 + C) voxel_coords: optional (num_voxels, 3) voxel_num_points: optional (num_voxels) ... """ if 'gt_boxes' in data_dict: gt_boxes_mask = np.array([n in self.class_names for n in data_dict['gt_names']], dtype=np.bool_) data_dict={ **data_dict, 'gt_boxes_mask': gt_boxes_mask } if self.share_augmentor is not None: data_dict = self.share_augmentor.forward(data_dict) if 'teacher' in output_dicts: teacher_data_dict = self.teacher_augmentor.forward(copy.deepcopy(data_dict)) else: teacher_data_dict = None if 'student' in output_dicts: student_data_dict = self.student_augmentor.forward(copy.deepcopy(data_dict)) else: student_data_dict = None if data_dict != None and student_data_dict == None and teacher_data_dict == None: if 'gt_boxes' in data_dict: if len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes data_dict = self.point_feature_encoder.forward(data_dict) data_dict = self.data_processor.forward( data_dict=data_dict ) data_dict.pop('gt_names', None) return data_dict for data_dict in [teacher_data_dict, student_data_dict]: if data_dict is None: continue if 'gt_boxes' in data_dict: if len(data_dict['gt_boxes']) == 0: new_index = np.random.randint(self.__len__()) return self.__getitem__(new_index) selected = common_utils.keep_arrays_by_name(data_dict['gt_names'], self.class_names) data_dict['gt_boxes'] = data_dict['gt_boxes'][selected] data_dict['gt_names'] = data_dict['gt_names'][selected] gt_classes = np.array([self.class_names.index(n) + 1 for n in data_dict['gt_names']], dtype=np.int32) gt_boxes = np.concatenate((data_dict['gt_boxes'], gt_classes.reshape(-1, 1).astype(np.float32)), axis=1) data_dict['gt_boxes'] = gt_boxes data_dict = self.point_feature_encoder.forward(data_dict) teacher_data_dict, student_data_dict = self.data_processor.forward( data_dict_1=teacher_data_dict, data_dict_2=student_data_dict ) data_dict.pop('gt_names', None) return teacher_data_dict, student_data_dict @staticmethod def collate_batch(batch_list, _unused=False): def collate_single_batch(batch_list): data_dict = defaultdict(list) for cur_sample in batch_list: if isinstance(cur_sample, dict): for key, val in cur_sample.items(): data_dict[key].append(val) else: raise Exception('batch samples must be dict') batch_size = len(batch_list) ret = {} for key, val in data_dict.items(): try: if key in ['voxels', 'voxel_num_points']: ret[key] = np.concatenate(val, axis=0) elif key in ['points', 'voxel_coords']: coors = [] for i, coor in enumerate(val): coor_pad = np.pad(coor, ((0, 0), (1, 0)), mode='constant', constant_values=i) coors.append(coor_pad) ret[key] = np.concatenate(coors, axis=0) elif key in ['gt_boxes']: max_gt = max([len(x) for x in val]) batch_gt_boxes3d = np.zeros((batch_size, max_gt, val[0].shape[-1]), dtype=np.float32) for k in range(batch_size): batch_gt_boxes3d[k, :val[k].__len__(), :] = val[k] ret[key] = batch_gt_boxes3d elif key in ['augmentation_list', 'augmentation_params']: ret[key] = val else: ret[key] = np.stack(val, axis=0) except: print('Error in collate_batch: key=%s' % key) raise TypeError ret['batch_size'] = batch_size return ret if isinstance(batch_list[0], dict): return collate_single_batch(batch_list) elif isinstance(batch_list[0], tuple): if batch_list[0][0] is None: teacher_batch = None else: teacher_batch_list = [sample[0] for sample in batch_list] teacher_batch = collate_single_batch(teacher_batch_list) if batch_list[0][1] is None: student_batch = None else: student_batch_list = [sample[1] for sample in batch_list] student_batch = collate_single_batch(student_batch_list) return teacher_batch, student_batch else: raise Exception('batch samples must be dict or tuple')
18,381
41.848485
179
py
3DTrans
3DTrans-master/pcdet/datasets/__init__.py
import torch from torch.utils.data import DataLoader from torch.utils.data import DistributedSampler as _DistributedSampler from pcdet.utils import common_utils from .dataset import DatasetTemplate from .kitti.kitti_dataset import KittiDataset from .kitti.kitti_dataset_ada import ActiveKittiDataset from .nuscenes.nuscenes_dataset import NuScenesDataset from .nuscenes.nuscenes_dataset_ada import ActiveNuScenesDataset from .waymo.waymo_dataset import WaymoDataset from .waymo.waymo_dataset_ada import ActiveWaymoDataset from .pandaset.pandaset_dataset import PandasetDataset from .lyft.lyft_dataset import LyftDataset from .lyft.lyft_dataset_ada import ActiveLyftDataset from .once.once_dataset import ONCEDataset from .once.once_dataset_ada import ActiveONCEDataset from .once.once_semi_dataset import ONCEPretrainDataset, ONCELabeledDataset, ONCEUnlabeledDataset, ONCETestDataset, ONCEUnlabeledPairDataset, split_once_semi_data from .nuscenes.nuscenes_semi_dataset import NuScenesPretrainDataset, NuScenesLabeledDataset, NuScenesUnlabeledDataset, NuScenesTestDataset, split_nuscenes_semi_data from .kitti.kitti_semi_dataset import KittiPretrainDataset, KittiLabeledDataset, KittiUnlabeledDataset, KittiTestDataset, split_kitti_semi_data __all__ = { 'DatasetTemplate': DatasetTemplate, 'KittiDataset': KittiDataset, 'ActiveKittiDataset': ActiveKittiDataset, 'NuScenesDataset': NuScenesDataset, 'ActiveNuScenesDataset': ActiveNuScenesDataset, 'WaymoDataset': WaymoDataset, 'ActiveWaymoDataset': ActiveWaymoDataset, 'PandasetDataset': PandasetDataset, 'LyftDataset': LyftDataset, 'ONCEDataset': ONCEDataset, 'ActiveLyftDataset': ActiveLyftDataset, 'ActiveONCEDataset': ActiveONCEDataset, } _semi_dataset_dict = { 'ONCEDataset': { 'PARTITION_FUNC': split_once_semi_data, 'PRETRAIN': ONCEPretrainDataset, 'LABELED': ONCELabeledDataset, 'UNLABELED': ONCEUnlabeledDataset, 'UNLABELED_PAIR': ONCEUnlabeledPairDataset, 'TEST': ONCETestDataset }, 'NuScenesDataset': { 'PARTITION_FUNC': split_nuscenes_semi_data, 'PRETRAIN': NuScenesPretrainDataset, 'LABELED': NuScenesLabeledDataset, 'UNLABELED': NuScenesUnlabeledDataset, 'TEST': NuScenesTestDataset }, 'KittiDataset': { 'PARTITION_FUNC': split_kitti_semi_data, 'PRETRAIN': KittiPretrainDataset, 'LABELED': KittiLabeledDataset, 'UNLABELED': KittiUnlabeledDataset, 'TEST': KittiTestDataset } } class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True): super().__init__(dataset, num_replicas=num_replicas, rank=rank) self.shuffle = shuffle def __iter__(self): if self.shuffle: g = torch.Generator() g.manual_seed(self.epoch) indices = torch.randperm(len(self.dataset), generator=g).tolist() else: indices = torch.arange(len(self.dataset)).tolist() indices += indices[:(self.total_size - len(indices))] assert len(indices) == self.total_size indices = indices[self.rank:self.total_size:self.num_replicas] assert len(indices) == self.num_samples return iter(indices) def build_dataloader(dataset_cfg, class_names, batch_size, dist, root_path=None, workers=4, logger=None, training=True, merge_all_iters_to_one_epoch=False, total_epochs=0): dataset = __all__[dataset_cfg.DATASET]( dataset_cfg=dataset_cfg, class_names=class_names, root_path=root_path, training=training, logger=logger, ) if merge_all_iters_to_one_epoch: assert hasattr(dataset, 'merge_all_iters_to_one_epoch') dataset.merge_all_iters_to_one_epoch(merge=True, epochs=total_epochs) if dist: if training: sampler = torch.utils.data.distributed.DistributedSampler(dataset) else: rank, world_size = common_utils.get_dist_info() sampler = DistributedSampler(dataset, world_size, rank, shuffle=False) else: sampler = None dataloader = DataLoader( dataset, batch_size=batch_size, pin_memory=True, num_workers=workers, shuffle=(sampler is None) and training, collate_fn=dataset.collate_batch, drop_last=False, sampler=sampler, timeout=0 ) return dataset, dataloader, sampler def build_dataloader_ada(dataset_cfg, class_names, batch_size, dist, root_path=None, workers=4, logger=None, training=True, info_path=None, merge_all_iters_to_one_epoch=False, total_epochs=0): dataset = __all__[dataset_cfg.DATASET]( dataset_cfg=dataset_cfg, class_names=class_names, root_path=root_path, training=training, logger=logger, sample_info_path=info_path, ) if merge_all_iters_to_one_epoch: assert hasattr(dataset, 'merge_all_iters_to_one_epoch') dataset.merge_all_iters_to_one_epoch(merge=True, epochs=total_epochs) if dist: if training: sampler = torch.utils.data.distributed.DistributedSampler(dataset) else: rank, world_size = common_utils.get_dist_info() sampler = DistributedSampler(dataset, world_size, rank, shuffle=False) else: sampler = None dataloader = DataLoader( dataset, batch_size=batch_size, pin_memory=True, num_workers=workers, shuffle=(sampler is None) and training, collate_fn=dataset.collate_batch, drop_last=False, sampler=sampler, timeout=0 ) return dataset, dataloader, sampler def build_dataloader_mdf(dataset_cfg, class_names, batch_size, dist, root_path=None, workers=4, drop_last=True, logger=None, training=True, merge_all_iters_to_one_epoch=False, total_epochs=0): dataset = __all__[dataset_cfg.DATASET]( dataset_cfg=dataset_cfg, class_names=class_names, root_path=root_path, training=training, logger=logger, ) if merge_all_iters_to_one_epoch: assert hasattr(dataset, 'merge_all_iters_to_one_epoch') dataset.merge_all_iters_to_one_epoch(merge=True, epochs=total_epochs) if dist: if training: sampler = torch.utils.data.distributed.DistributedSampler(dataset) else: rank, world_size = common_utils.get_dist_info() sampler = DistributedSampler(dataset, world_size, rank, shuffle=False) else: sampler = None dataloader = DataLoader( dataset, batch_size=batch_size, pin_memory=True, num_workers=workers, shuffle=(sampler is None) and training, collate_fn=dataset.collate_batch, drop_last=drop_last, sampler=sampler, timeout=0 ) return dataset, dataloader, sampler def build_semi_dataloader(dataset_cfg, class_names, batch_size, dist, root_path=None, workers=4, logger=None, merge_all_iters_to_one_epoch=False): assert merge_all_iters_to_one_epoch is False train_infos, test_infos, labeled_infos, unlabeled_infos = _semi_dataset_dict[dataset_cfg.DATASET]['PARTITION_FUNC']( dataset_cfg = dataset_cfg, info_paths = dataset_cfg.INFO_PATH, data_splits = dataset_cfg.DATA_SPLIT, root_path = root_path, labeled_ratio = dataset_cfg.LABELED_RATIO, logger = logger, ) pretrain_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['PRETRAIN']( dataset_cfg=dataset_cfg, class_names=class_names, infos = train_infos, root_path=root_path, logger=logger, ) if dist: pretrain_sampler = torch.utils.data.distributed.DistributedSampler(pretrain_dataset) else: pretrain_sampler = None pretrain_dataloader = DataLoader( pretrain_dataset, batch_size=batch_size['pretrain'], pin_memory=True, num_workers=workers, shuffle=(pretrain_sampler is None) and True, collate_fn=pretrain_dataset.collate_batch, drop_last=False, sampler=pretrain_sampler, timeout=0 ) labeled_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['LABELED']( dataset_cfg=dataset_cfg, class_names=class_names, infos = labeled_infos, root_path=root_path, logger=logger, ) if dist: labeled_sampler = torch.utils.data.distributed.DistributedSampler(labeled_dataset) else: labeled_sampler = None labeled_dataloader = DataLoader( labeled_dataset, batch_size=batch_size['labeled'], pin_memory=True, num_workers=workers, shuffle=(labeled_sampler is None) and True, collate_fn=labeled_dataset.collate_batch, drop_last=False, sampler=labeled_sampler, timeout=0 ) unlabeled_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['UNLABELED']( dataset_cfg=dataset_cfg, class_names=class_names, infos = unlabeled_infos, root_path=root_path, logger=logger, ) if dist: unlabeled_sampler = torch.utils.data.distributed.DistributedSampler(unlabeled_dataset) else: unlabeled_sampler = None unlabeled_dataloader = DataLoader( unlabeled_dataset, batch_size=batch_size['unlabeled'], pin_memory=True, num_workers=workers, shuffle=(unlabeled_sampler is None) and True, collate_fn=unlabeled_dataset.collate_batch, drop_last=False, sampler=unlabeled_sampler, timeout=0 ) test_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['TEST']( dataset_cfg=dataset_cfg, class_names=class_names, infos = test_infos, root_path=root_path, logger=logger, ) if dist: rank, world_size = common_utils.get_dist_info() test_sampler = DistributedSampler(test_dataset, world_size, rank, shuffle=False) else: test_sampler = None test_dataloader = DataLoader( test_dataset, batch_size=batch_size['test'], pin_memory=True, num_workers=workers, shuffle=(test_sampler is None) and False, collate_fn=test_dataset.collate_batch, drop_last=False, sampler=test_sampler, timeout=0 ) datasets = { 'pretrain': pretrain_dataset, 'labeled': labeled_dataset, 'unlabeled': unlabeled_dataset, 'test': test_dataset } dataloaders = { 'pretrain': pretrain_dataloader, 'labeled': labeled_dataloader, 'unlabeled': unlabeled_dataloader, 'test': test_dataloader } samplers = { 'pretrain': pretrain_sampler, 'labeled': labeled_sampler, 'unlabeled': unlabeled_sampler, 'test': test_sampler } return datasets, dataloaders, samplers def build_unsupervised_dataloader(dataset_cfg, class_names, batch_size, dist, root_path=None, workers=4, logger=None, merge_all_iters_to_one_epoch=False): assert merge_all_iters_to_one_epoch is False train_infos, test_infos, labeled_infos, unlabeled_infos = _semi_dataset_dict[dataset_cfg.DATASET]['PARTITION_FUNC']( dataset_cfg = dataset_cfg, info_paths = dataset_cfg.INFO_PATH, data_splits = dataset_cfg.DATA_SPLIT, root_path = root_path, labeled_ratio = dataset_cfg.LABELED_RATIO, logger = logger, ) unlabeled_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['UNLABELED_PAIR']( dataset_cfg=dataset_cfg, class_names=class_names, infos = unlabeled_infos, root_path=root_path, logger=logger, ) if dist: unlabeled_sampler = torch.utils.data.distributed.DistributedSampler(unlabeled_dataset) else: unlabeled_sampler = None unlabeled_dataloader = DataLoader( unlabeled_dataset, batch_size=batch_size['unlabeled'], pin_memory=True, num_workers=workers, shuffle=(unlabeled_sampler is None) and True, collate_fn=unlabeled_dataset.collate_batch, drop_last=False, sampler=unlabeled_sampler, timeout=0 ) test_dataset = _semi_dataset_dict[dataset_cfg.DATASET]['TEST']( dataset_cfg=dataset_cfg, class_names=class_names, infos = test_infos, root_path=root_path, logger=logger, ) if dist: rank, world_size = common_utils.get_dist_info() test_sampler = DistributedSampler(test_dataset, world_size, rank, shuffle=False) else: test_sampler = None test_dataloader = DataLoader( test_dataset, batch_size=batch_size['test'], pin_memory=True, num_workers=workers, shuffle=(test_sampler is None) and False, collate_fn=test_dataset.collate_batch, drop_last=False, sampler=test_sampler, timeout=0 ) datasets = { 'unlabeled': unlabeled_dataset, 'test': test_dataset } dataloaders = { 'unlabeled': unlabeled_dataloader, 'test': test_dataloader } samplers = { 'unlabeled': unlabeled_sampler, 'test': test_sampler } return datasets, dataloaders, samplers
13,075
36.36
164
py
3DTrans
3DTrans-master/pcdet/datasets/waymo/waymo_dataset.py
# OpenPCDet PyTorch Dataloader and Evaluation Tools for Waymo Open Dataset # Reference https://github.com/open-mmlab/OpenPCDet # Written by Shaoshuai Shi, Chaoxu Guo # All Rights Reserved 2019-2020. import os import io import pickle import copy import numpy as np import torch import multiprocessing import SharedArray import torch.distributed as dist from tqdm import tqdm from pathlib import Path from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils, common_utils from ..dataset import DatasetTemplate class WaymoDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/waymo' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) if self.oss_path is not None: self.data_path = os.path.join(self.oss_path, self.dataset_cfg.PROCESSED_DATA_TAG) from petrel_client.client import Client self.client = Client('~/.petreloss.conf') logger.info(f'self.data_path: {self.data_path}') oss_data_list_manifest = self.oss_path + '/manifest.lst' if not self.client.contains(oss_data_list_manifest): logger.info(f'listing files in {self.data_path}') self.oss_data_list = self.list_oss_dir(self.data_path, with_info=False) self.client.put(oss_data_list_manifest, '\n'.join(self.oss_data_list).encode()) logger.info(f'Listing finished and cache the oss_data_list to {oss_data_list_manifest}') else: logger.info(f'loading the self.oss_data_list from {oss_data_list_manifest}') self.oss_data_list = self.client.get(oss_data_list_manifest).decode().splitlines() else: self.data_path = self.root_path / self.dataset_cfg.PROCESSED_DATA_TAG self.split = self.dataset_cfg.DATA_SPLIT[self.mode] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.include_waymo_data(self.mode) self.use_shared_memory = self.dataset_cfg.get('USE_SHARED_MEMORY', False) and self.training if self.use_shared_memory: self.shared_memory_file_limit = self.dataset_cfg.get('SHARED_MEMORY_FILE_LIMIT', 0x7FFFFFFF) self.load_data_to_shared_memory() def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = os.path.join(self.root_path, 'ImageSets', self.split+'.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.include_waymo_data(self.mode) def include_waymo_data(self, mode): self.logger.info('Loading Waymo dataset') waymo_infos = [] num_skipped_infos = 0 self.logger.info('start to include waymo data') for k in tqdm(range(len(self.sample_sequence_list))): sequence_name = os.path.splitext(self.sample_sequence_list[k])[0] if self.oss_path is None: info_path = self.data_path / sequence_name / ('%s.pkl' % sequence_name) info_path = self.check_sequence_name_with_all_version(info_path) if not info_path.exists(): num_skipped_infos += 1 continue else: info_path = os.path.join(self.data_path, sequence_name, ('%s.pkl' % sequence_name)) info_path = self.check_sequence_name_with_all_version(info_path) if not self.oss_exist(info_path): num_skipped_infos += 1 continue if self.oss_path is None: with open(info_path, 'rb') as f: infos = pickle.load(f) waymo_infos.extend(infos) else: #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) waymo_infos.extend(infos) self.infos.extend(waymo_infos[:]) self.logger.info('Total skipped info %s' % num_skipped_infos) self.logger.info('Total samples for Waymo dataset: %d' % (len(waymo_infos))) if self.dataset_cfg.SAMPLED_INTERVAL[mode] > 1: sampled_waymo_infos = [] for k in range(0, len(self.infos), self.dataset_cfg.SAMPLED_INTERVAL[mode]): sampled_waymo_infos.append(self.infos[k]) self.infos = sampled_waymo_infos self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos)) def load_data_to_shared_memory(self): self.logger.info(f'Loading training data to shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if os.path.exists(f"/dev/shm/{sa_key}"): continue points = self.get_lidar(sequence_name, sample_idx) common_utils.sa_create(f"shm://{sa_key}", points) dist.barrier() self.logger.info('Training data has been saved to shared memory') def clean_shared_memory(self): self.logger.info(f'Clean training data from shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if not os.path.exists(f"/dev/shm/{sa_key}"): continue SharedArray.delete(f"shm://{sa_key}") if num_gpus > 1: dist.barrier() self.logger.info('Training data has been deleted from shared memory') # @staticmethod # def check_sequence_name_with_all_version(sequence_file): # if not sequence_file.exists(): # found_sequence_file = sequence_file # for pre_text in ['training', 'validation', 'testing']: # if not sequence_file.exists(): # temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) # if temp_sequence_file.exists(): # found_sequence_file = temp_sequence_file # break # if not found_sequence_file.exists(): # found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) # if found_sequence_file.exists(): # sequence_file = found_sequence_file # return sequence_file def check_sequence_name_with_all_version(self, sequence_file): if self.oss_path is None: if not sequence_file.exists(): found_sequence_file = sequence_file for pre_text in ['training', 'validation', 'testing']: if not sequence_file.exists(): temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) if temp_sequence_file.exists(): found_sequence_file = temp_sequence_file break if not found_sequence_file.exists(): found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) if found_sequence_file.exists(): sequence_file = found_sequence_file else: if not self.oss_exist(sequence_file): found_sequence_file = sequence_file for pre_text in ['training', 'validation', 'testing']: if not self.oss_exist(sequence_file): #temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) temp_sequence_file = sequence_file.replace('segment', pre_text + '_segment') if self.oss_exist(temp_sequence_file): found_sequence_file = temp_sequence_file break if not self.oss_exist(found_sequence_file): #found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) found_sequence_file = sequence_file.replace('_with_camera_labels', '') if self.oss_exist(found_sequence_file): sequence_file = found_sequence_file return sequence_file # def check_sequence_name_with_all_version(self, sequence_file): # if self.oss_path is not None: # if '_with_camera_labels' not in sequence_file and not self.oss_exist(sequence_file): # sequence_file = sequence_file[:-9] + '_with_camera_labels.tfrecord' # if '_with_camera_labels' in sequence_file and not self.oss_exist(sequence_file): # sequence_file = sequence_file.replace('_with_camera_labels', '') # else: # if '_with_camera_labels' not in str(sequence_file) and not os.path.exists(sequence_file): # sequence_file = Path(str(sequence_file[:-9]) + '_with_camera_labels.tfrecord') # if '_with_camera_labels' in str(sequence_file) and not os.path.exists(sequence_file): # sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) # return sequence_file """ For loading files from OSS """ def list_oss_dir(self, oss_path, with_info=False): s3_dir = self.fix_path(oss_path) files_iter = self.client.get_file_iterator(s3_dir) if with_info: file_list = {p: k for p, k in files_iter} else: file_list = [p for p, k in files_iter] return file_list @staticmethod def fix_path(path_str): try: st_ = str(path_str) if "s3://" in st_: return st_ if "s3:/" in st_: st_ = "s3://" + st_.strip('s3:/') return st_ else: st_ = "s3://" + st_ return st_ except: raise TypeError def oss_exist(self, file_path, refresh=False): if self.data_path is None: raise IndexError("No initialized path set!") if refresh: self.oss_data_list = self.list_oss_dir(self.data_path, with_info=False) pure_name = self.fix_path(file_path).strip("s3://") if pure_name in self.oss_data_list: return True else: return False def get_infos(self, raw_data_path, save_path, num_workers=multiprocessing.cpu_count(), has_label=True, sampled_interval=1): from functools import partial from . import waymo_utils print('---------------The waymo sample interval is %d, total sequecnes is %d-----------------' % (sampled_interval, len(self.sample_sequence_list))) process_single_sequence = partial( waymo_utils.process_single_sequence, save_path=save_path, sampled_interval=sampled_interval, has_label=has_label ) sample_sequence_file_list = [ self.check_sequence_name_with_all_version(raw_data_path / sequence_file) for sequence_file in self.sample_sequence_list ] with multiprocessing.Pool(num_workers) as p: sequence_infos = list(tqdm(p.imap(process_single_sequence, sample_sequence_file_list), total=len(sample_sequence_file_list))) all_sequences_infos = [item for infos in sequence_infos for item in infos] return all_sequences_infos def get_lidar(self, sequence_name, sample_idx): if self.oss_path is None: #lidar_file = self.data_path / sequence_name / ('%04d.npy' % sample_idx) # lidar_file = os.path.join(self.data_path, sequence_name, ('%04d.npy' % sample_idx)) point_features = np.load(lidar_file) # (N, 7): [x, y, z, intensity, elongation, NLZ_flag] else: lidar_file = os.path.join(self.data_path, sequence_name, ('%04d.npy' % sample_idx)) #npy_bytes = self.client.get(lidar_file) npy_bytes = self.client.get(lidar_file, update_cache=True) point_features = np.load(io.BytesIO(npy_bytes)) points_all, NLZ_flag = point_features[:, 0:5], point_features[:, 5] if not self.dataset_cfg.get('DISABLE_NLZ_FLAG_ON_POINTS', False): points_all = points_all[NLZ_flag == -1] points_all[:, 3] = np.tanh(points_all[:, 3]) return points_all def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] if self.use_shared_memory and index < self.shared_memory_file_limit: sa_key = f'{sequence_name}___{sample_idx}' points = SharedArray.attach(f"shm://{sa_key}").copy() else: points = self.get_lidar(sequence_name, sample_idx) lidar_z = points[:, 2] input_dict = { 'db_flag': "waymo", 'points': points, 'frame_id': info['frame_id'], } if 'annos' in info: annos = info['annos'] annos = common_utils.drop_info_with_name(annos, name='unknown') if self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False): gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(annos['gt_boxes_lidar']) else: gt_boxes_lidar = annos['gt_boxes_lidar'] lidar_z = gt_boxes_lidar[:, 2] if self.training and self.dataset_cfg.get('FILTER_EMPTY_BOXES_FOR_TRAIN', False): mask = (annos['num_points_in_gt'] > 0) # filter empty boxes annos['name'] = annos['name'][mask] gt_boxes_lidar = gt_boxes_lidar[mask] annos['num_points_in_gt'] = annos['num_points_in_gt'][mask] input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': gt_boxes_lidar, 'num_points_in_gt': annos.get('num_points_in_gt', None) }) if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None if self.dataset_cfg.get('FOV_POINTS_ONLY', None): input_dict['points'] = self.extract_fov_data( input_dict['points'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) if input_dict['gt_boxes'] is not None: fov_gt_flag = self.extract_fov_gt( input_dict['gt_boxes'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) input_dict.update({ 'gt_names': input_dict['gt_names'][fov_gt_flag], 'gt_boxes': input_dict['gt_boxes'][fov_gt_flag], 'num_points_in_gt': input_dict['num_points_in_gt'][fov_gt_flag] if input_dict['num_points_in_gt'] is not None else None }) # load saved pseudo label for unlabeled data if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) data_dict['metadata'] = info.get('metadata', info['frame_id']) data_dict.pop('num_points_in_gt', None) return data_dict @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def evaluation(self, det_annos, class_names, **kwargs): if 'annos' not in self.infos[0].keys(): return 'No ground-truth boxes for evaluation', {} def kitti_eval(eval_det_annos, eval_gt_annos): from ..kitti.kitti_object_eval_python import eval as kitti_eval from ..kitti import kitti_utils map_name_to_kitti = { 'Vehicle': 'Car', 'Pedestrian': 'Pedestrian', 'Cyclist': 'Cyclist', 'Sign': 'Sign', 'Car': 'Car' } kitti_utils.transform_annotations_to_kitti_format(eval_det_annos, map_name_to_kitti=map_name_to_kitti) kitti_utils.transform_annotations_to_kitti_format( eval_gt_annos, map_name_to_kitti=map_name_to_kitti, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def waymo_eval(eval_det_annos, eval_gt_annos): from .waymo_eval import OpenPCDetWaymoDetectionMetricsEstimator eval = OpenPCDetWaymoDetectionMetricsEstimator() ap_dict = eval.waymo_evaluation( eval_det_annos, eval_gt_annos, class_name=class_names, distance_thresh=1000, fake_gt_infos=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) ap_result_str = '\n' for key in ap_dict: ap_dict[key] = ap_dict[key][0] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) return ap_result_str, ap_dict eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.infos] if kwargs['eval_metric'] == 'kitti': ap_result_str, ap_dict = kitti_eval(eval_det_annos, eval_gt_annos) elif kwargs['eval_metric'] == 'waymo': ap_result_str, ap_dict = waymo_eval(eval_det_annos, eval_gt_annos) else: raise NotImplementedError return ap_result_str, ap_dict def create_groundtruth_database(self, info_path, save_path, used_classes=None, split='train', sampled_interval=10, processed_data_tag=None): database_save_path = save_path / ('%s_gt_database_%s_sampled_%d' % (processed_data_tag, split, sampled_interval)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d.pkl' % (processed_data_tag, split, sampled_interval)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_global.npy' % (processed_data_tag, split, sampled_interval)) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) point_offset_cnt = 0 stacked_gt_points = [] for k in range(0, len(infos), sampled_interval): print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] points = self.get_lidar(sequence_name, sample_idx) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] gt_boxes = annos['gt_boxes_lidar'] if k % 4 != 0 and len(names) > 0: mask = (names == 'Vehicle') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] if k % 2 != 0 and len(names) > 0: mask = (names == 'Pedestrian') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] num_obj = gt_boxes.shape[0] if num_obj == 0: continue box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(num_obj): filename = '%s_%04d_%s_%d.bin' % (sequence_name, sample_idx, names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] if (used_classes is None) or names[i] in used_classes: with open(filepath, 'w') as f: gt_points.tofile(f) db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'sequence_name': sequence_name, 'sample_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0], 'difficulty': difficulty[i]} # it will be used if you choose to use shared memory for gt sampling stacked_gt_points.append(gt_points) db_info['global_data_offset'] = [point_offset_cnt, point_offset_cnt + gt_points.shape[0]] point_offset_cnt += gt_points.shape[0] if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) # it will be used if you choose to use shared memory for gt sampling stacked_gt_points = np.concatenate(stacked_gt_points, axis=0) np.save(db_data_save_path, stacked_gt_points) def create_waymo_infos(dataset_cfg, class_names, data_path, save_path, raw_data_tag='raw_data', processed_data_tag='waymo_processed_data', workers=min(16, multiprocessing.cpu_count())): dataset = WaymoDataset( dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False, logger=common_utils.create_logger() ) train_split, val_split = 'train', 'val' train_filename = save_path / ('%s_infos_%s.pkl' % (processed_data_tag, train_split)) val_filename = save_path / ('%s_infos_%s.pkl' % (processed_data_tag, val_split)) os.environ["CUDA_VISIBLE_DEVICES"] = "-1" print('---------------Start to generate data infos---------------') dataset.set_split(train_split) waymo_infos_train = dataset.get_infos( raw_data_path=data_path / raw_data_tag, save_path=save_path / processed_data_tag, num_workers=workers, has_label=True, sampled_interval=1 ) with open(train_filename, 'wb') as f: pickle.dump(waymo_infos_train, f) print('----------------Waymo info train file is saved to %s----------------' % train_filename) dataset.set_split(val_split) waymo_infos_val = dataset.get_infos( raw_data_path=data_path / raw_data_tag, save_path=save_path / processed_data_tag, num_workers=workers, has_label=True, sampled_interval=1 ) with open(val_filename, 'wb') as f: pickle.dump(waymo_infos_val, f) print('----------------Waymo info val file is saved to %s----------------' % val_filename) print('---------------Start create groundtruth database for data augmentation---------------') os.environ["CUDA_VISIBLE_DEVICES"] = "0" dataset.set_split(train_split) dataset.create_groundtruth_database( info_path=train_filename, save_path=save_path, split='train', sampled_interval=1, used_classes=['Vehicle', 'Pedestrian', 'Cyclist'], processed_data_tag=processed_data_tag ) print('---------------Data preparation Done---------------') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_waymo_infos', help='') parser.add_argument('--processed_data_tag', type=str, default='waymo_processed_data_v0_5_0', help='') args = parser.parse_args() if args.func == 'create_waymo_infos': import yaml from easydict import EasyDict try: yaml_config = yaml.safe_load(open(args.cfg_file), Loader=yaml.FullLoader) except: yaml_config = yaml.safe_load(open(args.cfg_file)) dataset_cfg = EasyDict(yaml_config) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.PROCESSED_DATA_TAG = args.processed_data_tag create_waymo_infos( dataset_cfg=dataset_cfg, class_names=['Vehicle', 'Pedestrian', 'Cyclist'], data_path=ROOT_DIR / 'data' / 'waymo', save_path=ROOT_DIR / 'data' / 'waymo', raw_data_tag='raw_data', processed_data_tag=args.processed_data_tag )
28,281
44.035032
139
py
3DTrans
3DTrans-master/pcdet/datasets/waymo/waymo_dataset_ada.py
import os import io import pickle import copy import numpy as np import torch import multiprocessing import SharedArray import torch.distributed as dist from tqdm import tqdm from pathlib import Path from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils, common_utils from ..dataset import DatasetTemplate class ActiveWaymoDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/waymo' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None, sample_info_path=None): super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) if self.oss_path is not None: self.data_path = os.path.join(self.oss_path, self.dataset_cfg.PROCESSED_DATA_TAG) from petrel_client.client import Client self.client = Client('~/.petreloss.conf') logger.info(f'self.data_path: {self.data_path}') oss_data_list_manifest = self.oss_path + '/manifest.lst' if not self.client.contains(oss_data_list_manifest): logger.info(f'listing files in {self.data_path}') self.oss_data_list = self.list_oss_dir(self.data_path, with_info=False) self.client.put(oss_data_list_manifest, '\n'.join(self.oss_data_list).encode()) logger.info(f'Listing finished and cache the oss_data_list to {oss_data_list_manifest}') else: logger.info(f'loading the self.oss_data_list from {oss_data_list_manifest}') self.oss_data_list = self.client.get(oss_data_list_manifest).decode().splitlines() else: self.data_path = self.root_path / self.dataset_cfg.PROCESSED_DATA_TAG self.split = self.dataset_cfg.DATA_SPLIT[self.mode] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.include_waymo_data(self.mode, sample_info_path) self.use_shared_memory = self.dataset_cfg.get('USE_SHARED_MEMORY', False) and self.training if self.use_shared_memory: self.shared_memory_file_limit = self.dataset_cfg.get('SHARED_MEMORY_FILE_LIMIT', 0x7FFFFFFF) self.load_data_to_shared_memory() def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = os.path.join(self.root_path, 'ImageSets', self.split+'.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.include_waymo_data(self.mode) def include_waymo_data(self, mode, sample_info_path=None): self.logger.info('Loading Waymo dataset') waymo_infos = [] num_skipped_infos = 0 self.logger.info('start to include waymo data') if sample_info_path != None: with open(sample_info_path, 'rb') as f: infos = pickle.load(f) waymo_infos.extend(infos) else: for k in tqdm(range(len(self.sample_sequence_list))): sequence_name = os.path.splitext(self.sample_sequence_list[k])[0] if self.oss_path is None: info_path = self.data_path / sequence_name / ('%s.pkl' % sequence_name) info_path = self.check_sequence_name_with_all_version(info_path) if not info_path.exists(): num_skipped_infos += 1 continue else: info_path = os.path.join(self.data_path, sequence_name, ('%s.pkl' % sequence_name)) info_path = self.check_sequence_name_with_all_version(info_path) if not self.oss_exist(info_path): num_skipped_infos += 1 continue if self.oss_path is None: with open(info_path, 'rb') as f: infos = pickle.load(f) waymo_infos.extend(infos) else: #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) waymo_infos.extend(infos) self.infos.extend(waymo_infos[:]) self.logger.info('Total skipped info %s' % num_skipped_infos) self.logger.info('Total samples for Waymo dataset: %d' % (len(waymo_infos))) if self.dataset_cfg.get('SOURCE_SAMPLE', False) == True: sampled_waymo_infos = [] for k in range(0, len(self.infos), self.dataset_cfg.SOURCE_SAMPLED_INTERVAL): sampled_waymo_infos.append(self.infos[k]) self.infos = sampled_waymo_infos self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos)) elif self.dataset_cfg.SAMPLED_INTERVAL[mode] > 1 and sample_info_path == None: sampled_waymo_infos = [] for k in range(0, len(self.infos), self.dataset_cfg.SAMPLED_INTERVAL[mode]): sampled_waymo_infos.append(self.infos[k]) self.infos = sampled_waymo_infos self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos)) def load_data_to_shared_memory(self): self.logger.info(f'Loading training data to shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if os.path.exists(f"/dev/shm/{sa_key}"): continue points = self.get_lidar(sequence_name, sample_idx) common_utils.sa_create(f"shm://{sa_key}", points) dist.barrier() self.logger.info('Training data has been saved to shared memory') def clean_shared_memory(self): self.logger.info(f'Clean training data from shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if not os.path.exists(f"/dev/shm/{sa_key}"): continue SharedArray.delete(f"shm://{sa_key}") if num_gpus > 1: dist.barrier() self.logger.info('Training data has been deleted from shared memory') # @staticmethod # def check_sequence_name_with_all_version(sequence_file): # if not sequence_file.exists(): # found_sequence_file = sequence_file # for pre_text in ['training', 'validation', 'testing']: # if not sequence_file.exists(): # temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) # if temp_sequence_file.exists(): # found_sequence_file = temp_sequence_file # break # if not found_sequence_file.exists(): # found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) # if found_sequence_file.exists(): # sequence_file = found_sequence_file # return sequence_file def check_sequence_name_with_all_version(self, sequence_file): if self.oss_path is None: if not sequence_file.exists(): found_sequence_file = sequence_file for pre_text in ['training', 'validation', 'testing']: if not sequence_file.exists(): temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) if temp_sequence_file.exists(): found_sequence_file = temp_sequence_file break if not found_sequence_file.exists(): found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) if found_sequence_file.exists(): sequence_file = found_sequence_file else: if not self.oss_exist(sequence_file): found_sequence_file = sequence_file for pre_text in ['training', 'validation', 'testing']: if not self.oss_exist(sequence_file): #temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) temp_sequence_file = sequence_file.replace('segment', pre_text + '_segment') if self.oss_exist(temp_sequence_file): found_sequence_file = temp_sequence_file break if not self.oss_exist(found_sequence_file): #found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) found_sequence_file = sequence_file.replace('_with_camera_labels', '') if self.oss_exist(found_sequence_file): sequence_file = found_sequence_file return sequence_file # def check_sequence_name_with_all_version(self, sequence_file): # if self.oss_path is not None: # if '_with_camera_labels' not in sequence_file and not self.oss_exist(sequence_file): # sequence_file = sequence_file[:-9] + '_with_camera_labels.tfrecord' # if '_with_camera_labels' in sequence_file and not self.oss_exist(sequence_file): # sequence_file = sequence_file.replace('_with_camera_labels', '') # else: # if '_with_camera_labels' not in str(sequence_file) and not os.path.exists(sequence_file): # sequence_file = Path(str(sequence_file[:-9]) + '_with_camera_labels.tfrecord') # if '_with_camera_labels' in str(sequence_file) and not os.path.exists(sequence_file): # sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) # return sequence_file """ For loading files from OSS """ def list_oss_dir(self, oss_path, with_info=False): s3_dir = self.fix_path(oss_path) files_iter = self.client.get_file_iterator(s3_dir) if with_info: file_list = {p: k for p, k in files_iter} else: file_list = [p for p, k in files_iter] return file_list @staticmethod def fix_path(path_str): try: st_ = str(path_str) if "s3://" in st_: return st_ if "s3:/" in st_: st_ = "s3://" + st_.strip('s3:/') return st_ else: st_ = "s3://" + st_ return st_ except: raise TypeError def oss_exist(self, file_path, refresh=False): if self.data_path is None: raise IndexError("No initialized path set!") if refresh: self.oss_data_list = self.list_oss_dir(self.data_path, with_info=False) pure_name = self.fix_path(file_path).strip("s3://") if pure_name in self.oss_data_list: return True else: return False def get_infos(self, raw_data_path, save_path, num_workers=multiprocessing.cpu_count(), has_label=True, sampled_interval=1): from functools import partial from . import waymo_utils print('---------------The waymo sample interval is %d, total sequecnes is %d-----------------' % (sampled_interval, len(self.sample_sequence_list))) process_single_sequence = partial( waymo_utils.process_single_sequence, save_path=save_path, sampled_interval=sampled_interval, has_label=has_label ) sample_sequence_file_list = [ self.check_sequence_name_with_all_version(raw_data_path / sequence_file) for sequence_file in self.sample_sequence_list ] with multiprocessing.Pool(num_workers) as p: sequence_infos = list(tqdm(p.imap(process_single_sequence, sample_sequence_file_list), total=len(sample_sequence_file_list))) all_sequences_infos = [item for infos in sequence_infos for item in infos] return all_sequences_infos def get_lidar(self, sequence_name, sample_idx): if self.oss_path is None: #lidar_file = self.data_path / sequence_name / ('%04d.npy' % sample_idx) # lidar_file = os.path.join(self.data_path, sequence_name, ('%04d.npy' % sample_idx)) point_features = np.load(lidar_file) # (N, 7): [x, y, z, intensity, elongation, NLZ_flag] else: lidar_file = os.path.join(self.data_path, sequence_name, ('%04d.npy' % sample_idx)) #npy_bytes = self.client.get(lidar_file) npy_bytes = self.client.get(lidar_file, update_cache=True) point_features = np.load(io.BytesIO(npy_bytes)) points_all, NLZ_flag = point_features[:, 0:5], point_features[:, 5] if not self.dataset_cfg.get('DISABLE_NLZ_FLAG_ON_POINTS', False): points_all = points_all[NLZ_flag == -1] points_all[:, 3] = np.tanh(points_all[:, 3]) return points_all def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] if self.use_shared_memory and index < self.shared_memory_file_limit: sa_key = f'{sequence_name}___{sample_idx}' points = SharedArray.attach(f"shm://{sa_key}").copy() else: points = self.get_lidar(sequence_name, sample_idx) lidar_z = points[:, 2] input_dict = { 'db_flag': "waymo", 'points': points, 'frame_id': info['frame_id'], } if 'annos' in info: annos = info['annos'] annos = common_utils.drop_info_with_name(annos, name='unknown') if self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False): gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(annos['gt_boxes_lidar']) else: gt_boxes_lidar = annos['gt_boxes_lidar'] lidar_z = gt_boxes_lidar[:, 2] if self.training and self.dataset_cfg.get('FILTER_EMPTY_BOXES_FOR_TRAIN', False): mask = (annos['num_points_in_gt'] > 0) # filter empty boxes annos['name'] = annos['name'][mask] gt_boxes_lidar = gt_boxes_lidar[mask] annos['num_points_in_gt'] = annos['num_points_in_gt'][mask] input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': gt_boxes_lidar, 'num_points_in_gt': annos.get('num_points_in_gt', None) }) if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None if self.dataset_cfg.get('FOV_POINTS_ONLY', None): input_dict['points'] = self.extract_fov_data( input_dict['points'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) if input_dict['gt_boxes'] is not None: fov_gt_flag = self.extract_fov_gt( input_dict['gt_boxes'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) input_dict.update({ 'gt_names': input_dict['gt_names'][fov_gt_flag], 'gt_boxes': input_dict['gt_boxes'][fov_gt_flag], 'num_points_in_gt': input_dict['num_points_in_gt'][fov_gt_flag] if input_dict['num_points_in_gt'] is not None else None }) # load saved pseudo label for unlabeled data if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) data_dict['metadata'] = info.get('metadata', info['frame_id']) data_dict.pop('num_points_in_gt', None) return data_dict @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def evaluation(self, det_annos, class_names, **kwargs): if 'annos' not in self.infos[0].keys(): return 'No ground-truth boxes for evaluation', {} def kitti_eval(eval_det_annos, eval_gt_annos): from ..kitti.kitti_object_eval_python import eval as kitti_eval from ..kitti import kitti_utils map_name_to_kitti = { 'Vehicle': 'Car', 'Pedestrian': 'Pedestrian', 'Cyclist': 'Cyclist', 'Sign': 'Sign', 'Car': 'Car' } kitti_utils.transform_annotations_to_kitti_format(eval_det_annos, map_name_to_kitti=map_name_to_kitti) kitti_utils.transform_annotations_to_kitti_format( eval_gt_annos, map_name_to_kitti=map_name_to_kitti, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def waymo_eval(eval_det_annos, eval_gt_annos): from .waymo_eval import OpenPCDetWaymoDetectionMetricsEstimator eval = OpenPCDetWaymoDetectionMetricsEstimator() ap_dict = eval.waymo_evaluation( eval_det_annos, eval_gt_annos, class_name=class_names, distance_thresh=1000, fake_gt_infos=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) ap_result_str = '\n' for key in ap_dict: ap_dict[key] = ap_dict[key][0] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) return ap_result_str, ap_dict eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.infos] if kwargs['eval_metric'] == 'kitti': ap_result_str, ap_dict = kitti_eval(eval_det_annos, eval_gt_annos) elif kwargs['eval_metric'] == 'waymo': ap_result_str, ap_dict = waymo_eval(eval_det_annos, eval_gt_annos) else: raise NotImplementedError return ap_result_str, ap_dict def create_groundtruth_database(self, info_path, save_path, used_classes=None, split='train', sampled_interval=10, processed_data_tag=None): database_save_path = save_path / ('%s_gt_database_%s_sampled_%d' % (processed_data_tag, split, sampled_interval)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d.pkl' % (processed_data_tag, split, sampled_interval)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_global.npy' % (processed_data_tag, split, sampled_interval)) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) point_offset_cnt = 0 stacked_gt_points = [] for k in range(0, len(infos), sampled_interval): print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] points = self.get_lidar(sequence_name, sample_idx) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] gt_boxes = annos['gt_boxes_lidar'] if k % 4 != 0 and len(names) > 0: mask = (names == 'Vehicle') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] if k % 2 != 0 and len(names) > 0: mask = (names == 'Pedestrian') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] num_obj = gt_boxes.shape[0] if num_obj == 0: continue box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(num_obj): filename = '%s_%04d_%s_%d.bin' % (sequence_name, sample_idx, names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] if (used_classes is None) or names[i] in used_classes: with open(filepath, 'w') as f: gt_points.tofile(f) db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'sequence_name': sequence_name, 'sample_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0], 'difficulty': difficulty[i]} # it will be used if you choose to use shared memory for gt sampling stacked_gt_points.append(gt_points) db_info['global_data_offset'] = [point_offset_cnt, point_offset_cnt + gt_points.shape[0]] point_offset_cnt += gt_points.shape[0] if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) # it will be used if you choose to use shared memory for gt sampling stacked_gt_points = np.concatenate(stacked_gt_points, axis=0) np.save(db_data_save_path, stacked_gt_points) def create_waymo_infos(dataset_cfg, class_names, data_path, save_path, raw_data_tag='raw_data', processed_data_tag='waymo_processed_data', workers=min(16, multiprocessing.cpu_count())): dataset = WaymoDataset( dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False, logger=common_utils.create_logger() ) train_split, val_split = 'train', 'val' train_filename = save_path / ('%s_infos_%s.pkl' % (processed_data_tag, train_split)) val_filename = save_path / ('%s_infos_%s.pkl' % (processed_data_tag, val_split)) os.environ["CUDA_VISIBLE_DEVICES"] = "-1" print('---------------Start to generate data infos---------------') dataset.set_split(train_split) waymo_infos_train = dataset.get_infos( raw_data_path=data_path / raw_data_tag, save_path=save_path / processed_data_tag, num_workers=workers, has_label=True, sampled_interval=1 ) with open(train_filename, 'wb') as f: pickle.dump(waymo_infos_train, f) print('----------------Waymo info train file is saved to %s----------------' % train_filename) dataset.set_split(val_split) waymo_infos_val = dataset.get_infos( raw_data_path=data_path / raw_data_tag, save_path=save_path / processed_data_tag, num_workers=workers, has_label=True, sampled_interval=1 ) with open(val_filename, 'wb') as f: pickle.dump(waymo_infos_val, f) print('----------------Waymo info val file is saved to %s----------------' % val_filename) print('---------------Start create groundtruth database for data augmentation---------------') os.environ["CUDA_VISIBLE_DEVICES"] = "0" dataset.set_split(train_split) dataset.create_groundtruth_database( info_path=train_filename, save_path=save_path, split='train', sampled_interval=1, used_classes=['Vehicle', 'Pedestrian', 'Cyclist'], processed_data_tag=processed_data_tag ) print('---------------Data preparation Done---------------') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_waymo_infos', help='') parser.add_argument('--processed_data_tag', type=str, default='waymo_processed_data_v0_5_0', help='') args = parser.parse_args() if args.func == 'create_waymo_infos': import yaml from easydict import EasyDict try: yaml_config = yaml.safe_load(open(args.cfg_file), Loader=yaml.FullLoader) except: yaml_config = yaml.safe_load(open(args.cfg_file)) dataset_cfg = EasyDict(yaml_config) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.PROCESSED_DATA_TAG = args.processed_data_tag create_waymo_infos( dataset_cfg=dataset_cfg, class_names=['Vehicle', 'Pedestrian', 'Cyclist'], data_path=ROOT_DIR / 'data' / 'waymo', save_path=ROOT_DIR / 'data' / 'waymo', raw_data_tag='raw_data', processed_data_tag=args.processed_data_tag )
28,867
44.247649
139
py
3DTrans
3DTrans-master/pcdet/datasets/once/once_dataset.py
import copy import pickle import os import numpy as np from PIL import Image import torch import torch.nn.functional as F from pathlib import Path from ..dataset import DatasetTemplate from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils from .once_toolkits import Octopus # Since we use petrel OSS import io class ONCEDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/ONCE' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.split = dataset_cfg.DATA_SPLIT['train'] if training else dataset_cfg.DATA_SPLIT['test'] assert self.split in ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None self.cam_names = ['cam01', 'cam03', 'cam05', 'cam06', 'cam07', 'cam08', 'cam09'] self.cam_tags = ['top', 'top2', 'left_back', 'left_front', 'right_front', 'right_back', 'back'] if self.oss_path is None: self.toolkits = Octopus(self.root_path) else: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') self.toolkits = Octopus(self.root_path, self.oss_path, self.client) self.once_infos = [] self.include_once_data(self.split) def include_once_data(self, split): if self.logger is not None: self.logger.info('Loading ONCE dataset') once_infos = [] for info_path in self.dataset_cfg.INFO_PATH[split]: if self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) once_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) once_infos.extend(infos) def check_annos(info): return 'annos' in info if self.split.split('_')[0] != 'raw': once_infos = list(filter(check_annos,once_infos)) self.once_infos.extend(once_infos) if self.logger is not None: self.logger.info('Total samples for ONCE dataset: %d' % (len(once_infos))) def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None def get_lidar(self, sequence_id, frame_id): return self.toolkits.load_point_cloud(sequence_id, frame_id) def get_image(self, sequence_id, frame_id, cam_name): return self.toolkits.load_image(sequence_id, frame_id, cam_name) def project_lidar_to_image(self, sequence_id, frame_id): return self.toolkits.project_lidar_to_image(sequence_id, frame_id) def point_painting(self, points, info): semseg_dir = './' # add your own seg directory used_classes = [0,1,2,3,4,5] num_classes = len(used_classes) frame_id = str(info['frame_id']) seq_id = str(info['sequence_id']) painted = np.zeros((points.shape[0], num_classes)) # classes + bg for cam_name in self.cam_names: img_path = Path(semseg_dir) / Path(seq_id) / Path(cam_name) / Path(frame_id+'_label.png') calib_info = info['calib'][cam_name] cam_2_velo = calib_info['cam_to_velo'] cam_intri = np.hstack([calib_info['cam_intrinsic'], np.zeros((3, 1), dtype=np.float32)]) point_xyz = points[:, :3] points_homo = np.hstack( [point_xyz, np.ones(point_xyz.shape[0], dtype=np.float32).reshape((-1, 1))]) points_lidar = np.dot(points_homo, np.linalg.inv(cam_2_velo).T) mask = points_lidar[:, 2] > 0 points_lidar = points_lidar[mask] points_img = np.dot(points_lidar, cam_intri.T) points_img = points_img / points_img[:, [2]] uv = points_img[:, [0,1]] #depth = points_img[:, [2]] seg_map = np.array(Image.open(img_path)) # (H, W) H, W = seg_map.shape seg_feats = np.zeros((H*W, num_classes)) seg_map = seg_map.reshape(-1) for cls_i in used_classes: seg_feats[seg_map==cls_i, cls_i] = 1 seg_feats = seg_feats.reshape(H, W, num_classes).transpose(2, 0, 1) uv[:, 0] = (uv[:, 0] - W / 2) / (W / 2) uv[:, 1] = (uv[:, 1] - H / 2) / (H / 2) uv_tensor = torch.from_numpy(uv).unsqueeze(0).unsqueeze(0) # [1,1,N,2] seg_feats = torch.from_numpy(seg_feats).unsqueeze(0) # [1,C,H,W] proj_scores = F.grid_sample(seg_feats, uv_tensor, mode='bilinear', padding_mode='zeros') # [1, C, 1, N] proj_scores = proj_scores.squeeze(0).squeeze(1).transpose(0, 1).contiguous() # [N, C] painted[mask] = proj_scores.numpy() return np.concatenate([points, painted], axis=1) def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.once_infos) * self.total_epochs return len(self.once_infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.once_infos) info = copy.deepcopy(self.once_infos[index]) frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) if self.dataset_cfg.get('POINT_PAINTING', False): points = self.point_painting(points, info) input_dict = { 'db_flag': "once", 'points': points, 'frame_id': frame_id, } if 'annos' in info: annos = info['annos'] input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': annos['boxes_3d'], 'num_points_in_gt': annos.get('num_points_in_gt', None) }) data_dict = self.prepare_data(data_dict=input_dict) data_dict.pop('num_points_in_gt', None) return data_dict def get_infos(self, num_workers=4, sample_seq_list=None): import concurrent.futures as futures import json root_path = self.root_path cam_names = self.cam_names """ # dataset json format { 'meta_info': 'calib': { 'cam01': { 'cam_to_velo': list 'cam_intrinsic': list 'distortion': list } ... } 'frames': [ { 'frame_id': timestamp, 'annos': { 'names': list 'boxes_3d': list of list 'boxes_2d': { 'cam01': list of list ... } } 'pose': list }, ... ] } # open pcdet format { 'meta_info': 'sequence_id': seq_idx 'frame_id': timestamp 'timestamp': timestamp 'lidar': path 'cam01': path ... 'calib': { 'cam01': { 'cam_to_velo': np.array 'cam_intrinsic': np.array 'distortion': np.array } ... } 'pose': np.array 'annos': { 'name': np.array 'boxes_3d': np.array 'boxes_2d': { 'cam01': np.array .... } } } """ def process_single_sequence(seq_idx): print('%s seq_idx: %s' % (self.split, seq_idx)) seq_infos = [] seq_path = Path(root_path) / 'data' / seq_idx json_path = seq_path / ('%s.json' % seq_idx) with open(json_path, 'r') as f: info_this_seq = json.load(f) meta_info = info_this_seq['meta_info'] calib = info_this_seq['calib'] for f_idx, frame in enumerate(info_this_seq['frames']): frame_id = frame['frame_id'] if f_idx == 0: prev_id = None else: prev_id = info_this_seq['frames'][f_idx-1]['frame_id'] if f_idx == len(info_this_seq['frames'])-1: next_id = None else: next_id = info_this_seq['frames'][f_idx+1]['frame_id'] pc_path = str(seq_path / 'lidar_roof' / ('%s.bin' % frame_id)) pose = np.array(frame['pose']) frame_dict = { 'sequence_id': seq_idx, 'frame_id': frame_id, 'timestamp': int(frame_id), 'prev_id': prev_id, 'next_id': next_id, 'meta_info': meta_info, 'lidar': pc_path, 'pose': pose } calib_dict = {} for cam_name in cam_names: cam_path = str(seq_path / cam_name / ('%s.jpg' % frame_id)) frame_dict.update({cam_name: cam_path}) calib_dict[cam_name] = {} calib_dict[cam_name]['cam_to_velo'] = np.array(calib[cam_name]['cam_to_velo']) calib_dict[cam_name]['cam_intrinsic'] = np.array(calib[cam_name]['cam_intrinsic']) calib_dict[cam_name]['distortion'] = np.array(calib[cam_name]['distortion']) frame_dict.update({'calib': calib_dict}) if 'annos' in frame: annos = frame['annos'] boxes_3d = np.array(annos['boxes_3d']) if boxes_3d.shape[0] == 0: print(frame_id) continue boxes_2d_dict = {} for cam_name in cam_names: boxes_2d_dict[cam_name] = np.array(annos['boxes_2d'][cam_name]) annos_dict = { 'name': np.array(annos['names']), 'boxes_3d': boxes_3d, 'boxes_2d': boxes_2d_dict } points = self.get_lidar(seq_idx, frame_id) corners_lidar = box_utils.boxes_to_corners_3d(np.array(annos['boxes_3d'])) num_gt = boxes_3d.shape[0] num_points_in_gt = -np.ones(num_gt, dtype=np.int32) for k in range(num_gt): flag = box_utils.in_hull(points[:, 0:3], corners_lidar[k]) num_points_in_gt[k] = flag.sum() annos_dict['num_points_in_gt'] = num_points_in_gt frame_dict.update({'annos': annos_dict}) seq_infos.append(frame_dict) return seq_infos sample_seq_list = sample_seq_list if sample_seq_list is not None else self.sample_seq_list with futures.ThreadPoolExecutor(num_workers) as executor: infos = executor.map(process_single_sequence, sample_seq_list) all_infos = [] for info in infos: all_infos.extend(info) return all_infos def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): import torch database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split)) db_info_save_path = Path(self.root_path) / ('once_dbinfos_%s.pkl' % split) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): if 'annos' not in infos[k]: continue print('gt_database sample: %d' % (k + 1)) info = infos[k] frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) annos = info['annos'] names = annos['name'] gt_boxes = annos['boxes_3d'] num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): # TODO: use the pseudo-labeling, threshold > 0.9, to generate the BINs filename = '%s_%s_%d.bin' % (frame_id, names[i], i) filepath = database_save_path / filename gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_3d': np.zeros((num_samples, 7)) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_3d'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): frame_id = batch_dict['frame_id'][index] single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = frame_id annos.append(single_pred_dict) if output_path is not None: raise NotImplementedError return annos def evaluation(self, det_annos, class_names, **kwargs): from .once_eval.evaluation import get_evaluation_results eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.once_infos] ap_result_str, ap_dict = get_evaluation_results(eval_gt_annos, eval_det_annos, class_names) return ap_result_str, ap_dict def create_once_infos(dataset_cfg, class_names, data_path, save_path, workers=4): dataset = ONCEDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) splits = ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] #ignore raw_small/raw_medium/raw_large ignore = ['test', 'raw_small', 'raw_medium', 'raw_large'] print('---------------Start to generate data infos---------------') for split in splits: if split in ignore: continue filename = 'once_infos_%s.pkl' % split filename = save_path / Path(filename) dataset.set_split(split) once_infos = dataset.get_infos(num_workers=workers) with open(filename, 'wb') as f: pickle.dump(once_infos, f) print('ONCE info %s file is saved to %s' % (split, filename)) train_filename = save_path / 'once_infos_train.pkl' print('---------------Start create groundtruth database for data augmentation---------------') dataset.set_split('train') dataset.create_groundtruth_database(train_filename, split='train') print('---------------Data preparation Done---------------') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_waymo_infos', help='') parser.add_argument('--runs_on', type=str, default='server', help='') args = parser.parse_args() if args.func == 'create_once_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.load(open(args.cfg_file))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() once_data_path = ROOT_DIR / 'data' / 'once' once_save_path = ROOT_DIR / 'data' / 'once' if args.runs_on == 'cloud': once_data_path = Path('/cache/once/') once_save_path = Path('/cache/once/') dataset_cfg.DATA_PATH = dataset_cfg.CLOUD_DATA_PATH create_once_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Bus', 'Truck', 'Pedestrian', 'Bicycle'], data_path=once_data_path, save_path=once_save_path )
18,925
39.353945
140
py
3DTrans
3DTrans-master/pcdet/datasets/once/once_target_dataset.py
import copy import pickle import numpy as np from ..dataset import DatasetTemplate from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils from .once_toolkits import Octopus class ONCEDataset(DatasetTemplate): def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.split = 'train' if training else 'val' assert self.split in ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None self.cam_names = ['cam01', 'cam03', 'cam05', 'cam06', 'cam07', 'cam08', 'cam09'] self.cam_tags = ['top', 'top2', 'left_back', 'left_front', 'right_front', 'right_back', 'back'] self.toolkits = Octopus(self.root_path) self.once_infos = [] self.include_once_data(self.split) def include_once_data(self, split): if self.logger is not None: self.logger.info('Loading ONCE dataset') once_infos = [] for info_path in self.dataset_cfg.INFO_PATH[split]: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) once_infos.extend(infos) def check_annos(info): return 'annos' in info if self.split != 'raw': once_infos = list(filter(check_annos,once_infos)) self.once_infos.extend(once_infos) if self.logger is not None: self.logger.info('Total samples for ONCE dataset: %d' % (len(once_infos))) def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None def get_lidar(self, sequence_id, frame_id): return self.toolkits.load_point_cloud(sequence_id, frame_id) def get_image(self, sequence_id, frame_id, cam_name): return self.toolkits.load_image(sequence_id, frame_id, cam_name) def project_lidar_to_image(self, sequence_id, frame_id, cam_name): return self.toolkits.project_lidar_to_image(sequence_id, frame_id, cam_name) def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.once_infos) * self.total_epochs return len(self.once_infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.once_infos) info = copy.deepcopy(self.once_infos[index]) frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict = { 'points': points, 'frame_id': frame_id, } if 'annos' in info: annos = info['annos'] gt_boxes_lidar = annos['boxes_3d'] if self.dataset_cfg.get('SHIFT_COOR', None): gt_boxes_lidar[:, 0:3] += self.dataset_cfg.SHIFT_COOR input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': gt_boxes_lidar, 'num_points_in_gt': annos.get('num_points_in_gt', None) }) if self.dataset_cfg.get('REMOVE_ORIGIN_GTS', None) and self.training: input_dict['points'] = box_utils.remove_points_in_boxes3d(input_dict['points'], input_dict['gt_boxes']) mask = np.zeros(gt_boxes_lidar.shape[0], dtype=np.bool_) input_dict['gt_boxes'] = input_dict['gt_boxes'][mask] input_dict['gt_names'] = input_dict['gt_names'][mask] if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None # load saved pseudo label for unlabel data #print(self.training) if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) data_dict.pop('num_points_in_gt', None) return data_dict def get_infos(self, num_workers=4, sample_seq_list=None): import concurrent.futures as futures import json root_path = self.root_path cam_names = self.cam_names """ # dataset json format { 'meta_info': 'calib': { 'cam01': { 'cam_to_velo': list 'cam_intrinsic': list 'distortion': list } ... } 'frames': [ { 'frame_id': timestamp, 'annos': { 'names': list 'boxes_3d': list of list 'boxes_2d': { 'cam01': list of list ... } } 'pose': list }, ... ] } # open pcdet format { 'meta_info': 'sequence_id': seq_idx 'frame_id': timestamp 'timestamp': timestamp 'lidar': path 'cam01': path ... 'calib': { 'cam01': { 'cam_to_velo': np.array 'cam_intrinsic': np.array 'distortion': np.array } ... } 'pose': np.array 'annos': { 'name': np.array 'boxes_3d': np.array 'boxes_2d': { 'cam01': np.array .... } } } """ def process_single_sequence(seq_idx): print('%s seq_idx: %s' % (self.split, seq_idx)) seq_infos = [] seq_path = Path(root_path) / 'data' / seq_idx json_path = seq_path / ('%s.json' % seq_idx) with open(json_path, 'r') as f: info_this_seq = json.load(f) meta_info = info_this_seq['meta_info'] calib = info_this_seq['calib'] for f_idx, frame in enumerate(info_this_seq['frames']): frame_id = frame['frame_id'] if f_idx == 0: prev_id = None else: prev_id = info_this_seq['frames'][f_idx-1]['frame_id'] if f_idx == len(info_this_seq['frames'])-1: next_id = None else: next_id = info_this_seq['frames'][f_idx+1]['frame_id'] pc_path = str(seq_path / 'lidar_roof' / ('%s.bin' % frame_id)) pose = np.array(frame['pose']) frame_dict = { 'sequence_id': seq_idx, 'frame_id': frame_id, 'timestamp': int(frame_id), 'prev_id': prev_id, 'next_id': next_id, 'meta_info': meta_info, 'lidar': pc_path, 'pose': pose } calib_dict = {} for cam_name in cam_names: cam_path = str(seq_path / cam_name / ('%s.jpg' % frame_id)) frame_dict.update({cam_name: cam_path}) calib_dict[cam_name] = {} calib_dict[cam_name]['cam_to_velo'] = np.array(calib[cam_name]['cam_to_velo']) calib_dict[cam_name]['cam_intrinsic'] = np.array(calib[cam_name]['cam_intrinsic']) calib_dict[cam_name]['distortion'] = np.array(calib[cam_name]['distortion']) frame_dict.update({'calib': calib_dict}) if 'annos' in frame: annos = frame['annos'] boxes_3d = np.array(annos['boxes_3d']) if boxes_3d.shape[0] == 0: print(frame_id) continue boxes_2d_dict = {} for cam_name in cam_names: boxes_2d_dict[cam_name] = np.array(annos['boxes_2d'][cam_name]) annos_dict = { 'name': np.array(annos['names']), 'boxes_3d': boxes_3d, 'boxes_2d': boxes_2d_dict } points = self.get_lidar(seq_idx, frame_id) corners_lidar = box_utils.boxes_to_corners_3d(np.array(annos['boxes_3d'])) num_gt = boxes_3d.shape[0] num_points_in_gt = -np.ones(num_gt, dtype=np.int32) for k in range(num_gt): flag = box_utils.in_hull(points[:, 0:3], corners_lidar[k]) num_points_in_gt[k] = flag.sum() annos_dict['num_points_in_gt'] = num_points_in_gt frame_dict.update({'annos': annos_dict}) seq_infos.append(frame_dict) return seq_infos sample_seq_list = sample_seq_list if sample_seq_list is not None else self.sample_seq_list with futures.ThreadPoolExecutor(num_workers) as executor: infos = executor.map(process_single_sequence, sample_seq_list) all_infos = [] for info in infos: all_infos.extend(info) return all_infos def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): import torch database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split)) db_info_save_path = Path(self.root_path) / ('once_dbinfos_%s.pkl' % split) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): if 'annos' not in infos[k]: continue print('gt_database sample: %d' % (k + 1)) info = infos[k] frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) annos = info['annos'] names = annos['name'] gt_boxes = annos['boxes_3d'] num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): filename = '%s_%s_%d.bin' % (frame_id, names[i], i) filepath = database_save_path / filename gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_3d': np.zeros((num_samples, 7)) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_3d'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): frame_id = batch_dict['frame_id'][index] single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = frame_id annos.append(single_pred_dict) if output_path is not None: raise NotImplementedError return annos def kitti_eval(self, eval_det_annos, eval_gt_annos, class_names): from ..kitti.kitti_object_eval_python import eval as kitti_eval map_name_to_kitti = { 'Car': 'Car', 'Pedestrian': 'Pedestrian', 'Truck': 'Truck', } def transform_to_kitti_format(annos, info_with_fakelidar=False, is_gt=False): for anno in annos: if 'name' not in anno: anno['name'] = anno['gt_names'] anno.pop('gt_names') for k in range(anno['name'].shape[0]): if anno['name'][k] in map_name_to_kitti: anno['name'][k] = map_name_to_kitti[anno['name'][k]] else: anno['name'][k] = 'Person_sitting' """ if 'boxes_lidar' in anno: gt_boxes_lidar = anno['boxes_lidar'].copy() else: gt_boxes_lidar = anno['gt_boxes'].copy() """ gt_boxes_lidar = anno['boxes_3d'].copy() # filter by fov if is_gt and self.dataset_cfg.get('GT_FILTER', None): if self.dataset_cfg.GT_FILTER.get('FOV_FILTER', None): fov_gt_flag = self.extract_fov_gt( gt_boxes_lidar, self.dataset_cfg['FOV_DEGREE'], self.dataset_cfg['FOV_ANGLE'] ) gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag] anno['name'] = anno['name'][fov_gt_flag] anno['bbox'] = np.zeros((len(anno['name']), 4)) anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50] anno['truncated'] = np.zeros(len(anno['name'])) anno['occluded'] = np.zeros(len(anno['name'])) if len(gt_boxes_lidar) > 0: if info_with_fakelidar: gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar) gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2 anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3)) anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar dxdydz = gt_boxes_lidar[:, 3:6] anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0 anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y'] else: anno['location'] = anno['dimensions'] = np.zeros((0, 3)) anno['rotation_y'] = anno['alpha'] = np.zeros(0) transform_to_kitti_format(eval_det_annos) transform_to_kitti_format(eval_gt_annos, info_with_fakelidar=False, is_gt=True) kitti_class_names = [] for x in class_names: if x in map_name_to_kitti: kitti_class_names.append(map_name_to_kitti[x]) else: kitti_class_names.append('Person_sitting') ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def evaluation(self, det_annos, class_names, **kwargs): eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.once_infos] if kwargs['eval_metric'] == 'kitti': return self.kitti_eval(eval_det_annos, eval_gt_annos, class_names) elif kwargs['eval_metric'] == 'once': from .once_eval.evaluation import get_evaluation_results ap_result_str, ap_dict = get_evaluation_results(eval_gt_annos, eval_det_annos, class_names) return ap_result_str, ap_dict else: raise NotImplementedError def create_once_infos(dataset_cfg, class_names, data_path, save_path, workers=4): dataset = ONCEDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) splits = ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] ignore = ['test'] print('---------------Start to generate data infos---------------') for split in splits: if split in ignore: continue filename = 'once_infos_%s.pkl' % split filename = save_path / Path(filename) dataset.set_split(split) once_infos = dataset.get_infos(num_workers=workers) with open(filename, 'wb') as f: pickle.dump(once_infos, f) print('ONCE info %s file is saved to %s' % (split, filename)) train_filename = save_path / 'once_infos_train.pkl' print('---------------Start create groundtruth database for data augmentation---------------') dataset.set_split('train') dataset.create_groundtruth_database(train_filename, split='train') print('---------------Data preparation Done---------------') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_waymo_infos', help='') parser.add_argument('--runs_on', type=str, default='server', help='') args = parser.parse_args() if args.func == 'create_once_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.load(open(args.cfg_file))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() once_data_path = ROOT_DIR / 'data' / 'once' once_save_path = ROOT_DIR / 'data' / 'once' if args.runs_on == 'cloud': once_data_path = Path('/cache/once/') once_save_path = Path('/cache/once/') dataset_cfg.DATA_PATH = dataset_cfg.CLOUD_DATA_PATH create_once_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Bus', 'Truck', 'Pedestrian', 'Bicycle'], data_path=once_data_path, save_path=once_save_path )
20,276
39.554
140
py
3DTrans
3DTrans-master/pcdet/datasets/once/once_dataset_ada.py
import copy import pickle import os import numpy as np from PIL import Image import torch import torch.nn.functional as F from pathlib import Path from ..dataset import DatasetTemplate from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils from .once_toolkits import Octopus # Since we use petrel OSS import io class ActiveONCEDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/ONCE' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None, sample_info_path=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.split = dataset_cfg.DATA_SPLIT['train'] if training else dataset_cfg.DATA_SPLIT['test'] assert self.split in ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None self.cam_names = ['cam01', 'cam03', 'cam05', 'cam06', 'cam07', 'cam08', 'cam09'] self.cam_tags = ['top', 'top2', 'left_back', 'left_front', 'right_front', 'right_back', 'back'] if self.oss_path is None: self.toolkits = Octopus(self.root_path) else: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') self.toolkits = Octopus(self.root_path, self.oss_path, self.client) self.once_infos = [] self.include_once_data(self.split, sample_info_path) def include_once_data(self, split, sample_info_path=None): if self.logger is not None: self.logger.info('Loading ONCE dataset') once_infos = [] for info_path in self.dataset_cfg.INFO_PATH[split]: if sample_info_path is not None and str(sample_info_path).split(':')[0] != 's3': info_path = sample_info_path if not Path(info_path).exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) once_infos.extend(infos) elif sample_info_path is not None and str(sample_info_path).split(':')[0] == 's3': info_path = sample_info_path pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) once_infos.extend(infos) elif self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) once_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) once_infos.extend(infos) def check_annos(info): return 'annos' in info if self.split.split('_')[0] != 'raw': once_infos = list(filter(check_annos,once_infos)) self.once_infos.extend(once_infos) if self.logger is not None: self.logger.info('Total samples for ONCE dataset: %d' % (len(once_infos))) def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_seq_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None def get_lidar(self, sequence_id, frame_id): return self.toolkits.load_point_cloud(sequence_id, frame_id) def get_image(self, sequence_id, frame_id, cam_name): return self.toolkits.load_image(sequence_id, frame_id, cam_name) def project_lidar_to_image(self, sequence_id, frame_id): return self.toolkits.project_lidar_to_image(sequence_id, frame_id) def point_painting(self, points, info): semseg_dir = './' # add your own seg directory used_classes = [0,1,2,3,4,5] num_classes = len(used_classes) frame_id = str(info['frame_id']) seq_id = str(info['sequence_id']) painted = np.zeros((points.shape[0], num_classes)) # classes + bg for cam_name in self.cam_names: img_path = Path(semseg_dir) / Path(seq_id) / Path(cam_name) / Path(frame_id+'_label.png') calib_info = info['calib'][cam_name] cam_2_velo = calib_info['cam_to_velo'] cam_intri = np.hstack([calib_info['cam_intrinsic'], np.zeros((3, 1), dtype=np.float32)]) point_xyz = points[:, :3] points_homo = np.hstack( [point_xyz, np.ones(point_xyz.shape[0], dtype=np.float32).reshape((-1, 1))]) points_lidar = np.dot(points_homo, np.linalg.inv(cam_2_velo).T) mask = points_lidar[:, 2] > 0 points_lidar = points_lidar[mask] points_img = np.dot(points_lidar, cam_intri.T) points_img = points_img / points_img[:, [2]] uv = points_img[:, [0,1]] #depth = points_img[:, [2]] seg_map = np.array(Image.open(img_path)) # (H, W) H, W = seg_map.shape seg_feats = np.zeros((H*W, num_classes)) seg_map = seg_map.reshape(-1) for cls_i in used_classes: seg_feats[seg_map==cls_i, cls_i] = 1 seg_feats = seg_feats.reshape(H, W, num_classes).transpose(2, 0, 1) uv[:, 0] = (uv[:, 0] - W / 2) / (W / 2) uv[:, 1] = (uv[:, 1] - H / 2) / (H / 2) uv_tensor = torch.from_numpy(uv).unsqueeze(0).unsqueeze(0) # [1,1,N,2] seg_feats = torch.from_numpy(seg_feats).unsqueeze(0) # [1,C,H,W] proj_scores = F.grid_sample(seg_feats, uv_tensor, mode='bilinear', padding_mode='zeros') # [1, C, 1, N] proj_scores = proj_scores.squeeze(0).squeeze(1).transpose(0, 1).contiguous() # [N, C] painted[mask] = proj_scores.numpy() return np.concatenate([points, painted], axis=1) def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.once_infos) * self.total_epochs return len(self.once_infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.once_infos) info = copy.deepcopy(self.once_infos[index]) frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) # add shift coordinate if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) if self.dataset_cfg.get('POINT_PAINTING', False): points = self.point_painting(points, info) input_dict = { 'db_flag': "once", 'points': points, 'frame_id': frame_id, } if 'annos' in info: annos = info['annos'] input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': annos['boxes_3d'], 'num_points_in_gt': annos.get('num_points_in_gt', None) }) # add shift coordinate if self.dataset_cfg.get('SHIFT_COOR', None): input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR data_dict = self.prepare_data(data_dict=input_dict) data_dict.pop('num_points_in_gt', None) return data_dict def get_infos(self, num_workers=4, sample_seq_list=None): import concurrent.futures as futures import json root_path = self.root_path cam_names = self.cam_names """ # dataset json format { 'meta_info': 'calib': { 'cam01': { 'cam_to_velo': list 'cam_intrinsic': list 'distortion': list } ... } 'frames': [ { 'frame_id': timestamp, 'annos': { 'names': list 'boxes_3d': list of list 'boxes_2d': { 'cam01': list of list ... } } 'pose': list }, ... ] } # open pcdet format { 'meta_info': 'sequence_id': seq_idx 'frame_id': timestamp 'timestamp': timestamp 'lidar': path 'cam01': path ... 'calib': { 'cam01': { 'cam_to_velo': np.array 'cam_intrinsic': np.array 'distortion': np.array } ... } 'pose': np.array 'annos': { 'name': np.array 'boxes_3d': np.array 'boxes_2d': { 'cam01': np.array .... } } } """ def process_single_sequence(seq_idx): print('%s seq_idx: %s' % (self.split, seq_idx)) seq_infos = [] seq_path = Path(root_path) / 'data' / seq_idx json_path = seq_path / ('%s.json' % seq_idx) with open(json_path, 'r') as f: info_this_seq = json.load(f) meta_info = info_this_seq['meta_info'] calib = info_this_seq['calib'] for f_idx, frame in enumerate(info_this_seq['frames']): frame_id = frame['frame_id'] if f_idx == 0: prev_id = None else: prev_id = info_this_seq['frames'][f_idx-1]['frame_id'] if f_idx == len(info_this_seq['frames'])-1: next_id = None else: next_id = info_this_seq['frames'][f_idx+1]['frame_id'] pc_path = str(seq_path / 'lidar_roof' / ('%s.bin' % frame_id)) pose = np.array(frame['pose']) frame_dict = { 'sequence_id': seq_idx, 'frame_id': frame_id, 'timestamp': int(frame_id), 'prev_id': prev_id, 'next_id': next_id, 'meta_info': meta_info, 'lidar': pc_path, 'pose': pose } calib_dict = {} for cam_name in cam_names: cam_path = str(seq_path / cam_name / ('%s.jpg' % frame_id)) frame_dict.update({cam_name: cam_path}) calib_dict[cam_name] = {} calib_dict[cam_name]['cam_to_velo'] = np.array(calib[cam_name]['cam_to_velo']) calib_dict[cam_name]['cam_intrinsic'] = np.array(calib[cam_name]['cam_intrinsic']) calib_dict[cam_name]['distortion'] = np.array(calib[cam_name]['distortion']) frame_dict.update({'calib': calib_dict}) if 'annos' in frame: annos = frame['annos'] boxes_3d = np.array(annos['boxes_3d']) if boxes_3d.shape[0] == 0: print(frame_id) continue boxes_2d_dict = {} for cam_name in cam_names: boxes_2d_dict[cam_name] = np.array(annos['boxes_2d'][cam_name]) annos_dict = { 'name': np.array(annos['names']), 'boxes_3d': boxes_3d, 'boxes_2d': boxes_2d_dict } points = self.get_lidar(seq_idx, frame_id) corners_lidar = box_utils.boxes_to_corners_3d(np.array(annos['boxes_3d'])) num_gt = boxes_3d.shape[0] num_points_in_gt = -np.ones(num_gt, dtype=np.int32) for k in range(num_gt): flag = box_utils.in_hull(points[:, 0:3], corners_lidar[k]) num_points_in_gt[k] = flag.sum() annos_dict['num_points_in_gt'] = num_points_in_gt frame_dict.update({'annos': annos_dict}) seq_infos.append(frame_dict) return seq_infos sample_seq_list = sample_seq_list if sample_seq_list is not None else self.sample_seq_list with futures.ThreadPoolExecutor(num_workers) as executor: infos = executor.map(process_single_sequence, sample_seq_list) all_infos = [] for info in infos: all_infos.extend(info) return all_infos def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): import torch database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split)) db_info_save_path = Path(self.root_path) / ('once_dbinfos_%s.pkl' % split) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): if 'annos' not in infos[k]: continue print('gt_database sample: %d' % (k + 1)) info = infos[k] frame_id = info['frame_id'] seq_id = info['sequence_id'] points = self.get_lidar(seq_id, frame_id) annos = info['annos'] names = annos['name'] gt_boxes = annos['boxes_3d'] num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): filename = '%s_%s_%d.bin' % (frame_id, names[i], i) filepath = database_save_path / filename gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) # @staticmethod def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_3d': np.zeros((num_samples, 7)) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict if self.dataset_cfg.get('SHIFT_COOR', None): pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_3d'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): frame_id = batch_dict['frame_id'][index] single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = frame_id annos.append(single_pred_dict) if output_path is not None: raise NotImplementedError return annos def evaluation(self, det_annos, class_names, **kwargs): from .once_eval.evaluation import get_evaluation_results eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.once_infos] ap_result_str, ap_dict = get_evaluation_results(eval_gt_annos, eval_det_annos, class_names) return ap_result_str, ap_dict def create_once_infos(dataset_cfg, class_names, data_path, save_path, workers=4): dataset = ONCEDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) splits = ['train', 'val', 'test', 'raw_small', 'raw_medium', 'raw_large'] #ignore raw_small/raw_medium/raw_large ignore = ['test', 'raw_small', 'raw_medium', 'raw_large'] print('---------------Start to generate data infos---------------') for split in splits: if split in ignore: continue filename = 'once_infos_%s.pkl' % split filename = save_path / Path(filename) dataset.set_split(split) once_infos = dataset.get_infos(num_workers=workers) with open(filename, 'wb') as f: pickle.dump(once_infos, f) print('ONCE info %s file is saved to %s' % (split, filename)) train_filename = save_path / 'once_infos_train.pkl' print('---------------Start create groundtruth database for data augmentation---------------') dataset.set_split('train') dataset.create_groundtruth_database(train_filename, split='train') print('---------------Data preparation Done---------------') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_waymo_infos', help='') parser.add_argument('--runs_on', type=str, default='server', help='') args = parser.parse_args() if args.func == 'create_once_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.load(open(args.cfg_file))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() once_data_path = ROOT_DIR / 'data' / 'once' once_save_path = ROOT_DIR / 'data' / 'once' if args.runs_on == 'cloud': once_data_path = Path('/cache/once/') once_save_path = Path('/cache/once/') dataset_cfg.DATA_PATH = dataset_cfg.CLOUD_DATA_PATH create_once_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Bus', 'Truck', 'Pedestrian', 'Bicycle'], data_path=once_data_path, save_path=once_save_path )
20,079
39.89613
140
py
3DTrans
3DTrans-master/pcdet/datasets/lyft/lyft_dataset_ada.py
import copy import pickle from pathlib import Path import os import io import numpy as np from tqdm import tqdm from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import common_utils, box_utils from ..dataset import DatasetTemplate class ActiveLyftDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/Lyft' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None, sample_info_path=None): self.root_path = (root_path if root_path is not None else Path(dataset_cfg.DATA_PATH)) / dataset_cfg.VERSION super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=self.root_path, logger=logger ) if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') self.infos = [] self.include_lyft_data(self.mode, sample_info_path) def include_lyft_data(self, mode, sample_info_path=None): self.logger.info('Loading lyft dataset') lyft_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if sample_info_path is not None and str(sample_info_path).split(':')[0] != 's3': info_path = sample_info_path if not Path(info_path).exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) lyft_infos.extend(infos) elif sample_info_path is not None and str(sample_info_path).split(':')[0] == 's3': info_path = sample_info_path pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) lyft_infos.extend(infos) elif self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) lyft_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) lyft_infos.extend(infos) self.infos.extend(lyft_infos) self.logger.info('Total samples for lyft dataset: %d' % (len(lyft_infos))) @staticmethod def remove_ego_points(points, center_radius=1.0): mask = ~((np.abs(points[:, 0]) < center_radius*1.5) & (np.abs(points[:, 1]) < center_radius)) return points[mask] def get_sweep(self, sweep_info): if self.oss_path is None: lidar_path = self.root_path / sweep_info['lidar_path'] points_sweep = np.fromfile(str(lidar_path), dtype=np.float32, count=-1) else: lidar_path = os.path.join(self.oss_path, sweep_info['lidar_path']) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_sweep = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1) if points_sweep.shape[0] % 5 != 0: points_sweep = points_sweep[: points_sweep.shape[0] - (points_sweep.shape[0] % 5)] points_sweep = points_sweep.reshape([-1, 5])[:, :4] points_sweep = self.remove_ego_points(points_sweep).T if sweep_info['transform_matrix'] is not None: num_points = points_sweep.shape[1] points_sweep[:3, :] = sweep_info['transform_matrix'].dot( np.vstack((points_sweep[:3, :], np.ones(num_points))))[:3, :] cur_times = sweep_info['time_lag'] * np.ones((1, points_sweep.shape[1])) return points_sweep.T, cur_times.T def get_lidar_with_sweeps(self, index, max_sweeps=1): info = self.infos[index] if self.oss_path is None: lidar_path = self.root_path / info['lidar_path'] points = np.fromfile(str(lidar_path), dtype=np.float32, count=-1) else: lidar_path = os.path.join(self.oss_path, info['lidar_path']) # print(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).copy() if points.shape[0] % 5 != 0: points = points[: points.shape[0] - (points.shape[0] % 5)] points = points.reshape([-1, 5])[:, :4] sweep_points_list = [points] sweep_times_list = [np.zeros((points.shape[0], 1))] for k in np.random.choice(len(info['sweeps']), max_sweeps - 1, replace=False): points_sweep, times_sweep = self.get_sweep(info['sweeps'][k]) sweep_points_list.append(points_sweep) sweep_times_list.append(times_sweep) points = np.concatenate(sweep_points_list, axis=0) times = np.concatenate(sweep_times_list, axis=0).astype(points.dtype) points = np.concatenate((points, times), axis=1) return points def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) points = self.get_lidar_with_sweeps(index, max_sweeps=self.dataset_cfg.MAX_SWEEPS) if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict = { 'db_flag': "lyft", 'points': points, 'frame_id': Path(info['lidar_path']).stem, 'metadata': {'token': info['token']} } if 'gt_boxes' in info: # if self.dataset_cfg.get('FILTER_MIN_POINTS_IN_GT', False): # mask = (info['num_lidar_pts'] > self.dataset_cfg.FILTER_MIN_POINTS_IN_GT - 1) # else: # mask = None # input_dict.update({ # 'gt_names': info['gt_names'] if mask is None else info['gt_names'][mask], # 'gt_boxes': info['gt_boxes'] if mask is None else info['gt_boxes'][mask] # }) # if self.dataset_cfg.get('SHIFT_COOR', None): # input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR # if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: # input_dict['gt_boxes'] = None # # for debug only # # gt_boxes_mask = np.array([n in self.class_names for n in input_dict['gt_names']], dtype=np.bool_) # # debug_dict = {'gt_boxes': copy.deepcopy(input_dict['gt_boxes'][gt_boxes_mask])} # if self.dataset_cfg.get('FOV_POINTS_ONLY', None): # input_dict['points'] = self.extract_fov_data( # input_dict['points'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE # ) # if input_dict['gt_boxes'] is not None: # fov_gt_flag = self.extract_fov_gt( # input_dict['gt_boxes'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE # ) input_dict.update({ 'gt_boxes': info['gt_boxes'], 'gt_names': info['gt_names'] }) if self.dataset_cfg.get('SHIFT_COOR', None): input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) if self.dataset_cfg.get('SETNAN_VELOCITY_TO_ZEROS', False) and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): gt_boxes = input_dict['gt_boxes'] gt_boxes[np.isnan(gt_boxes)] = 0 input_dict['gt_boxes'] = gt_boxes if not self.dataset_cfg.PRED_VELOCITY and 'gt_boxes' in input_dict and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): input_dict['gt_boxes'] = input_dict['gt_boxes'][:, [0, 1, 2, 3, 4, 5, 6]] data_dict = self.prepare_data(data_dict=input_dict) return data_dict def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]), 'pred_labels': np.zeros(num_samples) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes pred_dict['pred_labels'] = pred_labels return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def kitti_eval(self, eval_det_annos, eval_gt_annos, class_names): from ..kitti.kitti_object_eval_python import eval as kitti_eval from ..kitti import kitti_utils map_name_to_kitti = { 'car': 'Car', 'pedestrian': 'Pedestrian', 'truck': 'Truck', 'bicycle': 'Cyclist', 'motorcycle': 'Cyclist' } def transform_to_kitti_format(annos, info_with_fakelidar=False, is_gt=False): for anno in annos: if 'name' not in anno: anno['name'] = anno['gt_names'] anno.pop('gt_names') for k in range(anno['name'].shape[0]): if anno['name'][k] in map_name_to_kitti: anno['name'][k] = map_name_to_kitti[anno['name'][k]] else: anno['name'][k] = 'Person_sitting' if 'boxes_lidar' in anno: gt_boxes_lidar = anno['boxes_lidar'].copy() else: gt_boxes_lidar = anno['gt_boxes'].copy() # filter by range if self.dataset_cfg.get('GT_FILTER', None) and \ self.dataset_cfg.GT_FILTER.RANGE_FILTER: if self.dataset_cfg.GT_FILTER.get('RANGE', None): point_cloud_range = self.dataset_cfg.GT_FILTER.RANGE else: point_cloud_range = self.point_cloud_range point_cloud_range[2] = -10 point_cloud_range[5] = 10 mask = box_utils.mask_boxes_outside_range_numpy(gt_boxes_lidar, point_cloud_range, min_num_corners=1) gt_boxes_lidar = gt_boxes_lidar[mask] anno['name'] = anno['name'][mask] if not is_gt: anno['score'] = anno['score'][mask] anno['pred_labels'] = anno['pred_labels'][mask] # filter by fov if is_gt and self.dataset_cfg.get('GT_FILTER', None): if self.dataset_cfg.GT_FILTER.get('FOV_FILTER', None): fov_gt_flag = self.extract_fov_gt( gt_boxes_lidar, self.dataset_cfg['FOV_DEGREE'], self.dataset_cfg['FOV_ANGLE'] ) gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag] anno['name'] = anno['name'][fov_gt_flag] anno['bbox'] = np.zeros((len(anno['name']), 4)) anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50] anno['truncated'] = np.zeros(len(anno['name'])) anno['occluded'] = np.zeros(len(anno['name'])) if len(gt_boxes_lidar) > 0: if info_with_fakelidar: gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar) gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2 anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3)) anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar dxdydz = gt_boxes_lidar[:, 3:6] anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0 anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y'] else: anno['location'] = anno['dimensions'] = np.zeros((0, 3)) anno['rotation_y'] = anno['alpha'] = np.zeros(0) transform_to_kitti_format(eval_det_annos) transform_to_kitti_format( eval_gt_annos, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False), is_gt=True ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def evaluation(self, det_annos, class_names, **kwargs): if kwargs['eval_metric'] == 'kitti': eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = copy.deepcopy(self.infos) return self.kitti_eval(eval_det_annos, eval_gt_annos, class_names) elif kwargs['eval_metric'] == 'lyft': return self.lyft_eval(det_annos, class_names, iou_thresholds=self.dataset_cfg.EVAL_LYFT_IOU_LIST) else: raise NotImplementedError def lyft_eval(self, det_annos, class_names, iou_thresholds=[0.5]): from lyft_dataset_sdk.lyftdataset import LyftDataset as Lyft from . import lyft_utils # from lyft_dataset_sdk.eval.detection.mAP_evaluation import get_average_precisions from .lyft_mAP_eval.lyft_eval import get_average_precisions lyft = Lyft(json_path=self.root_path / 'data', data_path=self.root_path, verbose=True) det_lyft_boxes, sample_tokens = lyft_utils.convert_det_to_lyft_format(lyft, det_annos) gt_lyft_boxes = lyft_utils.load_lyft_gt_by_tokens(lyft, sample_tokens) average_precisions = get_average_precisions(gt_lyft_boxes, det_lyft_boxes, class_names, iou_thresholds) ap_result_str, ap_dict = lyft_utils.format_lyft_results(average_precisions, class_names, iou_thresholds, version=self.dataset_cfg.VERSION) return ap_result_str, ap_dict def create_groundtruth_database(self, used_classes=None, max_sweeps=10): import torch database_save_path = self.root_path / f'gt_database' db_info_save_path = self.root_path / f'lyft_dbinfos_{max_sweeps}sweeps.pkl' database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} for idx in tqdm(range(len(self.infos))): sample_idx = idx info = self.infos[idx] points = self.get_lidar_with_sweeps(idx, max_sweeps=max_sweeps) gt_boxes = info['gt_boxes'] gt_names = info['gt_names'] box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(gt_boxes.shape[0]): filename = '%s_%s_%d.bin' % (sample_idx, gt_names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or gt_names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': gt_names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if gt_names[i] in all_db_infos: all_db_infos[gt_names[i]].append(db_info) else: all_db_infos[gt_names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def create_lyft_info(version, data_path, save_path, split, max_sweeps=10): from lyft_dataset_sdk.lyftdataset import LyftDataset from . import lyft_utils data_path = data_path / version save_path = save_path / version split_path = data_path.parent / 'ImageSets' if split is not None: save_path = save_path / split split_path = split_path / split save_path.mkdir(exist_ok=True) assert version in ['trainval', 'one_scene', 'test'] if version == 'trainval': train_split_path = split_path / 'train.txt' val_split_path = split_path / 'val.txt' elif version == 'test': train_split_path = split_path / 'test.txt' val_split_path = None elif version == 'one_scene': train_split_path = split_path / 'one_scene.txt' val_split_path = split_path / 'one_scene.txt' else: raise NotImplementedError train_scenes = [x.strip() for x in open(train_split_path).readlines()] if train_split_path.exists() else [] val_scenes = [x.strip() for x in open(val_split_path).readlines()] if val_split_path is not None and val_split_path.exists() else [] lyft = LyftDataset(json_path=data_path / 'data', data_path=data_path, verbose=True) available_scenes = lyft_utils.get_available_scenes(lyft) available_scene_names = [s['name'] for s in available_scenes] train_scenes = list(filter(lambda x: x in available_scene_names, train_scenes)) val_scenes = list(filter(lambda x: x in available_scene_names, val_scenes)) train_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in train_scenes]) val_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in val_scenes]) print('%s: train scene(%d), val scene(%d)' % (version, len(train_scenes), len(val_scenes))) train_lyft_infos, val_lyft_infos = lyft_utils.fill_trainval_infos( data_path=data_path, lyft=lyft, train_scenes=train_scenes, val_scenes=val_scenes, test='test' in version, max_sweeps=max_sweeps ) if version == 'test': print('test sample: %d' % len(train_lyft_infos)) with open(save_path / f'lyft_infos_test.pkl', 'wb') as f: pickle.dump(train_lyft_infos, f) else: print('train sample: %d, val sample: %d' % (len(train_lyft_infos), len(val_lyft_infos))) with open(save_path / f'lyft_infos_train.pkl', 'wb') as f: pickle.dump(train_lyft_infos, f) with open(save_path / f'lyft_infos_val.pkl', 'wb') as f: pickle.dump(val_lyft_infos, f) if __name__ == '__main__': import yaml import argparse from pathlib import Path from easydict import EasyDict parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_lyft_infos', help='') parser.add_argument('--version', type=str, default='trainval', help='') parser.add_argument('--split', type=str, default=None, help='') parser.add_argument('--max_sweeps', type=int, default=10, help='') args = parser.parse_args() if args.func == 'create_lyft_infos': try: yaml_config = yaml.safe_load(open(args.cfg_file), Loader=yaml.FullLoader) except: yaml_config = yaml.safe_load(open(args.cfg_file)) dataset_cfg = EasyDict(yaml_config) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.VERSION = args.version dataset_cfg.MAX_SWEEPS = args.max_sweeps create_lyft_info( version=dataset_cfg.VERSION, data_path=ROOT_DIR / 'data' / 'lyft', save_path=ROOT_DIR / 'data' / 'lyft', split=args.split, max_sweeps=dataset_cfg.MAX_SWEEPS ) lyft_dataset = ActiveLyftDataset( dataset_cfg=dataset_cfg, class_names=None, root_path=ROOT_DIR / 'data' / 'lyft', logger=common_utils.create_logger(), training=True ) if args.version != 'test': lyft_dataset.create_groundtruth_database(max_sweeps=dataset_cfg.MAX_SWEEPS)
22,729
44.009901
146
py
3DTrans
3DTrans-master/pcdet/datasets/lyft/lyft_dataset.py
import copy import pickle from pathlib import Path import os import io import numpy as np from tqdm import tqdm from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import common_utils, box_utils from ..dataset import DatasetTemplate class LyftDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/Lyft' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): self.root_path = (root_path if root_path is not None else Path(dataset_cfg.DATA_PATH)) / dataset_cfg.VERSION super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=self.root_path, logger=logger ) if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') self.infos = [] self.include_lyft_data(self.mode) def include_lyft_data(self, mode): self.logger.info('Loading lyft dataset') lyft_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) lyft_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) lyft_infos.extend(infos) self.infos.extend(lyft_infos) self.logger.info('Total samples for lyft dataset: %d' % (len(lyft_infos))) @staticmethod def remove_ego_points(points, center_radius=1.0): mask = ~((np.abs(points[:, 0]) < center_radius*1.5) & (np.abs(points[:, 1]) < center_radius)) return points[mask] def get_sweep(self, sweep_info): if self.oss_path is None: lidar_path = self.root_path / sweep_info['lidar_path'] points_sweep = np.fromfile(str(lidar_path), dtype=np.float32, count=-1) else: lidar_path = os.path.join(self.oss_path, sweep_info['lidar_path']) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_sweep = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1) if points_sweep.shape[0] % 5 != 0: points_sweep = points_sweep[: points_sweep.shape[0] - (points_sweep.shape[0] % 5)] points_sweep = points_sweep.reshape([-1, 5])[:, :4] points_sweep = self.remove_ego_points(points_sweep).T if sweep_info['transform_matrix'] is not None: num_points = points_sweep.shape[1] points_sweep[:3, :] = sweep_info['transform_matrix'].dot( np.vstack((points_sweep[:3, :], np.ones(num_points))))[:3, :] cur_times = sweep_info['time_lag'] * np.ones((1, points_sweep.shape[1])) return points_sweep.T, cur_times.T def get_lidar_with_sweeps(self, index, max_sweeps=1): info = self.infos[index] if self.oss_path is None: lidar_path = self.root_path / info['lidar_path'] points = np.fromfile(str(lidar_path), dtype=np.float32, count=-1) else: lidar_path = os.path.join(self.oss_path, info['lidar_path']) # print(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).copy() if points.shape[0] % 5 != 0: points = points[: points.shape[0] - (points.shape[0] % 5)] points = points.reshape([-1, 5])[:, :4] sweep_points_list = [points] sweep_times_list = [np.zeros((points.shape[0], 1))] for k in np.random.choice(len(info['sweeps']), max_sweeps - 1, replace=False): points_sweep, times_sweep = self.get_sweep(info['sweeps'][k]) sweep_points_list.append(points_sweep) sweep_times_list.append(times_sweep) points = np.concatenate(sweep_points_list, axis=0) times = np.concatenate(sweep_times_list, axis=0).astype(points.dtype) points = np.concatenate((points, times), axis=1) return points def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) points = self.get_lidar_with_sweeps(index, max_sweeps=self.dataset_cfg.MAX_SWEEPS) if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict = { 'db_flag': "lyft", 'points': points, 'frame_id': Path(info['lidar_path']).stem, 'metadata': {'token': info['token']} } if 'gt_boxes' in info: input_dict.update({ 'gt_boxes': info['gt_boxes'], 'gt_names': info['gt_names'] }) if self.dataset_cfg.get('SHIFT_COOR', None): input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) if self.dataset_cfg.get('SETNAN_VELOCITY_TO_ZEROS', False) and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): gt_boxes = input_dict['gt_boxes'] gt_boxes[np.isnan(gt_boxes)] = 0 input_dict['gt_boxes'] = gt_boxes if not self.dataset_cfg.PRED_VELOCITY and 'gt_boxes' in input_dict and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): input_dict['gt_boxes'] = input_dict['gt_boxes'][:, [0, 1, 2, 3, 4, 5, 6]] data_dict = self.prepare_data(data_dict=input_dict) return data_dict def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]), 'pred_labels': np.zeros(num_samples) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes pred_dict['pred_labels'] = pred_labels return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def kitti_eval(self, eval_det_annos, eval_gt_annos, class_names): from ..kitti.kitti_object_eval_python import eval as kitti_eval from ..kitti import kitti_utils map_name_to_kitti = { 'car': 'Car', 'pedestrian': 'Pedestrian', 'truck': 'Truck', 'bicycle': 'Cyclist', 'motorcycle': 'Cyclist' } def transform_to_kitti_format(annos, info_with_fakelidar=False, is_gt=False): for anno in annos: if 'name' not in anno: anno['name'] = anno['gt_names'] anno.pop('gt_names') for k in range(anno['name'].shape[0]): if anno['name'][k] in map_name_to_kitti: anno['name'][k] = map_name_to_kitti[anno['name'][k]] else: anno['name'][k] = 'Person_sitting' if 'boxes_lidar' in anno: gt_boxes_lidar = anno['boxes_lidar'].copy() else: gt_boxes_lidar = anno['gt_boxes'].copy() # filter by range if self.dataset_cfg.get('GT_FILTER', None) and \ self.dataset_cfg.GT_FILTER.RANGE_FILTER: if self.dataset_cfg.GT_FILTER.get('RANGE', None): point_cloud_range = self.dataset_cfg.GT_FILTER.RANGE else: point_cloud_range = self.point_cloud_range point_cloud_range[2] = -10 point_cloud_range[5] = 10 mask = box_utils.mask_boxes_outside_range_numpy(gt_boxes_lidar, point_cloud_range, min_num_corners=1) gt_boxes_lidar = gt_boxes_lidar[mask] anno['name'] = anno['name'][mask] if not is_gt: anno['score'] = anno['score'][mask] anno['pred_labels'] = anno['pred_labels'][mask] # filter by fov if is_gt and self.dataset_cfg.get('GT_FILTER', None): if self.dataset_cfg.GT_FILTER.get('FOV_FILTER', None): fov_gt_flag = self.extract_fov_gt( gt_boxes_lidar, self.dataset_cfg['FOV_DEGREE'], self.dataset_cfg['FOV_ANGLE'] ) gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag] anno['name'] = anno['name'][fov_gt_flag] anno['bbox'] = np.zeros((len(anno['name']), 4)) anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50] anno['truncated'] = np.zeros(len(anno['name'])) anno['occluded'] = np.zeros(len(anno['name'])) if len(gt_boxes_lidar) > 0: if info_with_fakelidar: gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar) gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2 anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3)) anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar dxdydz = gt_boxes_lidar[:, 3:6] anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0 anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y'] else: anno['location'] = anno['dimensions'] = np.zeros((0, 3)) anno['rotation_y'] = anno['alpha'] = np.zeros(0) transform_to_kitti_format(eval_det_annos) transform_to_kitti_format( eval_gt_annos, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False), is_gt=True ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def evaluation(self, det_annos, class_names, **kwargs): if kwargs['eval_metric'] == 'kitti': eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = copy.deepcopy(self.infos) return self.kitti_eval(eval_det_annos, eval_gt_annos, class_names) elif kwargs['eval_metric'] == 'lyft': return self.lyft_eval(det_annos, class_names, iou_thresholds=self.dataset_cfg.EVAL_LYFT_IOU_LIST) else: raise NotImplementedError def lyft_eval(self, det_annos, class_names, iou_thresholds=[0.5]): from lyft_dataset_sdk.lyftdataset import LyftDataset as Lyft from . import lyft_utils # from lyft_dataset_sdk.eval.detection.mAP_evaluation import get_average_precisions from .lyft_mAP_eval.lyft_eval import get_average_precisions lyft = Lyft(json_path=self.root_path / 'data', data_path=self.root_path, verbose=True) det_lyft_boxes, sample_tokens = lyft_utils.convert_det_to_lyft_format(lyft, det_annos) gt_lyft_boxes = lyft_utils.load_lyft_gt_by_tokens(lyft, sample_tokens) average_precisions = get_average_precisions(gt_lyft_boxes, det_lyft_boxes, class_names, iou_thresholds) ap_result_str, ap_dict = lyft_utils.format_lyft_results(average_precisions, class_names, iou_thresholds, version=self.dataset_cfg.VERSION) return ap_result_str, ap_dict def create_groundtruth_database(self, used_classes=None, max_sweeps=10): import torch database_save_path = self.root_path / f'gt_database' db_info_save_path = self.root_path / f'lyft_dbinfos_{max_sweeps}sweeps.pkl' database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} for idx in tqdm(range(len(self.infos))): sample_idx = idx info = self.infos[idx] points = self.get_lidar_with_sweeps(idx, max_sweeps=max_sweeps) gt_boxes = info['gt_boxes'] gt_names = info['gt_names'] box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(gt_boxes.shape[0]): filename = '%s_%s_%d.bin' % (sample_idx, gt_names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or gt_names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': gt_names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if gt_names[i] in all_db_infos: all_db_infos[gt_names[i]].append(db_info) else: all_db_infos[gt_names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def create_lyft_info(version, data_path, save_path, split, max_sweeps=10): from lyft_dataset_sdk.lyftdataset import LyftDataset from . import lyft_utils data_path = data_path / version save_path = save_path / version split_path = data_path.parent / 'ImageSets' if split is not None: save_path = save_path / split split_path = split_path / split save_path.mkdir(exist_ok=True) assert version in ['trainval', 'one_scene', 'test'] if version == 'trainval': train_split_path = split_path / 'train.txt' val_split_path = split_path / 'val.txt' elif version == 'test': train_split_path = split_path / 'test.txt' val_split_path = None elif version == 'one_scene': train_split_path = split_path / 'one_scene.txt' val_split_path = split_path / 'one_scene.txt' else: raise NotImplementedError train_scenes = [x.strip() for x in open(train_split_path).readlines()] if train_split_path.exists() else [] val_scenes = [x.strip() for x in open(val_split_path).readlines()] if val_split_path is not None and val_split_path.exists() else [] lyft = LyftDataset(json_path=data_path / 'data', data_path=data_path, verbose=True) available_scenes = lyft_utils.get_available_scenes(lyft) available_scene_names = [s['name'] for s in available_scenes] train_scenes = list(filter(lambda x: x in available_scene_names, train_scenes)) val_scenes = list(filter(lambda x: x in available_scene_names, val_scenes)) train_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in train_scenes]) val_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in val_scenes]) print('%s: train scene(%d), val scene(%d)' % (version, len(train_scenes), len(val_scenes))) train_lyft_infos, val_lyft_infos = lyft_utils.fill_trainval_infos( data_path=data_path, lyft=lyft, train_scenes=train_scenes, val_scenes=val_scenes, test='test' in version, max_sweeps=max_sweeps ) if version == 'test': print('test sample: %d' % len(train_lyft_infos)) with open(save_path / f'lyft_infos_test.pkl', 'wb') as f: pickle.dump(train_lyft_infos, f) else: print('train sample: %d, val sample: %d' % (len(train_lyft_infos), len(val_lyft_infos))) with open(save_path / f'lyft_infos_train.pkl', 'wb') as f: pickle.dump(train_lyft_infos, f) with open(save_path / f'lyft_infos_val.pkl', 'wb') as f: pickle.dump(val_lyft_infos, f) if __name__ == '__main__': import yaml import argparse from pathlib import Path from easydict import EasyDict parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_lyft_infos', help='') parser.add_argument('--version', type=str, default='trainval', help='') parser.add_argument('--split', type=str, default=None, help='') parser.add_argument('--max_sweeps', type=int, default=10, help='') args = parser.parse_args() if args.func == 'create_lyft_infos': try: yaml_config = yaml.safe_load(open(args.cfg_file), Loader=yaml.FullLoader) except: yaml_config = yaml.safe_load(open(args.cfg_file)) dataset_cfg = EasyDict(yaml_config) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.VERSION = args.version dataset_cfg.MAX_SWEEPS = args.max_sweeps create_lyft_info( version=dataset_cfg.VERSION, data_path=ROOT_DIR / 'data' / 'lyft', save_path=ROOT_DIR / 'data' / 'lyft', split=args.split, max_sweeps=dataset_cfg.MAX_SWEEPS ) lyft_dataset = LyftDataset( dataset_cfg=dataset_cfg, class_names=None, root_path=ROOT_DIR / 'data' / 'lyft', logger=common_utils.create_logger(), training=True ) if args.version != 'test': lyft_dataset.create_groundtruth_database(max_sweeps=dataset_cfg.MAX_SWEEPS)
20,471
43.12069
146
py
3DTrans
3DTrans-master/pcdet/datasets/augmentor/augmentor_utils.py
import torch import numpy as np import numba import math import copy from ...utils import common_utils from ...utils import box_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...ops.iou3d_nms import iou3d_nms_utils import warnings try: from numba.errors import NumbaPerformanceWarning warnings.filterwarnings("ignore", category=NumbaPerformanceWarning) except: pass def random_flip_along_x(gt_boxes, points): """ Args: gt_boxes: (N, 7 + C), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C) Returns: """ enable = np.random.choice([False, True], replace=False, p=[0.5, 0.5]) if enable: gt_boxes[:, 1] = -gt_boxes[:, 1] gt_boxes[:, 6] = -gt_boxes[:, 6] points[:, 1] = -points[:, 1] if gt_boxes.shape[1] > 7: gt_boxes[:, 8] = -gt_boxes[:, 8] return gt_boxes, points def random_flip_along_y(gt_boxes, points): """ Args: gt_boxes: (N, 7 + C), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C) Returns: """ enable = np.random.choice([False, True], replace=False, p=[0.5, 0.5]) if enable: gt_boxes[:, 0] = -gt_boxes[:, 0] gt_boxes[:, 6] = -(gt_boxes[:, 6] + np.pi) points[:, 0] = -points[:, 0] if gt_boxes.shape[1] > 7: gt_boxes[:, 7] = -gt_boxes[:, 7] return gt_boxes, points def global_rotation(gt_boxes, points, rot_range): """ Args: gt_boxes: (N, 7 + C), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), rot_range: [min, max] Returns: """ noise_rotation = np.random.uniform(rot_range[0], rot_range[1]) points = common_utils.rotate_points_along_z(points[np.newaxis, :, :], np.array([noise_rotation]))[0] gt_boxes[:, 0:3] = common_utils.rotate_points_along_z(gt_boxes[np.newaxis, :, 0:3], np.array([noise_rotation]))[0] gt_boxes[:, 6] += noise_rotation if gt_boxes.shape[1] > 7: gt_boxes[:, 7:9] = common_utils.rotate_points_along_z( np.hstack((gt_boxes[:, 7:9], np.zeros((gt_boxes.shape[0], 1))))[np.newaxis, :, :], np.array([noise_rotation]) )[0][:, 0:2] return gt_boxes, points def global_scaling(gt_boxes, points, scale_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading] points: (M, 3 + C), scale_range: [min, max] Returns: """ if scale_range[1] - scale_range[0] < 1e-3: return gt_boxes, points noise_scale = np.random.uniform(scale_range[0], scale_range[1]) points[:, :3] *= noise_scale gt_boxes[:, :6] *= noise_scale return gt_boxes, points def random_image_flip_horizontal(image, depth_map, gt_boxes, calib): """ Performs random horizontal flip augmentation Args: image: (H_image, W_image, 3), Image depth_map: (H_depth, W_depth), Depth map gt_boxes: (N, 7), 3D box labels in LiDAR coordinates [x, y, z, w, l, h, ry] calib: calibration.Calibration, Calibration object Returns: aug_image: (H_image, W_image, 3), Augmented image aug_depth_map: (H_depth, W_depth), Augmented depth map aug_gt_boxes: (N, 7), Augmented 3D box labels in LiDAR coordinates [x, y, z, w, l, h, ry] """ # Randomly augment with 50% chance enable = np.random.choice([False, True], replace=False, p=[0.5, 0.5]) if enable: # Flip images aug_image = np.fliplr(image) aug_depth_map = np.fliplr(depth_map) # Flip 3D gt_boxes by flipping the centroids in image space aug_gt_boxes = copy.copy(gt_boxes) locations = aug_gt_boxes[:, :3] img_pts, img_depth = calib.lidar_to_img(locations) W = image.shape[1] img_pts[:, 0] = W - img_pts[:, 0] pts_rect = calib.img_to_rect(u=img_pts[:, 0], v=img_pts[:, 1], depth_rect=img_depth) pts_lidar = calib.rect_to_lidar(pts_rect) aug_gt_boxes[:, :3] = pts_lidar aug_gt_boxes[:, 6] = -1 * aug_gt_boxes[:, 6] else: aug_image = image aug_depth_map = depth_map aug_gt_boxes = gt_boxes return aug_image, aug_depth_map, aug_gt_boxes def random_translation_along_x(gt_boxes, points, offset_std): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_std: float Returns: """ offset = np.random.normal(0, offset_std, 1) points[:, 0] += offset gt_boxes[:, 0] += offset # if gt_boxes.shape[1] > 7: # gt_boxes[:, 7] += offset return gt_boxes, points def random_translation_along_y(gt_boxes, points, offset_std): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_std: float Returns: """ offset = np.random.normal(0, offset_std, 1) points[:, 1] += offset gt_boxes[:, 1] += offset # if gt_boxes.shape[1] > 8: # gt_boxes[:, 8] += offset return gt_boxes, points def random_translation_along_z(gt_boxes, points, offset_std): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_std: float Returns: """ offset = np.random.normal(0, offset_std, 1) points[:, 2] += offset gt_boxes[:, 2] += offset return gt_boxes, points def random_local_translation_along_x(gt_boxes, points, offset_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_range: [min max]] Returns: """ # augs = {} for idx, box in enumerate(gt_boxes): offset = np.random.uniform(offset_range[0], offset_range[1]) # augs[f'object_{idx}'] = offset points_in_box, mask = get_points_in_box(points, box) points[mask, 0] += offset gt_boxes[idx, 0] += offset # if gt_boxes.shape[1] > 7: # gt_boxes[idx, 7] += offset return gt_boxes, points def random_local_translation_along_y(gt_boxes, points, offset_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_range: [min max]] Returns: """ # augs = {} for idx, box in enumerate(gt_boxes): offset = np.random.uniform(offset_range[0], offset_range[1]) # augs[f'object_{idx}'] = offset points_in_box, mask = get_points_in_box(points, box) points[mask, 1] += offset gt_boxes[idx, 1] += offset # if gt_boxes.shape[1] > 8: # gt_boxes[idx, 8] += offset return gt_boxes, points def random_local_translation_along_z(gt_boxes, points, offset_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_range: [min max]] Returns: """ # augs = {} for idx, box in enumerate(gt_boxes): offset = np.random.uniform(offset_range[0], offset_range[1]) # augs[f'object_{idx}'] = offset points_in_box, mask = get_points_in_box(points, box) points[mask, 2] += offset gt_boxes[idx, 2] += offset return gt_boxes, points def global_frustum_dropout_top(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ intensity = np.random.uniform(intensity_range[0], intensity_range[1]) # threshold = max - length * uniform(0 ~ 0.2) threshold = np.max(points[:, 2]) - intensity * (np.max(points[:, 2]) - np.min(points[:, 2])) points = points[points[:, 2] < threshold] gt_boxes = gt_boxes[gt_boxes[:, 2] < threshold] return gt_boxes, points def global_frustum_dropout_bottom(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ intensity = np.random.uniform(intensity_range[0], intensity_range[1]) threshold = np.min(points[:, 2]) + intensity * (np.max(points[:, 2]) - np.min(points[:, 2])) points = points[points[:, 2] > threshold] gt_boxes = gt_boxes[gt_boxes[:, 2] > threshold] return gt_boxes, points def global_frustum_dropout_left(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ intensity = np.random.uniform(intensity_range[0], intensity_range[1]) threshold = np.max(points[:, 1]) - intensity * (np.max(points[:, 1]) - np.min(points[:, 1])) points = points[points[:, 1] < threshold] gt_boxes = gt_boxes[gt_boxes[:, 1] < threshold] return gt_boxes, points def global_frustum_dropout_right(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ intensity = np.random.uniform(intensity_range[0], intensity_range[1]) threshold = np.min(points[:, 1]) + intensity * (np.max(points[:, 1]) - np.min(points[:, 1])) points = points[points[:, 1] > threshold] gt_boxes = gt_boxes[gt_boxes[:, 1] > threshold] return gt_boxes, points def local_scaling(gt_boxes, points, scale_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading] points: (M, 3 + C), scale_range: [min, max] Returns: """ if scale_range[1] - scale_range[0] < 1e-3: return gt_boxes, points # augs = {} for idx, box in enumerate(gt_boxes): noise_scale = np.random.uniform(scale_range[0], scale_range[1]) # augs[f'object_{idx}'] = noise_scale points_in_box, mask = get_points_in_box(points, box) # tranlation to axis center points[mask, 0] -= box[0] points[mask, 1] -= box[1] points[mask, 2] -= box[2] # apply scaling points[mask, :3] *= noise_scale # tranlation back to original position points[mask, 0] += box[0] points[mask, 1] += box[1] points[mask, 2] += box[2] gt_boxes[idx, 3:6] *= noise_scale return gt_boxes, points def local_rotation(gt_boxes, points, rot_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), rot_range: [min, max] Returns: """ # augs = {} for idx, box in enumerate(gt_boxes): noise_rotation = np.random.uniform(rot_range[0], rot_range[1]) # augs[f'object_{idx}'] = noise_rotation points_in_box, mask = get_points_in_box(points, box) centroid_x = box[0] centroid_y = box[1] centroid_z = box[2] # tranlation to axis center points[mask, 0] -= centroid_x points[mask, 1] -= centroid_y points[mask, 2] -= centroid_z box[0] -= centroid_x box[1] -= centroid_y box[2] -= centroid_z # apply rotation points[mask, :] = common_utils.rotate_points_along_z(points[np.newaxis, mask, :], np.array([noise_rotation]))[0] box[0:3] = common_utils.rotate_points_along_z(box[np.newaxis, np.newaxis, 0:3], np.array([noise_rotation]))[0][0] # tranlation back to original position points[mask, 0] += centroid_x points[mask, 1] += centroid_y points[mask, 2] += centroid_z box[0] += centroid_x box[1] += centroid_y box[2] += centroid_z gt_boxes[idx, 6] += noise_rotation if gt_boxes.shape[1] > 8: gt_boxes[idx, 7:9] = common_utils.rotate_points_along_z( np.hstack((gt_boxes[idx, 7:9], np.zeros((gt_boxes.shape[0], 1))))[np.newaxis, :, :], np.array([noise_rotation]) )[0][:, 0:2] return gt_boxes, points def local_frustum_dropout_top(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ for idx, box in enumerate(gt_boxes): x, y, z, dx, dy, dz = box[0], box[1], box[2], box[3], box[4], box[5] intensity = np.random.uniform(intensity_range[0], intensity_range[1]) points_in_box, mask = get_points_in_box(points, box) threshold = (z + dz / 2) - intensity * dz points = points[np.logical_not(np.logical_and(mask, points[:, 2] >= threshold))] return gt_boxes, points def local_frustum_dropout_bottom(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ for idx, box in enumerate(gt_boxes): x, y, z, dx, dy, dz = box[0], box[1], box[2], box[3], box[4], box[5] intensity = np.random.uniform(intensity_range[0], intensity_range[1]) points_in_box, mask = get_points_in_box(points, box) threshold = (z - dz / 2) + intensity * dz points = points[np.logical_not(np.logical_and(mask, points[:, 2] <= threshold))] return gt_boxes, points def local_frustum_dropout_left(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ for idx, box in enumerate(gt_boxes): x, y, z, dx, dy, dz = box[0], box[1], box[2], box[3], box[4], box[5] intensity = np.random.uniform(intensity_range[0], intensity_range[1]) points_in_box, mask = get_points_in_box(points, box) threshold = (y + dy / 2) - intensity * dy points = points[np.logical_not(np.logical_and(mask, points[:, 1] >= threshold))] return gt_boxes, points def local_frustum_dropout_right(gt_boxes, points, intensity_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]], points: (M, 3 + C), intensity: [min, max] Returns: """ for idx, box in enumerate(gt_boxes): x, y, z, dx, dy, dz = box[0], box[1], box[2], box[3], box[4], box[5] intensity = np.random.uniform(intensity_range[0], intensity_range[1]) points_in_box, mask = get_points_in_box(points, box) threshold = (y - dy / 2) + intensity * dy points = points[np.logical_not(np.logical_and(mask, points[:, 1] <= threshold))] return gt_boxes, points def get_points_in_box(points, gt_box): x, y, z = points[:, 0], points[:, 1], points[:, 2] cx, cy, cz = gt_box[0], gt_box[1], gt_box[2] dx, dy, dz, rz = gt_box[3], gt_box[4], gt_box[5], gt_box[6] shift_x, shift_y, shift_z = x - cx, y - cy, z - cz MARGIN = 1e-1 cosa, sina = math.cos(-rz), math.sin(-rz) local_x = shift_x * cosa + shift_y * (-sina) local_y = shift_x * sina + shift_y * cosa mask = np.logical_and(abs(shift_z) <= dz / 2.0, np.logical_and(abs(local_x) <= dx / 2.0 + MARGIN, abs(local_y) <= dy / 2.0 + MARGIN)) points = points[mask] return points, mask def get_pyramids(boxes): pyramid_orders = np.array([ [0, 1, 5, 4], [4, 5, 6, 7], [7, 6, 2, 3], [3, 2, 1, 0], [1, 2, 6, 5], [0, 4, 7, 3] ]) boxes_corners = box_utils.boxes_to_corners_3d(boxes).reshape(-1, 24) pyramid_list = [] for order in pyramid_orders: # frustum polygon: 5 corners, 5 surfaces pyramid = np.concatenate(( boxes[:, 0:3], boxes_corners[:, 3 * order[0]: 3 * order[0] + 3], boxes_corners[:, 3 * order[1]: 3 * order[1] + 3], boxes_corners[:, 3 * order[2]: 3 * order[2] + 3], boxes_corners[:, 3 * order[3]: 3 * order[3] + 3]), axis=1) pyramid_list.append(pyramid[:, None, :]) pyramids = np.concatenate(pyramid_list, axis=1) # [N, 6, 15], 15=5*3 return pyramids def one_hot(x, num_class=1): if num_class is None: num_class = 1 ohx = np.zeros((len(x), num_class)) ohx[range(len(x)), x] = 1 return ohx def points_in_pyramids_mask(points, pyramids): pyramids = pyramids.reshape(-1, 5, 3) flags = np.zeros((points.shape[0], pyramids.shape[0]), dtype=np.bool) for i, pyramid in enumerate(pyramids): flags[:, i] = np.logical_or(flags[:, i], box_utils.in_hull(points[:, 0:3], pyramid)) return flags def local_pyramid_dropout(gt_boxes, points, dropout_prob, pyramids=None): if pyramids is None: pyramids = get_pyramids(gt_boxes).reshape([-1, 6, 5, 3]) # each six surface of boxes: [num_boxes, 6, 15=3*5] drop_pyramid_indices = np.random.randint(0, 6, (pyramids.shape[0])) drop_pyramid_one_hot = one_hot(drop_pyramid_indices, num_class=6) drop_box_mask = np.random.uniform(0, 1, (pyramids.shape[0])) <= dropout_prob if np.sum(drop_box_mask) != 0: drop_pyramid_mask = (np.tile(drop_box_mask[:, None], [1, 6]) * drop_pyramid_one_hot) > 0 drop_pyramids = pyramids[drop_pyramid_mask] point_masks = points_in_pyramids_mask(points, drop_pyramids) points = points[np.logical_not(point_masks.any(-1))] # print(drop_box_mask) pyramids = pyramids[np.logical_not(drop_box_mask)] return gt_boxes, points, pyramids def local_pyramid_sparsify(gt_boxes, points, prob, max_num_pts, pyramids=None): if pyramids is None: pyramids = get_pyramids(gt_boxes).reshape([-1, 6, 5, 3]) # each six surface of boxes: [num_boxes, 6, 15=3*5] if pyramids.shape[0] > 0: sparsity_prob, sparsity_num = prob, max_num_pts sparsify_pyramid_indices = np.random.randint(0, 6, (pyramids.shape[0])) sparsify_pyramid_one_hot = one_hot(sparsify_pyramid_indices, num_class=6) sparsify_box_mask = np.random.uniform(0, 1, (pyramids.shape[0])) <= sparsity_prob sparsify_pyramid_mask = (np.tile(sparsify_box_mask[:, None], [1, 6]) * sparsify_pyramid_one_hot) > 0 # print(sparsify_box_mask) pyramid_sampled = pyramids[sparsify_pyramid_mask] # (-1,6,5,3)[(num_sample,6)] # print(pyramid_sampled.shape) pyramid_sampled_point_masks = points_in_pyramids_mask(points, pyramid_sampled) pyramid_sampled_points_num = pyramid_sampled_point_masks.sum(0) # the number of points in each surface pyramid valid_pyramid_sampled_mask = pyramid_sampled_points_num > sparsity_num # only much than sparsity_num should be sparse sparsify_pyramids = pyramid_sampled[valid_pyramid_sampled_mask] if sparsify_pyramids.shape[0] > 0: point_masks = pyramid_sampled_point_masks[:, valid_pyramid_sampled_mask] remain_points = points[ np.logical_not(point_masks.any(-1))] # points which outside the down sampling pyramid to_sparsify_points = [points[point_masks[:, i]] for i in range(point_masks.shape[1])] sparsified_points = [] for sample in to_sparsify_points: sampled_indices = np.random.choice(sample.shape[0], size=sparsity_num, replace=False) sparsified_points.append(sample[sampled_indices]) sparsified_points = np.concatenate(sparsified_points, axis=0) points = np.concatenate([remain_points, sparsified_points], axis=0) pyramids = pyramids[np.logical_not(sparsify_box_mask)] return gt_boxes, points, pyramids def local_pyramid_swap(gt_boxes, points, prob, max_num_pts, pyramids=None): def get_points_ratio(points, pyramid): surface_center = (pyramid[3:6] + pyramid[6:9] + pyramid[9:12] + pyramid[12:]) / 4.0 vector_0, vector_1, vector_2 = pyramid[6:9] - pyramid[3:6], pyramid[12:] - pyramid[3:6], pyramid[0:3] - surface_center alphas = ((points[:, 0:3] - pyramid[3:6]) * vector_0).sum(-1) / np.power(vector_0, 2).sum() betas = ((points[:, 0:3] - pyramid[3:6]) * vector_1).sum(-1) / np.power(vector_1, 2).sum() gammas = ((points[:, 0:3] - surface_center) * vector_2).sum(-1) / np.power(vector_2, 2).sum() return [alphas, betas, gammas] def recover_points_by_ratio(points_ratio, pyramid): alphas, betas, gammas = points_ratio surface_center = (pyramid[3:6] + pyramid[6:9] + pyramid[9:12] + pyramid[12:]) / 4.0 vector_0, vector_1, vector_2 = pyramid[6:9] - pyramid[3:6], pyramid[12:] - pyramid[3:6], pyramid[0:3] - surface_center points = (alphas[:, None] * vector_0 + betas[:, None] * vector_1) + pyramid[3:6] + gammas[:, None] * vector_2 return points def recover_points_intensity_by_ratio(points_intensity_ratio, max_intensity, min_intensity): return points_intensity_ratio * (max_intensity - min_intensity) + min_intensity # swap partition if pyramids is None: pyramids = get_pyramids(gt_boxes).reshape([-1, 6, 5, 3]) # each six surface of boxes: [num_boxes, 6, 15=3*5] swap_prob, num_thres = prob, max_num_pts swap_pyramid_mask = np.random.uniform(0, 1, (pyramids.shape[0])) <= swap_prob if swap_pyramid_mask.sum() > 0: point_masks = points_in_pyramids_mask(points, pyramids) point_nums = point_masks.sum(0).reshape(pyramids.shape[0], -1) # [N, 6] non_zero_pyramids_mask = point_nums > num_thres # ingore dropout pyramids or highly occluded pyramids selected_pyramids = non_zero_pyramids_mask * swap_pyramid_mask[:, None] # selected boxes and all their valid pyramids # print(selected_pyramids) if selected_pyramids.sum() > 0: # get to_swap pyramids index_i, index_j = np.nonzero(selected_pyramids) selected_pyramid_indices = [np.random.choice(index_j[index_i == i]) \ if e and (index_i == i).any() else 0 for i, e in enumerate(swap_pyramid_mask)] selected_pyramids_mask = selected_pyramids * one_hot(selected_pyramid_indices, num_class=6) == 1 to_swap_pyramids = pyramids[selected_pyramids_mask] # get swapped pyramids index_i, index_j = np.nonzero(selected_pyramids_mask) non_zero_pyramids_mask[selected_pyramids_mask] = False swapped_index_i = np.array([np.random.choice(np.where(non_zero_pyramids_mask[:, j])[0]) if \ np.where(non_zero_pyramids_mask[:, j])[0].shape[0] > 0 else index_i[i] for i, j in enumerate(index_j.tolist())]) swapped_indicies = np.concatenate([swapped_index_i[:, None], index_j[:, None]], axis=1) swapped_pyramids = pyramids[ swapped_indicies[:, 0].astype(np.int32), swapped_indicies[:, 1].astype(np.int32)] # concat to_swap&swapped pyramids swap_pyramids = np.concatenate([to_swap_pyramids, swapped_pyramids], axis=0) swap_point_masks = points_in_pyramids_mask(points, swap_pyramids) remain_points = points[np.logical_not(swap_point_masks.any(-1))] # swap pyramids points_res = [] num_swapped_pyramids = swapped_pyramids.shape[0] for i in range(num_swapped_pyramids): to_swap_pyramid = to_swap_pyramids[i] swapped_pyramid = swapped_pyramids[i] to_swap_points = points[swap_point_masks[:, i]] swapped_points = points[swap_point_masks[:, i + num_swapped_pyramids]] # for intensity transform to_swap_points_intensity_ratio = (to_swap_points[:, -1:] - to_swap_points[:, -1:].min()) / \ np.clip( (to_swap_points[:, -1:].max() - to_swap_points[:, -1:].min()), 1e-6, 1) swapped_points_intensity_ratio = (swapped_points[:, -1:] - swapped_points[:, -1:].min()) / \ np.clip( (swapped_points[:, -1:].max() - swapped_points[:, -1:].min()), 1e-6, 1) to_swap_points_ratio = get_points_ratio(to_swap_points, to_swap_pyramid.reshape(15)) swapped_points_ratio = get_points_ratio(swapped_points, swapped_pyramid.reshape(15)) new_to_swap_points = recover_points_by_ratio(swapped_points_ratio, to_swap_pyramid.reshape(15)) new_swapped_points = recover_points_by_ratio(to_swap_points_ratio, swapped_pyramid.reshape(15)) # for intensity transform new_to_swap_points_intensity = recover_points_intensity_by_ratio( swapped_points_intensity_ratio, to_swap_points[:, -1:].max(), to_swap_points[:, -1:].min()) new_swapped_points_intensity = recover_points_intensity_by_ratio( to_swap_points_intensity_ratio, swapped_points[:, -1:].max(), swapped_points[:, -1:].min()) # new_to_swap_points = np.concatenate([new_to_swap_points, swapped_points[:, -1:]], axis=1) # new_swapped_points = np.concatenate([new_swapped_points, to_swap_points[:, -1:]], axis=1) new_to_swap_points = np.concatenate([new_to_swap_points, new_to_swap_points_intensity], axis=1) new_swapped_points = np.concatenate([new_swapped_points, new_swapped_points_intensity], axis=1) points_res.append(new_to_swap_points) points_res.append(new_swapped_points) points_res = np.concatenate(points_res, axis=0) points = np.concatenate([remain_points, points_res], axis=0) return gt_boxes, points def global_sampling(gt_boxes, points, gt_boxes_mask, sample_ratio_range, prob): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading] points: (M, 3 + C) gt_boxes_mask: (N), boolen mask for gt_boxes sample_ratio_range: [min, max]. ratio to keep points remain. prob: prob to dentermine whether sampling this frame Returns: """ if np.random.uniform(0, 1) > prob: return gt_boxes, points, gt_boxes_mask num_points = points.shape[0] sample_ratio = np.random.uniform(sample_ratio_range[0], sample_ratio_range[1]) remain_points_num = int(num_points * sample_ratio) # shuffle points shuffle_idx = np.random.permutation(points.shape[0]) points = points[shuffle_idx] # sample points points = points[:remain_points_num] # mask empty gt_boxes num_points_in_gt = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, :3]), torch.from_numpy(gt_boxes[:, :7]) ).numpy().sum(axis=1) mask = (num_points_in_gt >= 1) gt_boxes_mask = gt_boxes_mask & mask return gt_boxes, points, gt_boxes_mask def scale_pre_object(gt_boxes, points, scale_perturb, num_try=50): """ uniform sacle object with given range Args: gt_boxes: (N, 7) under unified coordinates points: (M, 3 + C) points in lidar gt_boxes_mask: (N), boolen mask for scale_perturb: num_try: Returns: """ num_boxes = gt_boxes.shape[0] if not isinstance(scale_perturb, (list, tuple, np.ndarray)): scale_perturb = [-scale_perturb, scale_perturb] # boxes wise scale ratio scale_noises = np.random.uniform(scale_perturb[0], scale_perturb[1], size=[num_boxes, num_try]) for k in range(num_boxes): # if gt_boxes_mask[k] == 0: # continue scl_box = copy.deepcopy(gt_boxes[k]) scl_box = scl_box.reshape(1, -1).repeat([num_try], axis=0) scl_box[:, 3:6] = scl_box[:, 3:6] * scale_noises[k].reshape(-1, 1).repeat([3], axis=1) # detect conflict # [num_try, N-1] if num_boxes > 1: self_mask = np.ones(num_boxes, dtype=np.bool_) self_mask[k] = False iou_matrix = iou3d_nms_utils.boxes_bev_iou_cpu(scl_box, gt_boxes[self_mask]) ious = np.max(iou_matrix, axis=1) no_conflict_mask = (ious == 0) # all trys have conflict with other gts if no_conflict_mask.sum() == 0: continue # scale points and assign new box try_idx = no_conflict_mask.nonzero()[0][0] else: try_idx = 0 point_masks = roiaware_pool3d_utils.points_in_boxes_cpu( points[:, 0:3],np.expand_dims(gt_boxes[k], axis=0)).squeeze(0) obj_points = points[point_masks > 0] obj_center, lwh, ry = gt_boxes[k, 0:3], gt_boxes[k, 3:6], gt_boxes[k, 6] # relative coordinates obj_points[:, 0:3] -= obj_center obj_points = common_utils.rotate_points_along_z(np.expand_dims(obj_points, axis=0), -ry).squeeze(0) new_lwh = lwh * scale_noises[k][try_idx] obj_points[:, 0:3] = obj_points[:, 0:3] * scale_noises[k][try_idx] obj_points = common_utils.rotate_points_along_z(np.expand_dims(obj_points, axis=0), ry).squeeze(0) # calculate new object center to avoid object float over the road obj_center[2] += (new_lwh[2] - lwh[2]) / 2 obj_points[:, 0:3] += obj_center points[point_masks > 0] = obj_points gt_boxes[k, 3:6] = new_lwh # if enlarge boxes, remove bg points if scale_noises[k][try_idx] > 1: points_dst_mask = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], np.expand_dims(gt_boxes[k], axis=0)).squeeze(0) keep_mask = ~np.logical_xor(point_masks, points_dst_mask) points = points[keep_mask] return points, gt_boxes def normalize_object_size(boxes, points, boxes_mask, size_res): """ :param boxes: (N, 7) under unified boxes :param points: (N, 3 + C) :param boxes_mask :param size_res: (3) [l, w, h] :return: """ points = copy.deepcopy(points) boxes = copy.deepcopy(boxes) for k in range(boxes.shape[0]): # skip boxes that not need to normalize if boxes_mask[k] == 0: continue masks = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], boxes[k:k+1, :7]).squeeze(0) obj_points = points[masks > 0] obj_center, lwh, ry = boxes[k, 0:3], boxes[k, 3:6], boxes[k, 6] obj_points[:, 0:3] -= obj_center obj_points = common_utils.rotate_points_along_z(np.expand_dims(obj_points, axis=0), -ry).squeeze(0) new_lwh = lwh + np.array(size_res) # skip boxes that shift to have negative if (new_lwh < 0).any(): boxes_mask[k] = False continue scale_lwh = new_lwh / lwh obj_points[:, 0:3] = obj_points[:, 0:3] * scale_lwh obj_points = common_utils.rotate_points_along_z(np.expand_dims(obj_points, axis=0), ry).squeeze(0) # calculate new object center to avoid object float over the road obj_center[2] += size_res[2] / 2 obj_points[:, 0:3] += obj_center points[masks > 0] = obj_points boxes[k, 3:6] = new_lwh # if enlarge boxes, remove bg points if (np.array(size_res) > 0).any(): points_dst_mask = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], np.expand_dims(boxes[k], axis=0)).squeeze(0) keep_mask = ~np.logical_xor(masks, points_dst_mask) points = points[keep_mask] return points, boxes def rotate_objects(gt_boxes, points, gt_boxes_mask, rotation_perturb, prob, num_try=50): """ Args: gt_boxes: [N, 7] (x, y, z, dx, dy, dz, heading) on unified coordinate points: [M] gt_boxes_mask: [N] bool rotation_perturb: ratation noise parameter prob: prob to random rotate object num_try: times to try rotate one object Returns: """ num_boxes = gt_boxes.shape[0] if not isinstance(rotation_perturb, (list, tuple, np.ndarray)): rotation_perturb = [-rotation_perturb, rotation_perturb] # with prob to rotate each object rot_mask = np.random.uniform(0, 1, size=[num_boxes]) < prob # generate random ratate noise for each boxes rot_noise = np.random.uniform(rotation_perturb[0], rotation_perturb[1], size=[num_boxes, num_try]) for idx in range(num_boxes): # don't need to rotate this object if (not rot_mask[idx]) or (not gt_boxes_mask[idx]): continue # generate rotated boxes num_try times rot_box = copy.deepcopy(gt_boxes[idx]) # [num_try, 7] rot_box = rot_box.reshape(1, -1).repeat([num_try], axis=0) rot_box[:, 6] += rot_noise[idx] # detect conflict # [num_try, N-1] if num_boxes > 1: self_mask = np.ones(num_boxes, dtype=np.bool_) self_mask[idx] = False iou_matrix = iou3d_nms_utils.boxes_bev_iou_cpu(rot_box, gt_boxes[self_mask]) ious = np.max(iou_matrix, axis=1) no_conflict_mask = (ious == 0) # all trys have conflict with other gts if no_conflict_mask.sum() == 0: continue # rotate points and assign new box try_idx = no_conflict_mask.nonzero()[0][0] else: try_idx = 0 point_masks = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], np.expand_dims(gt_boxes[idx], axis=0)).squeeze(0) object_points = points[point_masks > 0] object_center = gt_boxes[idx][0:3] object_points[:, 0:3] -= object_center object_points = common_utils.rotate_points_along_z(object_points[np.newaxis, :, :], np.array([rot_noise[idx][try_idx]]))[0] object_points[:, 0:3] += object_center points[point_masks > 0] = object_points # remove bg points that lie the position we want to place object points_dst_mask = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], np.expand_dims(rot_box[try_idx], axis=0)).squeeze(0) keep_mask = ~np.logical_xor(point_masks, points_dst_mask) points = points[keep_mask] gt_boxes[idx] = rot_box[try_idx] return gt_boxes, points
35,553
37.3125
126
py
3DTrans
3DTrans-master/pcdet/datasets/augmentor/database_sampler.py
import pickle import os import copy import numpy as np import SharedArray import torch.distributed as dist from ...ops.iou3d_nms import iou3d_nms_utils from ...utils import box_utils, common_utils import os import io class DataBaseSampler(object): def __init__(self, root_path, sampler_cfg, class_names, logger=None, client=None, oss_flag=False): self.root_path = root_path self.class_names = class_names self.sampler_cfg = sampler_cfg self.logger = logger self.client = client self.oss_flag = oss_flag self.db_infos = {} for class_name in class_names: self.db_infos[class_name] = [] self.use_shared_memory = sampler_cfg.get('USE_SHARED_MEMORY', False) self.logger.info(f"*************root_path***********: {root_path}") if self.oss_flag: from petrel_client.client import Client # ~/.petreloss.conf: save the KEY/ACCESS_KEY of S3 Ceph self.client = Client('~/.petreloss.conf') for db_info_path in sampler_cfg.DB_INFO_PATH: if not self.oss_flag: db_info_path = self.root_path.resolve() / db_info_path self.logger.info(f"*************Load LINUX db_info_path*************: {db_info_path}") with open(str(db_info_path), 'rb') as f: infos = pickle.load(f) [self.db_infos[cur_class].extend(infos[cur_class]) for cur_class in class_names] else: db_info_path = os.path.join(self.root_path, db_info_path) self.logger.info(f"*************Load OSS db_info_path*************: {db_info_path}") # pkl_bytes = self.client.get(db_info_path) pkl_bytes = self.client.get(db_info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) [self.db_infos[cur_class].extend(infos[cur_class]) for cur_class in class_names] for func_name, val in sampler_cfg.PREPARE.items(): self.db_infos = getattr(self, func_name)(self.db_infos, val) self.gt_database_data_key = self.load_db_to_shared_memory() if self.use_shared_memory else None self.sample_groups = {} self.sample_class_num = {} self.limit_whole_scene = sampler_cfg.get('LIMIT_WHOLE_SCENE', False) for x in sampler_cfg.SAMPLE_GROUPS: class_name, sample_num = x.split(':') if class_name not in class_names: continue self.sample_class_num[class_name] = sample_num self.sample_groups[class_name] = { 'sample_num': sample_num, 'pointer': len(self.db_infos[class_name]), 'indices': np.arange(len(self.db_infos[class_name])) } def __getstate__(self): d = dict(self.__dict__) del d['logger'] return d def __setstate__(self, d): self.__dict__.update(d) def __del__(self): if self.use_shared_memory: self.logger.info('Deleting GT database from shared memory') cur_rank, num_gpus = common_utils.get_dist_info() sa_key = self.sampler_cfg.DB_DATA_PATH[0] if cur_rank % num_gpus == 0 and os.path.exists(f"/dev/shm/{sa_key}"): SharedArray.delete(f"shm://{sa_key}") if num_gpus > 1: dist.barrier() self.logger.info('GT database has been removed from shared memory') def load_db_to_shared_memory(self): self.logger.info('Loading GT database to shared memory') cur_rank, world_size, num_gpus = common_utils.get_dist_info(return_gpu_per_machine=True) assert self.sampler_cfg.DB_DATA_PATH.__len__() == 1, 'Current only support single DB_DATA' db_data_path = self.root_path.resolve() / self.sampler_cfg.DB_DATA_PATH[0] sa_key = self.sampler_cfg.DB_DATA_PATH[0] if cur_rank % num_gpus == 0 and not os.path.exists(f"/dev/shm/{sa_key}"): gt_database_data = np.load(db_data_path) common_utils.sa_create(f"shm://{sa_key}", gt_database_data) if num_gpus > 1: dist.barrier() self.logger.info('GT database has been saved to shared memory') return sa_key def filter_by_difficulty(self, db_infos, removed_difficulty): new_db_infos = {} for key, dinfos in db_infos.items(): pre_len = len(dinfos) new_db_infos[key] = [ info for info in dinfos if info['difficulty'] not in removed_difficulty ] if self.logger is not None: self.logger.info('Database filter by difficulty %s: %d => %d' % (key, pre_len, len(new_db_infos[key]))) return new_db_infos def filter_by_min_points(self, db_infos, min_gt_points_list): for name_num in min_gt_points_list: name, min_num = name_num.split(':') min_num = int(min_num) if min_num > 0 and name in db_infos.keys(): filtered_infos = [] for info in db_infos[name]: if info['num_points_in_gt'] >= min_num: filtered_infos.append(info) if self.logger is not None: self.logger.info('Database filter by min points %s: %d => %d' % (name, len(db_infos[name]), len(filtered_infos))) db_infos[name] = filtered_infos return db_infos def sample_with_fixed_number(self, class_name, sample_group): """ Args: class_name: sample_group: Returns: """ sample_num, pointer, indices = int(sample_group['sample_num']), sample_group['pointer'], sample_group['indices'] if pointer >= len(self.db_infos[class_name]): indices = np.random.permutation(len(self.db_infos[class_name])) pointer = 0 sampled_dict = [self.db_infos[class_name][idx] for idx in indices[pointer: pointer + sample_num]] pointer += sample_num sample_group['pointer'] = pointer sample_group['indices'] = indices return sampled_dict @staticmethod def put_boxes_on_road_planes(gt_boxes, road_planes, calib): """ Only validate in KITTIDataset Args: gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] road_planes: [a, b, c, d] calib: Returns: """ a, b, c, d = road_planes center_cam = calib.lidar_to_rect(gt_boxes[:, 0:3]) cur_height_cam = (-d - a * center_cam[:, 0] - c * center_cam[:, 2]) / b center_cam[:, 1] = cur_height_cam cur_lidar_height = calib.rect_to_lidar(center_cam)[:, 2] mv_height = gt_boxes[:, 2] - gt_boxes[:, 5] / 2 - cur_lidar_height gt_boxes[:, 2] -= mv_height # lidar view return gt_boxes, mv_height def add_sampled_boxes_to_scene(self, data_dict, sampled_gt_boxes, total_valid_sampled_dict): gt_boxes_mask = data_dict['gt_boxes_mask'] gt_boxes = data_dict['gt_boxes'][gt_boxes_mask] gt_names = data_dict['gt_names'][gt_boxes_mask] points = data_dict['points'] if self.sampler_cfg.get('USE_ROAD_PLANE', False): sampled_gt_boxes, mv_height = self.put_boxes_on_road_planes( sampled_gt_boxes, data_dict['road_plane'], data_dict['calib'] ) data_dict.pop('calib') data_dict.pop('road_plane') obj_points_list = [] if self.use_shared_memory: gt_database_data = SharedArray.attach(f"shm://{self.gt_database_data_key}") gt_database_data.setflags(write=0) else: gt_database_data = None for idx, info in enumerate(total_valid_sampled_dict): if self.use_shared_memory: start_offset, end_offset = info['global_data_offset'] obj_points = copy.deepcopy(gt_database_data[start_offset:end_offset]) else: #file_path = self.root_path / info['path'] file_path = os.path.join(self.root_path, info['path']) if self.oss_flag: #print ("*************file_path*************:", file_path) #sdk_local_bytes = self.client.get(file_path) sdk_local_bytes = self.client.get(file_path, update_cache=True) obj_points = np.frombuffer(sdk_local_bytes, dtype=np.float32).reshape( [-1, self.sampler_cfg.NUM_POINT_FEATURES]).copy() else: obj_points = np.fromfile(str(file_path), dtype=np.float32).reshape( [-1, self.sampler_cfg.NUM_POINT_FEATURES]) obj_points[:, :3] += info['box3d_lidar'][:3] if self.sampler_cfg.get('USE_ROAD_PLANE', False): # mv height obj_points[:, 2] -= mv_height[idx] obj_points_list.append(obj_points) obj_points = np.concatenate(obj_points_list, axis=0) sampled_gt_names = np.array([x['name'] for x in total_valid_sampled_dict]) large_sampled_gt_boxes = box_utils.enlarge_box3d( sampled_gt_boxes[:, 0:7], extra_width=self.sampler_cfg.REMOVE_EXTRA_WIDTH ) points = box_utils.remove_points_in_boxes3d(points, large_sampled_gt_boxes) points = np.concatenate([obj_points, points], axis=0) gt_names = np.concatenate([gt_names, sampled_gt_names], axis=0) gt_boxes = np.concatenate([gt_boxes, sampled_gt_boxes], axis=0) data_dict['gt_boxes'] = gt_boxes data_dict['gt_names'] = gt_names data_dict['points'] = points return data_dict def __call__(self, data_dict): """ Args: data_dict: gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] Returns: """ gt_boxes = data_dict['gt_boxes'] gt_names = data_dict['gt_names'].astype(str) existed_boxes = gt_boxes total_valid_sampled_dict = [] for class_name, sample_group in self.sample_groups.items(): if self.limit_whole_scene: num_gt = np.sum(class_name == gt_names) sample_group['sample_num'] = str(int(self.sample_class_num[class_name]) - num_gt) if int(sample_group['sample_num']) > 0: sampled_dict = self.sample_with_fixed_number(class_name, sample_group) sampled_boxes = np.stack([x['box3d_lidar'] for x in sampled_dict], axis=0).astype(np.float32) if self.sampler_cfg.get('DATABASE_WITH_FAKELIDAR', False): sampled_boxes = box_utils.boxes3d_kitti_fakelidar_to_lidar(sampled_boxes) iou1 = iou3d_nms_utils.boxes_bev_iou_cpu(sampled_boxes[:, 0:7], existed_boxes[:, 0:7]) iou2 = iou3d_nms_utils.boxes_bev_iou_cpu(sampled_boxes[:, 0:7], sampled_boxes[:, 0:7]) iou2[range(sampled_boxes.shape[0]), range(sampled_boxes.shape[0])] = 0 iou1 = iou1 if iou1.shape[1] > 0 else iou2 valid_mask = ((iou1.max(axis=1) + iou2.max(axis=1)) == 0).nonzero()[0] valid_sampled_dict = [sampled_dict[x] for x in valid_mask] valid_sampled_boxes = sampled_boxes[valid_mask] existed_boxes = np.concatenate((existed_boxes, valid_sampled_boxes), axis=0) total_valid_sampled_dict.extend(valid_sampled_dict) sampled_gt_boxes = existed_boxes[gt_boxes.shape[0]:, :] if total_valid_sampled_dict.__len__() > 0: data_dict = self.add_sampled_boxes_to_scene(data_dict, sampled_gt_boxes, total_valid_sampled_dict) data_dict.pop('gt_boxes_mask') return data_dict
11,921
42.510949
120
py
3DTrans
3DTrans-master/pcdet/datasets/nuscenes/nuscenes_utils.py
""" The NuScenes data pre-processing and evaluation is modified from https://github.com/traveller59/second.pytorch and https://github.com/poodarchu/Det3D """ import operator from functools import reduce from pathlib import Path import numpy as np import tqdm from nuscenes.utils.data_classes import Box from nuscenes.utils.geometry_utils import transform_matrix from pyquaternion import Quaternion map_name_from_general_to_detection = { 'human.pedestrian.adult': 'pedestrian', 'human.pedestrian.child': 'pedestrian', 'human.pedestrian.wheelchair': 'ignore', 'human.pedestrian.stroller': 'ignore', 'human.pedestrian.personal_mobility': 'ignore', 'human.pedestrian.police_officer': 'pedestrian', 'human.pedestrian.construction_worker': 'pedestrian', 'animal': 'ignore', 'vehicle.car': 'car', 'vehicle.motorcycle': 'motorcycle', 'vehicle.bicycle': 'bicycle', 'vehicle.bus.bendy': 'bus', 'vehicle.bus.rigid': 'bus', 'vehicle.truck': 'truck', 'vehicle.construction': 'construction_vehicle', 'vehicle.emergency.ambulance': 'ignore', 'vehicle.emergency.police': 'ignore', 'vehicle.trailer': 'trailer', 'movable_object.barrier': 'barrier', 'movable_object.trafficcone': 'traffic_cone', 'movable_object.pushable_pullable': 'ignore', 'movable_object.debris': 'ignore', 'static_object.bicycle_rack': 'ignore', } map_name_from_general_to_detection_mdf = { 'human.pedestrian.adult': 'Pedestrian', 'human.pedestrian.child': 'Pedestrian', 'human.pedestrian.wheelchair': 'ignore', 'human.pedestrian.stroller': 'ignore', 'human.pedestrian.personal_mobility': 'ignore', 'human.pedestrian.police_officer': 'Pedestrian', 'human.pedestrian.construction_worker': 'Pedestrian', 'animal': 'ignore', 'vehicle.car': 'Vehicle', 'vehicle.motorcycle': 'Cyclist', 'vehicle.bicycle': 'Cyclist', 'vehicle.bus.bendy': 'Vehicle', 'vehicle.bus.rigid': 'Vehicle', 'vehicle.truck': 'Vehicle', 'vehicle.construction': 'Vehicle', 'vehicle.emergency.ambulance': 'ignore', 'vehicle.emergency.police': 'ignore', 'vehicle.trailer': 'Vehicle', 'movable_object.barrier': 'ignore', 'movable_object.trafficcone': 'ignore', 'movable_object.pushable_pullable': 'ignore', 'movable_object.debris': 'ignore', 'static_object.bicycle_rack': 'ignore', } cls_attr_dist = { 'barrier': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 0, 'vehicle.parked': 0, 'vehicle.stopped': 0, }, 'bicycle': { 'cycle.with_rider': 2791, 'cycle.without_rider': 8946, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 0, 'vehicle.parked': 0, 'vehicle.stopped': 0, }, 'bus': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 9092, 'vehicle.parked': 3294, 'vehicle.stopped': 3881, }, 'car': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 114304, 'vehicle.parked': 330133, 'vehicle.stopped': 46898, }, 'construction_vehicle': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 882, 'vehicle.parked': 11549, 'vehicle.stopped': 2102, }, 'ignore': { 'cycle.with_rider': 307, 'cycle.without_rider': 73, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 165, 'vehicle.parked': 400, 'vehicle.stopped': 102, }, 'motorcycle': { 'cycle.with_rider': 4233, 'cycle.without_rider': 8326, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 0, 'vehicle.parked': 0, 'vehicle.stopped': 0, }, 'pedestrian': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 157444, 'pedestrian.sitting_lying_down': 13939, 'pedestrian.standing': 46530, 'vehicle.moving': 0, 'vehicle.parked': 0, 'vehicle.stopped': 0, }, 'traffic_cone': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 0, 'vehicle.parked': 0, 'vehicle.stopped': 0, }, 'trailer': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 3421, 'vehicle.parked': 19224, 'vehicle.stopped': 1895, }, 'truck': { 'cycle.with_rider': 0, 'cycle.without_rider': 0, 'pedestrian.moving': 0, 'pedestrian.sitting_lying_down': 0, 'pedestrian.standing': 0, 'vehicle.moving': 21339, 'vehicle.parked': 55626, 'vehicle.stopped': 11097, }, } def get_available_scenes(nusc): available_scenes = [] print('total scene num:', len(nusc.scene)) for scene in nusc.scene: scene_token = scene['token'] scene_rec = nusc.get('scene', scene_token) sample_rec = nusc.get('sample', scene_rec['first_sample_token']) sd_rec = nusc.get('sample_data', sample_rec['data']['LIDAR_TOP']) has_more_frames = True scene_not_exist = False while has_more_frames: lidar_path, boxes, _ = nusc.get_sample_data(sd_rec['token']) if not Path(lidar_path).exists(): scene_not_exist = True break else: break # if not sd_rec['next'] == '': # sd_rec = nusc.get('sample_data', sd_rec['next']) # else: # has_more_frames = False if scene_not_exist: continue available_scenes.append(scene) print('exist scene num:', len(available_scenes)) return available_scenes def get_sample_data(nusc, sample_data_token, selected_anntokens=None): """ Returns the data path as well as all annotations related to that sample_data. Note that the boxes are transformed into the current sensor's coordinate frame. Args: nusc: sample_data_token: Sample_data token. selected_anntokens: If provided only return the selected annotation. Returns: """ # Retrieve sensor & pose records sd_record = nusc.get('sample_data', sample_data_token) cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token']) sensor_record = nusc.get('sensor', cs_record['sensor_token']) pose_record = nusc.get('ego_pose', sd_record['ego_pose_token']) data_path = nusc.get_sample_data_path(sample_data_token) if sensor_record['modality'] == 'camera': cam_intrinsic = np.array(cs_record['camera_intrinsic']) imsize = (sd_record['width'], sd_record['height']) else: cam_intrinsic = imsize = None # Retrieve all sample annotations and map to sensor coordinate system. if selected_anntokens is not None: boxes = list(map(nusc.get_box, selected_anntokens)) else: boxes = nusc.get_boxes(sample_data_token) # Make list of Box objects including coord system transforms. box_list = [] for box in boxes: box.velocity = nusc.box_velocity(box.token) # Move box to ego vehicle coord system box.translate(-np.array(pose_record['translation'])) box.rotate(Quaternion(pose_record['rotation']).inverse) # Move box to sensor coord system box.translate(-np.array(cs_record['translation'])) box.rotate(Quaternion(cs_record['rotation']).inverse) box_list.append(box) return data_path, box_list, cam_intrinsic def quaternion_yaw(q: Quaternion) -> float: """ Calculate the yaw angle from a quaternion. Note that this only works for a quaternion that represents a box in lidar or global coordinate frame. It does not work for a box in the camera frame. :param q: Quaternion of interest. :return: Yaw angle in radians. """ # Project into xy plane. v = np.dot(q.rotation_matrix, np.array([1, 0, 0])) # Measure yaw using arctan. yaw = np.arctan2(v[1], v[0]) return yaw def fill_trainval_infos(data_path, nusc, train_scenes, val_scenes, test=False, max_sweeps=10): train_nusc_infos = [] val_nusc_infos = [] progress_bar = tqdm.tqdm(total=len(nusc.sample), desc='create_info', dynamic_ncols=True) ref_chan = 'LIDAR_TOP' # The radar channel from which we track back n sweeps to aggregate the point cloud. chan = 'LIDAR_TOP' # The reference channel of the current sample_rec that the point clouds are mapped to. for index, sample in enumerate(nusc.sample): progress_bar.update() ref_sd_token = sample['data'][ref_chan] ref_sd_rec = nusc.get('sample_data', ref_sd_token) ref_cs_rec = nusc.get('calibrated_sensor', ref_sd_rec['calibrated_sensor_token']) ref_pose_rec = nusc.get('ego_pose', ref_sd_rec['ego_pose_token']) ref_time = 1e-6 * ref_sd_rec['timestamp'] ref_lidar_path, ref_boxes, _ = get_sample_data(nusc, ref_sd_token) ref_cam_front_token = sample['data']['CAM_FRONT'] ref_cam_path, _, ref_cam_intrinsic = nusc.get_sample_data(ref_cam_front_token) # Homogeneous transform from ego car frame to reference frame ref_from_car = transform_matrix( ref_cs_rec['translation'], Quaternion(ref_cs_rec['rotation']), inverse=True ) # Homogeneous transformation matrix from global to _current_ ego car frame car_from_global = transform_matrix( ref_pose_rec['translation'], Quaternion(ref_pose_rec['rotation']), inverse=True, ) info = { 'lidar_path': Path(ref_lidar_path).relative_to(data_path).__str__(), 'cam_front_path': Path(ref_cam_path).relative_to(data_path).__str__(), 'cam_intrinsic': ref_cam_intrinsic, 'token': sample['token'], 'sweeps': [], 'ref_from_car': ref_from_car, 'car_from_global': car_from_global, 'timestamp': ref_time, } sample_data_token = sample['data'][chan] curr_sd_rec = nusc.get('sample_data', sample_data_token) sweeps = [] while len(sweeps) < max_sweeps - 1: if curr_sd_rec['prev'] == '': if len(sweeps) == 0: sweep = { 'lidar_path': Path(ref_lidar_path).relative_to(data_path).__str__(), 'sample_data_token': curr_sd_rec['token'], 'transform_matrix': None, 'time_lag': curr_sd_rec['timestamp'] * 0, } sweeps.append(sweep) else: sweeps.append(sweeps[-1]) else: curr_sd_rec = nusc.get('sample_data', curr_sd_rec['prev']) # Get past pose current_pose_rec = nusc.get('ego_pose', curr_sd_rec['ego_pose_token']) global_from_car = transform_matrix( current_pose_rec['translation'], Quaternion(current_pose_rec['rotation']), inverse=False, ) # Homogeneous transformation matrix from sensor coordinate frame to ego car frame. current_cs_rec = nusc.get( 'calibrated_sensor', curr_sd_rec['calibrated_sensor_token'] ) car_from_current = transform_matrix( current_cs_rec['translation'], Quaternion(current_cs_rec['rotation']), inverse=False, ) tm = reduce(np.dot, [ref_from_car, car_from_global, global_from_car, car_from_current]) lidar_path = nusc.get_sample_data_path(curr_sd_rec['token']) time_lag = ref_time - 1e-6 * curr_sd_rec['timestamp'] sweep = { 'lidar_path': Path(lidar_path).relative_to(data_path).__str__(), 'sample_data_token': curr_sd_rec['token'], 'transform_matrix': tm, 'global_from_car': global_from_car, 'car_from_current': car_from_current, 'time_lag': time_lag, } sweeps.append(sweep) info['sweeps'] = sweeps assert len(info['sweeps']) == max_sweeps - 1, \ f"sweep {curr_sd_rec['token']} only has {len(info['sweeps'])} sweeps, " \ f"you should duplicate to sweep num {max_sweeps - 1}" if not test: annotations = [nusc.get('sample_annotation', token) for token in sample['anns']] # the filtering gives 0.5~1 map improvement num_lidar_pts = np.array([anno['num_lidar_pts'] for anno in annotations]) num_radar_pts = np.array([anno['num_radar_pts'] for anno in annotations]) mask = (num_lidar_pts + num_radar_pts > 0) locs = np.array([b.center for b in ref_boxes]).reshape(-1, 3) dims = np.array([b.wlh for b in ref_boxes]).reshape(-1, 3)[:, [1, 0, 2]] # wlh == > dxdydz (lwh) velocity = np.array([b.velocity for b in ref_boxes]).reshape(-1, 3) rots = np.array([quaternion_yaw(b.orientation) for b in ref_boxes]).reshape(-1, 1) names = np.array([b.name for b in ref_boxes]) tokens = np.array([b.token for b in ref_boxes]) gt_boxes = np.concatenate([locs, dims, rots, velocity[:, :2]], axis=1) assert len(annotations) == len(gt_boxes) == len(velocity) info['gt_boxes'] = gt_boxes[mask, :] info['gt_boxes_velocity'] = velocity[mask, :] info['gt_names'] = np.array([map_name_from_general_to_detection[name] for name in names])[mask] info['gt_boxes_token'] = tokens[mask] info['num_lidar_pts'] = num_lidar_pts[mask] info['num_radar_pts'] = num_radar_pts[mask] if sample['scene_token'] in train_scenes: train_nusc_infos.append(info) else: val_nusc_infos.append(info) progress_bar.close() return train_nusc_infos, val_nusc_infos def boxes_lidar_to_nusenes(det_info): boxes3d = det_info['boxes_lidar'] scores = det_info['score'] labels = det_info['pred_labels'] box_list = [] for k in range(boxes3d.shape[0]): quat = Quaternion(axis=[0, 0, 1], radians=boxes3d[k, 6]) velocity = (*boxes3d[k, 7:9], 0.0) if boxes3d.shape[1] == 9 else (0.0, 0.0, 0.0) box = Box( boxes3d[k, :3], boxes3d[k, [4, 3, 5]], # wlh quat, label=labels[k], score=scores[k], velocity=velocity, ) box_list.append(box) return box_list def lidar_nusc_box_to_global(nusc, boxes, sample_token): s_record = nusc.get('sample', sample_token) sample_data_token = s_record['data']['LIDAR_TOP'] sd_record = nusc.get('sample_data', sample_data_token) cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token']) sensor_record = nusc.get('sensor', cs_record['sensor_token']) pose_record = nusc.get('ego_pose', sd_record['ego_pose_token']) data_path = nusc.get_sample_data_path(sample_data_token) box_list = [] for box in boxes: # Move box to ego vehicle coord system box.rotate(Quaternion(cs_record['rotation'])) box.translate(np.array(cs_record['translation'])) # Move box to global coord system box.rotate(Quaternion(pose_record['rotation'])) box.translate(np.array(pose_record['translation'])) box_list.append(box) return box_list def transform_det_annos_to_nusc_annos(det_annos, nusc): nusc_annos = { 'results': {}, 'meta': None, } for det in det_annos: annos = [] box_list = boxes_lidar_to_nusenes(det) box_list = lidar_nusc_box_to_global( nusc=nusc, boxes=box_list, sample_token=det['metadata']['token'] ) for k, box in enumerate(box_list): name = det['name'][k] if np.sqrt(box.velocity[0] ** 2 + box.velocity[1] ** 2) > 0.2: if name in ['car', 'construction_vehicle', 'bus', 'truck', 'trailer']: attr = 'vehicle.moving' elif name in ['bicycle', 'motorcycle']: attr = 'cycle.with_rider' else: attr = None else: if name in ['pedestrian']: attr = 'pedestrian.standing' elif name in ['bus']: attr = 'vehicle.stopped' else: attr = None attr = attr if attr is not None else max( cls_attr_dist[name].items(), key=operator.itemgetter(1))[0] nusc_anno = { 'sample_token': det['metadata']['token'], 'translation': box.center.tolist(), 'size': box.wlh.tolist(), 'rotation': box.orientation.elements.tolist(), 'velocity': box.velocity[:2].tolist(), 'detection_name': name, 'detection_score': box.score, 'attribute_name': attr } annos.append(nusc_anno) nusc_annos['results'].update({det["metadata"]["token"]: annos}) return nusc_annos def format_nuscene_results(metrics, class_names, version='default'): result = '----------------Nuscene %s results-----------------\n' % version for name in class_names: threshs = ', '.join(list(metrics['label_aps'][name].keys())) ap_list = list(metrics['label_aps'][name].values()) err_name =', '.join([x.split('_')[0] for x in list(metrics['label_tp_errors'][name].keys())]) error_list = list(metrics['label_tp_errors'][name].values()) result += f'***{name} error@{err_name} | AP@{threshs}\n' result += ', '.join(['%.2f' % x for x in error_list]) + ' | ' result += ', '.join(['%.2f' % (x * 100) for x in ap_list]) result += f" | mean AP: {metrics['mean_dist_aps'][name]}" result += '\n' result += '--------------average performance-------------\n' details = {} for key, val in metrics['tp_errors'].items(): result += '%s:\t %.4f\n' % (key, val) details[key] = val result += 'mAP:\t %.4f\n' % metrics['mean_ap'] result += 'NDS:\t %.4f\n' % metrics['nd_score'] details.update({ 'mAP': metrics['mean_ap'], 'NDS': metrics['nd_score'], }) return result, details
19,464
36.005703
111
py
3DTrans
3DTrans-master/pcdet/datasets/nuscenes/nuscenes_dataset.py
import copy import pickle from pathlib import Path import os import io import numpy as np from tqdm import tqdm from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import common_utils from ..dataset import DatasetTemplate class NuScenesDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/nuScenes' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): root_path = (root_path if root_path is not None else Path(dataset_cfg.DATA_PATH)) / dataset_cfg.VERSION super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') # self.oss_data_list = self.list_oss_dir(self.oss_path, with_info=False) # zhangbo: for OSS format, list the nuScenes dataset will cause a Bug, # due to OSS cannot load too many objects self.infos = [] self.include_nuscenes_data(self.mode) if self.training and self.dataset_cfg.get('BALANCED_RESAMPLING', False): self.infos = self.balanced_infos_resampling(self.infos) def include_nuscenes_data(self, mode): self.logger.info('Loading NuScenes dataset') nuscenes_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) nuscenes_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) nuscenes_infos.extend(infos) self.infos.extend(nuscenes_infos) self.logger.info('Total samples for NuScenes dataset: %d' % (len(nuscenes_infos))) def balanced_infos_resampling(self, infos): """ Class-balanced sampling of nuScenes dataset from https://arxiv.org/abs/1908.09492 """ if self.class_names is None: return infos cls_infos = {name: [] for name in self.class_names} for info in infos: for name in set(info['gt_names']): if name in self.class_names: cls_infos[name].append(info) duplicated_samples = sum([len(v) for _, v in cls_infos.items()]) cls_dist = {k: len(v) / duplicated_samples for k, v in cls_infos.items()} sampled_infos = [] frac = 1.0 / len(self.class_names) ratios = [frac / v for v in cls_dist.values()] for cur_cls_infos, ratio in zip(list(cls_infos.values()), ratios): sampled_infos += np.random.choice( cur_cls_infos, int(len(cur_cls_infos) * ratio) ).tolist() self.logger.info('Total samples after balanced resampling: %s' % (len(sampled_infos))) cls_infos_new = {name: [] for name in self.class_names} for info in sampled_infos: for name in set(info['gt_names']): if name in self.class_names: cls_infos_new[name].append(info) cls_dist_new = {k: len(v) / len(sampled_infos) for k, v in cls_infos_new.items()} return sampled_infos def get_sweep(self, sweep_info): def remove_ego_points(points, center_radius=1.0): mask = ~((np.abs(points[:, 0]) < center_radius) & (np.abs(points[:, 1]) < center_radius)) return points[mask] if self.oss_path is None: lidar_path = self.root_path / sweep_info['lidar_path'] points_sweep = np.fromfile(str(lidar_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] else: lidar_path = os.path.join(self.oss_path, sweep_info['lidar_path']) #sdk_local_bytes = self.client.get(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_sweep = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] points_sweep = remove_ego_points(points_sweep).T if sweep_info['transform_matrix'] is not None: num_points = points_sweep.shape[1] points_sweep[:3, :] = sweep_info['transform_matrix'].dot( np.vstack((points_sweep[:3, :], np.ones(num_points))))[:3, :] cur_times = sweep_info['time_lag'] * np.ones((1, points_sweep.shape[1])) return points_sweep.T, cur_times.T def get_lidar_with_sweeps(self, index, max_sweeps=1): info = self.infos[index] if self.oss_path is None: lidar_path = self.root_path / info['lidar_path'] points = np.fromfile(str(lidar_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] else: lidar_path = os.path.join(self.oss_path, info['lidar_path']) #sdk_local_bytes = self.client.get(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_pre = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).reshape([-1, 5]).copy() points = points_pre[:, :4] sweep_points_list = [points] sweep_times_list = [np.zeros((points.shape[0], 1))] for k in np.random.choice(len(info['sweeps']), max_sweeps - 1, replace=False): points_sweep, times_sweep = self.get_sweep(info['sweeps'][k]) sweep_points_list.append(points_sweep) sweep_times_list.append(times_sweep) points = np.concatenate(sweep_points_list, axis=0) times = np.concatenate(sweep_times_list, axis=0).astype(points.dtype) points = np.concatenate((points, times), axis=1) return points def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) points = self.get_lidar_with_sweeps(index, max_sweeps=self.dataset_cfg.MAX_SWEEPS) if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict = { 'db_flag': "nusc", 'points': points, 'frame_id': Path(info['lidar_path']).stem, 'metadata': {'token': info['token']} } if 'gt_boxes' in info: if self.dataset_cfg.get('FILTER_MIN_POINTS_IN_GT', False): mask = (info['num_lidar_pts'] > self.dataset_cfg.FILTER_MIN_POINTS_IN_GT - 1) else: mask = None input_dict.update({ 'gt_names': info['gt_names'] if mask is None else info['gt_names'][mask], 'gt_boxes': info['gt_boxes'] if mask is None else info['gt_boxes'][mask] }) if self.dataset_cfg.get('SHIFT_COOR', None): input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None # for debug only # gt_boxes_mask = np.array([n in self.class_names for n in input_dict['gt_names']], dtype=np.bool_) # debug_dict = {'gt_boxes': copy.deepcopy(input_dict['gt_boxes'][gt_boxes_mask])} if self.dataset_cfg.get('FOV_POINTS_ONLY', None): input_dict['points'] = self.extract_fov_data( input_dict['points'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) if input_dict['gt_boxes'] is not None: fov_gt_flag = self.extract_fov_gt( input_dict['gt_boxes'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) input_dict.update({ 'gt_names': input_dict['gt_names'][fov_gt_flag], 'gt_boxes': input_dict['gt_boxes'][fov_gt_flag], }) if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) if self.dataset_cfg.get('SET_NAN_VELOCITY_TO_ZEROS', False) and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): gt_boxes = data_dict['gt_boxes'] gt_boxes[np.isnan(gt_boxes)] = 0 data_dict['gt_boxes'] = gt_boxes if not self.dataset_cfg.PRED_VELOCITY and 'gt_boxes' in data_dict and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): data_dict['gt_boxes'] = data_dict['gt_boxes'][:, [0, 1, 2, 3, 4, 5, 6, -1]] return data_dict #@staticmethod def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]), 'pred_labels': np.zeros(num_samples) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes pred_dict['pred_labels'] = pred_labels return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def kitti_eval(self, eval_det_annos, eval_gt_annos, class_names): from ..kitti.kitti_object_eval_python import eval as kitti_eval map_name_to_kitti = { 'car': 'Car', 'pedestrian': 'Pedestrian', 'truck': 'Truck', 'bicycle': 'Cyclist', } def transform_to_kitti_format(annos, info_with_fakelidar=False, is_gt=False): for anno in annos: if 'name' not in anno: anno['name'] = anno['gt_names'] anno.pop('gt_names') for k in range(anno['name'].shape[0]): if anno['name'][k] in map_name_to_kitti: anno['name'][k] = map_name_to_kitti[anno['name'][k]] else: anno['name'][k] = 'Person_sitting' if 'boxes_lidar' in anno: gt_boxes_lidar = anno['boxes_lidar'].copy() else: gt_boxes_lidar = anno['gt_boxes'].copy() # filter by fov if is_gt and self.dataset_cfg.get('GT_FILTER', None): if self.dataset_cfg.GT_FILTER.get('FOV_FILTER', None): fov_gt_flag = self.extract_fov_gt( gt_boxes_lidar, self.dataset_cfg['FOV_DEGREE'], self.dataset_cfg['FOV_ANGLE'] ) gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag] anno['name'] = anno['name'][fov_gt_flag] anno['bbox'] = np.zeros((len(anno['name']), 4)) anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50] anno['truncated'] = np.zeros(len(anno['name'])) anno['occluded'] = np.zeros(len(anno['name'])) if len(gt_boxes_lidar) > 0: if info_with_fakelidar: gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar) gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2 anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3)) anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar dxdydz = gt_boxes_lidar[:, 3:6] anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0 anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y'] else: anno['location'] = anno['dimensions'] = np.zeros((0, 3)) anno['rotation_y'] = anno['alpha'] = np.zeros(0) transform_to_kitti_format(eval_det_annos) transform_to_kitti_format(eval_gt_annos, info_with_fakelidar=False, is_gt=True) kitti_class_names = [] for x in class_names: if x in map_name_to_kitti: kitti_class_names.append(map_name_to_kitti[x]) else: kitti_class_names.append('Person_sitting') ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def nuscene_eval(self, det_annos, class_names, **kwargs): import json from nuscenes.nuscenes import NuScenes from . import nuscenes_utils nusc = NuScenes(version=self.dataset_cfg.VERSION, dataroot=str(self.root_path), verbose=True) nusc_annos = nuscenes_utils.transform_det_annos_to_nusc_annos(det_annos, nusc) nusc_annos['meta'] = { 'use_camera': False, 'use_lidar': True, 'use_radar': False, 'use_map': False, 'use_external': False, } output_path = Path(kwargs['output_path']) output_path.mkdir(exist_ok=True, parents=True) res_path = str(output_path / 'results_nusc.json') with open(res_path, 'w') as f: json.dump(nusc_annos, f) self.logger.info(f'The predictions of NuScenes have been saved to {res_path}') if self.dataset_cfg.VERSION == 'v1.0-test': return 'No ground-truth annotations for evaluation', {} from nuscenes.eval.detection.config import config_factory from nuscenes.eval.detection.evaluate import NuScenesEval eval_set_map = { 'v1.0-mini': 'mini_val', 'v1.0-trainval': 'val', 'v1.0-test': 'test' } try: eval_version = 'detection_cvpr_2019' eval_config = config_factory(eval_version) except: eval_version = 'cvpr_2019' eval_config = config_factory(eval_version) nusc_eval = NuScenesEval( nusc, config=eval_config, result_path=res_path, eval_set=eval_set_map[self.dataset_cfg.VERSION], output_dir=str(output_path), verbose=True, ) metrics_summary = nusc_eval.main(plot_examples=0, render_curves=False) with open(output_path / 'metrics_summary.json', 'r') as f: metrics = json.load(f) result_str, result_dict = nuscenes_utils.format_nuscene_results(metrics, self.class_names, version=eval_version) return result_str, result_dict def evaluation(self, det_annos, class_names, **kwargs): if kwargs['eval_metric'] == 'kitti': eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = copy.deepcopy(self.infos) return self.kitti_eval(eval_det_annos, eval_gt_annos, class_names) elif kwargs['eval_metric'] == 'nuscenes': return self.nuscene_eval(det_annos, class_names, **kwargs) else: raise NotImplementedError def create_groundtruth_database(self, used_classes=None, max_sweeps=10): import torch database_save_path = self.root_path / f'gt_database_{max_sweeps}sweeps_withvelo' db_info_save_path = self.root_path / f'nuscenes_dbinfos_{max_sweeps}sweeps_withvelo.pkl' database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} for idx in tqdm(range(len(self.infos))): sample_idx = idx info = self.infos[idx] points = self.get_lidar_with_sweeps(idx, max_sweeps=max_sweeps) gt_boxes = info['gt_boxes'] gt_names = info['gt_names'] box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(gt_boxes.shape[0]): filename = '%s_%s_%d.bin' % (sample_idx, gt_names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or gt_names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': gt_names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if gt_names[i] in all_db_infos: all_db_infos[gt_names[i]].append(db_info) else: all_db_infos[gt_names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def create_nuscenes_info(version, data_path, save_path, max_sweeps=10): from nuscenes.nuscenes import NuScenes from nuscenes.utils import splits from . import nuscenes_utils data_path = data_path / version save_path = save_path / version assert version in ['v1.0-trainval', 'v1.0-test', 'v1.0-mini'] if version == 'v1.0-trainval': train_scenes = splits.train val_scenes = splits.val elif version == 'v1.0-test': train_scenes = splits.test val_scenes = [] elif version == 'v1.0-mini': train_scenes = splits.mini_train val_scenes = splits.mini_val else: raise NotImplementedError nusc = NuScenes(version=version, dataroot=data_path, verbose=True) available_scenes = nuscenes_utils.get_available_scenes(nusc) available_scene_names = [s['name'] for s in available_scenes] train_scenes = list(filter(lambda x: x in available_scene_names, train_scenes)) val_scenes = list(filter(lambda x: x in available_scene_names, val_scenes)) train_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in train_scenes]) val_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in val_scenes]) print('%s: train scene(%d), val scene(%d)' % (version, len(train_scenes), len(val_scenes))) train_nusc_infos, val_nusc_infos = nuscenes_utils.fill_trainval_infos( data_path=data_path, nusc=nusc, train_scenes=train_scenes, val_scenes=val_scenes, test='test' in version, max_sweeps=max_sweeps ) if version == 'v1.0-test': print('test sample: %d' % len(train_nusc_infos)) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_test.pkl', 'wb') as f: pickle.dump(train_nusc_infos, f) else: print('train sample: %d, val sample: %d' % (len(train_nusc_infos), len(val_nusc_infos))) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_train.pkl', 'wb') as f: pickle.dump(train_nusc_infos, f) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_val.pkl', 'wb') as f: pickle.dump(val_nusc_infos, f) if __name__ == '__main__': import yaml import argparse from pathlib import Path from easydict import EasyDict parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_nuscenes_infos', help='') parser.add_argument('--version', type=str, default='v1.0-trainval', help='') args = parser.parse_args() if args.func == 'create_nuscenes_infos': dataset_cfg = EasyDict(yaml.safe_load(open(args.cfg_file))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.VERSION = args.version create_nuscenes_info( version=dataset_cfg.VERSION, data_path=ROOT_DIR / 'data' / 'nuscenes', save_path=ROOT_DIR / 'data' / 'nuscenes', max_sweeps=dataset_cfg.MAX_SWEEPS, ) nuscenes_dataset = NuScenesDataset( dataset_cfg=dataset_cfg, class_names=None, root_path=ROOT_DIR / 'data' / 'nuscenes', logger=common_utils.create_logger(), training=True ) nuscenes_dataset.create_groundtruth_database(max_sweeps=dataset_cfg.MAX_SWEEPS)
22,903
42.461101
129
py
3DTrans
3DTrans-master/pcdet/datasets/nuscenes/nuscenes_dataset_ada.py
import copy import pickle from pathlib import Path import os import io import numpy as np from tqdm import tqdm from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import common_utils from ..dataset import DatasetTemplate class ActiveNuScenesDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/nuScenes' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None, sample_info_path=None): root_path = (root_path if root_path is not None else Path(dataset_cfg.DATA_PATH)) / dataset_cfg.VERSION super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') # self.oss_data_list = self.list_oss_dir(self.oss_path, with_info=False) # zhangbo: for OSS format, list the nuScenes dataset will cause a Bug, # due to OSS cannot load too many objects self.infos = [] self.include_nuscenes_data(self.mode, sample_info_path) if self.training and self.dataset_cfg.get('BALANCED_RESAMPLING', False): self.infos = self.balanced_infos_resampling(self.infos) def include_nuscenes_data(self, mode, sample_info_path=None): self.logger.info('Loading NuScenes dataset') nuscenes_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if sample_info_path is not None and str(sample_info_path).split(':')[0] != 's3': info_path = sample_info_path if not Path(info_path).exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) nuscenes_infos.extend(infos) elif sample_info_path is not None and str(sample_info_path).split(':')[0] == 's3': info_path = sample_info_path pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) nuscenes_infos.extend(infos) elif self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) nuscenes_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) nuscenes_infos.extend(infos) self.infos.extend(nuscenes_infos) self.logger.info('Total samples for NuScenes dataset: %d' % (len(nuscenes_infos))) def balanced_infos_resampling(self, infos): """ Class-balanced sampling of nuScenes dataset from https://arxiv.org/abs/1908.09492 """ if self.class_names is None: return infos cls_infos = {name: [] for name in self.class_names} for info in infos: for name in set(info['gt_names']): if name in self.class_names: cls_infos[name].append(info) duplicated_samples = sum([len(v) for _, v in cls_infos.items()]) cls_dist = {k: len(v) / duplicated_samples for k, v in cls_infos.items()} sampled_infos = [] frac = 1.0 / len(self.class_names) ratios = [frac / v for v in cls_dist.values()] for cur_cls_infos, ratio in zip(list(cls_infos.values()), ratios): sampled_infos += np.random.choice( cur_cls_infos, int(len(cur_cls_infos) * ratio) ).tolist() self.logger.info('Total samples after balanced resampling: %s' % (len(sampled_infos))) cls_infos_new = {name: [] for name in self.class_names} for info in sampled_infos: for name in set(info['gt_names']): if name in self.class_names: cls_infos_new[name].append(info) cls_dist_new = {k: len(v) / len(sampled_infos) for k, v in cls_infos_new.items()} return sampled_infos def get_sweep(self, sweep_info): def remove_ego_points(points, center_radius=1.0): mask = ~((np.abs(points[:, 0]) < center_radius) & (np.abs(points[:, 1]) < center_radius)) return points[mask] if self.oss_path is None: lidar_path = self.root_path / sweep_info['lidar_path'] points_sweep = np.fromfile(str(lidar_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] else: lidar_path = os.path.join(self.oss_path, sweep_info['lidar_path']) #sdk_local_bytes = self.client.get(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_sweep = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] points_sweep = remove_ego_points(points_sweep).T if sweep_info['transform_matrix'] is not None: num_points = points_sweep.shape[1] points_sweep[:3, :] = sweep_info['transform_matrix'].dot( np.vstack((points_sweep[:3, :], np.ones(num_points))))[:3, :] cur_times = sweep_info['time_lag'] * np.ones((1, points_sweep.shape[1])) return points_sweep.T, cur_times.T def get_lidar_with_sweeps(self, index, max_sweeps=1): info = self.infos[index] if self.oss_path is None: lidar_path = self.root_path / info['lidar_path'] points = np.fromfile(str(lidar_path), dtype=np.float32, count=-1).reshape([-1, 5])[:, :4] else: lidar_path = os.path.join(self.oss_path, info['lidar_path']) #sdk_local_bytes = self.client.get(lidar_path) sdk_local_bytes = self.client.get(lidar_path, update_cache=True) points_pre = np.frombuffer(sdk_local_bytes, dtype=np.float32, count=-1).reshape([-1, 5]).copy() points = points_pre[:, :4] sweep_points_list = [points] sweep_times_list = [np.zeros((points.shape[0], 1))] for k in np.random.choice(len(info['sweeps']), max_sweeps - 1, replace=False): points_sweep, times_sweep = self.get_sweep(info['sweeps'][k]) sweep_points_list.append(points_sweep) sweep_times_list.append(times_sweep) points = np.concatenate(sweep_points_list, axis=0) times = np.concatenate(sweep_times_list, axis=0).astype(points.dtype) points = np.concatenate((points, times), axis=1) return points def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) points = self.get_lidar_with_sweeps(index, max_sweeps=self.dataset_cfg.MAX_SWEEPS) if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict = { 'db_flag': "nusc", 'points': points, 'frame_id': Path(info['lidar_path']).stem, 'metadata': {'token': info['token']} } if 'gt_boxes' in info: if self.dataset_cfg.get('FILTER_MIN_POINTS_IN_GT', False): mask = (info['num_lidar_pts'] > self.dataset_cfg.FILTER_MIN_POINTS_IN_GT - 1) else: mask = None input_dict.update({ 'gt_names': info['gt_names'] if mask is None else info['gt_names'][mask], 'gt_boxes': info['gt_boxes'] if mask is None else info['gt_boxes'][mask] }) if self.dataset_cfg.get('SHIFT_COOR', None): input_dict['gt_boxes'][:, 0:3] += self.dataset_cfg.SHIFT_COOR if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None # for debug only # gt_boxes_mask = np.array([n in self.class_names for n in input_dict['gt_names']], dtype=np.bool_) # debug_dict = {'gt_boxes': copy.deepcopy(input_dict['gt_boxes'][gt_boxes_mask])} if self.dataset_cfg.get('FOV_POINTS_ONLY', None): input_dict['points'] = self.extract_fov_data( input_dict['points'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) if input_dict['gt_boxes'] is not None: fov_gt_flag = self.extract_fov_gt( input_dict['gt_boxes'], self.dataset_cfg.FOV_DEGREE, self.dataset_cfg.FOV_ANGLE ) input_dict.update({ 'gt_names': input_dict['gt_names'][fov_gt_flag], 'gt_boxes': input_dict['gt_boxes'][fov_gt_flag], }) if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) if self.dataset_cfg.get('SETNAN_VELOCITY_TO_ZEROS', False) and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): gt_boxes = input_dict['gt_boxes'] gt_boxes[np.isnan(gt_boxes)] = 0 input_dict['gt_boxes'] = gt_boxes if not self.dataset_cfg.PRED_VELOCITY and 'gt_boxes' in input_dict and not self.dataset_cfg.get('USE_PSEUDO_LABEL', None): input_dict['gt_boxes'] = input_dict['gt_boxes'][:, [0, 1, 2, 3, 4, 5, 6]] data_dict = self.prepare_data(data_dict=input_dict) return data_dict #@staticmethod def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]), 'pred_labels': np.zeros(num_samples) } return ret_dict def generate_single_sample_dict(box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes pred_dict['pred_labels'] = pred_labels return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): single_pred_dict = generate_single_sample_dict(box_dict) single_pred_dict['frame_id'] = batch_dict['frame_id'][index] single_pred_dict['metadata'] = batch_dict['metadata'][index] annos.append(single_pred_dict) return annos def kitti_eval(self, eval_det_annos, eval_gt_annos, class_names): from ..kitti.kitti_object_eval_python import eval as kitti_eval map_name_to_kitti = { 'car': 'Car', 'pedestrian': 'Pedestrian', 'truck': 'Truck', } def transform_to_kitti_format(annos, info_with_fakelidar=False, is_gt=False): for anno in annos: if 'name' not in anno: anno['name'] = anno['gt_names'] anno.pop('gt_names') for k in range(anno['name'].shape[0]): if anno['name'][k] in map_name_to_kitti: anno['name'][k] = map_name_to_kitti[anno['name'][k]] else: anno['name'][k] = 'Person_sitting' if 'boxes_lidar' in anno: gt_boxes_lidar = anno['boxes_lidar'].copy() else: gt_boxes_lidar = anno['gt_boxes'].copy() # filter by fov if is_gt and self.dataset_cfg.get('GT_FILTER', None): if self.dataset_cfg.GT_FILTER.get('FOV_FILTER', None): fov_gt_flag = self.extract_fov_gt( gt_boxes_lidar, self.dataset_cfg['FOV_DEGREE'], self.dataset_cfg['FOV_ANGLE'] ) gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag] anno['name'] = anno['name'][fov_gt_flag] anno['bbox'] = np.zeros((len(anno['name']), 4)) anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50] anno['truncated'] = np.zeros(len(anno['name'])) anno['occluded'] = np.zeros(len(anno['name'])) if len(gt_boxes_lidar) > 0: if info_with_fakelidar: gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar) gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2 anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3)) anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar dxdydz = gt_boxes_lidar[:, 3:6] anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0 anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y'] else: anno['location'] = anno['dimensions'] = np.zeros((0, 3)) anno['rotation_y'] = anno['alpha'] = np.zeros(0) transform_to_kitti_format(eval_det_annos) transform_to_kitti_format(eval_gt_annos, info_with_fakelidar=False, is_gt=True) kitti_class_names = [] for x in class_names: if x in map_name_to_kitti: kitti_class_names.append(map_name_to_kitti[x]) else: kitti_class_names.append('Person_sitting') ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def nuscene_eval(self, det_annos, class_names, **kwargs): import json from nuscenes.nuscenes import NuScenes from . import nuscenes_utils nusc = NuScenes(version=self.dataset_cfg.VERSION, dataroot=str(self.root_path), verbose=True) nusc_annos = nuscenes_utils.transform_det_annos_to_nusc_annos(det_annos, nusc) nusc_annos['meta'] = { 'use_camera': False, 'use_lidar': True, 'use_radar': False, 'use_map': False, 'use_external': False, } output_path = Path(kwargs['output_path']) output_path.mkdir(exist_ok=True, parents=True) res_path = str(output_path / 'results_nusc.json') with open(res_path, 'w') as f: json.dump(nusc_annos, f) self.logger.info(f'The predictions of NuScenes have been saved to {res_path}') if self.dataset_cfg.VERSION == 'v1.0-test': return 'No ground-truth annotations for evaluation', {} from nuscenes.eval.detection.config import config_factory from nuscenes.eval.detection.evaluate import NuScenesEval eval_set_map = { 'v1.0-mini': 'mini_val', 'v1.0-trainval': 'val', 'v1.0-test': 'test' } try: eval_version = 'detection_cvpr_2019' eval_config = config_factory(eval_version) except: eval_version = 'cvpr_2019' eval_config = config_factory(eval_version) nusc_eval = NuScenesEval( nusc, config=eval_config, result_path=res_path, eval_set=eval_set_map[self.dataset_cfg.VERSION], output_dir=str(output_path), verbose=True, ) metrics_summary = nusc_eval.main(plot_examples=0, render_curves=False) with open(output_path / 'metrics_summary.json', 'r') as f: metrics = json.load(f) result_str, result_dict = nuscenes_utils.format_nuscene_results(metrics, self.class_names, version=eval_version) return result_str, result_dict def evaluation(self, det_annos, class_names, **kwargs): if kwargs['eval_metric'] == 'kitti': eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = copy.deepcopy(self.infos) return self.kitti_eval(eval_det_annos, eval_gt_annos, class_names) elif kwargs['eval_metric'] == 'nuscenes': return self.nuscene_eval(det_annos, class_names, **kwargs) else: raise NotImplementedError def create_groundtruth_database(self, used_classes=None, max_sweeps=10): import torch database_save_path = self.root_path / f'gt_database_{max_sweeps}sweeps_withvelo' db_info_save_path = self.root_path / f'nuscenes_dbinfos_{max_sweeps}sweeps_withvelo.pkl' database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} for idx in tqdm(range(len(self.infos))): sample_idx = idx info = self.infos[idx] points = self.get_lidar_with_sweeps(idx, max_sweeps=max_sweeps) gt_boxes = info['gt_boxes'] gt_names = info['gt_names'] box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu( torch.from_numpy(points[:, 0:3]).unsqueeze(dim=0).float().cuda(), torch.from_numpy(gt_boxes[:, 0:7]).unsqueeze(dim=0).float().cuda() ).long().squeeze(dim=0).cpu().numpy() for i in range(gt_boxes.shape[0]): filename = '%s_%s_%d.bin' % (sample_idx, gt_names[i], i) filepath = database_save_path / filename gt_points = points[box_idxs_of_pts == i] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or gt_names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': gt_names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0]} if gt_names[i] in all_db_infos: all_db_infos[gt_names[i]].append(db_info) else: all_db_infos[gt_names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def create_nuscenes_info(version, data_path, save_path, max_sweeps=10): from nuscenes.nuscenes import NuScenes from nuscenes.utils import splits from . import nuscenes_utils data_path = data_path / version save_path = save_path / version assert version in ['v1.0-trainval', 'v1.0-test', 'v1.0-mini'] if version == 'v1.0-trainval': train_scenes = splits.train val_scenes = splits.val elif version == 'v1.0-test': train_scenes = splits.test val_scenes = [] elif version == 'v1.0-mini': train_scenes = splits.mini_train val_scenes = splits.mini_val else: raise NotImplementedError nusc = NuScenes(version=version, dataroot=data_path, verbose=True) available_scenes = nuscenes_utils.get_available_scenes(nusc) available_scene_names = [s['name'] for s in available_scenes] train_scenes = list(filter(lambda x: x in available_scene_names, train_scenes)) val_scenes = list(filter(lambda x: x in available_scene_names, val_scenes)) train_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in train_scenes]) val_scenes = set([available_scenes[available_scene_names.index(s)]['token'] for s in val_scenes]) print('%s: train scene(%d), val scene(%d)' % (version, len(train_scenes), len(val_scenes))) train_nusc_infos, val_nusc_infos = nuscenes_utils.fill_trainval_infos( data_path=data_path, nusc=nusc, train_scenes=train_scenes, val_scenes=val_scenes, test='test' in version, max_sweeps=max_sweeps ) if version == 'v1.0-test': print('test sample: %d' % len(train_nusc_infos)) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_test.pkl', 'wb') as f: pickle.dump(train_nusc_infos, f) else: print('train sample: %d, val sample: %d' % (len(train_nusc_infos), len(val_nusc_infos))) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_train.pkl', 'wb') as f: pickle.dump(train_nusc_infos, f) with open(save_path / f'nuscenes_infos_{max_sweeps}sweeps_val.pkl', 'wb') as f: pickle.dump(val_nusc_infos, f) if __name__ == '__main__': import yaml import argparse from pathlib import Path from easydict import EasyDict parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default=None, help='specify the config of dataset') parser.add_argument('--func', type=str, default='create_nuscenes_infos', help='') parser.add_argument('--version', type=str, default='v1.0-trainval', help='') args = parser.parse_args() if args.func == 'create_nuscenes_infos': dataset_cfg = EasyDict(yaml.safe_load(open(args.cfg_file))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() dataset_cfg.VERSION = args.version create_nuscenes_info( version=dataset_cfg.VERSION, data_path=ROOT_DIR / 'data' / 'nuscenes', save_path=ROOT_DIR / 'data' / 'nuscenes', max_sweeps=dataset_cfg.MAX_SWEEPS, ) nuscenes_dataset = NuScenesDataset( dataset_cfg=dataset_cfg, class_names=None, root_path=ROOT_DIR / 'data' / 'nuscenes', logger=common_utils.create_logger(), training=True ) nuscenes_dataset.create_groundtruth_database(max_sweeps=dataset_cfg.MAX_SWEEPS)
23,617
42.899628
130
py
3DTrans
3DTrans-master/pcdet/datasets/pandaset/pandaset_dataset.py
""" Dataset from Pandaset (Hesai) """ import pickle import os try: import pandas as pd import pandaset as ps except: pass import numpy as np from ..dataset import DatasetTemplate from ...ops.roiaware_pool3d import roiaware_pool3d_utils import torch def pose_dict_to_numpy(pose): """ Conert pandaset pose dict to a numpy vector in order to pass it through the network """ pose_np = [pose["position"]["x"], pose["position"]["y"], pose["position"]["z"], pose["heading"]["w"], pose["heading"]["x"], pose["heading"]["y"], pose["heading"]["z"]] return pose_np def pose_numpy_to_dict(pose): """ Conert pandaset pose dict to a numpy vector in order to pass it through the network """ pose_dict = {'position': {'x': pose[0], 'y': pose[1], 'z': pose[2]}, 'heading': {'w': pose[3], 'x': pose[4], 'y': pose[5], 'z': pose[6]}} return pose_dict class PandasetDataset(DatasetTemplate): def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) if root_path is None: root_path = self.dataset_cfg.DATA_PATH self.dataset = ps.DataSet(os.path.join(root_path, 'dataset')) self.split = self.dataset_cfg.DATA_SPLIT[self.mode] self.pandaset_infos = [] self.include_pandaset_infos(self.mode) def include_pandaset_infos(self, mode): if self.logger is not None: self.logger.info('Loading PandaSet dataset') pandaset_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: info_path = os.path.join(self.root_path, info_path) if not os.path.exists(info_path): continue with open(info_path, 'rb') as f: infos = pickle.load(f) pandaset_infos.extend(infos) self.pandaset_infos.extend(pandaset_infos) if self.logger is not None: self.logger.info('Total samples for PandaSet dataset ({}): {}'.format(self.mode, len(pandaset_infos))) def set_split(self, split): self.sequences = self.dataset_cfg.SEQUENCES[split] self.split = split def __len__(self): return len(self.pandaset_infos) def __getitem__(self, index): """ To support a custom dataset, implement this function to load the raw data (and labels), then transform them to the unified normative coordinate (x pointing forward, z pointing upwards) and call the function self.prepare_data() to process the data and send them to the model. Args: index: Returns: """ info = self.pandaset_infos[index] seq_idx = info['sequence'] pose = self._get_pose(info) points = self._get_lidar_points(info, pose) boxes, labels, zrot_world_to_ego = self._get_annotations(info, pose) pose_np = pose_dict_to_numpy(pose) input_dict = {'points': points, 'gt_boxes': boxes, 'gt_names': labels, 'sequence': int(seq_idx), 'frame_idx': info['frame_idx'], 'zrot_world_to_ego': zrot_world_to_ego, 'pose': pose_dict_to_numpy(pose) } # seq_idx is converted to int because strings can't be passed to # the gpu in pytorch # zrot_world_to_ego is propagated in order to be able to transform the # predicted yaws back to world coordinates data_dict = self.prepare_data(data_dict=input_dict) return data_dict def _get_pose(self, info): seq_idx = info['sequence'] # get pose for world to ego frame transformation if self.dataset[seq_idx].lidar.poses is None: self.dataset[seq_idx].lidar._load_poses() pose = self.dataset[seq_idx].lidar.poses[info['frame_idx']] return pose def _get_lidar_points(self, info, pose): """ Get lidar in the unified normative coordinate system for a given frame The intensity is normalized to fit [0-1] range (pandaset intensity is in [0-255] range) """ # get lidar points lidar_frame = pd.read_pickle(info['lidar_path']) # get points for the required lidar(s) only device = self.dataset_cfg.get('LIDAR_DEVICE', 0) if device != -1: lidar_frame = lidar_frame[lidar_frame.d == device] world_points = lidar_frame.to_numpy() # There seems to be issues with the automatic deletion of pandas datasets sometimes del lidar_frame points_loc = world_points[:, :3] points_int = world_points[:, 3] # nromalize intensity points_int = points_int / 255 ego_points = ps.geometry.lidar_points_to_ego(points_loc, pose) # Pandaset ego coordinates are: # - x pointing to the right # - y pointing to the front # - z pointing up # Normative coordinates are: # - x pointing foreward # - y pointings to the left # - z pointing to the top # So a transformation is required to the match the normative coordinates ego_points = ego_points[:, [1, 0, 2]] # switch x and y ego_points[:, 1] = - ego_points[:, 1] # revert y axis return np.append(ego_points, np.expand_dims(points_int, axis=1), axis=1).astype(np.float32) def _get_annotations(self,info, pose): """ Get box informations in the unified normative coordinate system for a given frame """ # get boxes cuboids = pd.read_pickle(info["cuboids_path"]) device = self.dataset_cfg.get('LIDAR_DEVICE', 0) if device != -1: # keep cuboids that are seen by a given device cuboids = cuboids[cuboids["cuboids.sensor_id"] != 1 - device] xs = cuboids['position.x'].to_numpy() ys = cuboids['position.y'].to_numpy() zs = cuboids['position.z'].to_numpy() dxs = cuboids['dimensions.x'].to_numpy() dys = cuboids['dimensions.y'].to_numpy() dzs = cuboids['dimensions.z'].to_numpy() yaws = cuboids['yaw'].to_numpy() labels = cuboids['label'].to_numpy() del cuboids # There seem to be issues with the automatic deletion of pandas datasets sometimes labels = np.array([self.dataset_cfg.TRAINING_CATEGORIES.get(lab, lab) for lab in labels] ) # Compute the center points coordinates in ego coordinates centers = np.vstack([xs, ys, zs]).T ego_centers = ps.geometry.lidar_points_to_ego(centers, pose) # Compute the yaw in ego coordinates # The following implementation supposes that the pitch of the car is # negligible compared to its yaw, in order to be able to express the # bbox coordinates in the ego coordinate system with an {axis aligned # box + yaw} only representation yaxis_points_from_pose = ps.geometry.lidar_points_to_ego(np.array([[0, 0, 0], [0, 1., 0]]), pose) yaxis_from_pose = yaxis_points_from_pose[1, :] - yaxis_points_from_pose[0, :] if yaxis_from_pose[-1] >= 10**-1: if self.logger is not None: self.logger.warning("The car's pitch is supposed to be negligible " + "sin(pitch) is >= 10**-1 ({})".format(yaxis_from_pose[-1])) # rotation angle in rads of the y axis around thz z axis zrot_world_to_ego = np.arctan2(-yaxis_from_pose[0], yaxis_from_pose[1]) ego_yaws = yaws + zrot_world_to_ego # Pandaset ego coordinates are: # - x pointing to the right # - y pointing to the front # - z pointing up # Normative coordinates are: # - x pointing foreward # - y pointings to the left # - z pointing to the top # So a transformation is required to the match the normative coordinates ego_xs = ego_centers[:, 1] ego_ys = -ego_centers[:, 0] ego_zs = ego_centers[:, 2] ego_dxs = dys ego_dys = dxs # stays >= 0 ego_dzs = dzs ego_boxes = np.vstack([ego_xs, ego_ys, ego_zs, ego_dxs, ego_dys, ego_dzs, ego_yaws]).T return ego_boxes.astype(np.float32), labels, zrot_world_to_ego @staticmethod def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None): """ To support a custom dataset, implement this function to receive the predicted results from the model, and then transform the unified normative coordinate to your required coordinate, and optionally save them to disk. Args: batch_dict: dict of original data from the dataloader pred_dicts: dict of predicted results from the model pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: if it is not None, save the results to this path Returns: """ def generate_single_sample_dataframe(batch_index, box_dict, zrot_world_to_ego, pose): pred_boxes = box_dict["pred_boxes"].cpu().numpy() pred_scores = box_dict["pred_scores"].cpu().numpy() pred_labels = box_dict["pred_labels"].cpu().numpy() zrot = zrot_world_to_ego.cpu().numpy() pose_dict = pose_numpy_to_dict(pose.cpu().numpy()) xs = pred_boxes[:, 0] ys = pred_boxes[:, 1] zs = pred_boxes[:, 2] dxs = pred_boxes[:, 3] dys = pred_boxes[:, 4] dzs = pred_boxes[:, 5] yaws = pred_boxes[:, 6] names = np.array(class_names)[pred_labels - 1] # Predicted labels start on 1 # convert from normative coordinates to pandaset ego coordinates ego_xs = - ys ego_ys = xs ego_zs = zs ego_dxs = dys ego_dys = dxs ego_dzs = dzs ego_yaws = yaws # convert from pandaset ego coordinates to world coordinates # for the moment, an simplified estimation of the ego yaw is computed in __getitem__ # which sets ego_yaw = world_yaw + zrot_world_to_ego world_yaws = ego_yaws - zrot ego_centers = np.vstack([ego_xs, ego_ys, ego_zs]).T world_centers = ps.geometry.ego_to_lidar_points(ego_centers, pose_dict) world_xs = world_centers[:, 0] world_ys = world_centers[:, 1] world_zs = world_centers[:, 2] # dx, dy, dz remain unchanged as the bbox orientation is handled by # the yaw information data_dict = {'position.x': world_xs, 'position.y': world_ys, 'position.z': world_zs, 'dimensions.x': ego_dxs, 'dimensions.y': ego_dys, 'dimensions.z': ego_dzs, 'yaw': world_yaws % (2 * np.pi), 'label': names, 'score': pred_scores } return pd.DataFrame(data_dict) annos = [] for index, box_dict in enumerate(pred_dicts): frame_idx = batch_dict['frame_idx'][index] seq_idx = batch_dict['sequence'][index] zrot = batch_dict['zrot_world_to_ego'][index] pose = batch_dict['pose'][index] single_pred_df = generate_single_sample_dataframe(index, box_dict, zrot, pose) single_pred_dict = {'preds' : single_pred_df, # 'name 'ensures testing the number of detections in a compatible format as kitti 'name' : single_pred_df['label'].tolist(), 'frame_idx': frame_idx, 'sequence': str(seq_idx).zfill(3)} # seq_idx was converted to int in self.__getitem__` because strings # can't be passed to the gpu in pytorch. # To convert it back to a string, we assume that the sequence is # provided in pandaset format with 3 digits if output_path is not None: frame_id = str(int(frame_idx)).zfill(2) seq_id = str(int(seq_idx)).zfill(3) cur_det_file = os.path.join(output_path, seq_id, 'predictions', 'cuboids', ("{}.pkl.gz".format(frame_id))) os.makedirs(os.path.dirname(cur_det_file), exist_ok=True) single_pred_df.to_pickle(cur_det_file) annos.append(single_pred_dict) return annos def get_infos(self): """ Generate the dataset infos dict for each sample of the dataset. For each sample, this dict contains: - the sequence index - the frame index - the path to the lidar data - the path to the bounding box annotations """ infos = [] for seq in self.sequences: s = self.dataset[seq] s.load_lidar() if len(s.lidar.data) > 100: raise ValueError("The implementation for this dataset assumes that each sequence is " + "no longer than 100 frames. The current sequence has {}".format(len(s.lidar.data))) info = [{'sequence': seq, 'frame_idx': ii, 'lidar_path': os.path.join(self.root_path, 'dataset', seq, 'lidar', ("{:02d}.pkl.gz".format(ii))), 'cuboids_path': os.path.join(self.root_path, 'dataset', seq, 'annotations', 'cuboids', ("{:02d}.pkl.gz".format(ii))) } for ii in range(len(s.lidar.data))] infos.extend(info) del self.dataset._sequences[seq] return infos def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): database_save_path = os.path.join(self.root_path, 'gt_database' if split == 'train' else 'gt_database_{}'.format(split)) db_info_save_path = os.path.join(self.root_path, 'pandaset_dbinfos_{}.pkl'.format(split)) os.makedirs(database_save_path, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] sample_idx = info['frame_idx'] pose = self._get_pose(info) points = self._get_lidar_points(info, pose) gt_boxes, names, _ = self._get_annotations(info, pose) num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): tmp_name = names[i].replace("/", "").replace(" ", "") filename = '%s_%s_%d.bin' % (sample_idx, tmp_name, i) filepath = os.path.join(database_save_path, filename) gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'wb') as f: gt_points.tofile(f) if (used_classes is None) or names[i] in used_classes: db_path = os.path.relpath(filepath, self.root_path) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0], 'difficulty': -1} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) def evaluation(self, det_annos, class_names, **kwargs): self.logger.warning('Evaluation is not implemented for Pandaset as there is no official one. ' + 'Returning an empty evaluation result.') ap_result_str = '' ap_dict = {} return ap_result_str, ap_dict def create_pandaset_infos(dataset_cfg, class_names, data_path, save_path): """ Create dataset_infos files in order not to have it in a preprocessed pickle file with the info for each sample See PandasetDataset.get_infos for further details. """ dataset = PandasetDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) for split in ["train", "val", "test"]: print("---------------- Start to generate {} data infos ---------------".format(split)) dataset.set_split(split) infos = dataset.get_infos() file_path = os.path.join(save_path, 'pandaset_infos_{}.pkl'.format(split)) with open(file_path, 'wb') as f: pickle.dump(infos, f) print("Pandaset info {} file is saved to {}".format(split, file_path)) print('------------Start create groundtruth database for data augmentation-----------') dataset = PandasetDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) dataset.set_split("train") dataset.create_groundtruth_database( os.path.join(save_path, 'pandaset_infos_train.pkl'), split="train" ) print('---------------Data preparation Done---------------') if __name__ == '__main__': import sys if sys.argv.__len__() > 1 and sys.argv[1] == 'create_pandaset_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.safe_load(open(sys.argv[2]))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() create_pandaset_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Pedestrian', 'Cyclist'], data_path=ROOT_DIR / 'data' / 'pandaset', save_path=ROOT_DIR / 'data' / 'pandaset' )
19,065
37.910204
157
py
3DTrans
3DTrans-master/pcdet/datasets/kitti/kitti_dataset_ada.py
import copy import pickle import os from random import sample import numpy as np from pathlib import Path from . import kitti_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils, calibration_kitti, common_utils, object3d_kitti from ..dataset import DatasetTemplate # using from skimage import io when preprocessing the KITTI # from skimage import io # Since we use petrel OSS import io class ActiveKittiDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/KITTI' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None, sample_info_path=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.split = self.dataset_cfg.DATA_SPLIT[self.mode] if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') if self.split != 'test': self.root_split_path = os.path.join(self.oss_path, 'training') else: self.root_split_path = os.path.join(self.oss_path, 'testing') else: self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing') split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None self.kitti_infos = [] self.include_kitti_data(self.mode, sample_info_path) def include_kitti_data(self, mode, sample_info_path=None): if self.logger is not None: self.logger.info('Loading KITTI dataset') kitti_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if sample_info_path is not None and str(sample_info_path).split(':')[0] != 's3': info_path = sample_info_path if not Path(info_path).exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) kitti_infos.extend(infos) elif sample_info_path is not None and str(sample_info_path).split(':')[0] == 's3': info_path = sample_info_path pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) kitti_infos.extend(infos) elif self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) kitti_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) kitti_infos.extend(infos) self.kitti_infos.extend(kitti_infos) if self.logger is not None: self.logger.info('Total samples for KITTI dataset: %d' % (len(kitti_infos))) def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing') split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None def get_lidar(self, idx): if self.oss_path is None: lidar_file = self.root_split_path / 'velodyne' / ('%s.bin' % idx) assert lidar_file.exists() points = np.fromfile(str(lidar_file), dtype=np.float32).reshape(-1, 4) else: lidar_file = os.path.join(self.root_split_path, 'velodyne', ('%s.bin' % idx)) sdk_local_bytes = self.client.get(lidar_file, update_cache=True) points = np.frombuffer(sdk_local_bytes, dtype=np.float32).reshape(-1, 4).copy() return points def get_image(self, idx): """ Loads image for a sample Args: idx: int, Sample index Returns: image: (H, W, 3), RGB Image """ img_file = self.root_split_path / 'image_2' / ('%s.png' % idx) assert img_file.exists() image = io.imread(img_file) image = image.astype(np.float32) image /= 255.0 return image def get_image_shape(self, idx): from skimage import io img_file = self.root_split_path / 'image_2' / ('%s.png' % idx) assert img_file.exists() return np.array(io.imread(img_file).shape[:2], dtype=np.int32) def get_label(self, idx): label_file = self.root_split_path / 'label_2' / ('%s.txt' % idx) assert label_file.exists() return object3d_kitti.get_objects_from_label(label_file) def get_depth_map(self, idx): """ Loads depth map for a sample Args: idx: str, Sample index Returns: depth: (H, W), Depth map """ depth_file = self.root_split_path / 'depth_2' / ('%s.png' % idx) assert depth_file.exists() depth = io.imread(depth_file) depth = depth.astype(np.float32) depth /= 256.0 return depth def get_calib(self, idx): if self.oss_path is None: calib_file = self.root_split_path / 'calib' / ('%s.txt' % idx) assert calib_file.exists() calibrated_res = calibration_kitti.Calibration(calib_file, False) else: calib_file = os.path.join(self.root_split_path, 'calib', ('%s.txt' % idx)) text_bytes = self.client.get(calib_file, update_cache=True) text_bytes = text_bytes.decode('utf-8') calibrated_res = calibration_kitti.Calibration(io.StringIO(text_bytes), True) return calibrated_res def get_road_plane(self, idx): if self.oss_path is None: plane_file = self.root_split_path / 'planes' / ('%s.txt' % idx) if not plane_file.exists(): return None with open(plane_file, 'r') as f: lines = f.readlines() else: plane_file = os.path.join(self.root_split_path, 'planes', ('%s.txt' % idx)) text_bytes = self.client.get(plane_file, update_cache=True) text_bytes = text_bytes.decode('utf-8') lines = io.StringIO(text_bytes).readlines() lines = [float(i) for i in lines[3].split()] plane = np.asarray(lines) # Ensure normal is always facing up, this is in the rectified camera coordinate if plane[1] > 0: plane = -plane norm = np.linalg.norm(plane[0:3]) plane = plane / norm return plane @staticmethod def get_fov_flag(pts_rect, img_shape, calib, margin=0): """ Args: pts_rect: img_shape: calib: margin: Returns: """ pts_img, pts_rect_depth = calib.rect_to_img(pts_rect) val_flag_1 = np.logical_and(pts_img[:, 0] >= 0 - margin, pts_img[:, 0] < img_shape[1] + margin) val_flag_2 = np.logical_and(pts_img[:, 1] >= 0 - margin, pts_img[:, 1] < img_shape[0] + margin) val_flag_merge = np.logical_and(val_flag_1, val_flag_2) pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0) return pts_valid_flag def get_infos(self, num_workers=4, has_label=True, count_inside_pts=True, sample_id_list=None): import concurrent.futures as futures def process_single_scene(sample_idx): print('%s sample_idx: %s' % (self.split, sample_idx)) info = {} pc_info = {'num_features': 4, 'lidar_idx': sample_idx} info['point_cloud'] = pc_info image_info = {'image_idx': sample_idx, 'image_shape': self.get_image_shape(sample_idx)} info['image'] = image_info calib = self.get_calib(sample_idx) P2 = np.concatenate([calib.P2, np.array([[0., 0., 0., 1.]])], axis=0) R0_4x4 = np.zeros([4, 4], dtype=calib.R0.dtype) R0_4x4[3, 3] = 1. R0_4x4[:3, :3] = calib.R0 V2C_4x4 = np.concatenate([calib.V2C, np.array([[0., 0., 0., 1.]])], axis=0) calib_info = {'P2': P2, 'R0_rect': R0_4x4, 'Tr_velo_to_cam': V2C_4x4} info['calib'] = calib_info if has_label: obj_list = self.get_label(sample_idx) annotations = {} annotations['name'] = np.array([obj.cls_type for obj in obj_list]) annotations['truncated'] = np.array([obj.truncation for obj in obj_list]) annotations['occluded'] = np.array([obj.occlusion for obj in obj_list]) annotations['alpha'] = np.array([obj.alpha for obj in obj_list]) annotations['bbox'] = np.concatenate([obj.box2d.reshape(1, 4) for obj in obj_list], axis=0) annotations['dimensions'] = np.array([[obj.l, obj.h, obj.w] for obj in obj_list]) # lhw(camera) format annotations['location'] = np.concatenate([obj.loc.reshape(1, 3) for obj in obj_list], axis=0) annotations['rotation_y'] = np.array([obj.ry for obj in obj_list]) annotations['score'] = np.array([obj.score for obj in obj_list]) annotations['difficulty'] = np.array([obj.level for obj in obj_list], np.int32) num_objects = len([obj.cls_type for obj in obj_list if obj.cls_type != 'DontCare']) num_gt = len(annotations['name']) index = list(range(num_objects)) + [-1] * (num_gt - num_objects) annotations['index'] = np.array(index, dtype=np.int32) loc = annotations['location'][:num_objects] dims = annotations['dimensions'][:num_objects] rots = annotations['rotation_y'][:num_objects] loc_lidar = calib.rect_to_lidar(loc) l, h, w = dims[:, 0:1], dims[:, 1:2], dims[:, 2:3] loc_lidar[:, 2] += h[:, 0] / 2 gt_boxes_lidar = np.concatenate([loc_lidar, l, w, h, -(np.pi / 2 + rots[..., np.newaxis])], axis=1) annotations['gt_boxes_lidar'] = gt_boxes_lidar info['annos'] = annotations if count_inside_pts: points = self.get_lidar(sample_idx) calib = self.get_calib(sample_idx) pts_rect = calib.lidar_to_rect(points[:, 0:3]) fov_flag = self.get_fov_flag(pts_rect, info['image']['image_shape'], calib) pts_fov = points[fov_flag] corners_lidar = box_utils.boxes_to_corners_3d(gt_boxes_lidar) num_points_in_gt = -np.ones(num_gt, dtype=np.int32) for k in range(num_objects): flag = box_utils.in_hull(pts_fov[:, 0:3], corners_lidar[k]) num_points_in_gt[k] = flag.sum() annotations['num_points_in_gt'] = num_points_in_gt return info sample_id_list = sample_id_list if sample_id_list is not None else self.sample_id_list with futures.ThreadPoolExecutor(num_workers) as executor: infos = executor.map(process_single_scene, sample_id_list) return list(infos) def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): import torch database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split)) db_info_save_path = Path(self.root_path) / ('kitti_dbinfos_%s.pkl' % split) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] sample_idx = info['point_cloud']['lidar_idx'] points = self.get_lidar(sample_idx) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] bbox = annos['bbox'] gt_boxes = annos['gt_boxes_lidar'] num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): filename = '%s_%s_%d.bin' % (sample_idx, names[i], i) filepath = database_save_path / filename gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0], 'difficulty': difficulty[i], 'bbox': bbox[i], 'score': annos['score'][i]} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) #@staticmethod def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'truncated': np.zeros(num_samples), 'occluded': np.zeros(num_samples), 'alpha': np.zeros(num_samples), 'bbox': np.zeros([num_samples, 4]), 'dimensions': np.zeros([num_samples, 3]), 'location': np.zeros([num_samples, 3]), 'rotation_y': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]) } return ret_dict def generate_single_sample_dict(batch_index, box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict calib = batch_dict['calib'][batch_index] image_shape = batch_dict['image_shape'][batch_index].cpu().numpy() if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR # BOX FILTER if self.dataset_cfg.get('TEST', None) and self.dataset_cfg.TEST.BOX_FILTER['FOV_FILTER']: box_preds_lidar_center = pred_boxes[:, 0:3] pts_rect = calib.lidar_to_rect(box_preds_lidar_center) fov_flag = self.get_fov_flag(pts_rect, image_shape, calib, margin=5) pred_boxes = pred_boxes[fov_flag] pred_labels = pred_labels[fov_flag] pred_scores = pred_scores[fov_flag] pred_boxes_camera = box_utils.boxes3d_lidar_to_kitti_camera(pred_boxes, calib) pred_boxes_img = box_utils.boxes3d_kitti_camera_to_imageboxes( pred_boxes_camera, calib, image_shape=image_shape ) pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['alpha'] = -np.arctan2(-pred_boxes[:, 1], pred_boxes[:, 0]) + pred_boxes_camera[:, 6] pred_dict['bbox'] = pred_boxes_img pred_dict['dimensions'] = pred_boxes_camera[:, 3:6] pred_dict['location'] = pred_boxes_camera[:, 0:3] pred_dict['rotation_y'] = pred_boxes_camera[:, 6] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): frame_id = batch_dict['frame_id'][index] single_pred_dict = generate_single_sample_dict(index, box_dict) single_pred_dict['frame_id'] = frame_id annos.append(single_pred_dict) if output_path is not None: cur_det_file = output_path / ('%s.txt' % frame_id) with open(cur_det_file, 'w') as f: bbox = single_pred_dict['bbox'] loc = single_pred_dict['location'] dims = single_pred_dict['dimensions'] # lhw -> hwl for idx in range(len(bbox)): print('%s -1 -1 %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f' % (single_pred_dict['name'][idx], single_pred_dict['alpha'][idx], bbox[idx][0], bbox[idx][1], bbox[idx][2], bbox[idx][3], dims[idx][1], dims[idx][2], dims[idx][0], loc[idx][0], loc[idx][1], loc[idx][2], single_pred_dict['rotation_y'][idx], single_pred_dict['score'][idx]), file=f) return annos def evaluation(self, det_annos, class_names, **kwargs): if 'annos' not in self.kitti_infos[0].keys(): return None, {} from .kitti_object_eval_python import eval as kitti_eval eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.kitti_infos] ap_result_str, ap_dict = kitti_eval.get_official_eval_result(eval_gt_annos, eval_det_annos, class_names) return ap_result_str, ap_dict def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.kitti_infos) * self.total_epochs return len(self.kitti_infos) def __getitem__(self, index): # index = 4 if self._merge_all_iters_to_one_epoch: index = index % len(self.kitti_infos) info = copy.deepcopy(self.kitti_infos[index]) sample_idx = info['point_cloud']['lidar_idx'] calib = self.get_calib(sample_idx) get_item_list = self.dataset_cfg.get('GET_ITEM_LIST', ['points']) input_dict = { 'db_flag': "kitti", 'frame_id': sample_idx, 'calib': calib, } if 'annos' in info: annos = info['annos'] annos = common_utils.drop_info_with_name(annos, name='DontCare') loc, dims, rots = annos['location'], annos['dimensions'], annos['rotation_y'] gt_names = annos['name'] gt_boxes_camera = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1).astype(np.float32) gt_boxes_lidar = box_utils.boxes3d_kitti_camera_to_lidar(gt_boxes_camera, calib) if self.dataset_cfg.get('SHIFT_COOR', None): gt_boxes_lidar[:, 0:3] += self.dataset_cfg.SHIFT_COOR input_dict.update({ 'gt_names': gt_names, 'gt_boxes': gt_boxes_lidar }) if "gt_boxes2d" in get_item_list: input_dict['gt_boxes2d'] = annos["bbox"] if self.dataset_cfg.get('REMOVE_ORIGIN_GTS', None) and self.training: input_dict['points'] = box_utils.remove_points_in_boxes3d(input_dict['points'], input_dict['gt_boxes']) mask = np.zeros(gt_boxes_lidar.shape[0], dtype=np.bool_) input_dict['gt_boxes'] = input_dict['gt_boxes'][mask] input_dict['gt_names'] = input_dict['gt_names'][mask] if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None road_plane = self.get_road_plane(sample_idx) if road_plane is not None: input_dict['road_plane'] = road_plane # for debug only # gt_boxes_mask = np.array([n in self.class_names for n in input_dict['gt_names']], dtype=np.bool_) # debug_dict = {'gt_boxes': copy.deepcopy(gt_boxes_lidar[gt_boxes_mask])} if "points" in get_item_list: points = self.get_lidar(sample_idx) img_shape = info['image']['image_shape'] if self.dataset_cfg.FOV_POINTS_ONLY: pts_rect = calib.lidar_to_rect(points[:, 0:3]) fov_flag = self.get_fov_flag(pts_rect, img_shape, calib) points = points[fov_flag] if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict['points'] = points if "images" in get_item_list: input_dict['images'] = self.get_image(sample_idx) if "depth_maps" in get_item_list: input_dict['depth_maps'] = self.get_depth_map(sample_idx) if "calib_matricies" in get_item_list: input_dict["trans_lidar_to_cam"], input_dict["trans_cam_to_img"] = kitti_utils.calib_to_matricies(calib) # load saved pseudo label for unlabel data if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) data_dict['image_shape'] = img_shape return data_dict def create_kitti_infos(dataset_cfg, class_names, data_path, save_path, workers=4): dataset = KittiDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) train_split, val_split = 'train', 'val' train_filename = save_path / ('kitti_infos_%s.pkl' % train_split) val_filename = save_path / ('kitti_infos_%s.pkl' % val_split) trainval_filename = save_path / 'kitti_infos_trainval.pkl' test_filename = save_path / 'kitti_infos_test.pkl' print('---------------Start to generate data infos---------------') dataset.set_split(train_split) kitti_infos_train = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True) with open(train_filename, 'wb') as f: pickle.dump(kitti_infos_train, f) print('Kitti info train file is saved to %s' % train_filename) dataset.set_split(val_split) kitti_infos_val = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True) with open(val_filename, 'wb') as f: pickle.dump(kitti_infos_val, f) print('Kitti info val file is saved to %s' % val_filename) with open(trainval_filename, 'wb') as f: pickle.dump(kitti_infos_train + kitti_infos_val, f) print('Kitti info trainval file is saved to %s' % trainval_filename) dataset.set_split('test') kitti_infos_test = dataset.get_infos(num_workers=workers, has_label=False, count_inside_pts=False) with open(test_filename, 'wb') as f: pickle.dump(kitti_infos_test, f) print('Kitti info test file is saved to %s' % test_filename) print('---------------Start create groundtruth database for data augmentation---------------') dataset.set_split(train_split) dataset.create_groundtruth_database(train_filename, split=train_split) print('---------------Data preparation Done---------------') if __name__ == '__main__': import sys if sys.argv.__len__() > 1 and sys.argv[1] == 'create_kitti_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.safe_load(open(sys.argv[2]))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() create_kitti_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Pedestrian', 'Cyclist'], data_path=ROOT_DIR / 'data' / 'kitti', save_path=ROOT_DIR / 'data' / 'kitti' )
25,584
43.036145
140
py
3DTrans
3DTrans-master/pcdet/datasets/kitti/kitti_dataset.py
import copy import pickle import os import numpy as np from . import kitti_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils, calibration_kitti, common_utils, object3d_kitti from ..dataset import DatasetTemplate # using from skimage import io when preprocessing the KITTI # from skimage import io # Since we use petrel OSS import io class KittiDataset(DatasetTemplate): """Petrel Ceph storage backend. 3DTrans supports the reading and writing data from Ceph Usage: self.oss_path = 's3://path/of/KITTI' '~/.petreloss.conf': A config file of Ceph, saving the KEY/ACCESS_KEY of S3 Ceph """ def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.split = self.dataset_cfg.DATA_SPLIT[self.mode] if self.oss_path is not None: from petrel_client.client import Client self.client = Client('~/.petreloss.conf') if self.split != 'test': self.root_split_path = os.path.join(self.oss_path, 'training') else: self.root_split_path = os.path.join(self.oss_path, 'testing') else: self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing') split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None self.kitti_infos = [] self.include_kitti_data(self.mode) def include_kitti_data(self, mode): if self.logger is not None: self.logger.info('Loading KITTI dataset') kitti_infos = [] for info_path in self.dataset_cfg.INFO_PATH[mode]: if self.oss_path is None: info_path = self.root_path / info_path if not info_path.exists(): continue with open(info_path, 'rb') as f: infos = pickle.load(f) kitti_infos.extend(infos) else: info_path = os.path.join(self.oss_path, info_path) #pkl_bytes = self.client.get(info_path) pkl_bytes = self.client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) kitti_infos.extend(infos) self.kitti_infos.extend(kitti_infos) if self.logger is not None: self.logger.info('Total samples for KITTI dataset: %d' % (len(kitti_infos))) def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing') split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None def get_lidar(self, idx): if self.oss_path is None: lidar_file = self.root_split_path / 'velodyne' / ('%s.bin' % idx) assert lidar_file.exists() points = np.fromfile(str(lidar_file), dtype=np.float32).reshape(-1, 4) else: lidar_file = os.path.join(self.root_split_path, 'velodyne', ('%s.bin' % idx)) sdk_local_bytes = self.client.get(lidar_file, update_cache=True) points = np.frombuffer(sdk_local_bytes, dtype=np.float32).reshape(-1, 4).copy() return points def get_image(self, idx): """ Loads image for a sample Args: idx: int, Sample index Returns: image: (H, W, 3), RGB Image """ img_file = self.root_split_path / 'image_2' / ('%s.png' % idx) assert img_file.exists() image = io.imread(img_file) image = image.astype(np.float32) image /= 255.0 return image def get_image_shape(self, idx): from skimage import io img_file = self.root_split_path / 'image_2' / ('%s.png' % idx) assert img_file.exists() return np.array(io.imread(img_file).shape[:2], dtype=np.int32) def get_label(self, idx): label_file = self.root_split_path / 'label_2' / ('%s.txt' % idx) assert label_file.exists() return object3d_kitti.get_objects_from_label(label_file) def get_depth_map(self, idx): """ Loads depth map for a sample Args: idx: str, Sample index Returns: depth: (H, W), Depth map """ depth_file = self.root_split_path / 'depth_2' / ('%s.png' % idx) assert depth_file.exists() depth = io.imread(depth_file) depth = depth.astype(np.float32) depth /= 256.0 return depth def get_calib(self, idx): if self.oss_path is None: calib_file = self.root_split_path / 'calib' / ('%s.txt' % idx) assert calib_file.exists() calibrated_res = calibration_kitti.Calibration(calib_file, False) else: calib_file = os.path.join(self.root_split_path, 'calib', ('%s.txt' % idx)) text_bytes = self.client.get(calib_file, update_cache=True) text_bytes = text_bytes.decode('utf-8') calibrated_res = calibration_kitti.Calibration(io.StringIO(text_bytes), True) return calibrated_res def get_road_plane(self, idx): if self.oss_path is None: plane_file = self.root_split_path / 'planes' / ('%s.txt' % idx) if not plane_file.exists(): return None with open(plane_file, 'r') as f: lines = f.readlines() else: plane_file = os.path.join(self.root_split_path, 'planes', ('%s.txt' % idx)) text_bytes = self.client.get(plane_file, update_cache=True) text_bytes = text_bytes.decode('utf-8') lines = io.StringIO(text_bytes).readlines() lines = [float(i) for i in lines[3].split()] plane = np.asarray(lines) # Ensure normal is always facing up, this is in the rectified camera coordinate if plane[1] > 0: plane = -plane norm = np.linalg.norm(plane[0:3]) plane = plane / norm return plane @staticmethod def get_fov_flag(pts_rect, img_shape, calib, margin=0): """ Args: pts_rect: img_shape: calib: margin: Returns: """ pts_img, pts_rect_depth = calib.rect_to_img(pts_rect) val_flag_1 = np.logical_and(pts_img[:, 0] >= 0 - margin, pts_img[:, 0] < img_shape[1] + margin) val_flag_2 = np.logical_and(pts_img[:, 1] >= 0 - margin, pts_img[:, 1] < img_shape[0] + margin) val_flag_merge = np.logical_and(val_flag_1, val_flag_2) pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0) return pts_valid_flag def get_infos(self, num_workers=4, has_label=True, count_inside_pts=True, sample_id_list=None): import concurrent.futures as futures def process_single_scene(sample_idx): print('%s sample_idx: %s' % (self.split, sample_idx)) info = {} pc_info = {'num_features': 4, 'lidar_idx': sample_idx} info['point_cloud'] = pc_info image_info = {'image_idx': sample_idx, 'image_shape': self.get_image_shape(sample_idx)} info['image'] = image_info calib = self.get_calib(sample_idx) P2 = np.concatenate([calib.P2, np.array([[0., 0., 0., 1.]])], axis=0) R0_4x4 = np.zeros([4, 4], dtype=calib.R0.dtype) R0_4x4[3, 3] = 1. R0_4x4[:3, :3] = calib.R0 V2C_4x4 = np.concatenate([calib.V2C, np.array([[0., 0., 0., 1.]])], axis=0) calib_info = {'P2': P2, 'R0_rect': R0_4x4, 'Tr_velo_to_cam': V2C_4x4} info['calib'] = calib_info if has_label: obj_list = self.get_label(sample_idx) annotations = {} annotations['name'] = np.array([obj.cls_type for obj in obj_list]) annotations['truncated'] = np.array([obj.truncation for obj in obj_list]) annotations['occluded'] = np.array([obj.occlusion for obj in obj_list]) annotations['alpha'] = np.array([obj.alpha for obj in obj_list]) annotations['bbox'] = np.concatenate([obj.box2d.reshape(1, 4) for obj in obj_list], axis=0) annotations['dimensions'] = np.array([[obj.l, obj.h, obj.w] for obj in obj_list]) # lhw(camera) format annotations['location'] = np.concatenate([obj.loc.reshape(1, 3) for obj in obj_list], axis=0) annotations['rotation_y'] = np.array([obj.ry for obj in obj_list]) annotations['score'] = np.array([obj.score for obj in obj_list]) annotations['difficulty'] = np.array([obj.level for obj in obj_list], np.int32) num_objects = len([obj.cls_type for obj in obj_list if obj.cls_type != 'DontCare']) num_gt = len(annotations['name']) index = list(range(num_objects)) + [-1] * (num_gt - num_objects) annotations['index'] = np.array(index, dtype=np.int32) loc = annotations['location'][:num_objects] dims = annotations['dimensions'][:num_objects] rots = annotations['rotation_y'][:num_objects] loc_lidar = calib.rect_to_lidar(loc) l, h, w = dims[:, 0:1], dims[:, 1:2], dims[:, 2:3] loc_lidar[:, 2] += h[:, 0] / 2 gt_boxes_lidar = np.concatenate([loc_lidar, l, w, h, -(np.pi / 2 + rots[..., np.newaxis])], axis=1) annotations['gt_boxes_lidar'] = gt_boxes_lidar info['annos'] = annotations if count_inside_pts: points = self.get_lidar(sample_idx) calib = self.get_calib(sample_idx) pts_rect = calib.lidar_to_rect(points[:, 0:3]) fov_flag = self.get_fov_flag(pts_rect, info['image']['image_shape'], calib) pts_fov = points[fov_flag] corners_lidar = box_utils.boxes_to_corners_3d(gt_boxes_lidar) num_points_in_gt = -np.ones(num_gt, dtype=np.int32) for k in range(num_objects): flag = box_utils.in_hull(pts_fov[:, 0:3], corners_lidar[k]) num_points_in_gt[k] = flag.sum() annotations['num_points_in_gt'] = num_points_in_gt return info sample_id_list = sample_id_list if sample_id_list is not None else self.sample_id_list with futures.ThreadPoolExecutor(num_workers) as executor: infos = executor.map(process_single_scene, sample_id_list) return list(infos) def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'): import torch database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split)) db_info_save_path = Path(self.root_path) / ('kitti_dbinfos_%s.pkl' % split) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) for k in range(len(infos)): print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] sample_idx = info['point_cloud']['lidar_idx'] points = self.get_lidar(sample_idx) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] bbox = annos['bbox'] gt_boxes = annos['gt_boxes_lidar'] num_obj = gt_boxes.shape[0] point_indices = roiaware_pool3d_utils.points_in_boxes_cpu( torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes) ).numpy() # (nboxes, npoints) for i in range(num_obj): filename = '%s_%s_%d.bin' % (sample_idx, names[i], i) filepath = database_save_path / filename gt_points = points[point_indices[i] > 0] gt_points[:, :3] -= gt_boxes[i, :3] with open(filepath, 'w') as f: gt_points.tofile(f) if (used_classes is None) or names[i] in used_classes: db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin db_info = {'name': names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i, 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0], 'difficulty': difficulty[i], 'bbox': bbox[i], 'score': annos['score'][i]} if names[i] in all_db_infos: all_db_infos[names[i]].append(db_info) else: all_db_infos[names[i]] = [db_info] for k, v in all_db_infos.items(): print('Database %s: %d' % (k, len(v))) with open(db_info_save_path, 'wb') as f: pickle.dump(all_db_infos, f) #@staticmethod def generate_prediction_dicts(self, batch_dict, pred_dicts, class_names, output_path=None): """ Args: batch_dict: frame_id: pred_dicts: list of pred_dicts pred_boxes: (N, 7), Tensor pred_scores: (N), Tensor pred_labels: (N), Tensor class_names: output_path: Returns: """ def get_template_prediction(num_samples): ret_dict = { 'name': np.zeros(num_samples), 'truncated': np.zeros(num_samples), 'occluded': np.zeros(num_samples), 'alpha': np.zeros(num_samples), 'bbox': np.zeros([num_samples, 4]), 'dimensions': np.zeros([num_samples, 3]), 'location': np.zeros([num_samples, 3]), 'rotation_y': np.zeros(num_samples), 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7]) } return ret_dict def generate_single_sample_dict(batch_index, box_dict): pred_scores = box_dict['pred_scores'].cpu().numpy() pred_boxes = box_dict['pred_boxes'].cpu().numpy() pred_labels = box_dict['pred_labels'].cpu().numpy() pred_dict = get_template_prediction(pred_scores.shape[0]) if pred_scores.shape[0] == 0: return pred_dict calib = batch_dict['calib'][batch_index] image_shape = batch_dict['image_shape'][batch_index].cpu().numpy() if self.dataset_cfg.get('SHIFT_COOR', None): #print ("*******WARNING FOR SHIFT_COOR:", self.dataset_cfg.SHIFT_COOR) pred_boxes[:, 0:3] -= self.dataset_cfg.SHIFT_COOR # BOX FILTER if self.dataset_cfg.get('TEST', None) and self.dataset_cfg.TEST.BOX_FILTER['FOV_FILTER']: box_preds_lidar_center = pred_boxes[:, 0:3] pts_rect = calib.lidar_to_rect(box_preds_lidar_center) fov_flag = self.get_fov_flag(pts_rect, image_shape, calib, margin=5) pred_boxes = pred_boxes[fov_flag] pred_labels = pred_labels[fov_flag] pred_scores = pred_scores[fov_flag] pred_boxes_camera = box_utils.boxes3d_lidar_to_kitti_camera(pred_boxes, calib) pred_boxes_img = box_utils.boxes3d_kitti_camera_to_imageboxes( pred_boxes_camera, calib, image_shape=image_shape ) pred_dict['name'] = np.array(class_names)[pred_labels - 1] pred_dict['alpha'] = -np.arctan2(-pred_boxes[:, 1], pred_boxes[:, 0]) + pred_boxes_camera[:, 6] pred_dict['bbox'] = pred_boxes_img pred_dict['dimensions'] = pred_boxes_camera[:, 3:6] pred_dict['location'] = pred_boxes_camera[:, 0:3] pred_dict['rotation_y'] = pred_boxes_camera[:, 6] pred_dict['score'] = pred_scores pred_dict['boxes_lidar'] = pred_boxes return pred_dict annos = [] for index, box_dict in enumerate(pred_dicts): frame_id = batch_dict['frame_id'][index] single_pred_dict = generate_single_sample_dict(index, box_dict) single_pred_dict['frame_id'] = frame_id annos.append(single_pred_dict) if output_path is not None: cur_det_file = output_path / ('%s.txt' % frame_id) with open(cur_det_file, 'w') as f: bbox = single_pred_dict['bbox'] loc = single_pred_dict['location'] dims = single_pred_dict['dimensions'] # lhw -> hwl for idx in range(len(bbox)): print('%s -1 -1 %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f' % (single_pred_dict['name'][idx], single_pred_dict['alpha'][idx], bbox[idx][0], bbox[idx][1], bbox[idx][2], bbox[idx][3], dims[idx][1], dims[idx][2], dims[idx][0], loc[idx][0], loc[idx][1], loc[idx][2], single_pred_dict['rotation_y'][idx], single_pred_dict['score'][idx]), file=f) return annos def evaluation(self, det_annos, class_names, **kwargs): if 'annos' not in self.kitti_infos[0].keys(): return None, {} from .kitti_object_eval_python import eval as kitti_eval eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.kitti_infos] ap_result_str, ap_dict = kitti_eval.get_official_eval_result(eval_gt_annos, eval_det_annos, class_names) return ap_result_str, ap_dict def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.kitti_infos) * self.total_epochs return len(self.kitti_infos) def __getitem__(self, index): # index = 4 if self._merge_all_iters_to_one_epoch: index = index % len(self.kitti_infos) info = copy.deepcopy(self.kitti_infos[index]) sample_idx = info['point_cloud']['lidar_idx'] calib = self.get_calib(sample_idx) get_item_list = self.dataset_cfg.get('GET_ITEM_LIST', ['points']) input_dict = { 'db_flag': "kitti", 'frame_id': sample_idx, 'calib': calib, } if 'annos' in info: annos = info['annos'] annos = common_utils.drop_info_with_name(annos, name='DontCare') loc, dims, rots = annos['location'], annos['dimensions'], annos['rotation_y'] gt_names = annos['name'] gt_boxes_camera = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1).astype(np.float32) gt_boxes_lidar = box_utils.boxes3d_kitti_camera_to_lidar(gt_boxes_camera, calib) if self.dataset_cfg.get('SHIFT_COOR', None): gt_boxes_lidar[:, 0:3] += self.dataset_cfg.SHIFT_COOR input_dict.update({ 'gt_names': gt_names, 'gt_boxes': gt_boxes_lidar }) if "gt_boxes2d" in get_item_list: input_dict['gt_boxes2d'] = annos["bbox"] if self.dataset_cfg.get('REMOVE_ORIGIN_GTS', None) and self.training: input_dict['points'] = box_utils.remove_points_in_boxes3d(input_dict['points'], input_dict['gt_boxes']) mask = np.zeros(gt_boxes_lidar.shape[0], dtype=np.bool_) input_dict['gt_boxes'] = input_dict['gt_boxes'][mask] input_dict['gt_names'] = input_dict['gt_names'][mask] if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: input_dict['gt_boxes'] = None # Since we could use the Sim-KITTI, which excludes the ROAD-PLANE if not self.dataset_cfg.get('USE_SIM_DATA', None): road_plane = self.get_road_plane(sample_idx) if road_plane is not None: input_dict['road_plane'] = road_plane # for debug only # gt_boxes_mask = np.array([n in self.class_names for n in input_dict['gt_names']], dtype=np.bool_) # debug_dict = {'gt_boxes': copy.deepcopy(gt_boxes_lidar[gt_boxes_mask])} if "points" in get_item_list: points = self.get_lidar(sample_idx) img_shape = info['image']['image_shape'] if self.dataset_cfg.FOV_POINTS_ONLY: pts_rect = calib.lidar_to_rect(points[:, 0:3]) fov_flag = self.get_fov_flag(pts_rect, img_shape, calib) points = points[fov_flag] if self.dataset_cfg.get('SHIFT_COOR', None): points[:, 0:3] += np.array(self.dataset_cfg.SHIFT_COOR, dtype=np.float32) input_dict['points'] = points if "images" in get_item_list: input_dict['images'] = self.get_image(sample_idx) if "depth_maps" in get_item_list: input_dict['depth_maps'] = self.get_depth_map(sample_idx) if "calib_matricies" in get_item_list: input_dict["trans_lidar_to_cam"], input_dict["trans_cam_to_img"] = kitti_utils.calib_to_matricies(calib) # load saved pseudo label for unlabel data if self.dataset_cfg.get('USE_PSEUDO_LABEL', None) and self.training: self.fill_pseudo_labels(input_dict) data_dict = self.prepare_data(data_dict=input_dict) data_dict['image_shape'] = img_shape return data_dict def create_kitti_infos(dataset_cfg, class_names, data_path, save_path, workers=4): dataset = KittiDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False) train_split, val_split = 'train', 'val' train_filename = save_path / ('kitti_infos_%s.pkl' % train_split) val_filename = save_path / ('kitti_infos_%s.pkl' % val_split) trainval_filename = save_path / 'kitti_infos_trainval.pkl' test_filename = save_path / 'kitti_infos_test.pkl' print('---------------Start to generate data infos---------------') dataset.set_split(train_split) kitti_infos_train = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True) with open(train_filename, 'wb') as f: pickle.dump(kitti_infos_train, f) print('Kitti info train file is saved to %s' % train_filename) dataset.set_split(val_split) kitti_infos_val = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True) with open(val_filename, 'wb') as f: pickle.dump(kitti_infos_val, f) print('Kitti info val file is saved to %s' % val_filename) with open(trainval_filename, 'wb') as f: pickle.dump(kitti_infos_train + kitti_infos_val, f) print('Kitti info trainval file is saved to %s' % trainval_filename) dataset.set_split('test') kitti_infos_test = dataset.get_infos(num_workers=workers, has_label=False, count_inside_pts=False) with open(test_filename, 'wb') as f: pickle.dump(kitti_infos_test, f) print('Kitti info test file is saved to %s' % test_filename) print('---------------Start create groundtruth database for data augmentation---------------') dataset.set_split(train_split) dataset.create_groundtruth_database(train_filename, split=train_split) print('---------------Data preparation Done---------------') if __name__ == '__main__': import sys if sys.argv.__len__() > 1 and sys.argv[1] == 'create_kitti_infos': import yaml from pathlib import Path from easydict import EasyDict dataset_cfg = EasyDict(yaml.safe_load(open(sys.argv[2]))) ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve() create_kitti_infos( dataset_cfg=dataset_cfg, class_names=['Car', 'Pedestrian', 'Cyclist'], data_path=ROOT_DIR / 'data' / 'kitti', save_path=ROOT_DIR / 'data' / 'kitti' )
24,946
42.766667
140
py
3DTrans
3DTrans-master/pcdet/utils/box_utils.py
import numpy as np import scipy import torch import copy from scipy.spatial import Delaunay from ..ops.roiaware_pool3d import roiaware_pool3d_utils from . import common_utils def in_hull(p, hull): """ :param p: (N, K) test points :param hull: (M, K) M corners of a box :return (N) bool """ try: if not isinstance(hull, Delaunay): hull = Delaunay(hull) flag = hull.find_simplex(p) >= 0 except scipy.spatial.qhull.QhullError: print('Warning: not a hull %s' % str(hull)) flag = np.zeros(p.shape[0], dtype=np.bool) return flag def boxes_to_corners_3d(boxes3d): """ 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center Returns: """ boxes3d, is_numpy = common_utils.check_numpy_to_torch(boxes3d) template = boxes3d.new_tensor(( [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], )) / 2 corners3d = boxes3d[:, None, 3:6].repeat(1, 8, 1) * template[None, :, :] corners3d = common_utils.rotate_points_along_z(corners3d.view(-1, 8, 3), boxes3d[:, 6]).view(-1, 8, 3) corners3d += boxes3d[:, None, 0:3] return corners3d.numpy() if is_numpy else corners3d def mask_boxes_outside_range_numpy(boxes, limit_range, min_num_corners=1): """ Args: boxes: (N, 7) [x, y, z, dx, dy, dz, heading, ...], (x, y, z) is the box center limit_range: [minx, miny, minz, maxx, maxy, maxz] min_num_corners: Returns: """ if boxes.shape[1] > 7: boxes = boxes[:, 0:7] corners = boxes_to_corners_3d(boxes) # (N, 8, 3) mask = ((corners >= limit_range[0:3]) & (corners <= limit_range[3:6])).all(axis=2) mask = mask.sum(axis=1) >= min_num_corners # (N) return mask def remove_points_in_boxes3d(points, boxes3d): """ Args: points: (num_points, 3 + C) boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center, each box DO NOT overlaps Returns: """ boxes3d, is_numpy = common_utils.check_numpy_to_torch(boxes3d) points, is_numpy = common_utils.check_numpy_to_torch(points) point_masks = roiaware_pool3d_utils.points_in_boxes_cpu(points[:, 0:3], boxes3d) points = points[point_masks.sum(dim=0) == 0] return points.numpy() if is_numpy else points def boxes3d_kitti_camera_to_lidar(boxes3d_camera, calib): """ Args: boxes3d_camera: (N, 7) [x, y, z, l, h, w, r] in rect camera coords calib: Returns: boxes3d_lidar: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center """ boxes3d_camera_copy = copy.deepcopy(boxes3d_camera) xyz_camera, r = boxes3d_camera_copy[:, 0:3], boxes3d_camera_copy[:, 6:7] l, h, w = boxes3d_camera_copy[:, 3:4], boxes3d_camera_copy[:, 4:5], boxes3d_camera_copy[:, 5:6] xyz_lidar = calib.rect_to_lidar(xyz_camera) xyz_lidar[:, 2] += h[:, 0] / 2 return np.concatenate([xyz_lidar, l, w, h, -(r + np.pi / 2)], axis=-1) def boxes3d_kitti_fakelidar_to_lidar(boxes3d_lidar): """ Args: boxes3d_fakelidar: (N, 7) [x, y, z, w, l, h, r] in old LiDAR coordinates, z is bottom center Returns: boxes3d_lidar: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center """ boxes3d_lidar_copy = copy.deepcopy(boxes3d_lidar) w, l, h = boxes3d_lidar_copy[:, 3:4], boxes3d_lidar_copy[:, 4:5], boxes3d_lidar_copy[:, 5:6] r = boxes3d_lidar_copy[:, 6:7] boxes3d_lidar_copy[:, 2] += h[:, 0] / 2 return np.concatenate([boxes3d_lidar_copy[:, 0:3], l, w, h, -(r + np.pi / 2)], axis=-1) def boxes3d_kitti_lidar_to_fakelidar(boxes3d_lidar): """ Args: boxes3d_lidar: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center Returns: boxes3d_fakelidar: [x, y, z, w, l, h, r] in old LiDAR coordinates, z is bottom center """ boxes3d_lidar_copy = copy.deepcopy(boxes3d_lidar) dx, dy, dz = boxes3d_lidar_copy[:, 3:4], boxes3d_lidar_copy[:, 4:5], boxes3d_lidar_copy[:, 5:6] heading = boxes3d_lidar_copy[:, 6:7] boxes3d_lidar_copy[:, 2] -= dz[:, 0] / 2 return np.concatenate([boxes3d_lidar_copy[:, 0:3], dy, dx, dz, -heading - np.pi / 2], axis=-1) def enlarge_box3d(boxes3d, extra_width=(0, 0, 0)): """ Args: boxes3d: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center extra_width: [extra_x, extra_y, extra_z] Returns: """ boxes3d, is_numpy = common_utils.check_numpy_to_torch(boxes3d) large_boxes3d = boxes3d.clone() large_boxes3d[:, 3:6] += boxes3d.new_tensor(extra_width)[None, :] return large_boxes3d def boxes3d_lidar_to_kitti_camera(boxes3d_lidar, calib): """ :param boxes3d_lidar: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center :param calib: :return: boxes3d_camera: (N, 7) [x, y, z, l, h, w, r] in rect camera coords """ boxes3d_lidar_copy = copy.deepcopy(boxes3d_lidar) xyz_lidar = boxes3d_lidar_copy[:, 0:3] l, w, h = boxes3d_lidar_copy[:, 3:4], boxes3d_lidar_copy[:, 4:5], boxes3d_lidar_copy[:, 5:6] r = boxes3d_lidar_copy[:, 6:7] xyz_lidar[:, 2] -= h.reshape(-1) / 2 xyz_cam = calib.lidar_to_rect(xyz_lidar) # xyz_cam[:, 1] += h.reshape(-1) / 2 r = -r - np.pi / 2 return np.concatenate([xyz_cam, l, h, w, r], axis=-1) def boxes3d_to_corners3d_kitti_camera(boxes3d, bottom_center=True): """ :param boxes3d: (N, 7) [x, y, z, l, h, w, ry] in camera coords, see the definition of ry in KITTI dataset :param bottom_center: whether y is on the bottom center of object :return: corners3d: (N, 8, 3) 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 """ boxes_num = boxes3d.shape[0] l, h, w = boxes3d[:, 3], boxes3d[:, 4], boxes3d[:, 5] x_corners = np.array([l / 2., l / 2., -l / 2., -l / 2., l / 2., l / 2., -l / 2., -l / 2], dtype=np.float32).T z_corners = np.array([w / 2., -w / 2., -w / 2., w / 2., w / 2., -w / 2., -w / 2., w / 2.], dtype=np.float32).T if bottom_center: y_corners = np.zeros((boxes_num, 8), dtype=np.float32) y_corners[:, 4:8] = -h.reshape(boxes_num, 1).repeat(4, axis=1) # (N, 8) else: y_corners = np.array([h / 2., h / 2., h / 2., h / 2., -h / 2., -h / 2., -h / 2., -h / 2.], dtype=np.float32).T ry = boxes3d[:, 6] zeros, ones = np.zeros(ry.size, dtype=np.float32), np.ones(ry.size, dtype=np.float32) rot_list = np.array([[np.cos(ry), zeros, -np.sin(ry)], [zeros, ones, zeros], [np.sin(ry), zeros, np.cos(ry)]]) # (3, 3, N) R_list = np.transpose(rot_list, (2, 0, 1)) # (N, 3, 3) temp_corners = np.concatenate((x_corners.reshape(-1, 8, 1), y_corners.reshape(-1, 8, 1), z_corners.reshape(-1, 8, 1)), axis=2) # (N, 8, 3) rotated_corners = np.matmul(temp_corners, R_list) # (N, 8, 3) x_corners, y_corners, z_corners = rotated_corners[:, :, 0], rotated_corners[:, :, 1], rotated_corners[:, :, 2] x_loc, y_loc, z_loc = boxes3d[:, 0], boxes3d[:, 1], boxes3d[:, 2] x = x_loc.reshape(-1, 1) + x_corners.reshape(-1, 8) y = y_loc.reshape(-1, 1) + y_corners.reshape(-1, 8) z = z_loc.reshape(-1, 1) + z_corners.reshape(-1, 8) corners = np.concatenate((x.reshape(-1, 8, 1), y.reshape(-1, 8, 1), z.reshape(-1, 8, 1)), axis=2) return corners.astype(np.float32) def boxes3d_kitti_camera_to_imageboxes(boxes3d, calib, image_shape=None): """ :param boxes3d: (N, 7) [x, y, z, l, h, w, r] in rect camera coords :param calib: :return: box_2d_preds: (N, 4) [x1, y1, x2, y2] """ corners3d = boxes3d_to_corners3d_kitti_camera(boxes3d) pts_img, _ = calib.rect_to_img(corners3d.reshape(-1, 3)) corners_in_image = pts_img.reshape(-1, 8, 2) min_uv = np.min(corners_in_image, axis=1) # (N, 2) max_uv = np.max(corners_in_image, axis=1) # (N, 2) boxes2d_image = np.concatenate([min_uv, max_uv], axis=1) if image_shape is not None: boxes2d_image[:, 0] = np.clip(boxes2d_image[:, 0], a_min=0, a_max=image_shape[1] - 1) boxes2d_image[:, 1] = np.clip(boxes2d_image[:, 1], a_min=0, a_max=image_shape[0] - 1) boxes2d_image[:, 2] = np.clip(boxes2d_image[:, 2], a_min=0, a_max=image_shape[1] - 1) boxes2d_image[:, 3] = np.clip(boxes2d_image[:, 3], a_min=0, a_max=image_shape[0] - 1) return boxes2d_image def boxes_iou_normal(boxes_a, boxes_b): """ Args: boxes_a: (N, 4) [x1, y1, x2, y2] boxes_b: (M, 4) [x1, y1, x2, y2] Returns: """ assert boxes_a.shape[1] == boxes_b.shape[1] == 4 x_min = torch.max(boxes_a[:, 0, None], boxes_b[None, :, 0]) x_max = torch.min(boxes_a[:, 2, None], boxes_b[None, :, 2]) y_min = torch.max(boxes_a[:, 1, None], boxes_b[None, :, 1]) y_max = torch.min(boxes_a[:, 3, None], boxes_b[None, :, 3]) x_len = torch.clamp_min(x_max - x_min, min=0) y_len = torch.clamp_min(y_max - y_min, min=0) area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1]) area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1]) a_intersect_b = x_len * y_len iou = a_intersect_b / torch.clamp_min(area_a[:, None] + area_b[None, :] - a_intersect_b, min=1e-6) return iou def boxes3d_lidar_to_aligned_bev_boxes(boxes3d): """ Args: boxes3d: (N, 7 + C) [x, y, z, dx, dy, dz, heading] in lidar coordinate Returns: aligned_bev_boxes: (N, 4) [x1, y1, x2, y2] in the above lidar coordinate """ rot_angle = common_utils.limit_period(boxes3d[:, 6], offset=0.5, period=np.pi).abs() choose_dims = torch.where(rot_angle[:, None] < np.pi / 4, boxes3d[:, [3, 4]], boxes3d[:, [4, 3]]) aligned_bev_boxes = torch.cat((boxes3d[:, 0:2] - choose_dims / 2, boxes3d[:, 0:2] + choose_dims / 2), dim=1) return aligned_bev_boxes def boxes3d_nearest_bev_iou(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (N, 7) [x, y, z, dx, dy, dz, heading] Returns: """ boxes_bev_a = boxes3d_lidar_to_aligned_bev_boxes(boxes_a) boxes_bev_b = boxes3d_lidar_to_aligned_bev_boxes(boxes_b) return boxes_iou_normal(boxes_bev_a, boxes_bev_b) def transform_boxes3d(boxes, pose): """ Args: boxes: N * 9 x,y,z,dx,dy,dz,heading,vx,vy pose: Returns: """ center = boxes[:, :3] center = np.concatenate([center, np.ones((center.shape[0], 1))], axis=-1) center = center @ pose.T heading = boxes[:, [6]] + np.arctan2(pose[1, 0], pose[0, 0]) velocity = boxes[:, 7:] velocity = np.concatenate([velocity, np.zeros((velocity.shape[0], 1))], axis=-1) velocity = velocity @ pose[:3, :3].T return np.concatenate([center[:, :3], boxes[:, 3:6], heading, velocity[:, :2]], axis=-1)
11,158
33.981191
118
py
3DTrans
3DTrans-master/pcdet/utils/loss_utils.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from . import box_utils class SigmoidFocalClassificationLoss(nn.Module): """ Sigmoid focal cross entropy loss. """ def __init__(self, gamma: float = 2.0, alpha: float = 0.25): """ Args: gamma: Weighting parameter to balance loss for hard and easy examples. alpha: Weighting parameter to balance loss for positive and negative examples. """ super(SigmoidFocalClassificationLoss, self).__init__() self.alpha = alpha self.gamma = gamma @staticmethod def sigmoid_cross_entropy_with_logits(input: torch.Tensor, target: torch.Tensor): """ PyTorch Implementation for tf.nn.sigmoid_cross_entropy_with_logits: max(x, 0) - x * z + log(1 + exp(-abs(x))) in https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets Returns: loss: (B, #anchors, #classes) float tensor. Sigmoid cross entropy loss without reduction """ loss = torch.clamp(input, min=0) - input * target + \ torch.log1p(torch.exp(-torch.abs(input))) return loss def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: weighted_loss: (B, #anchors, #classes) float tensor after weighting. """ pred_sigmoid = torch.sigmoid(input) alpha_weight = target * self.alpha + (1 - target) * (1 - self.alpha) pt = target * (1.0 - pred_sigmoid) + (1.0 - target) * pred_sigmoid focal_weight = alpha_weight * torch.pow(pt, self.gamma) bce_loss = self.sigmoid_cross_entropy_with_logits(input, target) loss = focal_weight * bce_loss if weights.shape.__len__() == 2 or \ (weights.shape.__len__() == 1 and target.shape.__len__() == 2): weights = weights.unsqueeze(-1) assert weights.shape.__len__() == loss.shape.__len__() return loss * weights class WeightedClassificationLoss(nn.Module): def __init__(self): super(WeightedClassificationLoss, self).__init__() @staticmethod def sigmoid_cross_entropy_with_logits(input: torch.Tensor, target: torch.Tensor): """ PyTorch Implementation for tf.nn.sigmoid_cross_entropy_with_logits: max(x, 0) - x * z + log(1 + exp(-abs(x))) in https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets Returns: loss: (B, #anchors, #classes) float tensor. Sigmoid cross entropy loss without reduction """ loss = torch.clamp(input, min=0) - input * target + \ torch.log1p(torch.exp(-torch.abs(input))) return loss def forward(self, input: torch.Tensor, target: torch.Tensor, weights=None, reduction='none'): """ Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification targets. weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: loss: (B, #anchors) float tensor. Weighted cross entropy loss without reduction """ bce_loss = self.sigmoid_cross_entropy_with_logits(input, target) if weights is not None: if weights.shape.__len__() == 2 or \ (weights.shape.__len__() == 1 and target.shape.__len__() == 2): weights = weights.unsqueeze(-1) assert weights.shape.__len__() == bce_loss.shape.__len__() loss = weights * bce_loss else: loss = bce_loss if reduction == 'none': return loss elif reduction == 'sum': loss = loss.sum(dim=-1) elif reduction == 'mean': loss = loss.mean(dim=-1) return loss class WeightedSmoothL1Loss(nn.Module): """ Code-wise Weighted Smooth L1 Loss modified based on fvcore.nn.smooth_l1_loss https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/smooth_l1_loss.py | 0.5 * x ** 2 / beta if abs(x) < beta smoothl1(x) = | | abs(x) - 0.5 * beta otherwise, where x = input - target. """ def __init__(self, beta: float = 1.0 / 9.0, code_weights: list = None): """ Args: beta: Scalar float. L1 to L2 change point. For beta values < 1e-5, L1 loss is computed. code_weights: (#codes) float list if not None. Code-wise weights. """ super(WeightedSmoothL1Loss, self).__init__() self.beta = beta if code_weights is not None: self.code_weights = np.array(code_weights, dtype=np.float32) self.code_weights = torch.from_numpy(self.code_weights).cuda() @staticmethod def smooth_l1_loss(diff, beta): if beta < 1e-5: loss = torch.abs(diff) else: n = torch.abs(diff) loss = torch.where(n < beta, 0.5 * n ** 2 / beta, n - 0.5 * beta) return loss def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor = None): """ Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targets. weights: (B, #anchors) float tensor if not None. Returns: loss: (B, #anchors) float tensor. Weighted smooth l1 loss without reduction. """ target = torch.where(torch.isnan(target), input, target) # ignore nan targets diff = input - target # code-wise weighting if self.code_weights is not None: diff = diff * self.code_weights.view(1, 1, -1) loss = self.smooth_l1_loss(diff, self.beta) # anchor-wise weighting if weights is not None: assert weights.shape[0] == loss.shape[0] and weights.shape[1] == loss.shape[1] loss = loss * weights.unsqueeze(-1) return loss class WeightedL1Loss(nn.Module): def __init__(self, code_weights: list = None): """ Args: code_weights: (#codes) float list if not None. Code-wise weights. """ super(WeightedL1Loss, self).__init__() if code_weights is not None: self.code_weights = np.array(code_weights, dtype=np.float32) self.code_weights = torch.from_numpy(self.code_weights).cuda() def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor = None): """ Args: input: (B, #anchors, #codes) float tensor. Ecoded predicted locations of objects. target: (B, #anchors, #codes) float tensor. Regression targets. weights: (B, #anchors) float tensor if not None. Returns: loss: (B, #anchors) float tensor. Weighted smooth l1 loss without reduction. """ target = torch.where(torch.isnan(target), input, target) # ignore nan targets diff = input - target # code-wise weighting if self.code_weights is not None: diff = diff * self.code_weights.view(1, 1, -1) loss = torch.abs(diff) # anchor-wise weighting if weights is not None: assert weights.shape[0] == loss.shape[0] and weights.shape[1] == loss.shape[1] loss = loss * weights.unsqueeze(-1) return loss class WeightedBinaryCrossEntropyLoss(nn.Module): """ Transform input to fit the fomation of PyTorch offical cross entropy loss with anchor-wise weighting. """ def __init__(self): super(WeightedBinaryCrossEntropyLoss, self).__init__() def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification targets. weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: loss: (B, #anchors) float tensor. Weighted cross entropy loss without reduction """ loss = F.binary_cross_entropy_with_logits(input, target, reduction='none').mean(dim=-1) * weights return loss class WeightedCrossEntropyLoss(nn.Module): """ Transform input to fit the fomation of PyTorch offical cross entropy loss with anchor-wise weighting. """ def __init__(self): super(WeightedCrossEntropyLoss, self).__init__() def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor): """ Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification targets. weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: loss: (B, #anchors) float tensor. Weighted cross entropy loss without reduction """ input = input.permute(0, 2, 1) target = target.argmax(dim=-1) loss = F.cross_entropy(input, target, reduction='none') * weights return loss class WeightedCrossEntropyLoss_ver1(nn.Module): def __init__(self): super(WeightedCrossEntropyLoss, self).__init__() @staticmethod def sigmoid_cross_entropy_with_logits(input: torch.Tensor, target: torch.Tensor): """ PyTorch Implementation for tf.nn.sigmoid_cross_entropy_with_logits: max(x, 0) - x * z + log(1 + exp(-abs(x))) in https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits Args: input: (B, #anchors, #classes) float tensor. Predicted logits for each class target: (B, #anchors, #classes) float tensor. One-hot encoded classification targets Returns: loss: (B, #anchors, #classes) float tensor. Sigmoid cross entropy loss without reduction """ loss = torch.clamp(input, min=0) - input * target + \ torch.log1p(torch.exp(-torch.abs(input))) return loss def forward(self, input: torch.Tensor, target: torch.Tensor, weights: torch.Tensor, reduction='none'): """ Args: input: (B, #anchors, #classes) float tensor. Predited logits for each class. target: (B, #anchors, #classes) float tensor. One-hot classification targets. weights: (B, #anchors) float tensor. Anchor-wise weights. Returns: loss: (B, #anchors) float tensor. Weighted cross entropy loss without reduction """ loss = self.sigmoid_cross_entropy_with_logits(input, target) if reduction == 'none': return loss elif reduction == 'sum': loss = loss.sum(dim=-1) elif reduction == 'mean': loss = loss.mean(dim=-1) return loss def get_corner_loss_lidar(pred_bbox3d: torch.Tensor, gt_bbox3d: torch.Tensor): """ Args: pred_bbox3d: (N, 7) float Tensor. gt_bbox3d: (N, 7) float Tensor. Returns: corner_loss: (N) float Tensor. """ assert pred_bbox3d.shape[0] == gt_bbox3d.shape[0] pred_box_corners = box_utils.boxes_to_corners_3d(pred_bbox3d) gt_box_corners = box_utils.boxes_to_corners_3d(gt_bbox3d) gt_bbox3d_flip = gt_bbox3d.clone() gt_bbox3d_flip[:, 6] += np.pi gt_box_corners_flip = box_utils.boxes_to_corners_3d(gt_bbox3d_flip) # (N, 8) corner_dist = torch.min(torch.norm(pred_box_corners - gt_box_corners, dim=2), torch.norm(pred_box_corners - gt_box_corners_flip, dim=2)) # (N, 8) corner_loss = WeightedSmoothL1Loss.smooth_l1_loss(corner_dist, beta=1.0) return corner_loss.mean(dim=1) def compute_fg_mask(gt_boxes2d, shape, downsample_factor=1, device=torch.device("cpu")): """ Compute foreground mask for images Args: gt_boxes2d: (B, N, 4), 2D box labels shape: torch.Size or tuple, Foreground mask desired shape downsample_factor: int, Downsample factor for image device: torch.device, Foreground mask desired device Returns: fg_mask (shape), Foreground mask """ fg_mask = torch.zeros(shape, dtype=torch.bool, device=device) # Set box corners gt_boxes2d /= downsample_factor gt_boxes2d[:, :, :2] = torch.floor(gt_boxes2d[:, :, :2]) gt_boxes2d[:, :, 2:] = torch.ceil(gt_boxes2d[:, :, 2:]) gt_boxes2d = gt_boxes2d.long() # Set all values within each box to True B, N = gt_boxes2d.shape[:2] for b in range(B): for n in range(N): u1, v1, u2, v2 = gt_boxes2d[b, n] fg_mask[b, v1:v2, u1:u2] = True return fg_mask def neg_loss_cornernet(pred, gt, mask=None): """ Refer to https://github.com/tianweiy/CenterPoint. Modified focal loss. Exactly the same as CornerNet. Runs faster and costs a little bit more memory Args: pred: (batch x c x h x w) gt: (batch x c x h x w) mask: (batch x h x w) Returns: """ pos_inds = gt.eq(1).float() neg_inds = gt.lt(1).float() neg_weights = torch.pow(1 - gt, 4) loss = 0 pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_weights * neg_inds if mask is not None: mask = mask[:, None, :, :].float() pos_loss = pos_loss * mask neg_loss = neg_loss * mask num_pos = (pos_inds.float() * mask).sum() else: num_pos = pos_inds.float().sum() pos_loss = pos_loss.sum() neg_loss = neg_loss.sum() if num_pos == 0: loss = loss - neg_loss else: loss = loss - (pos_loss + neg_loss) / num_pos return loss class FocalLossCenterNet(nn.Module): """ Refer to https://github.com/tianweiy/CenterPoint """ def __init__(self): super(FocalLossCenterNet, self).__init__() self.neg_loss = neg_loss_cornernet def forward(self, out, target, mask=None): return self.neg_loss(out, target, mask=mask) def _reg_loss(regr, gt_regr, mask): """ Refer to https://github.com/tianweiy/CenterPoint L1 regression loss Args: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects) Returns: """ num = mask.float().sum() mask = mask.unsqueeze(2).expand_as(gt_regr).float() isnotnan = (~ torch.isnan(gt_regr)).float() mask *= isnotnan regr = regr * mask gt_regr = gt_regr * mask loss = torch.abs(regr - gt_regr) loss = loss.transpose(2, 0) loss = torch.sum(loss, dim=2) loss = torch.sum(loss, dim=1) # else: # # D x M x B # loss = loss.reshape(loss.shape[0], -1) # loss = loss / (num + 1e-4) loss = loss / torch.clamp_min(num, min=1.0) # import pdb; pdb.set_trace() return loss def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat class RegLossCenterNet(nn.Module): """ Refer to https://github.com/tianweiy/CenterPoint """ def __init__(self): super(RegLossCenterNet, self).__init__() def forward(self, output, mask, ind=None, target=None): """ Args: output: (batch x dim x h x w) or (batch x max_objects) mask: (batch x max_objects) ind: (batch x max_objects) target: (batch x max_objects x dim) Returns: """ if ind is None: pred = output else: pred = _transpose_and_gather_feat(output, ind) loss = _reg_loss(pred, target, mask) return loss class FastFocalLoss(nn.Module): ''' Reimplemented focal loss, exactly the same as the CornerNet version. Faster and costs much less memory. ''' def __init__(self, alpha, beta): super(FastFocalLoss, self).__init__() self.alpha = alpha self.beta = beta def _gather_feat(self, feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.reshape(-1, dim) return feat def forward(self, out, target, ind, mask, cat): ''' Arguments: out, target: B x C x H x W ind, mask: B x M cat (category id for peaks): B x M ''' mask = mask.float() gt = torch.pow(1 - target, self.beta) neg_loss = torch.log(1 - out + 1e-30) * torch.pow(out, self.alpha) * gt neg_loss = neg_loss.sum() out = out.reshape(out.size(0), -1, out.size(3)) pos_pred_pix = self._gather_feat(out, ind) # B x M x C pos_pred = pos_pred_pix.gather(2, cat.unsqueeze(2)) # B x M num_pos = mask.sum() pos_loss = torch.log(pos_pred + 1e-30) * torch.pow(1 - pos_pred, self.alpha) * \ mask.unsqueeze(2) pos_loss = pos_loss.sum() if num_pos == 0: return - neg_loss return - (pos_loss + neg_loss) / num_pos class BCELoss(nn.Module): def __init__(self): super(BCELoss, self).__init__() def forward(self, pred, target, weights=None): pred = torch.sigmoid(pred) loss = -target * torch.log(pred) - (1 - target) * torch.log(1 - pred) # anchor-wise weighting if weights is not None: assert weights.shape[0] == loss.shape[0] and weights.shape[1] == loss.shape[1] loss = loss * weights.unsqueeze(-1) return loss class RegLoss(nn.Module): '''Regression loss for an output tensor Arguments: output (batch x dim x h x w) mask (batch x max_objects) ind (batch x max_objects) target (batch x max_objects x dim) ''' def __init__(self, code_weights: list = None): super(RegLoss, self).__init__() def _gather_feat(self, feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.reshape(-1, dim) return feat def forward(self, out, target, ind, mask): mask = mask.float().unsqueeze(2) out = out.reshape(out.size(0), -1, out.size(3)) pred = self._gather_feat(out, ind) # B x M x C loss = F.l1_loss(pred * mask, target * mask, reduction='none') loss = loss / (mask.sum() + 1e-4) loss = loss.transpose(2, 0).sum(dim=2).sum(dim=1) return loss
20,744
32.622366
107
py
3DTrans
3DTrans-master/pcdet/utils/box_coder_utils.py
import numpy as np import torch class ResidualCoder(object): def __init__(self, code_size=7, encode_angle_by_sincos=False, **kwargs): super().__init__() self.code_size = code_size self.encode_angle_by_sincos = encode_angle_by_sincos if self.encode_angle_by_sincos: self.code_size += 1 def encode_torch(self, boxes, anchors): """ Args: boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] anchors: (N, 7 + C) [x, y, z, dx, dy, dz, heading or *[cos, sin], ...] Returns: """ anchors[:, 3:6] = torch.clamp_min(anchors[:, 3:6], min=1e-5) boxes[:, 3:6] = torch.clamp_min(boxes[:, 3:6], min=1e-5) xa, ya, za, dxa, dya, dza, ra, *cas = torch.split(anchors, 1, dim=-1) xg, yg, zg, dxg, dyg, dzg, rg, *cgs = torch.split(boxes, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xt = (xg - xa) / diagonal yt = (yg - ya) / diagonal zt = (zg - za) / dza dxt = torch.log(dxg / dxa) dyt = torch.log(dyg / dya) dzt = torch.log(dzg / dza) if self.encode_angle_by_sincos: rt_cos = torch.cos(rg) - torch.cos(ra) rt_sin = torch.sin(rg) - torch.sin(ra) rts = [rt_cos, rt_sin] else: rts = [rg - ra] cts = [g - a for g, a in zip(cgs, cas)] return torch.cat([xt, yt, zt, dxt, dyt, dzt, *rts, *cts], dim=-1) def decode_torch(self, box_encodings, anchors): """ Args: box_encodings: (B, N, 7 + C) or (N, 7 + C) [x, y, z, dx, dy, dz, heading or *[cos, sin], ...] anchors: (B, N, 7 + C) or (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] Returns: """ xa, ya, za, dxa, dya, dza, ra, *cas = torch.split(anchors, 1, dim=-1) if not self.encode_angle_by_sincos: xt, yt, zt, dxt, dyt, dzt, rt, *cts = torch.split(box_encodings, 1, dim=-1) else: xt, yt, zt, dxt, dyt, dzt, cost, sint, *cts = torch.split(box_encodings, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(dxt) * dxa dyg = torch.exp(dyt) * dya dzg = torch.exp(dzt) * dza if self.encode_angle_by_sincos: rg_cos = cost + torch.cos(ra) rg_sin = sint + torch.sin(ra) rg = torch.atan2(rg_sin, rg_cos) else: rg = rt + ra cgs = [t + a for t, a in zip(cts, cas)] return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg, *cgs], dim=-1) class PreviousResidualDecoder(object): def __init__(self, code_size=7, **kwargs): super().__init__() self.code_size = code_size @staticmethod def decode_torch(box_encodings, anchors): """ Args: box_encodings: (B, N, 7 + ?) x, y, z, w, l, h, r, custom values anchors: (B, N, 7 + C) or (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] Returns: """ xa, ya, za, dxa, dya, dza, ra, *cas = torch.split(anchors, 1, dim=-1) xt, yt, zt, wt, lt, ht, rt, *cts = torch.split(box_encodings, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(lt) * dxa dyg = torch.exp(wt) * dya dzg = torch.exp(ht) * dza rg = rt + ra cgs = [t + a for t, a in zip(cts, cas)] return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg, *cgs], dim=-1) class PreviousResidualRoIDecoder(object): def __init__(self, code_size=7, **kwargs): super().__init__() self.code_size = code_size @staticmethod def decode_torch(box_encodings, anchors): """ Args: box_encodings: (B, N, 7 + ?) x, y, z, w, l, h, r, custom values anchors: (B, N, 7 + C) or (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] Returns: """ xa, ya, za, dxa, dya, dza, ra, *cas = torch.split(anchors, 1, dim=-1) xt, yt, zt, wt, lt, ht, rt, *cts = torch.split(box_encodings, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(lt) * dxa dyg = torch.exp(wt) * dya dzg = torch.exp(ht) * dza rg = ra - rt cgs = [t + a for t, a in zip(cts, cas)] return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg, *cgs], dim=-1) class PointResidualCoder(object): def __init__(self, code_size=8, use_mean_size=True, **kwargs): super().__init__() self.code_size = code_size self.use_mean_size = use_mean_size if self.use_mean_size: self.mean_size = torch.from_numpy(np.array(kwargs['mean_size'])).cuda().float() assert self.mean_size.min() > 0 def encode_torch(self, gt_boxes, points, gt_classes=None): """ Args: gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] points: (N, 3) [x, y, z] gt_classes: (N) [1, num_classes] Returns: box_coding: (N, 8 + C) """ gt_boxes[:, 3:6] = torch.clamp_min(gt_boxes[:, 3:6], min=1e-5) xg, yg, zg, dxg, dyg, dzg, rg, *cgs = torch.split(gt_boxes, 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert gt_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[gt_classes - 1] dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xt = (xg - xa) / diagonal yt = (yg - ya) / diagonal zt = (zg - za) / dza dxt = torch.log(dxg / dxa) dyt = torch.log(dyg / dya) dzt = torch.log(dzg / dza) else: xt = (xg - xa) yt = (yg - ya) zt = (zg - za) dxt = torch.log(dxg) dyt = torch.log(dyg) dzt = torch.log(dzg) cts = [g for g in cgs] return torch.cat([xt, yt, zt, dxt, dyt, dzt, torch.cos(rg), torch.sin(rg), *cts], dim=-1) def decode_torch(self, box_encodings, points, pred_classes=None): """ Args: box_encodings: (N, 8 + C) [x, y, z, dx, dy, dz, cos, sin, ...] points: [x, y, z] pred_classes: (N) [1, num_classes] Returns: """ xt, yt, zt, dxt, dyt, dzt, cost, sint, *cts = torch.split(box_encodings, 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert pred_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[pred_classes - 1] dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(dxt) * dxa dyg = torch.exp(dyt) * dya dzg = torch.exp(dzt) * dza else: xg = xt + xa yg = yt + ya zg = zt + za dxg, dyg, dzg = torch.split(torch.exp(box_encodings[..., 3:6]), 1, dim=-1) rg = torch.atan2(sint, cost) cgs = [t for t in cts] return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg, *cgs], dim=-1) class PointResidual_BinOri_Coder(object): def __init__(self, code_size=8, use_mean_size=True, **kwargs): super().__init__() self.bin_size = kwargs.get('bin_size', 12) # self.bin_size = 12 self.code_size = 6 + 2 * self.bin_size self.bin_inter = 2 * np.pi / self.bin_size self.use_mean_size = use_mean_size if self.use_mean_size: self.mean_size = torch.from_numpy(np.array(kwargs['mean_size'])).cuda().float() assert self.mean_size.min() > 0 def encode_torch(self, gt_boxes, points, gt_classes=None): """ Args: gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] points: (N, 3) [x, y, z] gt_classes: (N) [1, num_classes] Returns: box_coding: (N, 8 + C) """ gt_boxes[:, 3:6] = torch.clamp_min(gt_boxes[:, 3:6], min=1e-5) xg, yg, zg, dxg, dyg, dzg, rg, *cgs = torch.split(gt_boxes, 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert gt_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[gt_classes - 1] # gt_classes.unique() dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xt = (xg - xa) / diagonal yt = (yg - ya) / diagonal zt = (zg - za) / dza dxt = torch.log(dxg / dxa) dyt = torch.log(dyg / dya) dzt = torch.log(dzg / dza) else: xt = (xg - xa) yt = (yg - ya) zt = (zg - za) dxt = torch.log(dxg) dyt = torch.log(dyg) dzt = torch.log(dzg) rg = torch.clamp(rg, max=np.pi - 1e-5, min=-np.pi + 1e-5) ################# bin_id = torch.floor((rg + np.pi) / self.bin_inter) # if bin_id.max() >= self.bin_size: # a = 1 bin_res = ((rg + np.pi) - (bin_id * self.bin_inter + self.bin_inter / 2)) / (self.bin_inter / 2) # norm to [-1, 1] cts = [g for g in cgs] return torch.cat([xt, yt, zt, dxt, dyt, dzt, bin_id, bin_res, *cts], dim=-1) def decode_torch(self, box_encodings, points, pred_classes=None): """ Args: box_encodings: (N, 8 + C) [x, y, z, dx, dy, dz, bin_id, bin_res , ...] points: [x, y, z] pred_classes: (N) [1, num_classes] Returns: """ xt, yt, zt, dxt, dyt, dzt = torch.split(box_encodings[..., :6], 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert pred_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[pred_classes - 1] dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(dxt) * dxa dyg = torch.exp(dyt) * dya dzg = torch.exp(dzt) * dza else: xg = xt + xa yg = yt + ya zg = zt + za dxg, dyg, dzg = torch.split(torch.exp(box_encodings[..., 3:6]), 1, dim=-1) bin_id = box_encodings[..., 6:6+self.bin_size] bin_res = box_encodings[..., 6+self.bin_size:] _, bin_id = torch.max(bin_id, dim=-1) bin_id_one_hot = torch.nn.functional.one_hot(bin_id.long(), self.bin_size) bin_res = torch.sum(bin_res * bin_id_one_hot.float(), dim=-1) rg = bin_id.float() * self.bin_inter - np.pi + self.bin_inter / 2 rg = rg + bin_res * (self.bin_inter / 2) rg = rg.unsqueeze(-1) return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg], dim=-1) class PointBinResidualCoder(object): def __init__(self, code_size=30, use_mean_size=True, angle_bin_num=12, pred_velo=False, **kwargs): super().__init__() self.code_size = 6 + 2 * angle_bin_num self.angle_bin_num = angle_bin_num self.pred_velo = pred_velo if pred_velo: self.code_size += 2 self.use_mean_size = use_mean_size if self.use_mean_size: self.mean_size = torch.from_numpy(np.array(kwargs['mean_size'])).cuda().float() assert self.mean_size.min() > 0 def encode_angle_torch(self, angle): """ Args: angle: (N) Returns: angle_cls: (N, angle_bin_num) angle_res: (N, angle_bin_num) """ angle = torch.remainder(angle, np.pi * 2.0) # -pi, pi -> 0, 2pi angle_per_class = np.pi * 2.0 / float(self.angle_bin_num) #0.5235987755982988 (pi/6) shifted_angle = torch.remainder(angle + angle_per_class / 2.0, np.pi * 2.0) angle_cls_f = (shifted_angle / angle_per_class).floor() angle_cls = angle_cls_f.new_zeros(*list(angle_cls_f.shape), self.angle_bin_num) angle_cls.scatter_(-1, angle_cls_f.unsqueeze(-1).long(), 1.0) angle_res = shifted_angle - (angle_cls_f * angle_per_class + angle_per_class / 2.0) angle_res = angle_res / angle_per_class # normalize residual angle to [0, 1] angle_res = angle_cls * angle_res.unsqueeze(-1) return angle_cls, angle_res def decode_angle_torch(self, angle_cls, angle_res): """ Args: angle_cls: (N, angle_bin_num) angle_res: (N, angle_bin_num) Returns: angle: (N) """ angle_cls_idx = angle_cls.argmax(dim=-1) angle_cls_onehot = angle_cls.new_zeros(angle_cls.shape) angle_cls_onehot.scatter_(-1, angle_cls_idx.unsqueeze(-1), 1.0) angle_res = (angle_cls_onehot * angle_res).sum(dim=-1) angle = (angle_cls_idx.float() + angle_res) * (np.pi * 2.0 / float(self.angle_bin_num)) return angle def encode_torch(self, gt_boxes, points, gt_classes=None): """ Args: gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...] points: (N, 3) [x, y, z] gt_classes: (N) [1, num_classes] Returns: box_coding: (N, 6 + 2 * B + C) """ gt_boxes[:, 3:6] = torch.clamp_min(gt_boxes[:, 3:6], min=1e-5) xg, yg, zg, dxg, dyg, dzg, rg, *cgs = torch.split(gt_boxes, 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert gt_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[gt_classes - 1] dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xt = (xg - xa) / diagonal yt = (yg - ya) / diagonal zt = (zg - za) / dza dxt = torch.log(dxg / dxa) dyt = torch.log(dyg / dya) dzt = torch.log(dzg / dza) else: xt = (xg - xa) yt = (yg - ya) zt = (zg - za) dxt = torch.log(dxg) dyt = torch.log(dyg) dzt = torch.log(dzg) rg_cls, rg_reg = self.encode_angle_torch(rg.squeeze(-1)) cts = [g for g in cgs] return torch.cat([xt, yt, zt, dxt, dyt, dzt, rg_cls, rg_reg, *cts], dim=-1) def decode_torch_kernel(self, box_offsets, box_angle_cls, box_angle_reg, points, pred_classes=None): """ Args: box_offsets: (N, 6) [x, y, z, dx, dy, dz] box_angle_cls: (N, angle_bin_num) box_angle_reg: (N, angle_bin_num) points: [x, y, z] pred_classes: (N) [1, num_classes] Returns: boxes3d: (N, 7) """ xt, yt, zt, dxt, dyt, dzt = torch.split(box_offsets, 1, dim=-1) xa, ya, za = torch.split(points, 1, dim=-1) if self.use_mean_size: assert pred_classes.max() <= self.mean_size.shape[0] point_anchor_size = self.mean_size[pred_classes - 1] dxa, dya, dza = torch.split(point_anchor_size, 1, dim=-1) diagonal = torch.sqrt(dxa ** 2 + dya ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya zg = zt * dza + za dxg = torch.exp(dxt) * dxa dyg = torch.exp(dyt) * dya dzg = torch.exp(dzt) * dza else: xg = xt + xa yg = yt + ya zg = zt + za dxg = torch.exp(dxt) dyg = torch.exp(dyt) dzg = torch.exp(dzt) rg = self.decode_angle_torch(box_angle_cls, box_angle_reg).unsqueeze(-1) return torch.cat([xg, yg, zg, dxg, dyg, dzg, rg], dim=-1) def decode_torch(self, box_encodings, points, pred_classes=None): """ Args: box_encodings: (N, 8 + C) [x, y, z, dx, dy, dz, bin_id, bin_res , ...] points: [x, y, z] pred_classes: (N) [1, num_classes] Returns: boxes3d: (N, 7) """ box_offsets = box_encodings[:, :6] box_angle_cls = box_encodings[:, 6:6 + self.angle_bin_num] box_angle_reg = box_encodings[:, 6 + self.angle_bin_num:6 + self.angle_bin_num * 2] cgs = box_encodings[:, 6 + self.angle_bin_num * 2:] boxes3d = self.decode_torch_kernel(box_offsets, box_angle_cls, box_angle_reg, points, pred_classes) return torch.cat([boxes3d, cgs], dim=-1)
17,075
36.041215
123
py
3DTrans
3DTrans-master/pcdet/utils/active_learning_2D_utils.py
import enum import io import os import tqdm import pickle import random import torch import numpy as np import torch.nn as nn import torch.distributed as dist import torch.nn.functional as F from pathlib import Path from pcdet.models import load_data_to_gpu from pcdet.utils import common_utils, commu_utils from sklearn.cluster import KMeans from sklearn.metrics.pairwise import euclidean_distances def active_evaluate(model, target_loader, rank): if rank == 0: print("======> Active Evaluate <======") dataloader_iter_tar = iter(target_loader) total_iter_tar = len(dataloader_iter_tar) frame_scores = [] return_scores = [] model.eval() if rank == 0: pbar = tqdm.tqdm(total=total_iter_tar, leave=False, desc='active_evaluate', dynamic_ncols=True) for cur_it in range(total_iter_tar): try: batch = next(dataloader_iter_tar) except StopIteration: dataloader_iter_tar = iter(target_loader) batch = next(dataloader_iter_tar) print('new iter') with torch.no_grad(): load_data_to_gpu(batch) forward_args = { 'mode': 'active_evaluate' } sample_score = model(batch, **forward_args) frame_scores.append(sample_score) if rank == 0: pbar.update() pbar.refresh() if rank == 0: pbar.close() gather_scores = gather_all_scores(frame_scores) for score in gather_scores: for f_score in score: return_scores += f_score return return_scores def active_evaluate_dual(model, target_loader, rank, domain): if rank == 0: print("======> Active Evaluate <======") dataloader_iter_tar = iter(target_loader) total_iter_tar = len(dataloader_iter_tar) frame_scores = [] return_scores = [] model.eval() if rank == 0: pbar = tqdm.tqdm(total=total_iter_tar, leave=False, desc='active_evaluate', dynamic_ncols=True) for cur_it in range(total_iter_tar): try: batch = next(dataloader_iter_tar) except StopIteration: dataloader_iter_tar = iter(target_loader) batch = next(dataloader_iter_tar) print('new iter') with torch.no_grad(): load_data_to_gpu(batch) forward_args = { 'mode': 'active_evaluate', 'domain': domain } sample_score = model(batch, **forward_args) frame_scores.append(sample_score) if rank == 0: pbar.update() pbar.refresh() if rank == 0: pbar.close() gather_scores = gather_all_scores(frame_scores) for score in gather_scores: for f_score in score: return_scores += f_score return return_scores # evaluate all frame (including sampled frame) def active_evaluate_dual_2(model, target_loader, rank, domain, sampled_frame_id=None): if rank == 0: print("======> Active Evaluate <======") dataloader_iter_tar = iter(target_loader) total_iter_tar = len(dataloader_iter_tar) frame_scores = [] sampled_frame_scores = [] return_scores = [] model.eval() if rank == 0: pbar = tqdm.tqdm(total=total_iter_tar, leave=False, desc='active_evaluate', dynamic_ncols=True) for cur_it in range(total_iter_tar): try: batch = next(dataloader_iter_tar) except StopIteration: dataloader_iter_tar = iter(target_loader) batch = next(dataloader_iter_tar) print('new iter') with torch.no_grad(): load_data_to_gpu(batch) forward_args = { 'mode': 'active_evaluate', 'domain': domain } sample_score = model(batch, **forward_args) frame_scores.append(sample_score) if rank == 0: pbar.update() pbar.refresh() if rank == 0: pbar.close() gather_scores = gather_all_scores(frame_scores) for score in gather_scores: for f_score in score: return_scores += f_score for i, score in enumerate(return_scores): if score['frame_id'] in sampled_frame_id: sampled_frame_scores.append(score) return_scores.pop(i) return return_scores, sampled_frame_scores def gather_all_scores(frame_scores): commu_utils.synchronize() if dist.is_initialized(): scores = commu_utils.all_gather(frame_scores) else: scores = [frame_scores] commu_utils.synchronize() return scores def distributed_concat(tensor): output_tensor = [tensor.clone() for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(output_tensor, tensor) concat_tensor = torch.cat(output_tensor, dim=0) return concat_tensor def get_target_list(target_pkl_file, oss): if oss == True: from petrel_client.client import Client client = Client('~/.petreloss.conf') pkl_bytes = client.get(target_pkl_file, update_cache=True) target_list = pickle.load(io.BytesIO(pkl_bytes)) else: with open(target_pkl_file, 'rb') as f: target_list = pickle.load(f) return target_list def get_dataset_list(dataset_file, oss, sample_interval=10, waymo=False): if oss == True: from petrel_client.client import Client client = Client('~/.petreloss.conf') if waymo == False: if oss == True: # from petrel_client.client import Client # client = Client('~/.petreloss.conf') pkl_bytes = client.get(dataset_file, update_cache=True) target_list = pickle.load(io.BytesIO(pkl_bytes)) else: with open(dataset_file, 'rb') as f: target_list = pickle.load(f) else: data_path = '../data/waymo/ImageSets/train.txt' target_list = [] sample_sequence_list = [x.strip() for x in open(data_path).readlines()] for k in tqdm.tqdm(range(len(sample_sequence_list))): sequence_name = os.path.splitext(sample_sequence_list[k])[0] if oss == False: info_path = Path(dataset_file) / sequence_name / ('%s.pkl' % sequence_name) if not Path(info_path).exists(): continue else: info_path = os.path.join(dataset_file, sequence_name, ('%s.pkl' % sequence_name)) # if not Path(info_path).exists(): # continue if oss == False: with open(info_path, 'rb') as f: infos = pickle.load(f) target_list.extend(infos) else: pkl_bytes = client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) target_list.extend(infos) if sample_interval > 1: sampled_waymo_infos = [] for k in range(0, len(target_list), sample_interval): sampled_waymo_infos.append(target_list[k]) target_list = sampled_waymo_infos return target_list def update_sample_list(sample_list, target_list, sample_frame_id, epoch, save_path, target_name, rank): if target_name == 'ActiveKittiDataset': new_sample_list = [item for item in target_list if item['point_cloud']['lidar_idx'] in sample_frame_id] elif target_name == 'ActiveNuScenesDataset': new_sample_list = [item for item in target_list if Path(item['lidar_path']).stem in sample_frame_id] sample_list = sample_list + new_sample_list sample_list_path = save_path / ('epoch-%d_sample_list.pkl' % epoch) if rank == 0: with open(sample_list_path, 'wb') as f: pickle.dump(sample_list, f) commu_utils.synchronize() return sample_list, sample_list_path def update_sample_list_dual(sample_list, dataset_list, sample_frame_id, epoch, save_path, dataset_name, rank, domain='source'): if dataset_name == 'ActiveKittiDataset': assert domain == 'target' new_sample_list = [item for item in dataset_list if item['point_cloud']['lidar_idx'] in sample_frame_id] sample_list = sample_list + new_sample_list elif dataset_name == 'ActiveNuScenesDataset': if domain == 'target': new_sample_list = [item for item in dataset_list if Path(item['lidar_path']).stem in sample_frame_id] sample_list = sample_list + new_sample_list else: sample_list = [item for item in dataset_list if Path(item['lidar_path']).stem in sample_frame_id] elif dataset_name == 'ActiveWaymoDataset': assert domain == 'source' # if rank == 0: # print(sample_frame_id) sample_list = [item for item in dataset_list if str(item['frame_id']) in sample_frame_id] # if rank == 0: # print('dataset_list: %d' % len(dataset_list)) # print('sample frame number: %d' % len(sample_list)) sample_list_path = save_path / ('epoch-%d_sample_list_' % epoch + '_' + domain + '.pkl') if rank == 0: with open(sample_list_path, 'wb') as f: pickle.dump(sample_list, f) commu_utils.synchronize() return sample_list, sample_list_path def update_target_list(target_list, sample_frame_id, epoch, save_path, target_name, rank): if target_name == 'ActiveKittiDataset': target_list = [item for item in target_list if item['point_cloud']['lidar_idx'] not in sample_frame_id] elif target_name == 'ActiveNuScenesDataset': target_list = [item for item in target_list if Path(item['lidar_path']).stem not in sample_frame_id] target_list_path = save_path / ('epoch-%d_target_list.pkl' % epoch) if rank == 0: with open(target_list_path, 'wb') as f: pickle.dump(target_list, f) commu_utils.synchronize() return target_list, target_list_path def active_sample(frame_scores, budget): frame_sorted = sorted(frame_scores, key=lambda keys: keys.get("total_score"), reverse=True) sampled_frame_info = frame_sorted[:budget] sampled_frame_id = [frame['frame_id'] for frame in sampled_frame_info] # fused_frame_info = [item for item in frame_scores if item['total_score'] > 0] # print('fused_frame: %d' % len(fused_frame_info)) return sampled_frame_id, sampled_frame_info def active_sample_source(frame_scores, budget): sampled_frame_info = [item for item in frame_scores if item['total_score'] > 0] sampled_frame_id = [frame['frame_id'] for frame in sampled_frame_info] return sampled_frame_id, sampled_frame_info def active_sample_CLUE(frame_scores, budget): roi_feature = frame_scores[0].get('roi_feature', None) tgt_emb_pen = roi_feature.new_zeros((len(frame_scores), roi_feature.shape[-1])) tgt_scores = roi_feature.new_zeros((len(frame_scores), 1)) for i, cur_score in enumerate (frame_scores): cur_feature = cur_score.get('roi_feature', None).to(tgt_emb_pen.device) cur_roi_score = cur_score.get('roi_score', None).to(tgt_scores.device) tgt_emb_pen[i] = cur_feature tgt_scores[i] = cur_roi_score tgt_emb_pen = tgt_emb_pen.cpu().numpy() tgt_scores = tgt_scores.view(-1) sample_weights = -(tgt_scores*torch.log(tgt_scores)).cpu().numpy() km = KMeans(budget) km.fit(tgt_emb_pen, sample_weight=sample_weights) dists = euclidean_distances(km.cluster_centers_, tgt_emb_pen) sort_idxs = dists.argsort(axis=1) q_idxs = [] ax, rem = 0, budget while rem > 0: q_idxs.extend(list(sort_idxs[:, ax][:rem])) q_idxs = list(set(q_idxs)) rem = budget - len(q_idxs) ax += 1 sample_frame_info = [] sample_frame_id = [] for i, cur_score in enumerate(frame_scores): if i in q_idxs: sample_frame_info.append(cur_score) sample_frame_id.append(cur_score.get('frame_id')) return sample_frame_id, sample_frame_info
12,079
36.055215
127
py
3DTrans
3DTrans-master/pcdet/utils/common_utils.py
import logging import os import pickle import random import shutil import subprocess import SharedArray import numpy as np import torch import torch.distributed as dist import torch.multiprocessing as mp from torch.autograd import Variable,Function from ..utils.spconv_utils import spconv def check_numpy_to_torch(x): if isinstance(x, np.ndarray): return torch.from_numpy(x).float(), True elif isinstance(x, (int, float)): # modified d = np.array([x],dtype=np.float32) return torch.from_numpy(d).float(), True return x, False def limit_period(val, offset=0.5, period=np.pi): val, is_numpy = check_numpy_to_torch(val) ans = val - torch.floor(val / period + offset) * period return ans.numpy() if is_numpy else ans def drop_info_with_name(info, name): ret_info = {} keep_indices = [i for i, x in enumerate(info['name']) if x != name] for key in info.keys(): ret_info[key] = info[key][keep_indices] return ret_info def rotate_points_along_z(points, angle): """ Args: points: (B, N, 3 + C) angle: (B), angle along z-axis, angle increases x ==> y Returns: """ points, is_numpy = check_numpy_to_torch(points) angle, _ = check_numpy_to_torch(angle) cosa = torch.cos(angle) sina = torch.sin(angle) zeros = angle.new_zeros(points.shape[0]) ones = angle.new_ones(points.shape[0]) rot_matrix = torch.stack(( cosa, sina, zeros, -sina, cosa, zeros, zeros, zeros, ones ), dim=1).view(-1, 3, 3).float() points_rot = torch.matmul(points[:, :, 0:3], rot_matrix) points_rot = torch.cat((points_rot, points[:, :, 3:]), dim=-1) return points_rot.numpy() if is_numpy else points_rot def mask_points_by_range(points, limit_range): mask = (points[:, 0] >= limit_range[0]) & (points[:, 0] <= limit_range[3]) \ & (points[:, 1] >= limit_range[1]) & (points[:, 1] <= limit_range[4]) return mask def get_voxel_centers(voxel_coords, downsample_times, voxel_size, point_cloud_range): """ Args: voxel_coords: (N, 3) downsample_times: voxel_size: point_cloud_range: Returns: """ assert voxel_coords.shape[1] == 3 voxel_centers = voxel_coords[:, [2, 1, 0]].float() # (xyz) voxel_size = torch.tensor(voxel_size, device=voxel_centers.device).float() * downsample_times pc_range = torch.tensor(point_cloud_range[0:3], device=voxel_centers.device).float() voxel_centers = (voxel_centers + 0.5) * voxel_size + pc_range return voxel_centers def create_logger(log_file=None, rank=0, log_level=logging.INFO): logger = logging.getLogger(__name__) logger.setLevel(log_level if rank == 0 else 'ERROR') formatter = logging.Formatter('%(asctime)s %(filename)s %(funcName)s %(lineno)d %(levelname)5s %(message)s') console = logging.StreamHandler() console.setLevel(log_level if rank == 0 else 'ERROR') console.setFormatter(formatter) logger.addHandler(console) if log_file is not None: file_handler = logging.FileHandler(filename=log_file) file_handler.setLevel(log_level if rank == 0 else 'ERROR') file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.propagate = False return logger def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def get_pad_params(desired_size, cur_size): """ Get padding parameters for np.pad function Args: desired_size: int, Desired padded output size cur_size: int, Current size. Should always be less than or equal to cur_size Returns: pad_params: tuple(int), Number of values padded to the edges (before, after) """ assert desired_size >= cur_size # Calculate amount to pad diff = desired_size - cur_size pad_params = (0, diff) return pad_params def keep_arrays_by_name(gt_names, used_classes): inds = [i for i, x in enumerate(gt_names) if x in used_classes] inds = np.array(inds, dtype=np.int64) return inds def init_dist_slurm(tcp_port, local_rank, backend='nccl'): """ modified from https://github.com/open-mmlab/mmdetection Args: tcp_port: backend: Returns: """ proc_id = int(os.environ['SLURM_PROCID']) ntasks = int(os.environ['SLURM_NTASKS']) node_list = os.environ['SLURM_NODELIST'] num_gpus = torch.cuda.device_count() torch.cuda.set_device(proc_id % num_gpus) addr = subprocess.getoutput('scontrol show hostname {} | head -n1'.format(node_list)) os.environ['MASTER_PORT'] = str(tcp_port) os.environ['MASTER_ADDR'] = addr os.environ['WORLD_SIZE'] = str(ntasks) os.environ['RANK'] = str(proc_id) dist.init_process_group(backend=backend) total_gpus = dist.get_world_size() rank = dist.get_rank() return total_gpus, rank def init_dist_pytorch(tcp_port, local_rank, backend='nccl'): if mp.get_start_method(allow_none=True) is None: mp.set_start_method('spawn') # os.environ['MASTER_PORT'] = str(tcp_port) # os.environ['MASTER_ADDR'] = 'localhost' num_gpus = torch.cuda.device_count() torch.cuda.set_device(local_rank % num_gpus) dist.init_process_group( backend=backend, # init_method='tcp://127.0.0.1:%d' % tcp_port, # rank=local_rank, # world_size=num_gpus ) rank = dist.get_rank() return num_gpus, rank def get_dist_info(return_gpu_per_machine=False): if torch.__version__ < '1.0': initialized = dist._initialized else: if dist.is_available(): initialized = dist.is_initialized() else: initialized = False if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: rank = 0 world_size = 1 if return_gpu_per_machine: gpu_per_machine = torch.cuda.device_count() return rank, world_size, gpu_per_machine return rank, world_size def merge_results_dist(result_part, size, tmpdir): rank, world_size = get_dist_info() os.makedirs(tmpdir, exist_ok=True) dist.barrier() pickle.dump(result_part, open(os.path.join(tmpdir, 'result_part_{}.pkl'.format(rank)), 'wb')) dist.barrier() if rank != 0: return None part_list = [] for i in range(world_size): part_file = os.path.join(tmpdir, 'result_part_{}.pkl'.format(i)) part_list.append(pickle.load(open(part_file, 'rb'))) ordered_results = [] for res in zip(*part_list): ordered_results.extend(list(res)) ordered_results = ordered_results[:size] shutil.rmtree(tmpdir) return ordered_results def scatter_point_inds(indices, point_inds, shape): ret = -1 * torch.ones(*shape, dtype=point_inds.dtype, device=point_inds.device) ndim = indices.shape[-1] flattened_indices = indices.view(-1, ndim) slices = [flattened_indices[:, i] for i in range(ndim)] ret[slices] = point_inds return ret def generate_voxel2pinds(sparse_tensor): device = sparse_tensor.indices.device batch_size = sparse_tensor.batch_size spatial_shape = sparse_tensor.spatial_shape indices = sparse_tensor.indices.long() point_indices = torch.arange(indices.shape[0], device=device, dtype=torch.int32) output_shape = [batch_size] + list(spatial_shape) v2pinds_tensor = scatter_point_inds(indices, point_indices, output_shape) return v2pinds_tensor def sa_create(name, var): """ Args: name: identify the shared memory, file:// prefix to indicate file while shm:// to indicate to be a POSIX shared memory object var: only use the var.shape and var.dtype to create SA object see more: https://pypi.org/project/SharedArray/ """ x = SharedArray.create(name, var.shape, dtype=var.dtype) x[...] = var[...] x.flags.writeable = False return x def add_prefix_to_dict(dict, prefix): for key in list(dict.keys()): dict[prefix + key] = dict.pop(key) return dict class DataReader(object): def __init__(self, dataloader, sampler): self.dataloader = dataloader self.sampler = sampler def construct_iter(self): self.dataloader_iter = iter(self.dataloader) def set_cur_epoch(self, cur_epoch): self.cur_epoch = cur_epoch def read_data(self): try: return self.dataloader_iter.next() except: if self.sampler is not None: self.sampler.set_epoch(self.cur_epoch) self.construct_iter() return self.dataloader_iter.next() class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() 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 set_bn_train(m): classname = m.__class__.__name__ if classname.find('BatchNorm') != -1: m.train() def calculate_gradient_norm(model): total_norm = 0 for p in model.parameters(): param_norm = p.grad.data.norm(2) total_norm += param_norm.item() ** 2 total_norm = total_norm ** (1. / 2) return total_norm class GRLayer(Function): @staticmethod def forward(ctx, input, weight): ctx.alpha = weight return input.view_as(input) @staticmethod def backward(ctx, grad_outputs): output = grad_outputs.neg() * ctx.alpha return output, None def grad_reverse(x, weight): return GRLayer.apply(x, weight) def split_two_spare_tensor(split_tag_s1, split_tag_s2, sparse_tensor): """ Function: split the sparse_tensor into two sparse_tensor, accodring to the given batch_size Args: split_tag_s1: array (batch_len) split_tag_s2: array (batch_len) sparse_tensor: Returns: """ voxel_features = sparse_tensor.features voxel_coords = sparse_tensor.indices # split the voxel_coords of the dataset-merged voxel_coords tar_coor_s1 = [] tar_coor_s2 = [] bs_s1 = 0 bs_s2 = 0 for i in split_tag_s1: voxel_coords_s1 = voxel_coords[i==voxel_coords[:,0]] voxel_coords_s1[:,0] = bs_s1 bs_s1 += 1 tar_coor_s1.append(voxel_coords_s1) tar_s1 = torch.cat(tar_coor_s1, axis=0) for j in split_tag_s2: voxel_coords_s2 = voxel_coords[j==voxel_coords[:,0]] voxel_coords_s2[:,0] = bs_s2 bs_s2 += 1 tar_coor_s2.append(voxel_coords_s2) tar_s2 = torch.cat(tar_coor_s2, axis=0) # split the voxel_tensor of the dataset-merged voxel_coords tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: voxel_s1 = voxel_features[i==voxel_coords[:,0]] tar_list_s1.append(voxel_s1.reshape(-1, voxel_s1.shape[-1])) for j in split_tag_s2: voxel_s2 = voxel_features[j==voxel_coords[:,0]] tar_list_s2.append(voxel_s2.reshape(-1, voxel_s2.shape[-1])) voxel_features_s1 = torch.cat(tar_list_s1, axis=0) voxel_features_s2 = torch.cat(tar_list_s2, axis=0) # convert the dense_tensor of voxel into the sparse representations input_sp_tensor_s1 = spconv.SparseConvTensor( features=voxel_features_s1, indices=tar_s1.int(), spatial_shape=sparse_tensor.spatial_shape, batch_size=len(split_tag_s1) ) input_sp_tensor_s2 = spconv.SparseConvTensor( features=voxel_features_s2, indices=tar_s2.int(), spatial_shape=sparse_tensor.spatial_shape, batch_size=len(split_tag_s2) ) return input_sp_tensor_s1, input_sp_tensor_s2 # For split the batch_dict for two head def split_two_batch_dict(split_tag_s1, split_tag_s2, batch_dict): tar_dicts_s1 = {} tar_dicts_s2 = {} for key, val in batch_dict.items(): if key in ['db_flag', 'frame_id', 'use_lead_xyz']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: tar_list_s1.append(val[i]) for j in split_tag_s2: tar_list_s2.append(val[j]) tar_dicts_s1[key] = tar_list_s1 tar_dicts_s2[key] = tar_list_s2 elif key in ['points', 'voxel_coords']: tar_list_s1 = [] tar_list_s2 = [] bs_s1 = 0 bs_s2 = 0 for i in split_tag_s1: idx_bs_s1 = [np.where(i==val[:,0])] point_s1 = val[tuple(idx_bs_s1)] point_s1[0,:,0] = bs_s1 bs_s1 = bs_s1 + 1 tar_list_s1.append(point_s1.reshape(-1, point_s1.shape[2])) for j in split_tag_s2: idx_bs_s2 = [np.where(j==val[:,0])] point_s2 = val[tuple(idx_bs_s2)] point_s2[0,:,0] = bs_s2 bs_s2 += 1 tar_list_s2.append(point_s2.reshape(-1, point_s2.shape[2])) tar_dicts_s1[key] = np.concatenate(tar_list_s1, axis=0) tar_dicts_s2[key] = np.concatenate(tar_list_s2, axis=0) elif key in ['gt_boxes']: tar_dicts_s1[key] = val[split_tag_s1, :, :] tar_dicts_s2[key] = val[split_tag_s2, :, :] elif key in ['voxels']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: idx_bs_s1 = [np.where(i==batch_dict['voxel_coords'][:,0])] voxel_s1 = val[tuple(idx_bs_s1)] tar_list_s1.append(voxel_s1.reshape(-1, voxel_s1.shape[-2], voxel_s1.shape[-1])) for j in split_tag_s2: idx_bs_s2 = [np.where(j==batch_dict['voxel_coords'][:,0])] voxel_s2 = val[tuple(idx_bs_s2)] tar_list_s2.append(voxel_s2.reshape(-1, voxel_s2.shape[-2], voxel_s2.shape[-1])) tar_dicts_s1[key] = np.concatenate(tar_list_s1, axis=0) tar_dicts_s2[key] = np.concatenate(tar_list_s2, axis=0) elif key in ['voxel_num_points']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: idx_bs_s1 = [np.where(i==batch_dict['voxel_coords'][:,0])] voxel_s1 = val[tuple(idx_bs_s1)] tar_list_s1.append(voxel_s1.reshape(-1)) for j in split_tag_s2: idx_bs_s2 = [np.where(j==batch_dict['voxel_coords'][:,0])] voxel_s2 = val[tuple(idx_bs_s2)] tar_list_s2.append(voxel_s2.reshape(-1)) tar_dicts_s1[key] = np.concatenate(tar_list_s1, axis=0) tar_dicts_s2[key] = np.concatenate(tar_list_s2, axis=0) elif key in [ 'metadata' ]: # Due to that the kitti do not have the 'metadata' key, and give the 'metadata' key to nusc branch if "kitti" in batch_dict['db_flag']: tar_dicts_s2[key] = val else: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: tar_list_s1.append(val[i]) for j in split_tag_s2: tar_list_s2.append(val[j]) tar_dicts_s1[key] = tar_list_s1 tar_dicts_s2[key] = tar_list_s2 elif key in ['image_shape']: # Due to that the waymo and nusc do not have the 'image_shape' key, # and assume that kitti feeds into the Branch ONE if "kitti" in batch_dict['db_flag']: tar_list_s1 = [] for i in split_tag_s1: tar_list_s1.append(val[i]) tar_dicts_s1[key] = tar_list_s1 elif key in ['batch_size']: tar_dicts_s1[key] = len(split_tag_s1) tar_dicts_s2[key] = len(split_tag_s2) else: continue return tar_dicts_s1, tar_dicts_s2 def split_two_batch_dict_gpu(split_tag_s1, split_tag_s2, batch_dict): tar_dicts_s1 = {} tar_dicts_s2 = {} for key, val in batch_dict.items(): if key in ['db_flag', 'frame_id', 'use_lead_xyz']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: tar_list_s1.append(val[i]) for j in split_tag_s2: tar_list_s2.append(val[j]) tar_dicts_s1[key] = tar_list_s1 tar_dicts_s2[key] = tar_list_s2 elif key in ['points', 'voxel_coords', 'point_coords']: tar_list_s1 = [] tar_list_s2 = [] bs_s1 = 0 bs_s2 = 0 for i in split_tag_s1: point_s1 = val[i==val[:,0]] point_s1[:,0] = bs_s1 bs_s1 += 1 tar_list_s1.append(point_s1) for j in split_tag_s2: point_s2 = val[j==val[:,0]] point_s2[:,0] = bs_s2 bs_s2 += 1 tar_list_s2.append(point_s2) tar_dicts_s1[key] = torch.cat(tar_list_s1, axis=0) tar_dicts_s2[key] = torch.cat(tar_list_s2, axis=0) elif key in ['gt_boxes']: tar_dicts_s1[key] = val[split_tag_s1, :, :] tar_dicts_s2[key] = val[split_tag_s2, :, :] elif key in ['voxel_features']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: voxel_s1 = val[i==batch_dict['voxel_coords'][:,0]] tar_list_s1.append(voxel_s1.reshape(-1, voxel_s1.shape[-1])) for j in split_tag_s2: voxel_s2 = val[j==batch_dict['voxel_coords'][:,0]] tar_list_s2.append(voxel_s2.reshape(-1, voxel_s2.shape[-1])) tar_dicts_s1[key] = torch.cat(tar_list_s1, axis=0) tar_dicts_s2[key] = torch.cat(tar_list_s2, axis=0) elif key in ['point_features', 'point_features_before_fusion']: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: point_s1 = val[i==batch_dict['point_coords'][:,0]] tar_list_s1.append(point_s1.reshape(-1, point_s1.shape[-1])) for j in split_tag_s2: point_s2 = val[j==batch_dict['point_coords'][:,0]] tar_list_s2.append(point_s2.reshape(-1, point_s2.shape[-1])) tar_dicts_s1[key] = torch.cat(tar_list_s1, axis=0) tar_dicts_s2[key] = torch.cat(tar_list_s2, axis=0) elif key in ['spatial_features', 'spatial_features_2d']: tar_dicts_s1[key] = val[split_tag_s1, :, :, :] tar_dicts_s2[key] = val[split_tag_s2, :, :, :] elif key in [ 'metadata' ]: # Due to that the kitti and once do not have the 'metadata' key, # and only give the 'metadata' key to nusc branch if "kitti" or "once" in batch_dict['db_flag']: tar_dicts_s1[key] = val else: tar_list_s1 = [] tar_list_s2 = [] for i in split_tag_s1: tar_list_s1.append(val[i]) for j in split_tag_s2: tar_list_s2.append(val[j]) tar_dicts_s1[key] = tar_list_s1 tar_dicts_s2[key] = tar_list_s2 elif key in ['image_shape']: # Due to that the waymo and nusc do not have the 'image_shape' key, if "kitti" in batch_dict['db_flag']: # assume that kitti feeds into the Branch ONE if batch_dict['db_flag'][0] == 'kitti': tar_list_s1 = [] for i in split_tag_s1: tar_list_s1.append(val) tar_dicts_s1[key] = torch.cat(tar_list_s1, axis=0) # assume that kitti feeds into the Branch TWO else: tar_list_s2 = [] for i in split_tag_s2: tar_list_s2.append(val) tar_dicts_s2[key] = torch.cat(tar_list_s2, axis=0) elif key in ['multi_scale_3d_strides']: # Since different datasets for the 'multi_scale_3d_strides' key have the same value, # we directly copy this value into tar_dicts_s1, tar_dicts_s2 tar_dicts_s1[key] = val tar_dicts_s2[key] = val elif key in ['multi_scale_3d_features']: # We need to transfer the sparse tensor into the dense tensor sp_3d_s1 = {} sp_3d_s2 = {} for src_name in ['x_conv1', 'x_conv2', 'x_conv3', 'x_conv4']: input_sp_tensor_s1, input_sp_tensor_s2 = split_two_spare_tensor(split_tag_s1, split_tag_s2, val[src_name]) sp_3d_s1[src_name] = input_sp_tensor_s1 sp_3d_s2[src_name] = input_sp_tensor_s2 tar_dicts_s1[key] = sp_3d_s1 tar_dicts_s2[key] = sp_3d_s2 elif key in ['batch_size']: tar_dicts_s1[key] = len(split_tag_s1) tar_dicts_s2[key] = len(split_tag_s2) elif key in ['spatial_features_stride']: tar_dicts_s1[key] = val tar_dicts_s2[key] = val else: continue return tar_dicts_s1, tar_dicts_s2 def split_batch_dict(source_one_name, batch_dict): split_tag_s1 = [] split_tag_s2 = [] for k in range(batch_dict['batch_size']): if source_one_name in batch_dict['db_flag'][k]: split_tag_s1.append(k) else: split_tag_s2.append(k) return split_tag_s1, split_tag_s2 def merge_two_batch_dict(batch_dict_1, batch_dict_2): """ To support a custom dataset, implement this function to merge two batch_dict (and labels) from different datasets Args: batch_dict_1: batch_dict_2: Returns: batch_merge_dict: """ batch_merge_dict = {} batch_merge_dict['batch_size'] = batch_dict_1['batch_size'] + batch_dict_2['batch_size'] for key, val in batch_dict_1.items(): if key in ['batch_size']: continue elif key in ['db_flag', 'frame_id', 'use_lead_xyz']: tar_list_merge = [] tar_list_merge = [val, batch_dict_2[key]] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) elif key in ['voxels', 'voxel_num_points']: tar_list_merge = [] tar_list_merge = [val, batch_dict_2[key]] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) elif key in ['points', 'voxel_coords']: tar_list_merge = [] batch_bias = batch_dict_1['batch_size'] val_2 = batch_dict_2[key] val_2[:,0] = val_2[:,0] + batch_bias tar_list_merge = [val, val_2] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) elif key in ['gt_boxes']: max_gt_1 = max([len(x) for x in val]) max_gt_2 = max([len(x) for x in batch_dict_2[key]]) if max_gt_1 > max_gt_2: val_2 = batch_dict_2['gt_boxes'] batch_gt_boxes3d = np.zeros((batch_dict_2['batch_size'], max_gt_1, val_2[0].shape[-1]), dtype=np.float32) #filling the gt_boxes of the batch_dict_2 for k in range(batch_dict_2['batch_size']): batch_gt_boxes3d[k, :val_2[k].__len__(), :] = val_2[k] tar_list_merge = [] tar_list_merge = [val, batch_gt_boxes3d] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) else: val_2 = batch_dict_2['gt_boxes'] batch_gt_boxes3d = np.zeros((batch_dict_1['batch_size'], max_gt_2, val[0].shape[-1]), dtype=np.float32) #filling the gt_boxes of the batch_dict_1 for k in range(batch_dict_1['batch_size']): batch_gt_boxes3d[k, :val[k].__len__(), :] = val[k] tar_list_merge = [] tar_list_merge = [batch_gt_boxes3d, val_2] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) elif key in ['metadata', 'image_shape', 'road_plane', 'calib']: # Due to that the kitti do not have the 'metadata' key, and give the 'metadata' key to nusc branch if key in batch_dict_2.keys(): # both dataset have the 'metadata key' tar_list_merge = [] tar_list_merge = [val, batch_dict_2[key]] batch_merge_dict[key] = np.concatenate(tar_list_merge, axis=0) else: batch_merge_dict[key] = val if 'metadata' in batch_dict_2.keys() and 'metadata' not in batch_dict_1.keys() : batch_merge_dict['metadata'] = batch_dict_2['metadata'] if 'image_shape' in batch_dict_2.keys() and 'image_shape' not in batch_dict_1.keys() : batch_merge_dict['image_shape'] = batch_dict_2['image_shape'] if 'road_plane' in batch_dict_2.keys() and 'road_plane' not in batch_dict_1.keys() : batch_merge_dict['road_plane'] = batch_dict_2['road_plane'] if 'calib' in batch_dict_2.keys() and 'calib' not in batch_dict_1.keys() : batch_merge_dict['calib'] = batch_dict_2['calib'] return batch_merge_dict def merge_two_batch_dict_gpu(split_tag_s1, split_tag_s2, batch_dict): """ To support a custom dataset, implement this function to merge two batch_dict (and labels) from different datasets Args: split_tag_s1: split_tag_s2: batch_dict: Returns: batch_merge_dict: """ raise NotImplementedError
25,895
34.966667
137
py
3DTrans
3DTrans-master/pcdet/utils/uni3d_norm_2_in.py
import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.module import Module from torch.nn.parameter import Parameter import torch import itertools class _UniNorm(Module): def __init__(self, num_features, dataset_from_flag=1, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, voxel_coord=False): super(_UniNorm, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum self.affine = affine self.track_running_stats = track_running_stats self.voxel_coord = voxel_coord self.dataset_from_flag = dataset_from_flag if self.affine: self.weight = Parameter(torch.Tensor(num_features)) self.bias = Parameter(torch.Tensor(num_features)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) if self.track_running_stats: self.register_buffer('running_mean_source', torch.zeros(num_features)) self.register_buffer('running_mean_target', torch.zeros(num_features)) self.register_buffer('running_var_source', torch.ones(num_features)) self.register_buffer('running_var_target', torch.ones(num_features)) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) else: self.register_parameter('running_mean_source', None) self.register_parameter('running_mean_target', None) self.register_parameter('running_var_source', None) self.register_parameter('running_var_target', None) self.reset_parameters() def reset_parameters(self): if self.track_running_stats: self.running_mean_source.zero_() self.running_mean_target.zero_() self.running_var_source.fill_(1) self.running_var_target.fill_(1) if self.affine: self.weight.data.uniform_() self.bias.data.zero_() def _check_input_dim(self, input): return NotImplemented def _load_from_state_dict_from_pretrained_model(self, state_dict, prefix, metadata, strict, missing_keys, unexpected_keys, error_msgs): r"""Copies parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr`metadata`. For state dicts without meta data, :attr`metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `metadata.get("version", None)`. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Arguments: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module metadata (dict): a dict containing the metadata for this moodule. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=False``, add missing keys to this list unexpected_keys (list of str): if ``strict=False``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` """ local_name_params = itertools.chain(self._parameters.items(), self._buffers.items()) local_state = {k: v.data for k, v in local_name_params if v is not None} for name, param in local_state.items(): key = prefix + name if 'source' in key or 'target' in key: key = key[:-7] print(key) if key in state_dict: input_param = state_dict[key] if input_param.shape != param.shape: # local shape should match the one in checkpoint error_msgs.append('size mismatch for {}: copying a param of {} from checkpoint, ' 'where the shape is {} in current model.' .format(key, param.shape, input_param.shape)) continue if isinstance(input_param, Parameter): # backwards compatibility for serialized parameters input_param = input_param.data try: param.copy_(input_param) except Exception: error_msgs.append('While copying the parameter named "{}", ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(key, param.size(), input_param.size())) elif strict: missing_keys.append(key) def forward(self, input, voxel_coords): self._check_input_dim(input) if self.training: ## train mode ## Split the input into the source and target batches ## and calculate the corresponding variances input_source_list = [] input_target_list = [] if self.voxel_coord: bs = (voxel_coords[-1,0]+1) // 2 for i in range(0, int(bs)): input_source_list.append(input[voxel_coords[:,0]==i]) input_source = torch.cat(input_source_list, axis=0) for j in range(int(bs), int(voxel_coords[-1,0]+1)): input_target_list.append(input[voxel_coords[:,0]==j]) input_target = torch.cat(input_target_list, axis=0) else: batch_size = input.size()[0] // 2 input_source = input[:batch_size] input_target = input[batch_size:] ## In order to remap the rescaled source or target features into ## the shared space, we use the shared self.weight and self.bias z_source = F.batch_norm( input_source, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z_target = F.batch_norm( input_target, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z = torch.cat((z_source, z_target), dim=0) # In order to address different dims if input.dim() == 4: input_source = input_source.permute(0,2,3,1).contiguous().view(-1,self.num_features) input_target = input_target.permute(0,2,3,1).contiguous().view(-1,self.num_features) ## Obtain the channel-wise transferability ## Assume that source_one and source_two features have different transferability along with channel dimension cur_mean_source = torch.mean(input_source, dim=0) cur_var_source = torch.var(input_source,dim=0) cur_mean_target = torch.mean(input_target, dim=0) cur_var_target = torch.var(input_target, dim=0) ## Global Statistic-level channel-wise transferability dis = torch.abs(cur_mean_source / torch.sqrt(cur_var_source + self.eps) - cur_mean_target / torch.sqrt(cur_var_target + self.eps)) ## Convert the channel-wise transferability into the probability distribution prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) ## Attention return z * (1 + alpha.detach()) else: ##test mode if self.dataset_from_flag == 1: z = F.batch_norm( input, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) dis = torch.abs(self.running_mean_source / torch.sqrt(self.running_var_source + self.eps) - self.running_mean_target / torch.sqrt(self.running_var_target + self.eps)) prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) elif self.dataset_from_flag == 2: z = F.batch_norm( input, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) dis = torch.abs(self.running_mean_source / torch.sqrt(self.running_var_source + self.eps) - self.running_mean_target / torch.sqrt(self.running_var_target + self.eps)) prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) return z * (1 + alpha.detach()) def extra_repr(self): return '{num_features}, eps={eps}, momentum={momentum}, affine={affine}, ' \ 'track_running_stats={track_running_stats}'.format(**self.__dict__) class UniNorm1d(_UniNorm): r"""Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C)` or :math:`(N, C, L)` - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm1d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm1d(100, affine=False) >>> input = torch.randn(20, 100) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 2 and input.dim() != 3: raise ValueError('expected 2D or 3D input (got {}D input)' .format(input.dim())) class UniNorm2d(_UniNorm): r"""Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, H, W)` slices, it's common terminology to call this Spatial Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, H, W)` - Output: :math:`(N, C, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm2d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm2d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 4: raise ValueError('expected 4D input (got {}D input)' .format(input.dim())) class UniNorm3d(_UniNorm): r"""Applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, D, H, W)` slices, it's common terminology to call this Volumetric Batch Normalization or Spatio-temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, D, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, D, H, W)` - Output: :math:`(N, C, D, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm3d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm3d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45, 10) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 5: raise ValueError('expected 5D input (got {}D input)' .format(input.dim()))
19,844
46.362768
140
py
3DTrans
3DTrans-master/pcdet/utils/transform_utils.py
import math import torch try: from kornia.geometry.conversions import ( convert_points_to_homogeneous, convert_points_from_homogeneous, ) except: pass # print('Warning: kornia is not installed. This package is only required by CaDDN') def project_to_image(project, points): """ Project points to image Args: project [torch.tensor(..., 3, 4)]: Projection matrix points [torch.Tensor(..., 3)]: 3D points Returns: points_img [torch.Tensor(..., 2)]: Points in image points_depth [torch.Tensor(...)]: Depth of each point """ # Reshape tensors to expected shape points = convert_points_to_homogeneous(points) points = points.unsqueeze(dim=-1) project = project.unsqueeze(dim=1) # Transform points to image and get depths points_t = project @ points points_t = points_t.squeeze(dim=-1) points_img = convert_points_from_homogeneous(points_t) points_depth = points_t[..., -1] - project[..., 2, 3] return points_img, points_depth def normalize_coords(coords, shape): """ Normalize coordinates of a grid between [-1, 1] Args: coords: (..., 3), Coordinates in grid shape: (3), Grid shape Returns: norm_coords: (.., 3), Normalized coordinates in grid """ min_n = -1 max_n = 1 shape = torch.flip(shape, dims=[0]) # Reverse ordering of shape # Subtract 1 since pixel indexing from [0, shape - 1] norm_coords = coords / (shape - 1) * (max_n - min_n) + min_n return norm_coords def bin_depths(depth_map, mode, depth_min, depth_max, num_bins, target=False): """ Converts depth map into bin indices Args: depth_map: (H, W), Depth Map mode: string, Discretiziation mode (See https://arxiv.org/pdf/2005.13423.pdf for more details) UD: Uniform discretiziation LID: Linear increasing discretiziation SID: Spacing increasing discretiziation depth_min: float, Minimum depth value depth_max: float, Maximum depth value num_bins: int, Number of depth bins target: bool, Whether the depth bins indices will be used for a target tensor in loss comparison Returns: indices: (H, W), Depth bin indices """ if mode == "UD": bin_size = (depth_max - depth_min) / num_bins indices = ((depth_map - depth_min) / bin_size) elif mode == "LID": bin_size = 2 * (depth_max - depth_min) / (num_bins * (1 + num_bins)) indices = -0.5 + 0.5 * torch.sqrt(1 + 8 * (depth_map - depth_min) / bin_size) elif mode == "SID": indices = num_bins * (torch.log(1 + depth_map) - math.log(1 + depth_min)) / \ (math.log(1 + depth_max) - math.log(1 + depth_min)) else: raise NotImplementedError if target: # Remove indicies outside of bounds mask = (indices < 0) | (indices > num_bins) | (~torch.isfinite(indices)) indices[mask] = num_bins # Convert to integer indices = indices.type(torch.int64) return indices
3,092
32.619565
104
py
3DTrans
3DTrans-master/pcdet/utils/uni3d_norm_parallel.py
import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.module import Module from torch.nn.parameter import Parameter import torch import itertools class _UniNorm(Module): def __init__(self, num_features, dataset_from_flag=1, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, voxel_coord=False): super(_UniNorm, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum self.affine = affine self.track_running_stats = track_running_stats self.voxel_coord = voxel_coord self.dataset_from_flag = dataset_from_flag if self.affine: self.weight = Parameter(torch.Tensor(num_features)) self.bias = Parameter(torch.Tensor(num_features)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) if self.track_running_stats: self.register_buffer('running_mean_source', torch.zeros(num_features)) self.register_buffer('running_mean_target', torch.zeros(num_features)) self.register_buffer('running_var_source', torch.ones(num_features)) self.register_buffer('running_var_target', torch.ones(num_features)) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) else: self.register_parameter('running_mean_source', None) self.register_parameter('running_mean_target', None) self.register_parameter('running_var_source', None) self.register_parameter('running_var_target', None) self.reset_parameters() def reset_parameters(self): if self.track_running_stats: self.running_mean_source.zero_() self.running_mean_target.zero_() self.running_var_source.fill_(1) self.running_var_target.fill_(1) if self.affine: self.weight.data.uniform_() self.bias.data.zero_() def _check_input_dim(self, input): return NotImplemented def _load_from_state_dict_from_pretrained_model(self, state_dict, prefix, metadata, strict, missing_keys, unexpected_keys, error_msgs): r"""Copies parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr`metadata`. For state dicts without meta data, :attr`metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `metadata.get("version", None)`. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Arguments: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module metadata (dict): a dict containing the metadata for this moodule. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=False``, add missing keys to this list unexpected_keys (list of str): if ``strict=False``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` """ local_name_params = itertools.chain(self._parameters.items(), self._buffers.items()) local_state = {k: v.data for k, v in local_name_params if v is not None} for name, param in local_state.items(): key = prefix + name if 'source' in key or 'target' in key: key = key[:-7] print(key) if key in state_dict: input_param = state_dict[key] if input_param.shape != param.shape: # local shape should match the one in checkpoint error_msgs.append('size mismatch for {}: copying a param of {} from checkpoint, ' 'where the shape is {} in current model.' .format(key, param.shape, input_param.shape)) continue if isinstance(input_param, Parameter): # backwards compatibility for serialized parameters input_param = input_param.data try: param.copy_(input_param) except Exception: error_msgs.append('While copying the parameter named "{}", ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(key, param.size(), input_param.size())) elif strict: missing_keys.append(key) def forward(self, input): self._check_input_dim(input) if self.training : ## train mode ## Split the input into the source and target batches ## and calculate the corresponding variances batch_size = input.size()[0] // 2 input_source = input[:batch_size] input_target = input[batch_size:] ## In order to remap the rescaled source or target features into ## the shared space, we use the shared self.weight and self.bias z_source = F.batch_norm( input_source, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z_target = F.batch_norm( input_target, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z = torch.cat((z_source, z_target), dim=0) # In order to address different dims if input.dim() == 4: ## UniNorm2d input_source = input_source.permute(0,2,3,1).contiguous().view(-1,self.num_features) input_target = input_target.permute(0,2,3,1).contiguous().view(-1,self.num_features) cur_mean_source = torch.mean(input_source, dim=0) cur_var_source = torch.var(input_source,dim=0) cur_mean_target = torch.mean(input_target, dim=0) cur_var_target = torch.var(input_target, dim=0) ## Obtain the channel-wise transferability ## Assume that source_one and source_two features have different transferability along with channel dimension ## Global Statistic-level channel-wise transferability dis = torch.abs(cur_mean_source / torch.sqrt(cur_var_source + self.eps) - cur_mean_target / torch.sqrt(cur_var_target + self.eps)) ## Convert the channel-wise transferability into the probability distribution prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) # # Calculate the Cov Matrix # # Cov Matrix # if input_source.shape[0] == input_target.shape[0]: # cov_matrix_src_tar = torch.matmul((input_source - cur_mean_source).T, (input_target - cur_mean_target)) / (input_source.shape[0]-1) # # cov_vector = self.vote_cov(cov_matrix_src_tar) # cov_vector = torch.diag(cov_matrix_src_tar) # cov_vector = cov_vector.view(-1) # alpha_cov = self.num_features * cov_vector / sum(cov_vector) # alpha = (alpha + alpha_cov) / 2 if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) ## Attention return z * (1 + alpha.detach()) else: ##test mode # for testing using multiple datasets in parallel, # we need to split the input into the source and target batches # and calculate the corresponding variances batch_size = input.size()[0] // 2 input_source = input[:batch_size] input_target = input[batch_size:] assert len(input_source) != 0 assert len(input_target) != 0 # for source domain scaling: z_source = F.batch_norm( input_source, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) # for target domain scaling: z_target = F.batch_norm( input_target, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) dis = torch.abs(self.running_mean_source / torch.sqrt(self.running_var_source + self.eps) - self.running_mean_target / torch.sqrt(self.running_var_target + self.eps)) prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) z = torch.cat((z_source, z_target), dim=0) if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) return z * (1 + alpha.detach()) def extra_repr(self): return '{num_features}, eps={eps}, momentum={momentum}, affine={affine}, ' \ 'track_running_stats={track_running_stats}'.format(**self.__dict__) class UniNorm1d(_UniNorm): r"""Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C)` or :math:`(N, C, L)` - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm1d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm1d(100, affine=False) >>> input = torch.randn(20, 100) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 2 and input.dim() != 3: raise ValueError('expected 2D or 3D input (got {}D input)' .format(input.dim())) class UniNorm2d(_UniNorm): r"""Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, H, W)` slices, it's common terminology to call this Spatial Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, H, W)` - Output: :math:`(N, C, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm2d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm2d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 4: raise ValueError('expected 4D input (got {}D input)' .format(input.dim())) class UniNorm3d(_UniNorm): r"""Applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, D, H, W)` slices, it's common terminology to call this Volumetric Batch Normalization or Spatio-temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, D, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, D, H, W)` - Output: :math:`(N, C, D, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm3d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm3d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45, 10) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 5: raise ValueError('expected 5D input (got {}D input)' .format(input.dim()))
20,022
46.112941
149
py
3DTrans
3DTrans-master/pcdet/utils/uni3d_norm.py
import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.module import Module from torch.nn.parameter import Parameter import torch import itertools class _UniNorm(Module): def __init__(self, num_features, dataset_from_flag=1, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, voxel_coord=False): super(_UniNorm, self).__init__() self.num_features = num_features self.eps = eps self.momentum = momentum self.affine = affine self.track_running_stats = track_running_stats self.voxel_coord = voxel_coord self.dataset_from_flag = dataset_from_flag if self.affine: self.weight = Parameter(torch.Tensor(num_features)) self.bias = Parameter(torch.Tensor(num_features)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) if self.track_running_stats: self.register_buffer('running_mean_source', torch.zeros(num_features)) self.register_buffer('running_mean_target', torch.zeros(num_features)) self.register_buffer('running_var_source', torch.ones(num_features)) self.register_buffer('running_var_target', torch.ones(num_features)) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) else: self.register_parameter('running_mean_source', None) self.register_parameter('running_mean_target', None) self.register_parameter('running_var_source', None) self.register_parameter('running_var_target', None) self.reset_parameters() def reset_parameters(self): if self.track_running_stats: self.running_mean_source.zero_() self.running_mean_target.zero_() self.running_var_source.fill_(1) self.running_var_target.fill_(1) if self.affine: self.weight.data.uniform_() self.bias.data.zero_() def _check_input_dim(self, input): return NotImplemented def _load_from_state_dict_from_pretrained_model(self, state_dict, prefix, metadata, strict, missing_keys, unexpected_keys, error_msgs): r"""Copies parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr`metadata`. For state dicts without meta data, :attr`metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `metadata.get("version", None)`. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Arguments: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module metadata (dict): a dict containing the metadata for this moodule. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=False``, add missing keys to this list unexpected_keys (list of str): if ``strict=False``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` """ local_name_params = itertools.chain(self._parameters.items(), self._buffers.items()) local_state = {k: v.data for k, v in local_name_params if v is not None} for name, param in local_state.items(): key = prefix + name if 'source' in key or 'target' in key: key = key[:-7] print(key) if key in state_dict: input_param = state_dict[key] if input_param.shape != param.shape: # local shape should match the one in checkpoint error_msgs.append('size mismatch for {}: copying a param of {} from checkpoint, ' 'where the shape is {} in current model.' .format(key, param.shape, input_param.shape)) continue if isinstance(input_param, Parameter): # backwards compatibility for serialized parameters input_param = input_param.data try: param.copy_(input_param) except Exception: error_msgs.append('While copying the parameter named "{}", ' 'whose dimensions in the model are {} and ' 'whose dimensions in the checkpoint are {}.' .format(key, param.size(), input_param.size())) elif strict: missing_keys.append(key) def forward(self, input): self._check_input_dim(input) if self.training : ## train mode ## Split the input into the source and target batches ## and calculate the corresponding variances batch_size = input.size()[0] // 2 input_source = input[:batch_size] input_target = input[batch_size:] ## In order to remap the rescaled source or target features into ## the shared space, we use the shared self.weight and self.bias z_source = F.batch_norm( input_source, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z_target = F.batch_norm( input_target, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) z = torch.cat((z_source, z_target), dim=0) # In order to address different dims if input.dim() == 4: input_source = input_source.permute(0,2,3,1).contiguous().view(-1,self.num_features) input_target = input_target.permute(0,2,3,1).contiguous().view(-1,self.num_features) cur_mean_source = torch.mean(input_source, dim=0) cur_var_source = torch.var(input_source,dim=0) cur_mean_target = torch.mean(input_target, dim=0) cur_var_target = torch.var(input_target, dim=0) ## Obtain the channel-wise transferability ## Assume that source_one and source_two features have different transferability along with channel dimension ## Global Statistic-level channel-wise transferability dis = torch.abs(cur_mean_source / torch.sqrt(cur_var_source + self.eps) - cur_mean_target / torch.sqrt(cur_var_target + self.eps)) ## Convert the channel-wise transferability into the probability distribution prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) # # Calculate the Cov Matrix # # Cov Matrix # if input_source.shape[0] == input_target.shape[0]: # cov_matrix_src_tar = torch.matmul((input_source - cur_mean_source).T, (input_target - cur_mean_target)) / (input_source.shape[0]-1) # # cov_vector = self.vote_cov(cov_matrix_src_tar) # cov_vector = torch.diag(cov_matrix_src_tar) # cov_vector = cov_vector.view(-1) # alpha_cov = self.num_features * cov_vector / sum(cov_vector) # alpha = (alpha + alpha_cov) / 2 if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) ## Attention return z * (1 + alpha.detach()) else: ##test mode if self.dataset_from_flag == 1: z = F.batch_norm( input, self.running_mean_source, self.running_var_source, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) dis = torch.abs(self.running_mean_source / torch.sqrt(self.running_var_source + self.eps) - self.running_mean_target / torch.sqrt(self.running_var_target + self.eps)) prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) # # Add Cov Matrix: # if input.dim() == 4: # input = input.permute(0,2,3,1).contiguous().view(-1,self.num_features) # cov_matrix_src_tar = torch.matmul((input - self.running_mean_source).T, (input - self.running_mean_source)) / (input.shape[0]-1) # cov_vector = torch.diag(cov_matrix_src_tar) # cov_vector = cov_vector.view(-1) # alpha_cov = self.num_features * cov_vector / sum(cov_vector) # alpha = (alpha + alpha_cov) / 2 elif self.dataset_from_flag == 2: z = F.batch_norm( input, self.running_mean_target, self.running_var_target, self.weight, self.bias, self.training or not self.track_running_stats, self.momentum, self.eps) dis = torch.abs(self.running_mean_source / torch.sqrt(self.running_var_source + self.eps) - self.running_mean_target / torch.sqrt(self.running_var_target + self.eps)) prob = 1.0 / (1.0 + dis) alpha = self.num_features * prob / sum(prob) # # Add Cov Matrix: # if input.dim() == 4: # input = input.permute(0,2,3,1).contiguous().view(-1,self.num_features) # cov_matrix_src_tar = torch.matmul((input - self.running_mean_target).T, (input - self.running_mean_target)) / (input.shape[0]-1) # cov_vector = torch.diag(cov_matrix_src_tar) # cov_vector = cov_vector.view(-1) # alpha_cov = self.num_features * cov_vector / sum(cov_vector) # alpha = (alpha + alpha_cov) / 2 if input.dim() == 2: alpha = alpha.view(1, self.num_features) elif input.dim() == 4: alpha = alpha.view(1, self.num_features, 1, 1) return z * (1 + alpha.detach()) def extra_repr(self): return '{num_features}, eps={eps}, momentum={momentum}, affine={affine}, ' \ 'track_running_stats={track_running_stats}'.format(**self.__dict__) class UniNorm1d(_UniNorm): r"""Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C)` or :math:`(N, C, L)` - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm1d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm1d(100, affine=False) >>> input = torch.randn(20, 100) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 2 and input.dim() != 3: raise ValueError('expected 2D or 3D input (got {}D input)' .format(input.dim())) class UniNorm2d(_UniNorm): r"""Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, H, W)` slices, it's common terminology to call this Spatial Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, H, W)` - Output: :math:`(N, C, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm2d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm2d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 4: raise ValueError('expected 4D input (got {}D input)' .format(input.dim())) class UniNorm3d(_UniNorm): r"""Applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper `Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`_ . .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors of size `C` (where `C` is the input size). By default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default :attr:`momentum` of 0.1. If :attr:`track_running_stats` is set to ``False``, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well. .. note:: This :attr:`momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is :math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momemtum} \times x_t`, where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value. Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, D, H, W)` slices, it's common terminology to call this Volumetric Batch Normalization or Spatio-temporal Batch Normalization. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, D, H, W)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Shape: - Input: :math:`(N, C, D, H, W)` - Output: :math:`(N, C, D, H, W)` (same shape as input) Examples:: >>> # With Learnable Parameters >>> m = nn.BatchNorm3d(100) >>> # Without Learnable Parameters >>> m = nn.BatchNorm3d(100, affine=False) >>> input = torch.randn(20, 100, 35, 45, 10) >>> output = m(input) .. _`Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift`: https://arxiv.org/abs/1502.03167 """ def _check_input_dim(self, input): if input.dim() != 5: raise ValueError('expected 5D input (got {}D input)' .format(input.dim()))
21,012
46.648526
149
py
3DTrans
3DTrans-master/pcdet/utils/self_training_utils.py
import torch import os import glob import tqdm import numpy as np import torch.distributed as dist from pcdet.config import cfg from pcdet.models import load_data_to_gpu from pcdet.utils import common_utils, commu_utils, memory_ensemble_utils import pickle as pkl import re #PSEUDO_LABELS = {} from multiprocessing import Manager PSEUDO_LABELS = Manager().dict() #for multiple GPU training NEW_PSEUDO_LABELS = {} def check_already_exsit_pseudo_label(ps_label_dir, start_epoch): """ if we continue training, use this to directly load pseudo labels from exsiting result pkl if exsit, load latest result pkl to PSEUDO LABEL otherwise, return false and Args: ps_label_dir: dir to save pseudo label results pkls. start_epoch: start epoc Returns: """ # support init ps_label given by cfg if start_epoch == 0 and cfg.SELF_TRAIN.get('INIT_PS', None): if os.path.exists(cfg.SELF_TRAIN.INIT_PS): print ("********LOADING PS FROM:", cfg.SELF_TRAIN.INIT_PS) init_ps_label = pkl.load(open(cfg.SELF_TRAIN.INIT_PS, 'rb')) PSEUDO_LABELS.update(init_ps_label) if cfg.LOCAL_RANK == 0: ps_path = os.path.join(ps_label_dir, "ps_label_e0.pkl") with open(ps_path, 'wb') as f: pkl.dump(PSEUDO_LABELS, f) return cfg.SELF_TRAIN.INIT_PS ps_label_list = glob.glob(os.path.join(ps_label_dir, 'ps_label_e*.pkl')) if len(ps_label_list) == 0: return ps_label_list.sort(key=os.path.getmtime, reverse=True) for cur_pkl in ps_label_list: num_epoch = re.findall('ps_label_e(.*).pkl', cur_pkl) assert len(num_epoch) == 1 # load pseudo label and return if int(num_epoch[0]) <= start_epoch: latest_ps_label = pkl.load(open(cur_pkl, 'rb')) PSEUDO_LABELS.update(latest_ps_label) return cur_pkl return None def save_pseudo_label_epoch(model, val_loader, rank, leave_pbar, ps_label_dir, cur_epoch): """ Generate pseudo label with given model. Args: model: model to predict result for pseudo label val_loader: data_loader to predict pseudo label rank: process rank leave_pbar: tqdm bar controller ps_label_dir: dir to save pseudo label cur_epoch """ val_dataloader_iter = iter(val_loader) total_it_each_epoch = len(val_loader) if rank == 0: pbar = tqdm.tqdm(total=total_it_each_epoch, leave=leave_pbar, desc='generate_ps_e%d' % cur_epoch, dynamic_ncols=True) pos_ps_meter = common_utils.AverageMeter() ign_ps_meter = common_utils.AverageMeter() # Since the model is eval status, some object-level data augmentation methods such as # 'random_object_rotation', 'random_object_scaling', 'normalize_object_size' are not used model.eval() for cur_it in range(total_it_each_epoch): try: target_batch = next(val_dataloader_iter) except StopIteration: target_dataloader_iter = iter(val_loader) target_batch = next(target_dataloader_iter) # generate gt_boxes for target_batch and update model weights with torch.no_grad(): load_data_to_gpu(target_batch) pred_dicts, ret_dict = model(target_batch) pos_ps_batch, ign_ps_batch = save_pseudo_label_batch( target_batch, pred_dicts=pred_dicts, need_update=(cfg.SELF_TRAIN.get('MEMORY_ENSEMBLE', None) and cfg.SELF_TRAIN.MEMORY_ENSEMBLE.ENABLED and cur_epoch > 0) ) # log to console and tensorboard pos_ps_meter.update(pos_ps_batch) ign_ps_meter.update(ign_ps_batch) disp_dict = {'pos_ps_box': "{:.3f}({:.3f})".format(pos_ps_meter.val, pos_ps_meter.avg), 'ign_ps_box': "{:.3f}({:.3f})".format(ign_ps_meter.val, ign_ps_meter.avg)} if rank == 0: pbar.update() pbar.set_postfix(disp_dict) pbar.refresh() if rank == 0: pbar.close() gather_and_dump_pseudo_label_result(rank, ps_label_dir, cur_epoch) print(len(PSEUDO_LABELS)) def gather_and_dump_pseudo_label_result(rank, ps_label_dir, cur_epoch): commu_utils.synchronize() if dist.is_initialized(): part_pseudo_labels_list = commu_utils.all_gather(NEW_PSEUDO_LABELS) new_pseudo_label_dict = {} for pseudo_labels in part_pseudo_labels_list: new_pseudo_label_dict.update(pseudo_labels) NEW_PSEUDO_LABELS.update(new_pseudo_label_dict) # dump new pseudo label to given dir if rank == 0: ps_path = os.path.join(ps_label_dir, "ps_label_e{}.pkl".format(cur_epoch)) with open(ps_path, 'wb') as f: pkl.dump(NEW_PSEUDO_LABELS, f) commu_utils.synchronize() PSEUDO_LABELS.clear() PSEUDO_LABELS.update(NEW_PSEUDO_LABELS) NEW_PSEUDO_LABELS.clear() def save_pseudo_label_batch(input_dict, pred_dicts=None, need_update=True): """ Save pseudo label for give batch. If model is given, use model to inference pred_dicts, otherwise, directly use given pred_dicts. Args: input_dict: batch data read from dataloader pred_dicts: Dict if not given model. predict results to be generated pseudo label and saved need_update: Bool. If set to true, use consistency matching to update pseudo label """ pos_ps_meter = common_utils.AverageMeter() ign_ps_meter = common_utils.AverageMeter() batch_size = len(pred_dicts) for b_idx in range(batch_size): pred_cls_scores = pred_iou_scores = None if 'pred_boxes' in pred_dicts[b_idx]: # Exist predicted boxes passing self-training score threshold pred_boxes = pred_dicts[b_idx]['pred_boxes'].detach().cpu().numpy() pred_labels = pred_dicts[b_idx]['pred_labels'].detach().cpu().numpy() pred_scores = pred_dicts[b_idx]['pred_scores'].detach().cpu().numpy() if 'pred_cls_scores' in pred_dicts[b_idx]: pred_cls_scores = pred_dicts[b_idx]['pred_cls_scores'].detach().cpu().numpy() if 'pred_iou_scores' in pred_dicts[b_idx]: pred_iou_scores = pred_dicts[b_idx]['pred_iou_scores'].detach().cpu().numpy() # remove boxes under negative threshold if cfg.SELF_TRAIN.get('NEG_THRESH', None): labels_remove_scores = np.array(cfg.SELF_TRAIN.NEG_THRESH)[pred_labels - 1] remain_mask = pred_scores >= labels_remove_scores pred_labels = pred_labels[remain_mask] pred_scores = pred_scores[remain_mask] pred_boxes = pred_boxes[remain_mask] if 'pred_cls_scores' in pred_dicts[b_idx]: pred_cls_scores = pred_cls_scores[remain_mask] if 'pred_iou_scores' in pred_dicts[b_idx]: pred_iou_scores = pred_iou_scores[remain_mask] labels_ignore_scores = np.array(cfg.SELF_TRAIN.SCORE_THRESH)[pred_labels - 1] ignore_mask = pred_scores < labels_ignore_scores pred_labels[ignore_mask] = -1 gt_box = np.concatenate((pred_boxes, pred_labels.reshape(-1, 1), pred_scores.reshape(-1, 1)), axis=1) else: # no predicted boxes passes self-training score threshold gt_box = np.zeros((0, 9), dtype=np.float32) gt_infos = { 'gt_boxes': gt_box, 'cls_scores': pred_cls_scores, 'iou_scores': pred_iou_scores, 'memory_counter': np.zeros(gt_box.shape[0]) } # record pseudo label to pseudo label dict if need_update: ensemble_func = getattr(memory_ensemble_utils, cfg.SELF_TRAIN.MEMORY_ENSEMBLE.NAME) gt_infos = ensemble_func(PSEUDO_LABELS[input_dict['frame_id'][b_idx]], gt_infos, cfg.SELF_TRAIN.MEMORY_ENSEMBLE) if gt_infos['gt_boxes'].shape[0] > 0: ign_ps_meter.update((gt_infos['gt_boxes'][:, 7] < 0).sum()) else: ign_ps_meter.update(0) pos_ps_meter.update(gt_infos['gt_boxes'].shape[0] - ign_ps_meter.val) NEW_PSEUDO_LABELS[input_dict['frame_id'][b_idx]] = gt_infos return pos_ps_meter.avg, ign_ps_meter.avg def load_ps_label(frame_id): """ :param frame_id: file name of pseudo label :return gt_box: loaded gt boxes (N, 9) [x, y, z, w, l, h, ry, label, scores] """ if frame_id in PSEUDO_LABELS: gt_box = PSEUDO_LABELS[frame_id]['gt_boxes'] else: raise ValueError('Cannot find pseudo label for frame: %s' % frame_id) return gt_box
8,934
35.769547
95
py
3DTrans
3DTrans-master/pcdet/utils/spconv_utils.py
from typing import Set try: import spconv.pytorch as spconv except: import spconv as spconv import torch.nn as nn def find_all_spconv_keys(model: nn.Module, prefix="") -> Set[str]: """ Finds all spconv keys that need to have weight's transposed """ found_keys: Set[str] = set() for name, child in model.named_children(): new_prefix = f"{prefix}.{name}" if prefix != "" else name if isinstance(child, spconv.conv.SparseConvolution): new_prefix = f"{new_prefix}.weight" found_keys.add(new_prefix) found_keys.update(find_all_spconv_keys(child, prefix=new_prefix)) return found_keys def replace_feature(out, new_features): if "replace_feature" in out.__dir__(): # spconv 2.x behaviour return out.replace_feature(new_features) else: out.features = new_features return out
896
24.628571
73
py
3DTrans
3DTrans-master/pcdet/utils/active_learning_utils.py
import io import os import tqdm import pickle import random import torch import numpy as np import torch.distributed as dist import torch.nn.functional as F from pathlib import Path from pcdet.models import load_data_to_gpu from pcdet.utils import common_utils, commu_utils def active_evaluate(model, target_loader, rank): if rank == 0: print("======> Active Evaluate <======") dataloader_iter_tar = iter(target_loader) total_iter_tar = len(dataloader_iter_tar) frame_scores = [] return_scores = [] model.eval() if rank == 0: pbar = tqdm.tqdm(total=total_iter_tar, leave=False, desc='active_evaluate', dynamic_ncols=True) for cur_it in range(total_iter_tar): try: batch = next(dataloader_iter_tar) except StopIteration: dataloader_iter_tar = iter(target_loader) batch = next(dataloader_iter_tar) print('new iter') with torch.no_grad(): load_data_to_gpu(batch) forward_args = { 'mode': 'active_evaluate' } sample_score = model(batch, **forward_args) frame_scores.append(sample_score) if rank == 0: pbar.update() pbar.refresh() if rank == 0: pbar.close() gather_scores = gather_all_scores(frame_scores) for score in gather_scores: for f_score in score: return_scores += f_score return return_scores def active_evaluate_dual(model, target_loader, rank, domain): if rank == 0: print("======> Active Evaluate <======") dataloader_iter_tar = iter(target_loader) total_iter_tar = len(dataloader_iter_tar) frame_scores = [] return_scores = [] model.eval() if rank == 0: pbar = tqdm.tqdm(total=total_iter_tar, leave=False, desc='active_evaluate', dynamic_ncols=True) for cur_it in range(total_iter_tar): try: batch = next(dataloader_iter_tar) except StopIteration: dataloader_iter_tar = iter(target_loader) batch = next(dataloader_iter_tar) print('new iter') with torch.no_grad(): load_data_to_gpu(batch) forward_args = { 'mode': 'active_evaluate', 'domain': domain } sample_score = model(batch, **forward_args) frame_scores.append(sample_score) if rank == 0: pbar.update() pbar.refresh() if rank == 0: pbar.close() gather_scores = gather_all_scores(frame_scores) for score in gather_scores: for f_score in score: return_scores += f_score return return_scores def gather_all_scores(frame_scores): commu_utils.synchronize() if dist.is_initialized(): scores = commu_utils.all_gather(frame_scores) else: scores = [frame_scores] commu_utils.synchronize() return scores def distributed_concat(tensor): output_tensor = [tensor.clone() for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(output_tensor, tensor) concat_tensor = torch.cat(output_tensor, dim=0) return concat_tensor def get_target_list(target_pkl_file, oss): if oss == True: from petrel_client.client import Client client = Client('~/.petreloss.conf') pkl_bytes = client.get(target_pkl_file, update_cache=True) target_list = pickle.load(io.BytesIO(pkl_bytes)) else: with open(target_pkl_file, 'rb') as f: target_list = pickle.load(f) return target_list def get_dataset_list(dataset_file, oss, sample_interval=10, waymo=False): if oss == True: from petrel_client.client import Client client = Client('~/.petreloss.conf') if waymo == False: if oss == True: # from petrel_client.client import Client # client = Client('~/.petreloss.conf') pkl_bytes = client.get(dataset_file, update_cache=True) target_list = pickle.load(io.BytesIO(pkl_bytes)) else: with open(dataset_file, 'rb') as f: target_list = pickle.load(f) else: data_path = '../data/waymo/ImageSets/train.txt' target_list = [] sample_sequence_list = [x.strip() for x in open(data_path).readlines()] for k in tqdm.tqdm(range(len(sample_sequence_list))): sequence_name = os.path.splitext(sample_sequence_list[k])[0] if oss == False: info_path = Path(dataset_file) / sequence_name / ('%s.pkl' % sequence_name) if not Path(info_path).exists(): continue else: info_path = os.path.join(dataset_file, sequence_name, ('%s.pkl' % sequence_name)) # if not Path(info_path).exists(): # continue if oss == False: with open(info_path, 'rb') as f: infos = pickle.load(f) target_list.extend(infos) else: pkl_bytes = client.get(info_path, update_cache=True) infos = pickle.load(io.BytesIO(pkl_bytes)) target_list.extend(infos) if sample_interval > 1: sampled_waymo_infos = [] for k in range(0, len(target_list), sample_interval): sampled_waymo_infos.append(target_list[k]) target_list = sampled_waymo_infos return target_list def update_sample_list(sample_list, target_list, sample_frame_id, epoch, save_path, target_name, rank): if target_name == 'ActiveKittiDataset': new_sample_list = [item for item in target_list if item['point_cloud']['lidar_idx'] in sample_frame_id] elif target_name == 'ActiveNuScenesDataset': new_sample_list = [item for item in target_list if Path(item['lidar_path']).stem in sample_frame_id] sample_list = sample_list + new_sample_list sample_list_path = save_path / ('epoch-%d_sample_list.pkl' % epoch) if rank == 0: with open(sample_list_path, 'wb') as f: pickle.dump(sample_list, f) commu_utils.synchronize() return sample_list, sample_list_path def update_sample_list_dual(sample_list, dataset_list, sample_frame_id, epoch, save_path, dataset_name, rank, domain='source'): if dataset_name == 'ActiveKittiDataset': assert domain == 'target' new_sample_list = [item for item in dataset_list if item['point_cloud']['lidar_idx'] in sample_frame_id] sample_list = sample_list + new_sample_list elif dataset_name == 'ActiveNuScenesDataset': if domain == 'target': new_sample_list = [item for item in dataset_list if Path(item['lidar_path']).stem in sample_frame_id] sample_list = sample_list + new_sample_list else: sample_list = [item for item in dataset_list if Path(item['lidar_path']).stem in sample_frame_id] elif dataset_name =='ActiveLyftDataset': assert domain == 'target' new_sample_list = [item for item in dataset_list if Path(item['lidar_path']).stem in sample_frame_id] sample_list = sample_list + new_sample_list elif dataset_name == 'ActiveWaymoDataset': assert domain == 'source' sample_list = [item for item in dataset_list if str(item['frame_id']) in sample_frame_id] sample_list_path = save_path / ('epoch-%d_sample_list_' % epoch + '_' + domain + '.pkl') if rank == 0: with open(sample_list_path, 'wb') as f: pickle.dump(sample_list, f) commu_utils.synchronize() return sample_list, sample_list_path def update_target_list(target_list, sample_frame_id, epoch, save_path, target_name, rank): if target_name == 'ActiveKittiDataset': target_list = [item for item in target_list if item['point_cloud']['lidar_idx'] not in sample_frame_id] elif target_name == 'ActiveNuScenesDataset': target_list = [item for item in target_list if Path(item['lidar_path']).stem not in sample_frame_id] target_list_path = save_path / ('epoch-%d_target_list.pkl' % epoch) if rank == 0: with open(target_list_path, 'wb') as f: pickle.dump(target_list, f) commu_utils.synchronize() return target_list, target_list_path def active_sample(frame_scores, budget): frame_sorted = sorted(frame_scores, key=lambda keys: keys.get("total_score"), reverse=True) sampled_frame_info = frame_sorted[:budget] sampled_frame_id = [frame['frame_id'] for frame in sampled_frame_info] return sampled_frame_id, sampled_frame_info def active_sample_source(frame_scores, budget): sampled_frame_info = [item for item in frame_scores if item['total_score'] > 0] sampled_frame_id = [frame['frame_id'] for frame in sampled_frame_info] return sampled_frame_id, sampled_frame_info def active_sample_tar(frame_scores, budget, logger=None): roi_feature = frame_scores[0].get('roi_feature', None) feature_dim = roi_feature.shape[-1] sample_roi_feature = roi_feature.new_zeros((budget, feature_dim)) prototype_roi_feature = roi_feature.new_zeros((budget, feature_dim)) roi_feature = roi_feature.new_zeros((budget+1, feature_dim)) domainness_list = [] feature_list = [] sample_feature_list = [] for item in frame_scores: cur_roi_feature = item.get('roi_feature') cur_roi_feature = cur_roi_feature.to(roi_feature.device) cur_domainness = item.get('domainness_evaluate') cur_domainness = cur_domainness.to(roi_feature.device) if len(feature_list) < budget: sample_roi_feature[len(feature_list)] = cur_roi_feature prototype_roi_feature[len(feature_list)] = cur_roi_feature roi_feature[len(feature_list)] = cur_roi_feature feature_list.append([item]) sample_feature_list.append(item) domainness_list.append(cur_domainness) else: roi_feature[-1, :] = cur_roi_feature similarity_matrix = F.normalize(roi_feature, dim=1) @ F.normalize(roi_feature, dim=1).transpose(1,0).contiguous() similarity, inds = similarity_matrix.topk(k=2, dim=0) similarity = similarity[1] inds = inds[1] if similarity.min(dim=-1)[0] == similarity[-1]: similarity_max = similarity.max(dim=-1) inds_y = similarity.argmax(dim=-1) inds_x = inds[inds_y] domainness_x = domainness_list[inds_x] domainness_y = domainness_list[inds_y] roi_feature_1 = sample_roi_feature[inds_x] roi_feature_2 = sample_roi_feature[inds_y] num_merge_prototype_1 = len(feature_list[inds_x]) num_merge_prototype_2 = len(feature_list[inds_y]) merge_proto = (num_merge_prototype_1 * prototype_roi_feature[inds_x] + num_merge_prototype_2 * prototype_roi_feature[inds_y]) / (num_merge_prototype_1 + num_merge_prototype_2) if domainness_x > domainness_y: prototype_roi_feature[inds_x] = merge_proto sample_roi_feature[inds_y] = cur_roi_feature roi_feature[inds_y] = cur_roi_feature feature_list[inds_x] = feature_list[inds_x] + feature_list[inds_y] feature_list[inds_y] = [item] sample_feature_list[inds_y] = item domainness_list[inds_y] = cur_domainness else: prototype_roi_feature[inds_y] = merge_proto sample_roi_feature[inds_x] = cur_roi_feature roi_feature[inds_x] = cur_roi_feature feature_list[inds_y] = feature_list[inds_x] + feature_list[inds_y] feature_list[inds_x] = [item] sample_feature_list[inds_x] = item domainness_list[inds_x] = cur_domainness else: merge_inds = inds[budget] merge_domainness = domainness_list[merge_inds] num_merge_proto = len(feature_list[merge_inds]) merge_proto = (num_merge_proto * prototype_roi_feature[merge_inds] + cur_roi_feature) / (num_merge_proto + 1) prototype_roi_feature[merge_inds] = merge_proto if cur_domainness > merge_domainness: sample_roi_feature[merge_inds] = cur_roi_feature roi_feature[merge_inds] = cur_roi_feature sample_feature_list[merge_inds] = item domainness_list[merge_inds] = cur_domainness feature_list[merge_inds].append(item) for l in feature_list: sorted(l, key=lambda keys: keys.get("total_score"), reverse=True) num_each_group = [len(l) for l in feature_list] distance_matrix = F.normalize(prototype_roi_feature, dim=1) @ F.normalize(prototype_roi_feature, dim=1).transpose(0, 1).contiguous() distance, inds = distance_matrix.topk(k=2, dim=0) distance_each_group = distance[1] sample_num_each_group = distance_each_group.cpu() * torch.Tensor(num_each_group).cpu() sample_num_each_group = assign_sample_num(sample_num_each_group.numpy().tolist(), budget) sample_feature_list_new = [] for i, sample_num in enumerate(sample_num_each_group): sampled = 0 while sampled < sample_num: sample_feature_list_new.append(feature_list[i][sampled]) sampled += 1 sample_list_new = [] for item in sample_feature_list_new: sample_list_new.append(item['frame_id']) sample_list = [] for i, list in enumerate(feature_list): num = len(list) print('group %d has %d sample_frame' % (i, sample_num_each_group[i])) print('group %d has %d frame' % (i, num)) if logger != None: logger.info('group %d has %d sample_frame' % (i, sample_num_each_group[i])) logger.info('group %d has %d frame' % (i, num)) for item in sample_feature_list: sample_list.append(item['frame_id']) return sample_list_new, sample_feature_list_new def assign_sample_num(sample_num_list, budget): sampled_num = 0 sample_num_each_list = [0] * len(sample_num_list) while sampled_num < budget: ind = sample_num_list.index(max(sample_num_list)) sample_num_each_list[ind] += 1 sample_num_list[ind] /= 2 sampled_num += 1 return sample_num_each_list def random_sample(source_list, target_list, source_budget, target_budget, save_path): random.shuffle(target_list) random.shuffle(source_list) target_sample_list = random.sample(target_list, target_budget) source_sample_list = random.sample(source_list, source_budget) target_sample_path = save_path / ('random_target_list.pkl') source_sample_path = save_path / ('random_source_list.pkl') with open(target_sample_path, 'wb') as f: pickle.dump(target_sample_list, f) with open(source_sample_path, 'wb') as f: pickle.dump(source_sample_list, f) return source_sample_path, target_sample_path def random_sample_target(target_list, target_budget, save_path): random.shuffle(target_list) target_sample_list = random.sample(target_list, target_budget) target_sample_path = save_path / ('random_target_list.pkl') with open(target_sample_path, 'wb') as f: pickle.dump(target_sample_list, f) return target_sample_path
15,595
40.589333
191
py
3DTrans
3DTrans-master/pcdet/utils/memory_ensemble_utils.py
import torch import numpy as np from scipy.optimize import linear_sum_assignment from pcdet.utils import common_utils from pcdet.ops.iou3d_nms import iou3d_nms_utils from pcdet.models.model_utils.model_nms_utils import class_agnostic_nms def consistency_ensemble(gt_infos_a, gt_infos_b, memory_ensemble_cfg): """ Args: gt_infos_a: gt_boxes: (N, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for previous pseudo boxes cls_scores: (N) iou_scores: (N) memory_counter: (N) gt_infos_b: gt_boxes: (M, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for current pseudo boxes cls_scores: (M) iou_scores: (M) memory_counter: (M) memory_ensemble_cfg: Returns: gt_infos: gt_boxes: (K, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for merged pseudo boxes cls_scores: (K) iou_scores: (K) memory_counter: (K) """ gt_box_a, _ = common_utils.check_numpy_to_torch(gt_infos_a['gt_boxes']) gt_box_b, _ = common_utils.check_numpy_to_torch(gt_infos_b['gt_boxes']) gt_box_a, gt_box_b = gt_box_a.cuda(), gt_box_b.cuda() new_gt_box = gt_infos_a['gt_boxes'] new_cls_scores = gt_infos_a['cls_scores'] new_iou_scores = gt_infos_a['iou_scores'] new_memory_counter = gt_infos_a['memory_counter'] # if gt_box_b or gt_box_a don't have any predictions if gt_box_b.shape[0] == 0: gt_infos_a['memory_counter'] += 1 return gt_infos_a elif gt_box_a.shape[0] == 0: return gt_infos_b # get ious iou_matrix = iou3d_nms_utils.boxes_iou3d_gpu(gt_box_a[:, :7], gt_box_b[:, :7]).cpu() ious, match_idx = torch.max(iou_matrix, dim=1) ious, match_idx = ious.numpy(), match_idx.numpy() gt_box_a, gt_box_b = gt_box_a.cpu().numpy(), gt_box_b.cpu().numpy() match_pairs_idx = np.concatenate(( np.array(list(range(gt_box_a.shape[0]))).reshape(-1, 1), match_idx.reshape(-1, 1)), axis=1) ######################################################### # filter matched pair boxes by IoU # if matching succeeded, use boxes with higher confidence ######################################################### iou_mask = (ious >= memory_ensemble_cfg.IOU_THRESH) matching_selected = match_pairs_idx[iou_mask] gt_box_selected_a = gt_box_a[matching_selected[:, 0]] gt_box_selected_b = gt_box_b[matching_selected[:, 1]] # assign boxes with higher confidence score_mask = gt_box_selected_a[:, 8] < gt_box_selected_b[:, 8] if memory_ensemble_cfg.get('WEIGHTED', None): weight = gt_box_selected_a[:, 8] / (gt_box_selected_a[:, 8] + gt_box_selected_b[:, 8]) min_scores = np.minimum(gt_box_selected_a[:, 8], gt_box_selected_b[:, 8]) max_scores = np.maximum(gt_box_selected_a[:, 8], gt_box_selected_b[:, 8]) weighted_score = weight * (max_scores - min_scores) + min_scores new_gt_box[matching_selected[:, 0], :7] = weight.reshape(-1, 1) * gt_box_selected_a[:, :7] + \ (1 - weight.reshape(-1, 1)) * gt_box_selected_b[:, :7] new_gt_box[matching_selected[:, 0], 8] = weighted_score else: new_gt_box[matching_selected[score_mask, 0], :] = gt_box_selected_b[score_mask, :] if gt_infos_a['cls_scores'] is not None: new_cls_scores[matching_selected[score_mask, 0]] = gt_infos_b['cls_scores'][ matching_selected[score_mask, 1]] if gt_infos_a['iou_scores'] is not None: new_iou_scores[matching_selected[score_mask, 0]] = gt_infos_b['iou_scores'][ matching_selected[score_mask, 1]] # for matching pairs, clear the ignore counter new_memory_counter[matching_selected[:, 0]] = 0 ####################################################### # If previous bboxes disappeared: ious <= 0.1 ####################################################### disappear_idx = (ious < memory_ensemble_cfg.IOU_THRESH).nonzero()[0] if memory_ensemble_cfg.get('MEMORY_VOTING', None) and memory_ensemble_cfg.MEMORY_VOTING.ENABLED: new_memory_counter[disappear_idx] += 1 # ignore gt_boxes that ignore_count == IGNORE_THRESH ignore_mask = new_memory_counter >= memory_ensemble_cfg.MEMORY_VOTING.IGNORE_THRESH new_gt_box[ignore_mask, 7] = -1 # remove gt_boxes that ignore_count >= RM_THRESH remain_mask = new_memory_counter < memory_ensemble_cfg.MEMORY_VOTING.RM_THRESH new_gt_box = new_gt_box[remain_mask] new_memory_counter = new_memory_counter[remain_mask] if gt_infos_a['cls_scores'] is not None: new_cls_scores = new_cls_scores[remain_mask] if gt_infos_a['iou_scores'] is not None: new_iou_scores = new_iou_scores[remain_mask] # Add new appear boxes ious_b2a, match_idx_b2a = torch.max(iou_matrix, dim=0) ious_b2a, match_idx_b2a = ious_b2a.numpy(), match_idx_b2a.numpy() newboxes_idx = (ious_b2a < memory_ensemble_cfg.IOU_THRESH).nonzero()[0] if newboxes_idx.shape[0] != 0: new_gt_box = np.concatenate((new_gt_box, gt_infos_b['gt_boxes'][newboxes_idx, :]), axis=0) if gt_infos_a['cls_scores'] is not None: new_cls_scores = np.concatenate((new_cls_scores, gt_infos_b['cls_scores'][newboxes_idx]), axis=0) if gt_infos_a['iou_scores'] is not None: new_iou_scores = np.concatenate((new_iou_scores, gt_infos_b['iou_scores'][newboxes_idx]), axis=0) new_memory_counter = np.concatenate((new_memory_counter, gt_infos_b['memory_counter'][newboxes_idx]), axis=0) new_gt_infos = { 'gt_boxes': new_gt_box, 'cls_scores': new_cls_scores if gt_infos_a['cls_scores'] is not None else None, 'iou_scores': new_iou_scores if gt_infos_a['iou_scores'] is not None else None, 'memory_counter': new_memory_counter } return new_gt_infos def nms_ensemble(gt_infos_a, gt_infos_b, memory_ensemble_cfg): """ Args: gt_infos_a: gt_boxes: (N, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for previous pseudo boxes cls_scores: (N) iou_scores: (N) memory_counter: (N) gt_infos_b: gt_boxes: (M, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for current pseudo boxes cls_scores: (M) iou_scores: (M) memory_counter: (M) memory_ensemble_cfg: Returns: gt_infos: gt_boxes: (K, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for merged pseudo boxes cls_scores: (K) iou_scores: (K) memory_counter: (K) """ gt_box_a, _ = common_utils.check_numpy_to_torch(gt_infos_a['gt_boxes']) gt_box_b, _ = common_utils.check_numpy_to_torch(gt_infos_b['gt_boxes']) if gt_box_b.shape[0] == 0: if memory_ensemble_cfg.get('MEMORY_VOTING', None) and memory_ensemble_cfg.MEMORY_VOTING.ENABLED: gt_infos_a['memory_counter'] += 1 return gt_infos_a elif gt_box_a.shape[0] == 0: return gt_infos_b gt_box_a, gt_box_b = gt_box_a.cuda(), gt_box_b.cuda() gt_boxes = torch.cat((gt_box_a, gt_box_b), dim=0) if gt_infos_a['cls_scores'] is not None: new_cls_scores = np.concatenate((gt_infos_a['cls_scores'], gt_infos_b['cls_scores']), axis=0) if gt_infos_a['iou_scores'] is not None: new_iou_scores = np.concatenate((gt_infos_a['iou_scores'], gt_infos_b['iou_scores']), axis=0) new_memory_counter = np.concatenate((gt_infos_a['memory_counter'], gt_infos_b['memory_counter']), axis=0) selected, selected_scores = class_agnostic_nms( box_scores=gt_boxes[:, -1], box_preds=gt_boxes[:, :7], nms_config=memory_ensemble_cfg.NMS_CONFIG ) gt_boxes = gt_boxes.cpu().numpy() if isinstance(selected, list): selected = np.array(selected) else: selected = selected.cpu().numpy() if memory_ensemble_cfg.get('MEMORY_VOTING', None) and memory_ensemble_cfg.MEMORY_VOTING.ENABLED: iou_matrix = iou3d_nms_utils.boxes_iou3d_gpu(gt_box_a[:, :7], gt_box_b[:, :7]) ious, _ = torch.max(iou_matrix, dim=1) ious = ious.cpu().numpy() gt_box_a_size = gt_box_a.shape[0] selected_a = selected[selected < gt_box_a_size] matched_mask = (ious[selected_a] > memory_ensemble_cfg.NMS_CONFIG.NMS_THRESH) match_idx = selected_a[matched_mask] new_memory_counter[match_idx] = 0 # for previous bboxes disappeared disappear_idx = (ious < memory_ensemble_cfg.NMS_CONFIG.NMS_THRESH).nonzero()[0] new_memory_counter[disappear_idx] += 1 # ignore gt_boxes that ignore_count == IGNORE_THRESH ignore_mask = new_memory_counter >= memory_ensemble_cfg.MEMORY_VOTING.IGNORE_THRESH gt_boxes[ignore_mask, 7] = -1 # remove gt_boxes that ignore_count >= RM_THRESH rm_idx = (new_memory_counter >= memory_ensemble_cfg.MEMORY_VOTING.RM_THRESH).nonzero()[0] selected = np.setdiff1d(selected, rm_idx) selected_gt_boxes = gt_boxes[selected] new_gt_infos = { 'gt_boxes': selected_gt_boxes, 'cls_scores': new_cls_scores[selected] if gt_infos_a['cls_scores'] is not None else None, 'iou_scores': new_iou_scores[selected] if gt_infos_a['iou_scores'] is not None else None, 'memory_counter': new_memory_counter[selected] } return new_gt_infos def bipartite_ensemble(gt_infos_a, gt_infos_b, memory_ensemble_cfg): """ Args: gt_infos_a: gt_boxes: (N, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for previous pseudo boxes cls_scores: (N) iou_scores: (N) memory_counter: (N) gt_infos_b: gt_boxes: (M, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for current pseudo boxes cls_scores: (M) iou_scores: (M) memory_counter: (M) memory_ensemble_cfg: Returns: gt_infos: gt_boxes: (K, 9) [x, y, z, dx, dy, dz, heading, label, scores] in LiDAR for merged pseudo boxes cls_scores: (K) iou_scores: (K) memory_counter: (K) """ gt_box_a, _ = common_utils.check_numpy_to_torch(gt_infos_a['gt_boxes']) gt_box_b, _ = common_utils.check_numpy_to_torch(gt_infos_b['gt_boxes']) gt_box_a, gt_box_b = gt_box_a.cuda(), gt_box_b.cuda() new_gt_box = gt_infos_a['gt_boxes'] new_cls_scores = gt_infos_a['cls_scores'] new_iou_scores = gt_infos_a['iou_scores'] new_memory_counter = gt_infos_a['memory_counter'] # if gt_box_b or gt_box_a don't have any predictions if gt_box_b.shape[0] == 0: gt_infos_a['memory_counter'] += 1 return gt_infos_a elif gt_box_a.shape[0] == 0: return gt_infos_b # bipartite matching iou_matrix = iou3d_nms_utils.boxes_iou3d_gpu(gt_box_a[:, :7], gt_box_b[:, :7]) iou_matrix = iou_matrix.cpu().numpy() a_idx, b_idx = linear_sum_assignment(-iou_matrix) gt_box_a, gt_box_b = gt_box_a.cpu().numpy(), gt_box_b.cpu().numpy() matching_paris_idx = np.concatenate((a_idx.reshape(-1, 1), b_idx.reshape(-1, 1)), axis=1) ious = iou_matrix[matching_paris_idx[:, 0], matching_paris_idx[:, 1]] # matched a boxes. matched_mask = ious > memory_ensemble_cfg.IOU_THRESH matching_selected = matching_paris_idx[matched_mask] gt_box_selected_a = gt_box_a[matching_selected[:, 0]] gt_box_selected_b = gt_box_b[matching_selected[:, 1]] # assign boxes with higher confidence score_mask = gt_box_selected_a[:, 8] < gt_box_selected_b[:, 8] new_gt_box[matching_selected[score_mask, 0], :] = gt_box_selected_b[score_mask, :] if gt_infos_a['cls_scores'] is not None: new_cls_scores[matching_selected[score_mask, 0]] = gt_infos_b['cls_scores'][ matching_selected[score_mask, 1]] if gt_infos_a['iou_scores'] is not None: new_iou_scores[matching_selected[score_mask, 0]] = gt_infos_b['iou_scores'][ matching_selected[score_mask, 1]] # for matched pairs, clear the ignore counter new_memory_counter[matching_selected[:, 0]] = 0 ############################################## # disppeared boxes for previous pseudo boxes ############################################## gt_box_a_idx = np.array(list(range(gt_box_a.shape[0]))) disappear_idx = np.setdiff1d(gt_box_a_idx, matching_selected[:, 0]) if memory_ensemble_cfg.get('MEMORY_VOTING', None) and memory_ensemble_cfg.MEMORY_VOTING.ENABLED: new_memory_counter[disappear_idx] += 1 # ignore gt_boxes that ignore_count == IGNORE_THRESH ignore_mask = new_memory_counter >= memory_ensemble_cfg.MEMORY_VOTING.IGNORE_THRESH new_gt_box[ignore_mask, 7] = -1 # remove gt_boxes that ignore_count >= RM_THRESH remain_mask = new_memory_counter < memory_ensemble_cfg.MEMORY_VOTING.RM_THRESH new_gt_box = new_gt_box[remain_mask] new_memory_counter = new_memory_counter[remain_mask] if gt_infos_a['cls_scores'] is not None: new_cls_scores = new_cls_scores[remain_mask] if gt_infos_a['iou_scores'] is not None: new_iou_scores = new_iou_scores[remain_mask] ############################################## # new appear boxes for current pseudo boxes ############################################## gt_box_b_idx = np.array(list(range(gt_box_b.shape[0]))) newboxes_idx = np.setdiff1d(gt_box_b_idx, matching_selected[:, 1]) if newboxes_idx.shape[0] != 0: new_gt_box = np.concatenate((new_gt_box, gt_infos_b['gt_boxes'][newboxes_idx, :]), axis=0) if gt_infos_a['cls_scores'] is not None: new_cls_scores = np.concatenate((new_cls_scores, gt_infos_b['cls_scores'][newboxes_idx]), axis=0) if gt_infos_a['iou_scores'] is not None: new_iou_scores = np.concatenate((new_iou_scores, gt_infos_b['iou_scores'][newboxes_idx]), axis=0) new_memory_counter = np.concatenate((new_memory_counter, gt_infos_b['memory_counter'][newboxes_idx]), axis=0) new_gt_infos = { 'gt_boxes': new_gt_box, 'cls_scores': new_cls_scores if gt_infos_a['cls_scores'] is not None else None, 'iou_scores': new_iou_scores if gt_infos_a['iou_scores'] is not None else None, 'memory_counter': new_memory_counter } return new_gt_infos
14,715
41.90379
117
py
3DTrans
3DTrans-master/pcdet/utils/commu_utils.py
""" This file contains primitives for multi-gpu communication. This is useful when doing distributed training. deeply borrow from maskrcnn-benchmark and ST3D """ import pickle import time import torch import torch.distributed as dist def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank(): if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def is_main_process(): 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 dist.barrier() def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # serialized to a Tensor origin_size = None if not isinstance(data, torch.Tensor): buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to("cuda") else: origin_size = data.size() tensor = data.reshape(-1) tensor_type = tensor.dtype # obtain Tensor size of each rank local_size = torch.LongTensor([tensor.numel()]).to("cuda") size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # receiving Tensor from all ranks # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes tensor_list = [] for _ in size_list: tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type)) if local_size != max_size: padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type) tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor) data_list = [] for size, tensor in zip(size_list, tensor_list): if origin_size is None: buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) else: buffer = tensor[:size] data_list.append(buffer) if origin_size is not None: new_shape = [-1] + list(origin_size[1:]) resized_list = [] for data in data_list: # suppose the difference of tensor size exist in first dimension data = data.reshape(new_shape) resized_list.append(data) return resized_list else: return data_list def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields 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 def average_reduce_value(data): data_list = all_gather(data) return sum(data_list) / len(data_list) def all_reduce(data, op="sum", average=False): def op_map(op): op_dict = { "SUM": dist.ReduceOp.SUM, "MAX": dist.ReduceOp.MAX, "MIN": dist.ReduceOp.MIN, "PRODUCT": dist.ReduceOp.PRODUCT, } return op_dict[op] world_size = get_world_size() if world_size > 1: reduced_data = data.clone() dist.all_reduce(reduced_data, op=op_map(op.upper())) if average: assert op.upper() == 'SUM' return reduced_data / world_size else: return reduced_data return data @torch.no_grad() def concat_all_gather(tensor): """ Performs all_gather operation on the provided tensors. *** Warning ***: torch.distributed.all_gather has no gradient. """ tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) output = torch.cat(tensors_gather, dim=0) return output
5,253
27.710383
89
py
3DTrans
3DTrans-master/pcdet/ops/roipoint_pool3d/roipoint_pool3d_utils.py
import torch import torch.nn as nn from torch.autograd import Function from ...utils import box_utils from . import roipoint_pool3d_cuda class RoIPointPool3d(nn.Module): def __init__(self, num_sampled_points=512, pool_extra_width=1.0): super().__init__() self.num_sampled_points = num_sampled_points self.pool_extra_width = pool_extra_width def forward(self, points, point_features, boxes3d): """ Args: points: (B, N, 3) point_features: (B, N, C) boxes3d: (B, M, 7), [x, y, z, dx, dy, dz, heading] Returns: pooled_features: (B, M, 512, 3 + C) pooled_empty_flag: (B, M) """ return RoIPointPool3dFunction.apply( points, point_features, boxes3d, self.pool_extra_width, self.num_sampled_points ) class RoIPointPool3dFunction(Function): @staticmethod def forward(ctx, points, point_features, boxes3d, pool_extra_width, num_sampled_points=512): """ Args: ctx: points: (B, N, 3) point_features: (B, N, C) boxes3d: (B, num_boxes, 7), [x, y, z, dx, dy, dz, heading] pool_extra_width: num_sampled_points: Returns: pooled_features: (B, num_boxes, 512, 3 + C) pooled_empty_flag: (B, num_boxes) """ assert points.shape.__len__() == 3 and points.shape[2] == 3 batch_size, boxes_num, feature_len = points.shape[0], boxes3d.shape[1], point_features.shape[2] pooled_boxes3d = box_utils.enlarge_box3d(boxes3d.view(-1, 7), pool_extra_width).view(batch_size, -1, 7) pooled_features = point_features.new_zeros((batch_size, boxes_num, num_sampled_points, 3 + feature_len)) pooled_empty_flag = point_features.new_zeros((batch_size, boxes_num)).int() roipoint_pool3d_cuda.forward( points.contiguous(), pooled_boxes3d.contiguous(), point_features.contiguous(), pooled_features, pooled_empty_flag ) return pooled_features, pooled_empty_flag @staticmethod def backward(ctx, grad_out): raise NotImplementedError if __name__ == '__main__': pass
2,226
31.75
112
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_stack/voxel_query_utils.py
import torch from torch.autograd import Variable from torch.autograd import Function import torch.nn as nn from typing import List from . import pointnet2_stack_cuda as pointnet2 from . import pointnet2_utils class VoxelQuery(Function): @staticmethod def forward(ctx, max_range: int, radius: float, nsample: int, xyz: torch.Tensor, \ new_xyz: torch.Tensor, new_coords: torch.Tensor, point_indices: torch.Tensor): """ Args: ctx: max_range: int, max range of voxels to be grouped nsample: int, maximum number of features in the balls new_coords: (M1 + M2, 4), [batch_id, z, y, x] cooridnates of keypoints new_xyz_batch_cnt: (batch_size), [M1, M2, ...] point_indices: (batch_size, Z, Y, X) 4-D tensor recording the point indices of voxels Returns: idx: (M1 + M2, nsample) tensor with the indicies of the features that form the query balls """ assert new_xyz.is_contiguous() assert xyz.is_contiguous() assert new_coords.is_contiguous() assert point_indices.is_contiguous() M = new_coords.shape[0] B, Z, Y, X = point_indices.shape idx = torch.cuda.IntTensor(M, nsample).zero_() z_range, y_range, x_range = max_range pointnet2.voxel_query_wrapper(M, Z, Y, X, nsample, radius, z_range, y_range, x_range, \ new_xyz, xyz, new_coords, point_indices, idx) empty_ball_mask = (idx[:, 0] == -1) idx[empty_ball_mask] = 0 return idx, empty_ball_mask @staticmethod def backward(ctx, a=None): return None, None, None, None voxel_query = VoxelQuery.apply class VoxelQueryAndGrouping(nn.Module): def __init__(self, max_range: int, radius: float, nsample: int): """ Args: radius: float, radius of ball nsample: int, maximum number of features to gather in the ball """ super().__init__() self.max_range, self.radius, self.nsample = max_range, radius, nsample def forward(self, new_coords: torch.Tensor, xyz: torch.Tensor, xyz_batch_cnt: torch.Tensor, new_xyz: torch.Tensor, new_xyz_batch_cnt: torch.Tensor, features: torch.Tensor, voxel2point_indices: torch.Tensor): """ Args: new_coords: (M1 + M2 ..., 3) centers voxel indices of the ball query xyz: (N1 + N2 ..., 3) xyz coordinates of the features xyz_batch_cnt: (batch_size), [N1, N2, ...] new_xyz: (M1 + M2 ..., 3) centers of the ball query new_xyz_batch_cnt: (batch_size), [M1, M2, ...] features: (N1 + N2 ..., C) tensor of features to group voxel2point_indices: (B, Z, Y, X) tensor of points indices of voxels Returns: new_features: (M1 + M2, C, nsample) tensor """ assert xyz.shape[0] == xyz_batch_cnt.sum(), 'xyz: %s, xyz_batch_cnt: %s' % (str(xyz.shape), str(new_xyz_batch_cnt)) assert new_coords.shape[0] == new_xyz_batch_cnt.sum(), \ 'new_coords: %s, new_xyz_batch_cnt: %s' % (str(new_coords.shape), str(new_xyz_batch_cnt)) batch_size = xyz_batch_cnt.shape[0] # idx: (M1 + M2 ..., nsample), empty_ball_mask: (M1 + M2 ...) idx1, empty_ball_mask1 = voxel_query(self.max_range, self.radius, self.nsample, xyz, new_xyz, new_coords, voxel2point_indices) idx1 = idx1.view(batch_size, -1, self.nsample) count = 0 for bs_idx in range(batch_size): idx1[bs_idx] -= count count += xyz_batch_cnt[bs_idx] idx1 = idx1.view(-1, self.nsample) idx1[empty_ball_mask1] = 0 idx = idx1 empty_ball_mask = empty_ball_mask1 grouped_xyz = pointnet2_utils.grouping_operation(xyz, xyz_batch_cnt, idx, new_xyz_batch_cnt) # grouped_features: (M1 + M2, C, nsample) grouped_features = pointnet2_utils.grouping_operation(features, xyz_batch_cnt, idx, new_xyz_batch_cnt) return grouped_features, grouped_xyz, empty_ball_mask
4,148
40.079208
134
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_stack/pointnet2_utils.py
import torch import torch.nn as nn from torch.autograd import Function, Variable from . import pointnet2_stack_cuda as pointnet2 class BallQuery(Function): @staticmethod def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, xyz_batch_cnt: torch.Tensor, new_xyz: torch.Tensor, new_xyz_batch_cnt): """ Args: ctx: radius: float, radius of the balls nsample: int, maximum number of features in the balls xyz: (N1 + N2 ..., 3) xyz coordinates of the features xyz_batch_cnt: (batch_size), [N1, N2, ...] new_xyz: (M1 + M2 ..., 3) centers of the ball query new_xyz_batch_cnt: (batch_size), [M1, M2, ...] Returns: idx: (M1 + M2, nsample) tensor with the indicies of the features that form the query balls """ assert new_xyz.is_contiguous() assert new_xyz_batch_cnt.is_contiguous() assert xyz.is_contiguous() assert xyz_batch_cnt.is_contiguous() B = xyz_batch_cnt.shape[0] M = new_xyz.shape[0] idx = torch.cuda.IntTensor(M, nsample).zero_() pointnet2.ball_query_wrapper(B, M, radius, nsample, new_xyz, new_xyz_batch_cnt, xyz, xyz_batch_cnt, idx) empty_ball_mask = (idx[:, 0] == -1) idx[empty_ball_mask] = 0 ctx.mark_non_differentiable(idx) ctx.mark_non_differentiable(empty_ball_mask) return idx, empty_ball_mask @staticmethod def backward(ctx, a=None, b=None): return None, None, None, None, None, None ball_query = BallQuery.apply class GroupingOperation(Function): @staticmethod def forward(ctx, features: torch.Tensor, features_batch_cnt: torch.Tensor, idx: torch.Tensor, idx_batch_cnt: torch.Tensor): """ Args: ctx: features: (N1 + N2 ..., C) tensor of features to group features_batch_cnt: (batch_size) [N1 + N2 ...] tensor containing the indicies of features to group with idx: (M1 + M2 ..., nsample) tensor containing the indicies of features to group with idx_batch_cnt: (batch_size) [M1 + M2 ...] tensor containing the indicies of features to group with Returns: output: (M1 + M2, C, nsample) tensor """ assert features.is_contiguous() assert features_batch_cnt.is_contiguous() assert idx.is_contiguous() assert idx_batch_cnt.is_contiguous() assert features.shape[0] == features_batch_cnt.sum(), \ 'features: %s, features_batch_cnt: %s' % (str(features.shape), str(features_batch_cnt)) assert idx.shape[0] == idx_batch_cnt.sum(), \ 'idx: %s, idx_batch_cnt: %s' % (str(idx.shape), str(idx_batch_cnt)) M, nsample = idx.size() N, C = features.size() B = idx_batch_cnt.shape[0] output = torch.cuda.FloatTensor(M, C, nsample) pointnet2.group_points_wrapper(B, M, C, nsample, features, features_batch_cnt, idx, idx_batch_cnt, output) ctx.for_backwards = (B, N, idx, features_batch_cnt, idx_batch_cnt) return output @staticmethod def backward(ctx, grad_out: torch.Tensor): """ Args: ctx: grad_out: (M1 + M2 ..., C, nsample) tensor of the gradients of the output from forward Returns: grad_features: (N1 + N2 ..., C) gradient of the features """ B, N, idx, features_batch_cnt, idx_batch_cnt = ctx.for_backwards M, C, nsample = grad_out.size() grad_features = Variable(torch.cuda.FloatTensor(N, C).zero_()) grad_out_data = grad_out.data.contiguous() pointnet2.group_points_grad_wrapper(B, M, C, N, nsample, grad_out_data, idx, idx_batch_cnt, features_batch_cnt, grad_features.data) return grad_features, None, None, None grouping_operation = GroupingOperation.apply class QueryAndGroup(nn.Module): def __init__(self, radius: float, nsample: int, use_xyz: bool = True): """ Args: radius: float, radius of ball nsample: int, maximum number of features to gather in the ball use_xyz: """ super().__init__() self.radius, self.nsample, self.use_xyz = radius, nsample, use_xyz def forward(self, xyz: torch.Tensor, xyz_batch_cnt: torch.Tensor, new_xyz: torch.Tensor, new_xyz_batch_cnt: torch.Tensor, features: torch.Tensor = None): """ Args: xyz: (N1 + N2 ..., 3) xyz coordinates of the features xyz_batch_cnt: (batch_size), [N1, N2, ...] new_xyz: (M1 + M2 ..., 3) centers of the ball query new_xyz_batch_cnt: (batch_size), [M1, M2, ...] features: (N1 + N2 ..., C) tensor of features to group Returns: new_features: (M1 + M2, C, nsample) tensor """ assert xyz.shape[0] == xyz_batch_cnt.sum(), 'xyz: %s, xyz_batch_cnt: %s' % (str(xyz.shape), str(new_xyz_batch_cnt)) assert new_xyz.shape[0] == new_xyz_batch_cnt.sum(), \ 'new_xyz: %s, new_xyz_batch_cnt: %s' % (str(new_xyz.shape), str(new_xyz_batch_cnt)) # idx: (M1 + M2 ..., nsample), empty_ball_mask: (M1 + M2 ...) idx, empty_ball_mask = ball_query(self.radius, self.nsample, xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt) grouped_xyz = grouping_operation(xyz, xyz_batch_cnt, idx, new_xyz_batch_cnt) # (M1 + M2, 3, nsample) grouped_xyz -= new_xyz.unsqueeze(-1) grouped_xyz[empty_ball_mask] = 0 if features is not None: grouped_features = grouping_operation(features, xyz_batch_cnt, idx, new_xyz_batch_cnt) # (M1 + M2, C, nsample) grouped_features[empty_ball_mask] = 0 if self.use_xyz: new_features = torch.cat([grouped_xyz, grouped_features], dim=1) # (M1 + M2 ..., C + 3, nsample) else: new_features = grouped_features else: assert self.use_xyz, "Cannot have not features and not use xyz as a feature!" new_features = grouped_xyz return new_features, idx class FarthestPointSampling(Function): @staticmethod def forward(ctx, xyz: torch.Tensor, npoint: int): """ Args: ctx: xyz: (B, N, 3) where N > npoint npoint: int, number of features in the sampled set Returns: output: (B, npoint) tensor containing the set """ assert xyz.is_contiguous() B, N, _ = xyz.size() output = torch.cuda.IntTensor(B, npoint) temp = torch.cuda.FloatTensor(B, N).fill_(1e10) pointnet2.farthest_point_sampling_wrapper(B, N, npoint, xyz, temp, output) return output @staticmethod def backward(xyz, a=None): return None, None farthest_point_sample = furthest_point_sample = FarthestPointSampling.apply class StackFarthestPointSampling(Function): @staticmethod def forward(ctx, xyz, xyz_batch_cnt, npoint): """ Args: ctx: xyz: (N1 + N2 + ..., 3) where N > npoint xyz_batch_cnt: [N1, N2, ...] npoint: int, number of features in the sampled set Returns: output: (npoint.sum()) tensor containing the set, npoint: (M1, M2, ...) """ assert xyz.is_contiguous() and xyz.shape[1] == 3 batch_size = xyz_batch_cnt.__len__() if not isinstance(npoint, torch.Tensor): if not isinstance(npoint, list): npoint = [npoint for i in range(batch_size)] npoint = torch.tensor(npoint, device=xyz.device).int() N, _ = xyz.size() temp = torch.cuda.FloatTensor(N).fill_(1e10) output = torch.cuda.IntTensor(npoint.sum().item()) pointnet2.stack_farthest_point_sampling_wrapper(xyz, temp, xyz_batch_cnt, output, npoint) return output @staticmethod def backward(xyz, a=None): return None, None stack_farthest_point_sample = StackFarthestPointSampling.apply class ThreeNN(Function): @staticmethod def forward(ctx, unknown, unknown_batch_cnt, known, known_batch_cnt): """ Args: ctx: unknown: (N1 + N2..., 3) unknown_batch_cnt: (batch_size), [N1, N2, ...] known: (M1 + M2..., 3) known_batch_cnt: (batch_size), [M1, M2, ...] Returns: dist: (N1 + N2 ..., 3) l2 distance to the three nearest neighbors idx: (N1 + N2 ..., 3) index of the three nearest neighbors, range [0, M1+M2+...] """ assert unknown.shape.__len__() == 2 and unknown.shape[1] == 3 assert known.shape.__len__() == 2 and known.shape[1] == 3 assert unknown_batch_cnt.__len__() == known_batch_cnt.__len__() dist2 = unknown.new_zeros(unknown.shape) idx = unknown_batch_cnt.new_zeros(unknown.shape).int() pointnet2.three_nn_wrapper( unknown.contiguous(), unknown_batch_cnt.contiguous(), known.contiguous(), known_batch_cnt.contiguous(), dist2, idx ) return torch.sqrt(dist2), idx @staticmethod def backward(ctx, a=None, b=None): return None, None three_nn = ThreeNN.apply class ThreeInterpolate(Function): @staticmethod def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor): """ Args: ctx: features: (M1 + M2 ..., C) idx: [N1 + N2 ..., 3] weight: [N1 + N2 ..., 3] Returns: out_tensor: (N1 + N2 ..., C) """ assert idx.shape[0] == weight.shape[0] and idx.shape[1] == weight.shape[1] == 3 ctx.three_interpolate_for_backward = (idx, weight, features.shape[0]) output = features.new_zeros((idx.shape[0], features.shape[1])) pointnet2.three_interpolate_wrapper(features.contiguous(), idx.contiguous(), weight.contiguous(), output) return output @staticmethod def backward(ctx, grad_out: torch.Tensor): """ Args: ctx: grad_out: (N1 + N2 ..., C) Returns: grad_features: (M1 + M2 ..., C) """ idx, weight, M = ctx.three_interpolate_for_backward grad_features = grad_out.new_zeros((M, grad_out.shape[1])) pointnet2.three_interpolate_grad_wrapper( grad_out.contiguous(), idx.contiguous(), weight.contiguous(), grad_features ) return grad_features, None, None three_interpolate = ThreeInterpolate.apply class ThreeNNForVectorPoolByTwoStep(Function): @staticmethod def forward(ctx, support_xyz, xyz_batch_cnt, new_xyz, new_xyz_grid_centers, new_xyz_batch_cnt, max_neighbour_distance, nsample, neighbor_type, avg_length_of_neighbor_idxs, num_total_grids, neighbor_distance_multiplier): """ Args: ctx: // support_xyz: (N1 + N2 ..., 3) xyz coordinates of the features // xyz_batch_cnt: (batch_size), [N1, N2, ...] // new_xyz: (M1 + M2 ..., 3) centers of the ball query // new_xyz_grid_centers: (M1 + M2 ..., num_total_grids, 3) grids centers of each grid // new_xyz_batch_cnt: (batch_size), [M1, M2, ...] // nsample: find all (-1), find limited number(>0) // neighbor_type: 1: ball, others: cube // neighbor_distance_multiplier: query_distance = neighbor_distance_multiplier * max_neighbour_distance Returns: // new_xyz_grid_idxs: (M1 + M2 ..., num_total_grids, 3) three-nn // new_xyz_grid_dist2: (M1 + M2 ..., num_total_grids, 3) square of dist of three-nn """ num_new_xyz = new_xyz.shape[0] new_xyz_grid_dist2 = new_xyz_grid_centers.new_zeros(new_xyz_grid_centers.shape) new_xyz_grid_idxs = new_xyz_grid_centers.new_zeros(new_xyz_grid_centers.shape).int().fill_(-1) while True: num_max_sum_points = avg_length_of_neighbor_idxs * num_new_xyz stack_neighbor_idxs = new_xyz_grid_idxs.new_zeros(num_max_sum_points) start_len = new_xyz_grid_idxs.new_zeros(num_new_xyz, 2).int() cumsum = new_xyz_grid_idxs.new_zeros(1) pointnet2.query_stacked_local_neighbor_idxs_wrapper_stack( support_xyz.contiguous(), xyz_batch_cnt.contiguous(), new_xyz.contiguous(), new_xyz_batch_cnt.contiguous(), stack_neighbor_idxs.contiguous(), start_len.contiguous(), cumsum, avg_length_of_neighbor_idxs, max_neighbour_distance * neighbor_distance_multiplier, nsample, neighbor_type ) avg_length_of_neighbor_idxs = cumsum[0].item() // num_new_xyz + int(cumsum[0].item() % num_new_xyz > 0) if cumsum[0] <= num_max_sum_points: break stack_neighbor_idxs = stack_neighbor_idxs[:cumsum[0]] pointnet2.query_three_nn_by_stacked_local_idxs_wrapper_stack( support_xyz, new_xyz, new_xyz_grid_centers, new_xyz_grid_idxs, new_xyz_grid_dist2, stack_neighbor_idxs, start_len, num_new_xyz, num_total_grids ) return torch.sqrt(new_xyz_grid_dist2), new_xyz_grid_idxs, torch.tensor(avg_length_of_neighbor_idxs) three_nn_for_vector_pool_by_two_step = ThreeNNForVectorPoolByTwoStep.apply class VectorPoolWithVoxelQuery(Function): @staticmethod def forward(ctx, support_xyz: torch.Tensor, xyz_batch_cnt: torch.Tensor, support_features: torch.Tensor, new_xyz: torch.Tensor, new_xyz_batch_cnt: torch.Tensor, num_grid_x, num_grid_y, num_grid_z, max_neighbour_distance, num_c_out_each_grid, use_xyz, num_mean_points_per_grid=100, nsample=-1, neighbor_type=0, pooling_type=0): """ Args: ctx: support_xyz: (N1 + N2 ..., 3) xyz coordinates of the features xyz_batch_cnt: (batch_size), [N1, N2, ...] support_features: (N1 + N2 ..., C) new_xyz: (M1 + M2 ..., 3) centers of new positions new_xyz_batch_cnt: (batch_size), [M1, M2, ...] num_grid_x: number of grids in each local area centered at new_xyz num_grid_y: num_grid_z: max_neighbour_distance: num_c_out_each_grid: use_xyz: neighbor_type: 1: ball, others: cube: pooling_type: 0: avg_pool, 1: random choice Returns: new_features: (M1 + M2 ..., num_c_out) """ assert support_xyz.is_contiguous() assert support_features.is_contiguous() assert xyz_batch_cnt.is_contiguous() assert new_xyz.is_contiguous() assert new_xyz_batch_cnt.is_contiguous() num_total_grids = num_grid_x * num_grid_y * num_grid_z num_c_out = num_c_out_each_grid * num_total_grids N, num_c_in = support_features.shape M = new_xyz.shape[0] assert num_c_in % num_c_out_each_grid == 0, \ f'the input channels ({num_c_in}) should be an integral multiple of num_c_out_each_grid({num_c_out_each_grid})' while True: new_features = support_features.new_zeros((M, num_c_out)) new_local_xyz = support_features.new_zeros((M, 3 * num_total_grids)) point_cnt_of_grid = xyz_batch_cnt.new_zeros((M, num_total_grids)) num_max_sum_points = num_mean_points_per_grid * M grouped_idxs = xyz_batch_cnt.new_zeros((num_max_sum_points, 3)) num_cum_sum = pointnet2.vector_pool_wrapper( support_xyz, xyz_batch_cnt, support_features, new_xyz, new_xyz_batch_cnt, new_features, new_local_xyz, point_cnt_of_grid, grouped_idxs, num_grid_x, num_grid_y, num_grid_z, max_neighbour_distance, use_xyz, num_max_sum_points, nsample, neighbor_type, pooling_type ) num_mean_points_per_grid = num_cum_sum // M + int(num_cum_sum % M > 0) if num_cum_sum <= num_max_sum_points: break grouped_idxs = grouped_idxs[:num_cum_sum] normalizer = torch.clamp_min(point_cnt_of_grid[:, :, None].float(), min=1e-6) new_features = (new_features.view(-1, num_total_grids, num_c_out_each_grid) / normalizer).view(-1, num_c_out) if use_xyz: new_local_xyz = (new_local_xyz.view(-1, num_total_grids, 3) / normalizer).view(-1, num_total_grids * 3) num_mean_points_per_grid = torch.Tensor([num_mean_points_per_grid]).int() nsample = torch.Tensor([nsample]).int() ctx.vector_pool_for_backward = (point_cnt_of_grid, grouped_idxs, N, num_c_in) ctx.mark_non_differentiable(new_local_xyz, num_mean_points_per_grid, nsample, point_cnt_of_grid) return new_features, new_local_xyz, num_mean_points_per_grid, point_cnt_of_grid @staticmethod def backward(ctx, grad_new_features: torch.Tensor, grad_local_xyz: torch.Tensor, grad_num_cum_sum, grad_point_cnt_of_grid): """ Args: ctx: grad_new_features: (M1 + M2 ..., num_c_out), num_c_out = num_c_out_each_grid * num_total_grids Returns: grad_support_features: (N1 + N2 ..., C_in) """ point_cnt_of_grid, grouped_idxs, N, num_c_in = ctx.vector_pool_for_backward grad_support_features = grad_new_features.new_zeros((N, num_c_in)) if grouped_idxs.shape[0] > 0: pointnet2.vector_pool_grad_wrapper( grad_new_features.contiguous(), point_cnt_of_grid, grouped_idxs, grad_support_features ) return None, None, grad_support_features, None, None, None, None, None, None, None, None, None, None, None, None vector_pool_with_voxel_query_op = VectorPoolWithVoxelQuery.apply if __name__ == '__main__': pass
18,073
38.462882
127
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_stack/voxel_pool_modules.py
import torch import torch.nn as nn import torch.nn.functional as F from . import voxel_query_utils from typing import List class NeighborVoxelSAModuleMSG(nn.Module): def __init__(self, *, query_ranges: List[List[int]], radii: List[float], nsamples: List[int], mlps: List[List[int]], use_xyz: bool = True, pool_method='max_pool'): """ Args: query_ranges: list of int, list of neighbor ranges to group with nsamples: list of int, number of samples in each ball query mlps: list of list of int, spec of the pointnet before the global pooling for each scale use_xyz: pool_method: max_pool / avg_pool """ super().__init__() assert len(query_ranges) == len(nsamples) == len(mlps) self.groupers = nn.ModuleList() self.mlps_in = nn.ModuleList() self.mlps_pos = nn.ModuleList() self.mlps_out = nn.ModuleList() for i in range(len(query_ranges)): max_range = query_ranges[i] nsample = nsamples[i] radius = radii[i] self.groupers.append(voxel_query_utils.VoxelQueryAndGrouping(max_range, radius, nsample)) mlp_spec = mlps[i] cur_mlp_in = nn.Sequential( nn.Conv1d(mlp_spec[0], mlp_spec[1], kernel_size=1, bias=False), nn.BatchNorm1d(mlp_spec[1]) ) cur_mlp_pos = nn.Sequential( nn.Conv2d(3, mlp_spec[1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[1]) ) cur_mlp_out = nn.Sequential( nn.Conv1d(mlp_spec[1], mlp_spec[2], kernel_size=1, bias=False), nn.BatchNorm1d(mlp_spec[2]), nn.ReLU() ) self.mlps_in.append(cur_mlp_in) self.mlps_pos.append(cur_mlp_pos) self.mlps_out.append(cur_mlp_out) self.relu = nn.ReLU() self.pool_method = pool_method self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0) def forward(self, xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt, \ new_coords, features, voxel2point_indices): """ :param xyz: (N1 + N2 ..., 3) tensor of the xyz coordinates of the features :param xyz_batch_cnt: (batch_size), [N1, N2, ...] :param new_xyz: (M1 + M2 ..., 3) :param new_xyz_batch_cnt: (batch_size), [M1, M2, ...] :param features: (N1 + N2 ..., C) tensor of the descriptors of the the features :param point_indices: (B, Z, Y, X) tensor of point indices :return: new_xyz: (M1 + M2 ..., 3) tensor of the new features' xyz new_features: (M1 + M2 ..., \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ # change the order to [batch_idx, z, y, x] new_coords = new_coords[:, [0, 3, 2, 1]].contiguous() new_features_list = [] for k in range(len(self.groupers)): # features_in: (1, C, M1+M2) features_in = features.permute(1, 0).unsqueeze(0) features_in = self.mlps_in[k](features_in) # features_in: (1, M1+M2, C) features_in = features_in.permute(0, 2, 1).contiguous() # features_in: (M1+M2, C) features_in = features_in.view(-1, features_in.shape[-1]) # grouped_features: (M1+M2, C, nsample) # grouped_xyz: (M1+M2, 3, nsample) grouped_features, grouped_xyz, empty_ball_mask = self.groupers[k]( new_coords, xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt, features_in, voxel2point_indices ) grouped_features[empty_ball_mask] = 0 # grouped_features: (1, C, M1+M2, nsample) grouped_features = grouped_features.permute(1, 0, 2).unsqueeze(dim=0) # grouped_xyz: (M1+M2, 3, nsample) grouped_xyz = grouped_xyz - new_xyz.unsqueeze(-1) grouped_xyz[empty_ball_mask] = 0 # grouped_xyz: (1, 3, M1+M2, nsample) grouped_xyz = grouped_xyz.permute(1, 0, 2).unsqueeze(0) # grouped_xyz: (1, C, M1+M2, nsample) position_features = self.mlps_pos[k](grouped_xyz) new_features = grouped_features + position_features new_features = self.relu(new_features) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ).squeeze(dim=-1) # (1, C, M1 + M2 ...) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ).squeeze(dim=-1) # (1, C, M1 + M2 ...) else: raise NotImplementedError new_features = self.mlps_out[k](new_features) new_features = new_features.squeeze(dim=0).permute(1, 0) # (M1 + M2 ..., C) new_features_list.append(new_features) # (M1 + M2 ..., C) new_features = torch.cat(new_features_list, dim=1) return new_features
5,672
41.977273
108
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_stack/pointnet2_modules.py
from typing import List import torch import torch.nn as nn import torch.nn.functional as F from . import pointnet2_utils def build_local_aggregation_module(input_channels, config): local_aggregation_name = config.get('NAME', 'StackSAModuleMSG') if local_aggregation_name == 'StackSAModuleMSG': mlps = config.MLPS for k in range(len(mlps)): mlps[k] = [input_channels] + mlps[k] cur_layer = StackSAModuleMSG( radii=config.POOL_RADIUS, nsamples=config.NSAMPLE, mlps=mlps, use_xyz=True, pool_method='max_pool', ) num_c_out = sum([x[-1] for x in mlps]) elif local_aggregation_name == 'VectorPoolAggregationModuleMSG': cur_layer = VectorPoolAggregationModuleMSG(input_channels=input_channels, config=config) num_c_out = config.MSG_POST_MLPS[-1] else: raise NotImplementedError return cur_layer, num_c_out class StackSAModuleMSG(nn.Module): def __init__(self, *, radii: List[float], nsamples: List[int], mlps: List[List[int]], use_xyz: bool = True, pool_method='max_pool'): """ Args: radii: list of float, list of radii to group with nsamples: list of int, number of samples in each ball query mlps: list of list of int, spec of the pointnet before the global pooling for each scale use_xyz: pool_method: max_pool / avg_pool """ super().__init__() assert len(radii) == len(nsamples) == len(mlps) self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] self.groupers.append(pointnet2_utils.QueryAndGroup(radius, nsample, use_xyz=use_xyz)) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range(len(mlp_spec) - 1): shared_mlps.extend([ nn.Conv2d(mlp_spec[k], mlp_spec[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[k + 1]), nn.ReLU() ]) self.mlps.append(nn.Sequential(*shared_mlps)) self.pool_method = pool_method self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) if isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0) def forward(self, xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt, features=None, empty_voxel_set_zeros=True): """ :param xyz: (N1 + N2 ..., 3) tensor of the xyz coordinates of the features :param xyz_batch_cnt: (batch_size), [N1, N2, ...] :param new_xyz: (M1 + M2 ..., 3) :param new_xyz_batch_cnt: (batch_size), [M1, M2, ...] :param features: (N1 + N2 ..., C) tensor of the descriptors of the the features :return: new_xyz: (M1 + M2 ..., 3) tensor of the new features' xyz new_features: (M1 + M2 ..., \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ new_features_list = [] for k in range(len(self.groupers)): new_features, ball_idxs = self.groupers[k]( xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt, features ) # (M1 + M2, C, nsample) new_features = new_features.permute(1, 0, 2).unsqueeze(dim=0) # (1, C, M1 + M2 ..., nsample) new_features = self.mlps[k](new_features) # (1, C, M1 + M2 ..., nsample) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ).squeeze(dim=-1) # (1, C, M1 + M2 ...) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ).squeeze(dim=-1) # (1, C, M1 + M2 ...) else: raise NotImplementedError new_features = new_features.squeeze(dim=0).permute(1, 0) # (M1 + M2 ..., C) new_features_list.append(new_features) new_features = torch.cat(new_features_list, dim=1) # (M1 + M2 ..., C) return new_xyz, new_features class StackPointnetFPModule(nn.Module): def __init__(self, *, mlp: List[int]): """ Args: mlp: list of int """ super().__init__() shared_mlps = [] for k in range(len(mlp) - 1): shared_mlps.extend([ nn.Conv2d(mlp[k], mlp[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp[k + 1]), nn.ReLU() ]) self.mlp = nn.Sequential(*shared_mlps) def forward(self, unknown, unknown_batch_cnt, known, known_batch_cnt, unknown_feats=None, known_feats=None): """ Args: unknown: (N1 + N2 ..., 3) known: (M1 + M2 ..., 3) unknow_feats: (N1 + N2 ..., C1) known_feats: (M1 + M2 ..., C2) Returns: new_features: (N1 + N2 ..., C_out) """ dist, idx = pointnet2_utils.three_nn(unknown, unknown_batch_cnt, known, known_batch_cnt) dist_recip = 1.0 / (dist + 1e-8) norm = torch.sum(dist_recip, dim=-1, keepdim=True) weight = dist_recip / norm interpolated_feats = pointnet2_utils.three_interpolate(known_feats, idx, weight) if unknown_feats is not None: new_features = torch.cat([interpolated_feats, unknown_feats], dim=1) # (N1 + N2 ..., C2 + C1) else: new_features = interpolated_feats new_features = new_features.permute(1, 0)[None, :, :, None] # (1, C, N1 + N2 ..., 1) new_features = self.mlp(new_features) new_features = new_features.squeeze(dim=0).squeeze(dim=-1).permute(1, 0) # (N1 + N2 ..., C) return new_features class VectorPoolLocalInterpolateModule(nn.Module): def __init__(self, mlp, num_voxels, max_neighbour_distance, nsample, neighbor_type, use_xyz=True, neighbour_distance_multiplier=1.0, xyz_encoding_type='concat'): """ Args: mlp: num_voxels: max_neighbour_distance: neighbor_type: 1: ball, others: cube nsample: find all (-1), find limited number(>0) use_xyz: neighbour_distance_multiplier: xyz_encoding_type: """ super().__init__() self.num_voxels = num_voxels # [num_grid_x, num_grid_y, num_grid_z]: number of grids in each local area centered at new_xyz self.num_total_grids = self.num_voxels[0] * self.num_voxels[1] * self.num_voxels[2] self.max_neighbour_distance = max_neighbour_distance self.neighbor_distance_multiplier = neighbour_distance_multiplier self.nsample = nsample self.neighbor_type = neighbor_type self.use_xyz = use_xyz self.xyz_encoding_type = xyz_encoding_type if mlp is not None: if self.use_xyz: mlp[0] += 9 if self.xyz_encoding_type == 'concat' else 0 shared_mlps = [] for k in range(len(mlp) - 1): shared_mlps.extend([ nn.Conv2d(mlp[k], mlp[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp[k + 1]), nn.ReLU() ]) self.mlp = nn.Sequential(*shared_mlps) else: self.mlp = None self.num_avg_length_of_neighbor_idxs = 1000 def forward(self, support_xyz, support_features, xyz_batch_cnt, new_xyz, new_xyz_grid_centers, new_xyz_batch_cnt): """ Args: support_xyz: (N1 + N2 ..., 3) xyz coordinates of the features support_features: (N1 + N2 ..., C) point-wise features xyz_batch_cnt: (batch_size), [N1, N2, ...] new_xyz: (M1 + M2 ..., 3) centers of the ball query new_xyz_grid_centers: (M1 + M2 ..., num_total_grids, 3) grids centers of each grid new_xyz_batch_cnt: (batch_size), [M1, M2, ...] Returns: new_features: (N1 + N2 ..., C_out) """ with torch.no_grad(): dist, idx, num_avg_length_of_neighbor_idxs = pointnet2_utils.three_nn_for_vector_pool_by_two_step( support_xyz, xyz_batch_cnt, new_xyz, new_xyz_grid_centers, new_xyz_batch_cnt, self.max_neighbour_distance, self.nsample, self.neighbor_type, self.num_avg_length_of_neighbor_idxs, self.num_total_grids, self.neighbor_distance_multiplier ) self.num_avg_length_of_neighbor_idxs = max(self.num_avg_length_of_neighbor_idxs, num_avg_length_of_neighbor_idxs.item()) dist_recip = 1.0 / (dist + 1e-8) norm = torch.sum(dist_recip, dim=-1, keepdim=True) weight = dist_recip / torch.clamp_min(norm, min=1e-8) empty_mask = (idx.view(-1, 3)[:, 0] == -1) idx.view(-1, 3)[empty_mask] = 0 interpolated_feats = pointnet2_utils.three_interpolate(support_features, idx.view(-1, 3), weight.view(-1, 3)) interpolated_feats = interpolated_feats.view(idx.shape[0], idx.shape[1], -1) # (M1 + M2 ..., num_total_grids, C) if self.use_xyz: near_known_xyz = support_xyz[idx.view(-1, 3).long()].view(-1, 3, 3) # ( (M1 + M2 ...)*num_total_grids, 3) local_xyz = (new_xyz_grid_centers.view(-1, 1, 3) - near_known_xyz).view(-1, idx.shape[1], 9) if self.xyz_encoding_type == 'concat': interpolated_feats = torch.cat((interpolated_feats, local_xyz), dim=-1) # ( M1 + M2 ..., num_total_grids, 9+C) else: raise NotImplementedError new_features = interpolated_feats.view(-1, interpolated_feats.shape[-1]) # ((M1 + M2 ...) * num_total_grids, C) new_features[empty_mask, :] = 0 if self.mlp is not None: new_features = new_features.permute(1, 0)[None, :, :, None] # (1, C, N1 + N2 ..., 1) new_features = self.mlp(new_features) new_features = new_features.squeeze(dim=0).squeeze(dim=-1).permute(1, 0) # (N1 + N2 ..., C) return new_features class VectorPoolAggregationModule(nn.Module): def __init__( self, input_channels, num_local_voxel=(3, 3, 3), local_aggregation_type='local_interpolation', num_reduced_channels=30, num_channels_of_local_aggregation=32, post_mlps=(128,), max_neighbor_distance=None, neighbor_nsample=-1, neighbor_type=0, neighbor_distance_multiplier=2.0): super().__init__() self.num_local_voxel = num_local_voxel self.total_voxels = self.num_local_voxel[0] * self.num_local_voxel[1] * self.num_local_voxel[2] self.local_aggregation_type = local_aggregation_type assert self.local_aggregation_type in ['local_interpolation', 'voxel_avg_pool', 'voxel_random_choice'] self.input_channels = input_channels self.num_reduced_channels = input_channels if num_reduced_channels is None else num_reduced_channels self.num_channels_of_local_aggregation = num_channels_of_local_aggregation self.max_neighbour_distance = max_neighbor_distance self.neighbor_nsample = neighbor_nsample self.neighbor_type = neighbor_type # 1: ball, others: cube if self.local_aggregation_type == 'local_interpolation': self.local_interpolate_module = VectorPoolLocalInterpolateModule( mlp=None, num_voxels=self.num_local_voxel, max_neighbour_distance=self.max_neighbour_distance, nsample=self.neighbor_nsample, neighbor_type=self.neighbor_type, neighbour_distance_multiplier=neighbor_distance_multiplier, ) num_c_in = (self.num_reduced_channels + 9) * self.total_voxels else: self.local_interpolate_module = None num_c_in = (self.num_reduced_channels + 3) * self.total_voxels num_c_out = self.total_voxels * self.num_channels_of_local_aggregation self.separate_local_aggregation_layer = nn.Sequential( nn.Conv1d(num_c_in, num_c_out, kernel_size=1, groups=self.total_voxels, bias=False), nn.BatchNorm1d(num_c_out), nn.ReLU() ) post_mlp_list = [] c_in = num_c_out for cur_num_c in post_mlps: post_mlp_list.extend([ nn.Conv1d(c_in, cur_num_c, kernel_size=1, bias=False), nn.BatchNorm1d(cur_num_c), nn.ReLU() ]) c_in = cur_num_c self.post_mlps = nn.Sequential(*post_mlp_list) self.num_mean_points_per_grid = 20 self.init_weights() def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d): nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0) def extra_repr(self) -> str: ret = f'radius={self.max_neighbour_distance}, local_voxels=({self.num_local_voxel}, ' \ f'local_aggregation_type={self.local_aggregation_type}, ' \ f'num_c_reduction={self.input_channels}->{self.num_reduced_channels}, ' \ f'num_c_local_aggregation={self.num_channels_of_local_aggregation}' return ret def vector_pool_with_voxel_query(self, xyz, xyz_batch_cnt, features, new_xyz, new_xyz_batch_cnt): use_xyz = 1 pooling_type = 0 if self.local_aggregation_type == 'voxel_avg_pool' else 1 new_features, new_local_xyz, num_mean_points_per_grid, point_cnt_of_grid = pointnet2_utils.vector_pool_with_voxel_query_op( xyz, xyz_batch_cnt, features, new_xyz, new_xyz_batch_cnt, self.num_local_voxel[0], self.num_local_voxel[1], self.num_local_voxel[2], self.max_neighbour_distance, self.num_reduced_channels, use_xyz, self.num_mean_points_per_grid, self.neighbor_nsample, self.neighbor_type, pooling_type ) self.num_mean_points_per_grid = max(self.num_mean_points_per_grid, num_mean_points_per_grid.item()) num_new_pts = new_features.shape[0] new_local_xyz = new_local_xyz.view(num_new_pts, -1, 3) # (N, num_voxel, 3) new_features = new_features.view(num_new_pts, -1, self.num_reduced_channels) # (N, num_voxel, C) new_features = torch.cat((new_local_xyz, new_features), dim=-1).view(num_new_pts, -1) return new_features, point_cnt_of_grid @staticmethod def get_dense_voxels_by_center(point_centers, max_neighbour_distance, num_voxels): """ Args: point_centers: (N, 3) max_neighbour_distance: float num_voxels: [num_x, num_y, num_z] Returns: voxel_centers: (N, total_voxels, 3) """ R = max_neighbour_distance device = point_centers.device x_grids = torch.arange(-R + R / num_voxels[0], R - R / num_voxels[0] + 1e-5, 2 * R / num_voxels[0], device=device) y_grids = torch.arange(-R + R / num_voxels[1], R - R / num_voxels[1] + 1e-5, 2 * R / num_voxels[1], device=device) z_grids = torch.arange(-R + R / num_voxels[2], R - R / num_voxels[2] + 1e-5, 2 * R / num_voxels[2], device=device) x_offset, y_offset, z_offset = torch.meshgrid(x_grids, y_grids, z_grids) # shape: [num_x, num_y, num_z] xyz_offset = torch.cat(( x_offset.contiguous().view(-1, 1), y_offset.contiguous().view(-1, 1), z_offset.contiguous().view(-1, 1)), dim=-1 ) voxel_centers = point_centers[:, None, :] + xyz_offset[None, :, :] return voxel_centers def vector_pool_with_local_interpolate(self, xyz, xyz_batch_cnt, features, new_xyz, new_xyz_batch_cnt): """ Args: xyz: (N, 3) xyz_batch_cnt: (batch_size) features: (N, C) new_xyz: (M, 3) new_xyz_batch_cnt: (batch_size) Returns: new_features: (M, total_voxels * C) """ voxel_centers = self.get_dense_voxels_by_center( point_centers=new_xyz, max_neighbour_distance=self.max_neighbour_distance, num_voxels=self.num_local_voxel ) # (M1 + M2 + ..., total_voxels, 3) voxel_features = self.local_interpolate_module.forward( support_xyz=xyz, support_features=features, xyz_batch_cnt=xyz_batch_cnt, new_xyz=new_xyz, new_xyz_grid_centers=voxel_centers, new_xyz_batch_cnt=new_xyz_batch_cnt ) # ((M1 + M2 ...) * total_voxels, C) voxel_features = voxel_features.contiguous().view(-1, self.total_voxels * voxel_features.shape[-1]) return voxel_features def forward(self, xyz, xyz_batch_cnt, new_xyz, new_xyz_batch_cnt, features, **kwargs): """ :param xyz: (N1 + N2 ..., 3) tensor of the xyz coordinates of the features :param xyz_batch_cnt: (batch_size), [N1, N2, ...] :param new_xyz: (M1 + M2 ..., 3) :param new_xyz_batch_cnt: (batch_size), [M1, M2, ...] :param features: (N1 + N2 ..., C) tensor of the descriptors of the the features :return: new_xyz: (M1 + M2 ..., 3) tensor of the new features' xyz new_features: (M1 + M2 ..., \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ N, C = features.shape assert C % self.num_reduced_channels == 0, \ f'the input channels ({C}) should be an integral multiple of num_reduced_channels({self.num_reduced_channels})' features = features.view(N, -1, self.num_reduced_channels).sum(dim=1) if self.local_aggregation_type in ['voxel_avg_pool', 'voxel_random_choice']: vector_features, point_cnt_of_grid = self.vector_pool_with_voxel_query( xyz=xyz, xyz_batch_cnt=xyz_batch_cnt, features=features, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt ) elif self.local_aggregation_type == 'local_interpolation': vector_features = self.vector_pool_with_local_interpolate( xyz=xyz, xyz_batch_cnt=xyz_batch_cnt, features=features, new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt ) # (M1 + M2 + ..., total_voxels * C) else: raise NotImplementedError vector_features = vector_features.permute(1, 0)[None, :, :] # (1, num_voxels * C, M1 + M2 ...) new_features = self.separate_local_aggregation_layer(vector_features) new_features = self.post_mlps(new_features) new_features = new_features.squeeze(dim=0).permute(1, 0) return new_xyz, new_features class VectorPoolAggregationModuleMSG(nn.Module): def __init__(self, input_channels, config): super().__init__() self.model_cfg = config self.num_groups = self.model_cfg.NUM_GROUPS self.layers = [] c_in = 0 for k in range(self.num_groups): cur_config = self.model_cfg[f'GROUP_CFG_{k}'] cur_vector_pool_module = VectorPoolAggregationModule( input_channels=input_channels, num_local_voxel=cur_config.NUM_LOCAL_VOXEL, post_mlps=cur_config.POST_MLPS, max_neighbor_distance=cur_config.MAX_NEIGHBOR_DISTANCE, neighbor_nsample=cur_config.NEIGHBOR_NSAMPLE, local_aggregation_type=self.model_cfg.LOCAL_AGGREGATION_TYPE, num_reduced_channels=self.model_cfg.get('NUM_REDUCED_CHANNELS', None), num_channels_of_local_aggregation=self.model_cfg.NUM_CHANNELS_OF_LOCAL_AGGREGATION, neighbor_distance_multiplier=2.0 ) self.__setattr__(f'layer_{k}', cur_vector_pool_module) c_in += cur_config.POST_MLPS[-1] c_in += 3 # use_xyz shared_mlps = [] for cur_num_c in self.model_cfg.MSG_POST_MLPS: shared_mlps.extend([ nn.Conv1d(c_in, cur_num_c, kernel_size=1, bias=False), nn.BatchNorm1d(cur_num_c), nn.ReLU() ]) c_in = cur_num_c self.msg_post_mlps = nn.Sequential(*shared_mlps) def forward(self, **kwargs): features_list = [] for k in range(self.num_groups): cur_xyz, cur_features = self.__getattr__(f'layer_{k}')(**kwargs) features_list.append(cur_features) features = torch.cat(features_list, dim=-1) features = torch.cat((cur_xyz, features), dim=-1) features = features.permute(1, 0)[None, :, :] # (1, C, N) new_features = self.msg_post_mlps(features) new_features = new_features.squeeze(dim=0).permute(1, 0) # (N, C) return cur_xyz, new_features
21,385
44.40552
132
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_batch/pointnet2_utils.py
from typing import Tuple import torch import torch.nn as nn from torch.autograd import Function, Variable from . import pointnet2_batch_cuda as pointnet2 class FarthestPointSampling(Function): @staticmethod def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor: """ Uses iterative farthest point sampling to select a set of npoint features that have the largest minimum distance :param ctx: :param xyz: (B, N, 3) where N > npoint :param npoint: int, number of features in the sampled set :return: output: (B, npoint) tensor containing the set """ assert xyz.is_contiguous() B, N, _ = xyz.size() output = torch.cuda.IntTensor(B, npoint) temp = torch.cuda.FloatTensor(B, N).fill_(1e10) pointnet2.farthest_point_sampling_wrapper(B, N, npoint, xyz, temp, output) return output @staticmethod def backward(xyz, a=None): return None, None farthest_point_sample = furthest_point_sample = FarthestPointSampling.apply class GatherOperation(Function): @staticmethod def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """ :param ctx: :param features: (B, C, N) :param idx: (B, npoint) index tensor of the features to gather :return: output: (B, C, npoint) """ assert features.is_contiguous() assert idx.is_contiguous() B, npoint = idx.size() _, C, N = features.size() output = torch.cuda.FloatTensor(B, C, npoint) pointnet2.gather_points_wrapper(B, C, N, npoint, features, idx, output) ctx.for_backwards = (idx, C, N) return output @staticmethod def backward(ctx, grad_out): idx, C, N = ctx.for_backwards B, npoint = idx.size() grad_features = Variable(torch.cuda.FloatTensor(B, C, N).zero_()) grad_out_data = grad_out.data.contiguous() pointnet2.gather_points_grad_wrapper(B, C, N, npoint, grad_out_data, idx, grad_features.data) return grad_features, None gather_operation = GatherOperation.apply class ThreeNN(Function): @staticmethod def forward(ctx, unknown: torch.Tensor, known: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Find the three nearest neighbors of unknown in known :param ctx: :param unknown: (B, N, 3) :param known: (B, M, 3) :return: dist: (B, N, 3) l2 distance to the three nearest neighbors idx: (B, N, 3) index of 3 nearest neighbors """ assert unknown.is_contiguous() assert known.is_contiguous() B, N, _ = unknown.size() m = known.size(1) dist2 = torch.cuda.FloatTensor(B, N, 3) idx = torch.cuda.IntTensor(B, N, 3) pointnet2.three_nn_wrapper(B, N, m, unknown, known, dist2, idx) return torch.sqrt(dist2), idx @staticmethod def backward(ctx, a=None, b=None): return None, None three_nn = ThreeNN.apply class ThreeInterpolate(Function): @staticmethod def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """ Performs weight linear interpolation on 3 features :param ctx: :param features: (B, C, M) Features descriptors to be interpolated from :param idx: (B, n, 3) three nearest neighbors of the target features in features :param weight: (B, n, 3) weights :return: output: (B, C, N) tensor of the interpolated features """ assert features.is_contiguous() assert idx.is_contiguous() assert weight.is_contiguous() B, c, m = features.size() n = idx.size(1) ctx.three_interpolate_for_backward = (idx, weight, m) output = torch.cuda.FloatTensor(B, c, n) pointnet2.three_interpolate_wrapper(B, c, m, n, features, idx, weight, output) return output @staticmethod def backward(ctx, grad_out: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ :param ctx: :param grad_out: (B, C, N) tensor with gradients of outputs :return: grad_features: (B, C, M) tensor with gradients of features None: None: """ idx, weight, m = ctx.three_interpolate_for_backward B, c, n = grad_out.size() grad_features = Variable(torch.cuda.FloatTensor(B, c, m).zero_()) grad_out_data = grad_out.data.contiguous() pointnet2.three_interpolate_grad_wrapper(B, c, n, m, grad_out_data, idx, weight, grad_features.data) return grad_features, None, None three_interpolate = ThreeInterpolate.apply class GroupingOperation(Function): @staticmethod def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: """ :param ctx: :param features: (B, C, N) tensor of features to group :param idx: (B, npoint, nsample) tensor containing the indicies of features to group with :return: output: (B, C, npoint, nsample) tensor """ assert features.is_contiguous() assert idx.is_contiguous() B, nfeatures, nsample = idx.size() _, C, N = features.size() output = torch.cuda.FloatTensor(B, C, nfeatures, nsample) pointnet2.group_points_wrapper(B, C, N, nfeatures, nsample, features, idx, output) ctx.for_backwards = (idx, N) return output @staticmethod def backward(ctx, grad_out: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ :param ctx: :param grad_out: (B, C, npoint, nsample) tensor of the gradients of the output from forward :return: grad_features: (B, C, N) gradient of the features """ idx, N = ctx.for_backwards B, C, npoint, nsample = grad_out.size() grad_features = Variable(torch.cuda.FloatTensor(B, C, N).zero_()) grad_out_data = grad_out.data.contiguous() pointnet2.group_points_grad_wrapper(B, C, N, npoint, nsample, grad_out_data, idx, grad_features.data) return grad_features, None grouping_operation = GroupingOperation.apply class BallQuery(Function): @staticmethod def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, new_xyz: torch.Tensor) -> torch.Tensor: """ :param ctx: :param radius: float, radius of the balls :param nsample: int, maximum number of features in the balls :param xyz: (B, N, 3) xyz coordinates of the features :param new_xyz: (B, npoint, 3) centers of the ball query :return: idx: (B, npoint, nsample) tensor with the indicies of the features that form the query balls """ assert new_xyz.is_contiguous() assert xyz.is_contiguous() B, N, _ = xyz.size() npoint = new_xyz.size(1) idx = torch.cuda.IntTensor(B, npoint, nsample).zero_() pointnet2.ball_query_wrapper(B, N, npoint, radius, nsample, new_xyz, xyz, idx) return idx @staticmethod def backward(ctx, a=None): return None, None, None, None ball_query = BallQuery.apply class QueryAndGroup(nn.Module): def __init__(self, radius: float, nsample: int, use_xyz: bool = True): """ :param radius: float, radius of ball :param nsample: int, maximum number of features to gather in the ball :param use_xyz: """ super().__init__() self.radius, self.nsample, self.use_xyz = radius, nsample, use_xyz def forward(self, xyz: torch.Tensor, new_xyz: torch.Tensor, features: torch.Tensor = None) -> Tuple[torch.Tensor]: """ :param xyz: (B, N, 3) xyz coordinates of the features :param new_xyz: (B, npoint, 3) centroids :param features: (B, C, N) descriptors of the features :return: new_features: (B, 3 + C, npoint, nsample) """ idx = ball_query(self.radius, self.nsample, xyz, new_xyz) xyz_trans = xyz.transpose(1, 2).contiguous() grouped_xyz = grouping_operation(xyz_trans, idx) # (B, 3, npoint, nsample) grouped_xyz -= new_xyz.transpose(1, 2).unsqueeze(-1) if features is not None: grouped_features = grouping_operation(features, idx) if self.use_xyz: new_features = torch.cat([grouped_xyz, grouped_features], dim=1) # (B, C + 3, npoint, nsample) else: new_features = grouped_features else: assert self.use_xyz, "Cannot have not features and not use xyz as a feature!" new_features = grouped_xyz return new_features class GroupAll(nn.Module): def __init__(self, use_xyz: bool = True): super().__init__() self.use_xyz = use_xyz def forward(self, xyz: torch.Tensor, new_xyz: torch.Tensor, features: torch.Tensor = None): """ :param xyz: (B, N, 3) xyz coordinates of the features :param new_xyz: ignored :param features: (B, C, N) descriptors of the features :return: new_features: (B, C + 3, 1, N) """ grouped_xyz = xyz.transpose(1, 2).unsqueeze(2) if features is not None: grouped_features = features.unsqueeze(2) if self.use_xyz: new_features = torch.cat([grouped_xyz, grouped_features], dim=1) # (B, 3 + C, 1, N) else: new_features = grouped_features else: new_features = grouped_xyz return new_features
9,717
32.395189
118
py
3DTrans
3DTrans-master/pcdet/ops/pointnet2/pointnet2_batch/pointnet2_modules.py
from typing import List import torch import torch.nn as nn import torch.nn.functional as F from . import pointnet2_utils class _PointnetSAModuleBase(nn.Module): def __init__(self): super().__init__() self.npoint = None self.groupers = None self.mlps = None self.pool_method = 'max_pool' def calc_square_dist(self, a, b, norm=True): """ Calculating square distance between a and b a: [bs, n, c] b: [bs, m, c] """ n = a.shape[1] m = b.shape[1] num_channel = a.shape[-1] a_square = a.unsqueeze(dim=2) # [bs, n, 1, c] b_square = b.unsqueeze(dim=1) # [bs, 1, m, c] a_square = torch.sum(a_square * a_square, dim=-1) # [bs, n, 1] b_square = torch.sum(b_square * b_square, dim=-1) # [bs, 1, m] a_square = a_square.repeat((1, 1, m)) # [bs, n, m] b_square = b_square.repeat((1, n, 1)) # [bs, n, m] coor = torch.matmul(a, b.transpose(1, 2)) # [bs, n, m] if norm: dist = a_square + b_square - 2.0 * coor # [bs, npoint, ndataset] # dist = torch.sqrt(dist) else: dist = a_square + b_square - 2 * coor # dist = torch.sqrt(dist) return dist def forward(self, xyz: torch.Tensor, features: torch.Tensor = None, new_xyz=None) -> (torch.Tensor, torch.Tensor): """ :param xyz: (B, N, 3) tensor of the xyz coordinates of the features :param features: (B, N, C) tensor of the descriptors of the the features :param new_xyz: :return: new_xyz: (B, npoint, 3) tensor of the new features' xyz new_features: (B, npoint, \sum_k(mlps[k][-1])) tensor of the new_features descriptors """ new_features_list = [] xyz_flipped = xyz.transpose(1, 2).contiguous() if new_xyz is None: new_xyz = pointnet2_utils.gather_operation( xyz_flipped, pointnet2_utils.farthest_point_sample(xyz, self.npoint) ).transpose(1, 2).contiguous() if self.npoint is not None else None for i in range(len(self.groupers)): new_features = self.groupers[i](xyz, new_xyz, features) # (B, C, npoint, nsample) new_features = self.mlps[i](new_features) # (B, mlp[-1], npoint, nsample) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) else: raise NotImplementedError new_features = new_features.squeeze(-1) # (B, mlp[-1], npoint) new_features_list.append(new_features) return new_xyz, torch.cat(new_features_list, dim=1) class PointnetSAModuleMSG(_PointnetSAModuleBase): """Pointnet set abstraction layer with multiscale grouping""" def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], bn: bool = True, use_xyz: bool = True, pool_method='max_pool'): """ :param npoint: int :param radii: list of float, list of radii to group with :param nsamples: list of int, number of samples in each ball query :param mlps: list of list of int, spec of the pointnet before the global pooling for each scale :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__() assert len(radii) == len(nsamples) == len(mlps) self.npoint = npoint self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] self.groupers.append( pointnet2_utils.QueryAndGroup(radius, nsample, use_xyz=use_xyz) if npoint is not None else pointnet2_utils.GroupAll(use_xyz) ) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range(len(mlp_spec) - 1): shared_mlps.extend([ nn.Conv2d(mlp_spec[k], mlp_spec[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[k + 1]), nn.ReLU() ]) self.mlps.append(nn.Sequential(*shared_mlps)) self.pool_method = pool_method class PointnetSAModuleMSG_WithSampling(_PointnetSAModuleBase): """Pointnet set abstraction layer with specific downsampling and multiscale grouping """ def __init__(self, *, npoint_list: List[int], sample_range_list: List[int], sample_type_list: List[int], radii: List[float], nsamples: List[int], mlps: List[List[int]], use_xyz: bool = True, dilated_group=False, pool_method='max_pool', aggregation_mlp: List[int], confidence_mlp: List[int], num_class): """ :param npoint_list: list of int, number of samples for every sampling type :param sample_range_list: list of list of int, sample index range [left, right] for every sampling type :param sample_type_list: list of str, list of used sampling type, d-fps or f-fps :param radii: list of float, list of radii to group with :param nsamples: list of int, number of samples in each ball query :param mlps: list of list of int, spec of the pointnet before the global pooling for each scale :param use_xyz: :param pool_method: max_pool / avg_pool :param dilated_group: whether to use dilated group :param aggregation_mlp: list of int, spec aggregation mlp :param confidence_mlp: list of int, spec confidence mlp :param num_class: int, class for process """ super().__init__() self.sample_type_list = sample_type_list self.sample_range_list = sample_range_list self.dilated_group = dilated_group assert len(radii) == len(nsamples) == len(mlps) self.npoint_list = npoint_list self.groupers = nn.ModuleList() self.mlps = nn.ModuleList() out_channels = 0 for i in range(len(radii)): radius = radii[i] nsample = nsamples[i] if self.dilated_group: if i == 0: min_radius = 0. else: min_radius = radii[i-1] self.groupers.append( pointnet2_utils.QueryDilatedAndGroup( radius, min_radius, nsample, use_xyz=use_xyz) if npoint_list is not None else pointnet2_utils.GroupAll(use_xyz) ) else: self.groupers.append( pointnet2_utils.QueryAndGroup( radius, nsample, use_xyz=use_xyz) if npoint_list is not None else pointnet2_utils.GroupAll(use_xyz) ) mlp_spec = mlps[i] if use_xyz: mlp_spec[0] += 3 shared_mlps = [] for k in range(len(mlp_spec) - 1): shared_mlps.extend([ nn.Conv2d(mlp_spec[k], mlp_spec[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp_spec[k + 1]), nn.ReLU() ]) self.mlps.append(nn.Sequential(*shared_mlps)) out_channels += mlp_spec[-1] self.pool_method = pool_method if (aggregation_mlp is not None) and (len(aggregation_mlp) != 0) and (len(self.mlps) > 0): shared_mlp = [] for k in range(len(aggregation_mlp)): shared_mlp.extend([ nn.Conv1d(out_channels, aggregation_mlp[k], kernel_size=1, bias=False), nn.BatchNorm1d(aggregation_mlp[k]), nn.ReLU() ]) out_channels = aggregation_mlp[k] self.aggregation_layer = nn.Sequential(*shared_mlp) else: self.aggregation_layer = None if (confidence_mlp is not None) and (len(confidence_mlp) != 0): shared_mlp = [] for k in range(len(confidence_mlp)): shared_mlp.extend([ nn.Conv1d(out_channels, confidence_mlp[k], kernel_size=1, bias=False), nn.BatchNorm1d(confidence_mlp[k]), nn.ReLU() ]) out_channels = confidence_mlp[k] shared_mlp.append( nn.Conv1d(out_channels, num_class, kernel_size=1, bias=True), ) self.confidence_layers = nn.Sequential(*shared_mlp) else: self.confidence_layers = None def forward(self, xyz: torch.Tensor, features: torch.Tensor = None, cls_features: torch.Tensor = None, new_xyz=None, ctr_xyz=None): """ :param xyz: (B, N, 3) tensor of the xyz coordinates of the features :param features: (B, C, N) tensor of the descriptors of the the features :param cls_features: (B, N, num_class) tensor of the descriptors of the the confidence (classification) features :param new_xyz: (B, M, 3) tensor of the xyz coordinates of the sampled points "param ctr_xyz: tensor of the xyz coordinates of the centers :return: new_xyz: (B, npoint, 3) tensor of the new features' xyz new_features: (B, \sum_k(mlps[k][-1]), npoint) tensor of the new_features descriptors cls_features: (B, npoint, num_class) tensor of confidence (classification) features """ new_features_list = [] xyz_flipped = xyz.transpose(1, 2).contiguous() sampled_idx_list = [] if ctr_xyz is None: last_sample_end_index = 0 for i in range(len(self.sample_type_list)): sample_type = self.sample_type_list[i] sample_range = self.sample_range_list[i] npoint = self.npoint_list[i] if npoint <= 0: continue if sample_range == -1: #全部 xyz_tmp = xyz[:, last_sample_end_index:, :] feature_tmp = features.transpose(1, 2)[:, last_sample_end_index:, :].contiguous() cls_features_tmp = cls_features[:, last_sample_end_index:, :] if cls_features is not None else None else: xyz_tmp = xyz[:, last_sample_end_index:sample_range, :].contiguous() feature_tmp = features.transpose(1, 2)[:, last_sample_end_index:sample_range, :] cls_features_tmp = cls_features[:, last_sample_end_index:sample_range, :] if cls_features is not None else None last_sample_end_index += sample_range if xyz_tmp.shape[1] <= npoint: # No downsampling sample_idx = torch.arange(xyz_tmp.shape[1], device=xyz_tmp.device, dtype=torch.int32) * torch.ones(xyz_tmp.shape[0], xyz_tmp.shape[1], device=xyz_tmp.device, dtype=torch.int32) elif ('cls' in sample_type) or ('ctr' in sample_type): cls_features_max, class_pred = cls_features_tmp.max(dim=-1) score_pred = torch.sigmoid(cls_features_max) # B,N score_picked, sample_idx = torch.topk(score_pred, npoint, dim=-1) sample_idx = sample_idx.int() elif 'D-FPS' in sample_type or 'DFS' in sample_type: sample_idx = pointnet2_utils.furthest_point_sample(xyz_tmp.contiguous(), npoint) elif 'F-FPS' in sample_type or 'FFS' in sample_type: features_SSD = torch.cat([xyz_tmp, feature_tmp], dim=-1) features_for_fps_distance = self.calc_square_dist(features_SSD, features_SSD) features_for_fps_distance = features_for_fps_distance.contiguous() sample_idx = pointnet2_utils.furthest_point_sample_with_dist(features_for_fps_distance, npoint) elif sample_type == 'FS': features_SSD = torch.cat([xyz_tmp, feature_tmp], dim=-1) features_for_fps_distance = self.calc_square_dist(features_SSD, features_SSD) features_for_fps_distance = features_for_fps_distance.contiguous() sample_idx_1 = pointnet2_utils.furthest_point_sample_with_dist(features_for_fps_distance, npoint) sample_idx_2 = pointnet2_utils.furthest_point_sample(xyz_tmp, npoint) sample_idx = torch.cat([sample_idx_1, sample_idx_2], dim=-1) # [bs, npoint * 2] elif 'Rand' in sample_type: sample_idx = torch.randperm(xyz_tmp.shape[1],device=xyz_tmp.device)[None, :npoint].int().repeat(xyz_tmp.shape[0], 1) elif sample_type == 'ds_FPS' or sample_type == 'ds-FPS': part_num = 4 xyz_div = [] idx_div = [] for i in range(len(xyz_tmp)): per_xyz = xyz_tmp[i] radii = per_xyz.norm(dim=-1) -5 storted_radii, indince = radii.sort(dim=0, descending=False) per_xyz_sorted = per_xyz[indince] per_xyz_sorted_div = per_xyz_sorted.view(part_num, -1 ,3) per_idx_div = indince.view(part_num,-1) xyz_div.append(per_xyz_sorted_div) idx_div.append(per_idx_div) xyz_div = torch.cat(xyz_div ,dim=0) idx_div = torch.cat(idx_div ,dim=0) idx_sampled = pointnet2_utils.furthest_point_sample(xyz_div, (npoint//part_num)) indince_div = [] for idx_sampled_per, idx_per in zip(idx_sampled, idx_div): indince_div.append(idx_per[idx_sampled_per.long()]) index = torch.cat(indince_div, dim=-1) sample_idx = index.reshape(xyz.shape[0], npoint).int() elif sample_type == 'ry_FPS' or sample_type == 'ry-FPS': part_num = 4 xyz_div = [] idx_div = [] for i in range(len(xyz_tmp)): per_xyz = xyz_tmp[i] ry = torch.atan(per_xyz[:,0]/per_xyz[:,1]) storted_ry, indince = ry.sort(dim=0, descending=False) per_xyz_sorted = per_xyz[indince] per_xyz_sorted_div = per_xyz_sorted.view(part_num, -1 ,3) per_idx_div = indince.view(part_num,-1) xyz_div.append(per_xyz_sorted_div) idx_div.append(per_idx_div) xyz_div = torch.cat(xyz_div ,dim=0) idx_div = torch.cat(idx_div ,dim=0) idx_sampled = pointnet2_utils.furthest_point_sample(xyz_div, (npoint//part_num)) indince_div = [] for idx_sampled_per, idx_per in zip(idx_sampled, idx_div): indince_div.append(idx_per[idx_sampled_per.long()]) index = torch.cat(indince_div, dim=-1) sample_idx = index.reshape(xyz.shape[0], npoint).int() sampled_idx_list.append(sample_idx) sampled_idx_list = torch.cat(sampled_idx_list, dim=-1) new_xyz = pointnet2_utils.gather_operation(xyz_flipped, sampled_idx_list).transpose(1, 2).contiguous() else: new_xyz = ctr_xyz if len(self.groupers) > 0: for i in range(len(self.groupers)): new_features = self.groupers[i](xyz, new_xyz, features) # (B, C, npoint, nsample) new_features = self.mlps[i](new_features) # (B, mlp[-1], npoint, nsample) if self.pool_method == 'max_pool': new_features = F.max_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) elif self.pool_method == 'avg_pool': new_features = F.avg_pool2d( new_features, kernel_size=[1, new_features.size(3)] ) # (B, mlp[-1], npoint, 1) else: raise NotImplementedError new_features = new_features.squeeze(-1) # (B, mlp[-1], npoint) new_features_list.append(new_features) new_features = torch.cat(new_features_list, dim=1) if self.aggregation_layer is not None: new_features = self.aggregation_layer(new_features) else: new_features = pointnet2_utils.gather_operation(features, sampled_idx_list).contiguous() if self.confidence_layers is not None: cls_features = self.confidence_layers(new_features).transpose(1, 2) else: cls_features = None return new_xyz, new_features, cls_features class Vote_layer(nn.Module): """ Light voting module with limitation""" def __init__(self, mlp_list, pre_channel, max_translate_range): super().__init__() self.mlp_list = mlp_list if len(mlp_list) > 0: for i in range(len(mlp_list)): shared_mlps = [] shared_mlps.extend([ nn.Conv1d(pre_channel, mlp_list[i], kernel_size=1, bias=False), nn.BatchNorm1d(mlp_list[i]), nn.ReLU() ]) pre_channel = mlp_list[i] self.mlp_modules = nn.Sequential(*shared_mlps) else: self.mlp_modules = None self.ctr_reg = nn.Conv1d(pre_channel, 3, kernel_size=1) self.max_offset_limit = torch.tensor(max_translate_range).float() if max_translate_range is not None else None def forward(self, xyz, features): xyz_select = xyz features_select = features if self.mlp_modules is not None: new_features = self.mlp_modules(features_select) #([4, 256, 256]) ->([4, 128, 256]) else: new_features = new_features ctr_offsets = self.ctr_reg(new_features) #[4, 128, 256]) -> ([4, 3, 256]) ctr_offsets = ctr_offsets.transpose(1, 2)#([4, 256, 3]) feat_offets = ctr_offsets[..., 3:] new_features = feat_offets ctr_offsets = ctr_offsets[..., :3] if self.max_offset_limit is not None: max_offset_limit = self.max_offset_limit.view(1, 1, 3) max_offset_limit = self.max_offset_limit.repeat((xyz_select.shape[0], xyz_select.shape[1], 1)).to(xyz_select.device) #([4, 256, 3]) limited_ctr_offsets = torch.where(ctr_offsets > max_offset_limit, max_offset_limit, ctr_offsets) min_offset_limit = -1 * max_offset_limit limited_ctr_offsets = torch.where(limited_ctr_offsets < min_offset_limit, min_offset_limit, limited_ctr_offsets) vote_xyz = xyz_select + limited_ctr_offsets else: vote_xyz = xyz_select + ctr_offsets return vote_xyz, new_features, xyz_select, ctr_offsets class PointnetSAModule(PointnetSAModuleMSG): """Pointnet set abstraction layer""" def __init__(self, *, mlp: List[int], npoint: int = None, radius: float = None, nsample: int = None, bn: bool = True, use_xyz: bool = True, pool_method='max_pool'): """ :param mlp: list of int, spec of the pointnet before the global max_pool :param npoint: int, number of features :param radius: float, radius of ball :param nsample: int, number of samples in the ball query :param bn: whether to use batchnorm :param use_xyz: :param pool_method: max_pool / avg_pool """ super().__init__( mlps=[mlp], npoint=npoint, radii=[radius], nsamples=[nsample], bn=bn, use_xyz=use_xyz, pool_method=pool_method ) class PointnetFPModule(nn.Module): r"""Propigates the features of one set to another""" def __init__(self, *, mlp: List[int], bn: bool = True): """ :param mlp: list of int :param bn: whether to use batchnorm """ super().__init__() shared_mlps = [] for k in range(len(mlp) - 1): shared_mlps.extend([ nn.Conv2d(mlp[k], mlp[k + 1], kernel_size=1, bias=False), nn.BatchNorm2d(mlp[k + 1]), nn.ReLU() ]) self.mlp = nn.Sequential(*shared_mlps) def forward( self, unknown: torch.Tensor, known: torch.Tensor, unknow_feats: torch.Tensor, known_feats: torch.Tensor ) -> torch.Tensor: """ :param unknown: (B, n, 3) tensor of the xyz positions of the unknown features :param known: (B, m, 3) tensor of the xyz positions of the known features :param unknow_feats: (B, C1, n) tensor of the features to be propigated to :param known_feats: (B, C2, m) tensor of features to be propigated :return: new_features: (B, mlp[-1], n) tensor of the features of the unknown features """ if known is not None: dist, idx = pointnet2_utils.three_nn(unknown, known) dist_recip = 1.0 / (dist + 1e-8) norm = torch.sum(dist_recip, dim=2, keepdim=True) weight = dist_recip / norm interpolated_feats = pointnet2_utils.three_interpolate(known_feats, idx, weight) else: interpolated_feats = known_feats.expand(*known_feats.size()[0:2], unknown.size(1)) if unknow_feats is not None: new_features = torch.cat([interpolated_feats, unknow_feats], dim=1) # (B, C2 + C1, n) else: new_features = interpolated_feats new_features = new_features.unsqueeze(-1) new_features = self.mlp(new_features) return new_features.squeeze(-1) if __name__ == "__main__": pass
22,835
43.341748
196
py
3DTrans
3DTrans-master/pcdet/ops/iou3d_nms/iou3d_nms_utils.py
""" 3D IoU Calculation and Rotated NMS Written by Shaoshuai Shi All Rights Reserved 2019-2020. """ import torch from ...utils import common_utils from . import iou3d_nms_cuda def boxes_bev_iou_cpu(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ boxes_a, is_numpy = common_utils.check_numpy_to_torch(boxes_a) boxes_b, is_numpy = common_utils.check_numpy_to_torch(boxes_b) assert not (boxes_a.is_cuda or boxes_b.is_cuda), 'Only support CPU tensors' assert boxes_a.shape[1] == 7 and boxes_b.shape[1] == 7 ans_iou = boxes_a.new_zeros(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))) iou3d_nms_cuda.boxes_iou_bev_cpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou) return ans_iou.numpy() if is_numpy else ans_iou def boxes_iou_bev(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ assert boxes_a.shape[1] == boxes_b.shape[1] == 7 ans_iou = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_() iou3d_nms_cuda.boxes_iou_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), ans_iou) return ans_iou def boxes_iou3d_gpu(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (M, 7) [x, y, z, dx, dy, dz, heading] Returns: ans_iou: (N, M) """ assert boxes_a.shape[1] == boxes_b.shape[1] == 7 # height overlap boxes_a_height_max = (boxes_a[:, 2] + boxes_a[:, 5] / 2).view(-1, 1) boxes_a_height_min = (boxes_a[:, 2] - boxes_a[:, 5] / 2).view(-1, 1) boxes_b_height_max = (boxes_b[:, 2] + boxes_b[:, 5] / 2).view(1, -1) boxes_b_height_min = (boxes_b[:, 2] - boxes_b[:, 5] / 2).view(1, -1) # bev overlap overlaps_bev = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_() # (N, M) iou3d_nms_cuda.boxes_overlap_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(), overlaps_bev) max_of_min = torch.max(boxes_a_height_min, boxes_b_height_min) min_of_max = torch.min(boxes_a_height_max, boxes_b_height_max) overlaps_h = torch.clamp(min_of_max - max_of_min, min=0) # 3d iou overlaps_3d = overlaps_bev * overlaps_h vol_a = (boxes_a[:, 3] * boxes_a[:, 4] * boxes_a[:, 5]).view(-1, 1) vol_b = (boxes_b[:, 3] * boxes_b[:, 4] * boxes_b[:, 5]).view(1, -1) iou3d = overlaps_3d / torch.clamp(vol_a + vol_b - overlaps_3d, min=1e-6) return iou3d def nms_gpu(boxes, scores, thresh, pre_maxsize=None, **kwargs): """ :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading] :param scores: (N) :param thresh: :return: """ assert boxes.shape[1] == 7 order = scores.sort(0, descending=True)[1] if pre_maxsize is not None: order = order[:pre_maxsize] boxes = boxes[order].contiguous() keep = torch.LongTensor(boxes.size(0)) num_out = iou3d_nms_cuda.nms_gpu(boxes, keep, thresh) return order[keep[:num_out].cuda()].contiguous(), None def nms_normal_gpu(boxes, scores, thresh, **kwargs): """ :param boxes: (N, 7) [x, y, z, dx, dy, dz, heading] :param scores: (N) :param thresh: :return: """ assert boxes.shape[1] == 7 order = scores.sort(0, descending=True)[1] boxes = boxes[order].contiguous() keep = torch.LongTensor(boxes.size(0)) num_out = iou3d_nms_cuda.nms_normal_gpu(boxes, keep, thresh) return order[keep[:num_out].cuda()].contiguous(), None
3,673
30.401709
109
py
3DTrans
3DTrans-master/pcdet/ops/roiaware_pool3d/roiaware_pool3d_utils.py
import torch import torch.nn as nn from torch.autograd import Function from ...utils import common_utils from . import roiaware_pool3d_cuda def points_in_boxes_cpu(points, boxes): """ Args: points: (num_points, 3) boxes: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center, each box DO NOT overlaps Returns: point_indices: (N, num_points) """ assert boxes.shape[1] == 7 assert points.shape[1] == 3 points, is_numpy = common_utils.check_numpy_to_torch(points) boxes, is_numpy = common_utils.check_numpy_to_torch(boxes) point_indices = points.new_zeros((boxes.shape[0], points.shape[0]), dtype=torch.int) roiaware_pool3d_cuda.points_in_boxes_cpu(boxes.float().contiguous(), points.float().contiguous(), point_indices) return point_indices.numpy() if is_numpy else point_indices def points_in_boxes_gpu(points, boxes): """ :param points: (B, M, 3) :param boxes: (B, T, 7), num_valid_boxes <= T :return box_idxs_of_pts: (B, M), default background = -1 """ assert boxes.shape[0] == points.shape[0] assert boxes.shape[2] == 7 and points.shape[2] == 3 batch_size, num_points, _ = points.shape box_idxs_of_pts = points.new_zeros((batch_size, num_points), dtype=torch.int).fill_(-1) roiaware_pool3d_cuda.points_in_boxes_gpu(boxes.contiguous(), points.contiguous(), box_idxs_of_pts) return box_idxs_of_pts class RoIAwarePool3d(nn.Module): def __init__(self, out_size, max_pts_each_voxel=128): super().__init__() self.out_size = out_size self.max_pts_each_voxel = max_pts_each_voxel def forward(self, rois, pts, pts_feature, pool_method='max'): assert pool_method in ['max', 'avg'] return RoIAwarePool3dFunction.apply(rois, pts, pts_feature, self.out_size, self.max_pts_each_voxel, pool_method) class RoIAwarePool3dFunction(Function): @staticmethod def forward(ctx, rois, pts, pts_feature, out_size, max_pts_each_voxel, pool_method): """ Args: ctx: rois: (N, 7) [x, y, z, dx, dy, dz, heading] (x, y, z) is the box center pts: (npoints, 3) pts_feature: (npoints, C) out_size: int or tuple, like 7 or (7, 7, 7) max_pts_each_voxel: pool_method: 'max' or 'avg' Returns: pooled_features: (N, out_x, out_y, out_z, C) """ assert rois.shape[1] == 7 and pts.shape[1] == 3 if isinstance(out_size, int): out_x = out_y = out_z = out_size else: assert len(out_size) == 3 for k in range(3): assert isinstance(out_size[k], int) out_x, out_y, out_z = out_size num_rois = rois.shape[0] num_channels = pts_feature.shape[-1] num_pts = pts.shape[0] pooled_features = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, num_channels)) argmax = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, num_channels), dtype=torch.int) pts_idx_of_voxels = pts_feature.new_zeros((num_rois, out_x, out_y, out_z, max_pts_each_voxel), dtype=torch.int) pool_method_map = {'max': 0, 'avg': 1} pool_method = pool_method_map[pool_method] roiaware_pool3d_cuda.forward(rois, pts, pts_feature, argmax, pts_idx_of_voxels, pooled_features, pool_method) ctx.roiaware_pool3d_for_backward = (pts_idx_of_voxels, argmax, pool_method, num_pts, num_channels) return pooled_features @staticmethod def backward(ctx, grad_out): """ :param grad_out: (N, out_x, out_y, out_z, C) :return: grad_in: (npoints, C) """ pts_idx_of_voxels, argmax, pool_method, num_pts, num_channels = ctx.roiaware_pool3d_for_backward grad_in = grad_out.new_zeros((num_pts, num_channels)) roiaware_pool3d_cuda.backward(pts_idx_of_voxels, argmax, grad_out.contiguous(), grad_in, pool_method) return None, None, grad_in, None, None, None if __name__ == '__main__': pass
4,075
35.392857
120
py
GPTScore
GPTScore-main/opt_score.py
# %% import torch import torch.nn as nn import traceback from transformers import BartTokenizer, BartForConditionalGeneration from transformers import GPT2Tokenizer, OPTForCausalLM, GPT2LMHeadModel, GPTJForCausalLM class OPTScorer: def __init__(self, device='cuda:0', max_length=1024, checkpoint=None): # Set up model self.device = device if 'gpt2' in checkpoint: print('gpt2 model') self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = GPT2LMHeadModel.from_pretrained(checkpoint).to(self.device) max_length = 1000 elif 'gpt-j' in checkpoint: print('gpt-j model') self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = GPTJForCausalLM.from_pretrained(checkpoint).to(self.device) max_length = 2000 else: self.tokenizer = GPT2Tokenizer.from_pretrained(checkpoint) self.model = OPTForCausalLM.from_pretrained(checkpoint).to(self.device) max_length = 2000 self.max_length = max_length print('max_length: ', max_length) self.model.eval() def score(self, srcs, tgts, prompt_text, batch_size): """ Score a batch of examples """ def trunk_input(inputs, outputs, reduce_seq, max_length): input_ids = self.tokenizer.encode(inputs)[1:-1] output_ids = self.tokenizer.encode(outputs)[1:-1] reduce_seq_ids = self.tokenizer.encode(reduce_seq)[1:-1] total_len = len(input_ids) + len(output_ids) if total_len > max_length: del_len = len(input_ids) + len(output_ids) - max_length reduce_seq_ids = reduce_seq_ids[:len(reduce_seq_ids) - del_len] reduce_seq = self.tokenizer.decode(reduce_seq_ids[1:-1]) return reduce_seq score_list = [] for i,(src, tgt) in enumerate(zip(srcs, tgts)): print('process:'+str(i) + '/'+str(len(srcs)) ) new_src = trunk_input(src, tgt, src, max_length=self.max_length) src = new_src text = src + prompt_text + tgt if i <1: print('text: ', text) print('tgt: ', tgt) input_ids = self.tokenizer.encode(text) tgt_ids = self.tokenizer.encode(tgt)[1:] output_ids = [-100] * len(input_ids) output_ids[len(input_ids) - len(tgt_ids):] = tgt_ids input_ids = torch.LongTensor(input_ids).unsqueeze(0).to(self.device) output_ids = torch.LongTensor(output_ids).unsqueeze(0).to(self.device) try: with torch.no_grad(): outputs = self.model( input_ids=input_ids, labels=output_ids, output_hidden_states=True ) loss, logits, hidden_states = outputs[0], outputs[1], outputs.hidden_states[0] loss = loss.item() score = -loss score_list.append(score) print('score: ',score) except RuntimeError: # traceback.print_exc() print('input_ids: ',input_ids) print('output_ids: ', output_ids) print(f'source: {src}') print(f'target: {tgt}') # exit(0) return score_list
3,445
41.54321
94
py
GPTScore
GPTScore-main/flan_score.py
# %% import torch import torch.nn as nn import traceback from transformers import AutoModelForSeq2SeqLM, AutoTokenizer class FLANScorer: def __init__(self, device='cuda:0', max_length=1024, checkpoint='google/flan-t5-base'): # Set up model self.device = device self.max_length = max_length self.tokenizer = AutoTokenizer.from_pretrained(checkpoint) self.model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) self.model.eval() self.model.to(device) # Set up loss self.loss_fct = nn.NLLLoss(reduction='none', ignore_index=self.model.config.pad_token_id) self.lsm = nn.LogSoftmax(dim=1) def load(self): """ Load model from paraphrase finetuning """ self.model.load_state_dict(torch.load('models/bart.pth', map_location=self.device)) def score(self, srcs, tgts, batch_size): """ Score a batch of examples """ score_list = [] for i in range(0, len(srcs), batch_size): src_list = srcs[i: i + batch_size] tgt_list = tgts[i: i + batch_size] if i <1: print('src_list: ',src_list) print('tgt_list: ', tgt_list) try: with torch.no_grad(): encoded_src = self.tokenizer( src_list, max_length=self.max_length, truncation=True, padding=True, return_tensors='pt' ) encoded_tgt = self.tokenizer( tgt_list, max_length=self.max_length, truncation=True, padding=True, return_tensors='pt' ) src_tokens = encoded_src['input_ids'].to(self.device) src_mask = encoded_src['attention_mask'].to(self.device) tgt_tokens = encoded_tgt['input_ids'].to(self.device) tgt_mask = encoded_tgt['attention_mask'] tgt_len = tgt_mask.sum(dim=1).to(self.device) output = self.model( input_ids=src_tokens, attention_mask=src_mask, labels=tgt_tokens ) logits = output.logits.view(-1, self.model.config.vocab_size) loss = self.loss_fct(self.lsm(logits), tgt_tokens.view(-1)) loss = loss.view(tgt_tokens.shape[0], -1) loss = loss.sum(dim=1) / tgt_len curr_score_list = [-x.item() for x in loss] score_list += curr_score_list except RuntimeError: traceback.print_exc() print(f'source: {src_list}') print(f'target: {tgt_list}') exit(0) return score_list
2,981
39.849315
97
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/main.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import argparse import time import yaml import os import logging from collections import OrderedDict from contextlib import suppress from datetime import datetime import models import torch import torch.nn as nn import torchvision.utils from torch.nn.parallel import DistributedDataParallel as NativeDDP from timm.data import Dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from timm.models import load_checkpoint, create_model, resume_checkpoint, convert_splitbn_model from timm.utils import * from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, JsdCrossEntropy from timm.optim import create_optimizer from timm.scheduler import create_scheduler from timm.utils import ApexScaler, NativeScaler from checkpoint_saver import CheckpointSaver from labeled_memcached_dataset import McDataset torch.backends.cudnn.benchmark = True _logger = logging.getLogger('train') import warnings warnings.filterwarnings('ignore') config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser = argparse.ArgumentParser(description='CSWin Training and Evaluating') # Dataset / Model parameters parser.add_argument('--data', default='/mnt/blob/testset/ImageNet', metavar='DIR', help='path to dataset') parser.add_argument('--model', default='CSWin_64_12211_tiny_224', type=str, metavar='MODEL', help='Name of model to train (default: "countception"') parser.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)') parser.add_argument('--eval_checkpoint', default='', type=str, metavar='PATH', help='path to eval checkpoint (default: none)') parser.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model') parser.add_argument('--num-classes', type=int, default=1000, metavar='N', help='number of label classes (default: 1000)') parser.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') parser.add_argument('--img-size', type=int, default=224, metavar='N', help='Image patch size (default: None => model default)') parser.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)') parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset') parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of of dataset') parser.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)') parser.add_argument('-b', '--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('-vb', '--validation-batch-size-multiplier', type=int, default=1, metavar='N', help='ratio of validation batch size to training batch size (default: 1)') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)') parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.005 for adamw)') parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') # Learning rate schedule parameters parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)') parser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 0.0001)') parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 2)') parser.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_argument('--warmup-epochs', type=int, default=20, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation & regularization parameters parser.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args') parser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)') parser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)') parser.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability') parser.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability') parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". (default: None)'), parser.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)') parser.add_argument('--jsd', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "const")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.)') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') parser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)') parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') parser.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")') parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.0)') parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)') parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: None)') parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)') # Batch norm parameters (only works with gen_efficientnet based models currently) parser.add_argument('--bn-tf', action='store_true', default=False, help='Use Tensorflow BatchNorm defaults for models that support it (default: False)') parser.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)') parser.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)') parser.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') parser.add_argument('--dist-bn', type=str, default='', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') parser.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.') # Model Exponential Moving Average parser.add_argument('--model-ema', action='store_true', default=True, help='Enable tracking moving average of model weights') parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') parser.add_argument('--model-ema-decay', type=float, default=0.99992, help='decay factor for model weights moving average (default: 0.9998)') # Misc parser.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)') parser.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint') parser.add_argument('-j', '--workers', type=int, default=8, metavar='N', help='how many training processes to use (default: 1)') parser.add_argument('--num-gpu', type=int, default=1, help='Number of GPUS to use') parser.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging') parser.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training') parser.add_argument('--apex-amp', action='store_true', default=False, help='Use NVIDIA Apex AMP mixed precision') parser.add_argument('--native-amp', action='store_true', default=False, help='Use Native Torch AMP mixed precision') parser.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout') parser.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher') parser.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') parser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"') parser.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch') parser.add_argument('--use-chk', action='store_true', default=False, help='Enable tracking moving average of model weights') has_apex = False has_native_amp = False try: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = True except AttributeError: pass def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) # The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining) # Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text def main(): setup_default_logging() args, args_text = _parse_args() args.prefetcher = not args.no_prefetcher args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed and args.num_gpu > 1: _logger.warning( 'Using more than one GPU per process in distributed mode is not allowed.Setting num_gpu to 1.') args.num_gpu = 1 args.device = 'cuda:0' args.world_size = 1 args.rank = 0 # global rank if args.distributed: args.num_gpu = 1 args.device = 'cuda:%d' % args.local_rank torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() assert args.rank >= 0 if args.distributed: _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' % (args.rank, args.world_size)) else: _logger.info('Training with a single process on %d GPUs.' % args.num_gpu) torch.manual_seed(args.seed + args.rank) model = create_model( args.model, pretrained=args.pretrained, num_classes=args.num_classes, drop_rate=args.drop, drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_tf=args.bn_tf, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, checkpoint_path=args.initial_checkpoint, img_size=args.img_size, use_chk=args.use_chk) def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print ('Num:', count_parameters(model)/1e6) if args.local_rank == 0: _logger.info('Model %s created, param count: %d' % (args.model, sum([m.numel() for m in model.parameters()]))) data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0) num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) use_amp = None if args.amp: # for backwards compat, `--amp` arg tries apex before native amp if has_apex: args.apex_amp = True elif has_native_amp: args.native_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: _logger.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6") if args.num_gpu > 1: if use_amp == 'apex': _logger.warning( 'Apex AMP does not work well with nn.DataParallel, disabling. Use DDP or Torch AMP.') use_amp = None model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() assert not args.channels_last, "Channels last not supported with DP, use DDP." else: model.cuda() if args.channels_last: model = model.to(memory_format=torch.channels_last) optimizer = create_optimizer(args, model) amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if args.local_rank == 0: _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': amp_autocast = torch.cuda.amp.autocast loss_scaler = NativeScaler() if args.local_rank == 0: _logger.info('Using native Torch AMP. Training in mixed precision.') else: if args.local_rank == 0: _logger.info('AMP not enabled. Training in float32.') # optionally resume from a checkpoint resume_epoch = None if args.resume: resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, loss_scaler=None if args.no_resume_opt else loss_scaler, log_info=args.local_rank == 0) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume=args.resume) if args.distributed: if args.sync_bn: assert not args.split_bn try: if has_apex and use_amp != 'native': # Apex SyncBN preferred unless native amp is activated model = convert_syncbn_model(model) else: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if args.local_rank == 0: _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') except Exception as e: _logger.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1') if has_apex and use_amp != 'native': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[args.local_rank], find_unused_parameters=True) # can use device str in Torch >= 1.1 # NOTE: EMA model does not need to be wrapped by DDP lr_scheduler, num_epochs = create_scheduler(args, optimizer) start_epoch = 0 if args.start_epoch is not None: # a specified start_epoch will always override the resume epoch start_epoch = args.start_epoch elif resume_epoch is not None: start_epoch = resume_epoch if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch) if args.local_rank == 0: _logger.info('Scheduled epochs: {}'.format(num_epochs)) train_dir = os.path.join(args.data, 'train') if not os.path.exists(train_dir): _logger.error('Training folder does not exist at: {}'.format(train_dir)) exit(1) dataset_train = McDataset(args.data, './dataset/ILSVRC2012_name_train.txt', 'train') collate_fn = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_args = dict( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.num_classes) if args.prefetcher: assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) collate_fn = FastCollateMixup(**mixup_args) else: mixup_fn = Mixup(**mixup_args) if num_aug_splits > 1: dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits) train_interpolation = args.train_interpolation if args.no_aug or not train_interpolation: train_interpolation = data_config['interpolation'] if args.aa == 'None': args.aa = None loader_train = create_loader( dataset_train, input_size=data_config['input_size'], batch_size=args.batch_size, is_training=True, use_prefetcher=args.prefetcher, no_aug=args.no_aug, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, re_split=args.resplit, scale=args.scale, ratio=args.ratio, hflip=args.hflip, vflip=args.vflip, color_jitter=args.color_jitter, auto_augment=args.aa, num_aug_splits=num_aug_splits, interpolation=train_interpolation, mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, collate_fn=collate_fn, pin_memory=args.pin_mem, use_multi_epochs_loader=args.use_multi_epochs_loader ) eval_dir = os.path.join(args.data, 'val') if not os.path.isdir(eval_dir): eval_dir = os.path.join(args.data, 'validation') if not os.path.isdir(eval_dir): _logger.error('Validation folder does not exist at: {}'.format(eval_dir)) exit(1) dataset_eval = McDataset(args.data, './dataset/ILSVRC2012_name_val.txt', 'val') loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size_multiplier * args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, ) if args.jsd: assert num_aug_splits > 1 # JSD only valid with aug splits set train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing).cuda() elif mixup_active: # smoothing is handled with mixup target transform train_loss_fn = SoftTargetCrossEntropy().cuda() elif args.smoothing: train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing).cuda() else: train_loss_fn = nn.CrossEntropyLoss().cuda() validate_loss_fn = nn.CrossEntropyLoss().cuda() eval_metric = args.eval_metric best_metric = None best_epoch = None if args.eval_checkpoint: # evaluate the model load_checkpoint(model, args.eval_checkpoint, args.model_ema) val_metrics = validate(model, loader_eval, validate_loss_fn, args) print(f"Top-1 accuracy of the model is: {val_metrics['top1']:.1f}%") return saver = None output_dir = '' if args.local_rank == 0: output_base = args.output if args.output else './output' exp_name = '-'.join([ datetime.now().strftime("%Y%m%d-%H%M%S"), args.model, str(data_config['input_size'][-1]) ]) output_dir = get_outdir(output_base, 'train', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver( model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text) try: # train the model for epoch in range(start_epoch, num_epochs): if args.distributed: loader_train.sampler.set_epoch(epoch) train_metrics = train_epoch( epoch, model, loader_train, optimizer, train_loss_fn, args, lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn) if args.distributed and args.dist_bn in ('broadcast', 'reduce'): if args.local_rank == 0: _logger.info("Distributing BatchNorm running means and vars") distribute_bn(model, args.world_size, args.dist_bn == 'reduce') eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast) if model_ema is not None and not args.model_ema_force_cpu: if args.distributed and args.dist_bn in ('broadcast', 'reduce'): distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') ema_eval_metrics = validate( model_ema.ema, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') eval_metrics = ema_eval_metrics if lr_scheduler is not None: # step LR for next epoch lr_scheduler.step(epoch + 1, eval_metrics[eval_metric]) update_summary( epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), write_header=best_metric is None) if saver is not None: # save proper checkpoint with eval metric save_metric = eval_metrics[eval_metric] best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric) except KeyboardInterrupt: pass if best_metric is not None: _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch)) def train_epoch( epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None): if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: if args.prefetcher and loader.mixup_enabled: loader.mixup_enabled = False elif mixup_fn is not None: mixup_fn.mixup_enabled = False second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order batch_time_m = AverageMeter() data_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.train() end = time.time() last_idx = len(loader) - 1 num_updates = epoch * len(loader) for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx data_time_m.update(time.time() - end) if not args.prefetcher: input, target = input.cuda(), target.cuda() if mixup_fn is not None: input, target = mixup_fn(input, target) if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) loss = loss_fn(output, target) if not args.distributed: losses_m.update(loss.item(), input.size(0)) optimizer.zero_grad() if loss_scaler is not None: loss_scaler( loss, optimizer, clip_grad=args.clip_grad, parameters=model.parameters(), create_graph=second_order) else: loss.backward(create_graph=second_order) if args.clip_grad is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad) optimizer.step() torch.cuda.synchronize() if model_ema is not None: model_ema.update(model) num_updates += 1 batch_time_m.update(time.time() - end) if last_batch or batch_idx % args.log_interval == 0: lrl = [param_group['lr'] for param_group in optimizer.param_groups] lr = sum(lrl) / len(lrl) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) losses_m.update(reduced_loss.item(), input.size(0)) if args.local_rank == 0: _logger.info( 'Train: {} [{:>4d}/{} ({:>3.0f}%)] ' 'Loss: {loss.val:>9.6f} ({loss.avg:>6.4f}) ' 'Time: {rate:>4.0f}/s ({rate_avg:>4.0f}/s) ' 'LR: {lr:.3e} ' 'Data: {data_time.sum:.3f}'.format( epoch, batch_idx, len(loader), 100. * batch_idx / last_idx, loss=losses_m, batch_time=batch_time_m, rate=input.size(0) * args.world_size / batch_time_m.val, rate_avg=input.size(0) * args.world_size / batch_time_m.avg, lr=lr, data_time=data_time_m)) if args.save_images and output_dir: torchvision.utils.save_image( input, os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), padding=0, normalize=True) if saver is not None and args.recovery_interval and ( last_batch or (batch_idx + 1) % args.recovery_interval == 0): saver.save_recovery(epoch, batch_idx=batch_idx) if lr_scheduler is not None: lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg) end = time.time() # end for if hasattr(optimizer, 'sync_lookahead'): optimizer.sync_lookahead() return OrderedDict([('loss', losses_m.avg)]) def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.eval() end = time.time() last_idx = len(loader) - 1 with torch.no_grad(): for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx if not args.prefetcher: input = input.cuda() target = target.cuda() if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) if isinstance(output, (tuple, list)): output = output[0] # augmentation reduction reduce_factor = args.tta if reduce_factor > 1: output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) target = target[0:target.size(0):reduce_factor] loss = loss_fn(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) acc1 = reduce_tensor(acc1, args.world_size) acc5 = reduce_tensor(acc5, args.world_size) else: reduced_loss = loss.data torch.cuda.synchronize() losses_m.update(reduced_loss.item(), input.size(0)) top1_m.update(acc1.item(), output.size(0)) top5_m.update(acc5.item(), output.size(0)) batch_time_m.update(time.time() - end) end = time.time() if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): log_name = 'Test' + log_suffix _logger.info( '{0}: [{1:>4d}/{2}] ' 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( log_name, batch_idx, last_idx, batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m)) metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)]) return metrics if __name__ == '__main__': main()
36,210
46.272846
133
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/labeled_memcached_dataset.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ from torch.utils.data import Dataset import numpy as np import io from PIL import Image import os import json import random def load_img(filepath): img = Image.open(filepath).convert('RGB') return img class McDataset(Dataset): def __init__(self, data_root, file_list, phase = 'train', transform=None): self.transform = transform self.root = os.path.join(data_root, phase) temp_label = json.load(open('./dataset/imagenet_class_index.json', 'r')) self.labels = {} for i in range(1000): self.labels[temp_label[str(i)][0]] = i self.A_paths = [] self.A_labels = [] with open(file_list, 'r') as f: temp_path = f.readlines() for path in temp_path: label = self.labels[path.split('/')[0]] self.A_paths.append(os.path.join(self.root, path.strip())) self.A_labels.append(label) self.num = len(self.A_paths) self.A_size = len(self.A_paths) def __len__(self): return self.num def __getitem__(self, index): try: return self.load_img(index) except: return self.__getitem__(random.randint(0, self.__len__()-1)) def load_img(self, index): A_path = self.A_paths[index % self.A_size] A = load_img(A_path) if self.transform is not None: A = self.transform(A) A_label = self.A_labels[index % self.A_size] return A, A_label
1,700
29.375
80
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/finetune.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import argparse import time import yaml import os import logging from collections import OrderedDict from contextlib import suppress from datetime import datetime import models import torch import torch.nn as nn import torchvision.utils from torch.nn.parallel import DistributedDataParallel as NativeDDP from timm.data import Dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from timm.models import create_model, resume_checkpoint, convert_splitbn_model from timm.utils import * from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, JsdCrossEntropy from timm.scheduler import create_scheduler from timm.utils import ApexScaler, NativeScaler from checkpoint_saver import CheckpointSaver from labeled_memcached_dataset import McDataset import torch.optim as optim torch.backends.cudnn.benchmark = True _logger = logging.getLogger('train') # The first arg parser parses out only the --config argument, this argument is used to # load a yaml file containing key-values that override the defaults for the main parser below config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser = argparse.ArgumentParser(description='CSWin Training and Evaluating') # Dataset / Model parameters parser.add_argument('--data', default='/mnt/blob/testset/ImageNet', metavar='DIR', help='path to dataset') parser.add_argument('--model', default='', type=str, metavar='MODEL', help='Name of model to train (default: "countception"') parser.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') parser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)') parser.add_argument('--eval_checkpoint', default='', type=str, metavar='PATH', help='path to eval checkpoint (default: none)') parser.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model') parser.add_argument('--num-classes', type=int, default=1000, metavar='N', help='number of label classes (default: 1000)') parser.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') parser.add_argument('--img-size', type=int, default=224, metavar='N', help='Image patch size (default: None => model default)') parser.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)') parser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset') parser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of of dataset') parser.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)') parser.add_argument('-b', '--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('-vb', '--validation-batch-size-multiplier', type=int, default=1, metavar='N', help='ratio of validation batch size to training batch size (default: 1)') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)') parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.005 for adamw)') parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') # Learning rate schedule parameters parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--lr-scale', type=float, default=1e-2, help='learning rate finetune scale(default: 0.01)') parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)') parser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 0.0001)') parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 2)') parser.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation & regularization parameters parser.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args') parser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)') parser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)') parser.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability') parser.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability') parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". (default: None)'), parser.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)') parser.add_argument('--jsd', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "const")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.)') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') parser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)') parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') parser.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")') parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.0)') parser.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)') parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: None)') parser.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)') # Batch norm parameters (only works with gen_efficientnet based models currently) parser.add_argument('--bn-tf', action='store_true', default=False, help='Use Tensorflow BatchNorm defaults for models that support it (default: False)') parser.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)') parser.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)') parser.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') parser.add_argument('--dist-bn', type=str, default='', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') parser.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.') # Model Exponential Moving Average parser.add_argument('--model-ema', action='store_true', default=True, help='Enable tracking moving average of model weights') parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') parser.add_argument('--model-ema-decay', type=float, default=0.99996, help='decay factor for model weights moving average (default: 0.9998)') # Misc parser.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)') parser.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint') parser.add_argument('-j', '--workers', type=int, default=8, metavar='N', help='how many training processes to use (default: 1)') parser.add_argument('--num-gpu', type=int, default=1, help='Number of GPUS to use') parser.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging') parser.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training') parser.add_argument('--apex-amp', action='store_true', default=False, help='Use NVIDIA Apex AMP mixed precision') parser.add_argument('--native-amp', action='store_true', default=False, help='Use Native Torch AMP mixed precision') parser.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout') parser.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher') parser.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') parser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"') parser.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch') parser.add_argument('--finetune', default='', type=str, metavar='PATH', help='finetune full model and optimizer state from checkpoint (default: none)') parser.add_argument('--fine-22k', action='store_true', default=False, help='finetune 22k model') parser.add_argument('--use-chk', action='store_true', default=False, help='Enable tracking moving average of model weights') parser.add_argument('--ema-finetune', action='store_true', default=False, help='Enable tracking moving average of model weights') try: from apex import amp from apex.parallel import DistributedDataParallel as ApexDDP from apex.parallel import convert_syncbn_model has_apex = True except ImportError: has_apex = False has_native_amp = False try: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = True except AttributeError: pass def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) # The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining) # Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text def load_checkpoint(args, model, checkpoint_path, use_ema=False): if checkpoint_path and os.path.isfile(checkpoint_path): checkpoint = torch.load(checkpoint_path, map_location='cpu') state_dict_key = 'state_dict' model_key = 'model' if isinstance(checkpoint, dict): if use_ema and 'state_dict_ema' in checkpoint: state_dict_key = 'state_dict_ema' if state_dict_key and state_dict_key in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint[state_dict_key].items(): # strip `module.` prefix name = k[7:] if k.startswith('module') else k if args.fine_22k and 'head' in k: continue new_state_dict[name] = v state_dict = new_state_dict elif model_key and model_key in checkpoint: new_state_dict = OrderedDict() for k, v in checkpoint[model_key].items(): # strip `module.` prefix name = k[7:] if k.startswith('module') else k if args.fine_22k and 'head' in k: continue new_state_dict[name] = v state_dict = new_state_dict else: state_dict = checkpoint if args.local_rank == 0: _logger.info("Loaded {} from checkpoint '{}'".format(state_dict_key, checkpoint_path)) else: if args.local_rank == 0: _logger.error("No checkpoint found at '{}'".format(checkpoint_path)) raise FileNotFoundError() model_dict = model.state_dict() pretrained_dict = state_dict loaded_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} load_dic = [k for k, v in pretrained_dict.items() if k in model_dict] miss_dic = [k for k, v in pretrained_dict.items() if not (k in model_dict)] unexpect_dic = [k for k, v in model_dict.items() if not (k in pretrained_dict)] if args.local_rank == 0: print ("Miss Keys:", miss_dic) print ("Ubexpected Keys:", unexpect_dic) model_dict.update(loaded_dict) model.load_state_dict(model_dict, strict=True) def create_optimizer(args, parameters, filter_bias_and_bn=True): opt_lower = args.opt.lower() weight_decay = args.weight_decay if 'fused' in opt_lower: assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers' opt_args = dict(lr=args.lr, weight_decay=weight_decay) if hasattr(args, 'opt_eps') and args.opt_eps is not None: opt_args['eps'] = args.opt_eps if hasattr(args, 'opt_betas') and args.opt_betas is not None: opt_args['betas'] = args.opt_betas if hasattr(args, 'opt_args') and args.opt_args is not None: opt_args.update(args.opt_args) opt_split = opt_lower.split('_') opt_lower = opt_split[-1] if opt_lower == 'sgd' or opt_lower == 'nesterov': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'momentum': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'adam': optimizer = optim.Adam(parameters, **opt_args) elif opt_lower == 'adamw': optimizer = optim.AdamW(parameters, **opt_args) elif opt_lower == 'nadam': optimizer = Nadam(parameters, **opt_args) elif opt_lower == 'radam': optimizer = RAdam(parameters, **opt_args) elif opt_lower == 'adamp': optimizer = AdamP(parameters, wd_ratio=0.01, nesterov=True, **opt_args) elif opt_lower == 'sgdp': optimizer = SGDP(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'adadelta': optimizer = optim.Adadelta(parameters, **opt_args) elif opt_lower == 'adafactor': if not args.lr: opt_args['lr'] = None optimizer = Adafactor(parameters, **opt_args) elif opt_lower == 'adahessian': optimizer = Adahessian(parameters, **opt_args) elif opt_lower == 'rmsprop': optimizer = optim.RMSprop(parameters, alpha=0.9, momentum=args.momentum, **opt_args) elif opt_lower == 'rmsproptf': optimizer = RMSpropTF(parameters, alpha=0.9, momentum=args.momentum, **opt_args) elif opt_lower == 'novograd': optimizer = NovoGrad(parameters, **opt_args) elif opt_lower == 'nvnovograd': optimizer = NvNovoGrad(parameters, **opt_args) elif opt_lower == 'fusedsgd': opt_args.pop('eps', None) optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'fusedmomentum': opt_args.pop('eps', None) optimizer = FusedSGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'fusedadam': optimizer = FusedAdam(parameters, adam_w_mode=False, **opt_args) elif opt_lower == 'fusedadamw': optimizer = FusedAdam(parameters, adam_w_mode=True, **opt_args) elif opt_lower == 'fusedlamb': optimizer = FusedLAMB(parameters, **opt_args) elif opt_lower == 'fusednovograd': opt_args.setdefault('betas', (0.95, 0.98)) optimizer = FusedNovoGrad(parameters, **opt_args) else: assert False and "Invalid optimizer" raise ValueError if len(opt_split) > 1: if opt_split[0] == 'lookahead': optimizer = Lookahead(optimizer) return optimizer def main(): setup_default_logging() args, args_text = _parse_args() args.prefetcher = not args.no_prefetcher args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 if args.distributed and args.num_gpu > 1: _logger.warning( 'Using more than one GPU per process in distributed mode is not allowed.Setting num_gpu to 1.') args.num_gpu = 1 args.device = 'cuda:0' args.world_size = 1 args.rank = 0 # global rank if args.distributed: args.num_gpu = 1 args.device = 'cuda:%d' % args.local_rank torch.cuda.set_device(args.local_rank) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() assert args.rank >= 0 if args.distributed: _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.' % (args.rank, args.world_size)) else: _logger.info('Training with a single process on %d GPUs.' % args.num_gpu) torch.manual_seed(args.seed + args.rank) model = create_model( args.model, pretrained=args.pretrained, num_classes=args.num_classes, drop_rate=args.drop, drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_tf=args.bn_tf, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, checkpoint_path=args.initial_checkpoint, img_size=args.img_size, use_chk=args.use_chk) if args.local_rank == 0: _logger.info('Model %s created, param count: %d' % (args.model, sum([m.numel() for m in model.parameters()]))) data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0) num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) use_amp = None if args.amp: if has_apex: args.apex_amp = True elif has_native_amp: args.native_amp = True if args.apex_amp and has_apex: use_amp = 'apex' elif args.native_amp and has_native_amp: use_amp = 'native' elif args.apex_amp or args.native_amp: _logger.warning("Neither APEX or native Torch AMP is available, using float32. " "Install NVIDA apex or upgrade to PyTorch 1.6") if args.num_gpu > 1: if use_amp == 'apex': _logger.warning( 'Apex AMP does not work well with nn.DataParallel, disabling. Use DDP or Torch AMP.') use_amp = None model = nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() assert not args.channels_last, "Channels last not supported with DP, use DDP." else: model.cuda() if args.channels_last: model = model.to(memory_format=torch.channels_last) # optionally resume from a checkpoint resume_epoch = None if args.resume: head_para = [] base_para = [] for name, para in model.named_parameters(): if 'head' in name: head_para.append(para) else: base_para.append(para) parameters = [{'params': base_para, 'lr': args.lr_scale * args.lr}, {'params': head_para}] optimizer = create_optimizer(args, parameters) resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, log_info=args.local_rank == 0) if args.finetune: load_checkpoint(args, model, args.finetune, use_ema=args.ema_finetune) model.cuda() model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper if args.local_rank == 0: print ("Use EMA with decay:", args.model_ema_decay) model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume=args.resume) head_para = [] base_para = [] if not args.resume: for name, para in model.named_parameters(): if 'head' in name: head_para.append(para) else: base_para.append(para) parameters = [{'params': base_para, 'lr': args.lr_scale * args.lr}, {'params': head_para}] optimizer = create_optimizer(args, parameters) amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if args.local_rank == 0: _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': amp_autocast = torch.cuda.amp.autocast loss_scaler = NativeScaler() if args.local_rank == 0: _logger.info('Using native Torch AMP. Training in mixed precision.') else: if args.local_rank == 0: _logger.info('AMP not enabled. Training in float32.') if args.distributed: if args.sync_bn: assert not args.split_bn try: if has_apex and use_amp != 'native': # Apex SyncBN preferred unless native amp is activated model = convert_syncbn_model(model) else: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if args.local_rank == 0: _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') except Exception as e: _logger.error('Failed to enable Synchronized BatchNorm. Install Apex or Torch >= 1.1') if has_apex and use_amp != 'native': # Apex DDP preferred unless native amp is activated if args.local_rank == 0: _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if args.local_rank == 0: _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[args.local_rank], find_unused_parameters=False) # can use device str in Torch >= 1.1 # NOTE: EMA model does not need to be wrapped by DDP lr_scheduler, num_epochs = create_scheduler(args, optimizer) start_epoch = 0 if args.start_epoch is not None: # a specified start_epoch will always override the resume epoch start_epoch = args.start_epoch elif resume_epoch is not None: start_epoch = resume_epoch if lr_scheduler is not None and start_epoch > 0: lr_scheduler.step(start_epoch) if args.local_rank == 0: _logger.info('Scheduled epochs: {}'.format(num_epochs)) train_dir = os.path.join(args.data, 'train') if not os.path.exists(train_dir): _logger.error('Training folder does not exist at: {}'.format(train_dir)) exit(1) dataset_train = McDataset(args.data, './dataset/ILSVRC2012_name_train.txt', 'train') collate_fn = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_args = dict( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.num_classes) if args.prefetcher: assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup) collate_fn = FastCollateMixup(**mixup_args) else: mixup_fn = Mixup(**mixup_args) if num_aug_splits > 1: dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits) train_interpolation = args.train_interpolation if args.no_aug or not train_interpolation: train_interpolation = data_config['interpolation'] if args.aa == 'None': args.aa = None loader_train = create_loader( dataset_train, input_size=data_config['input_size'], batch_size=args.batch_size, is_training=True, use_prefetcher=args.prefetcher, no_aug=args.no_aug, re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, re_split=args.resplit, scale=args.scale, ratio=args.ratio, hflip=args.hflip, vflip=args.vflip, color_jitter=args.color_jitter, auto_augment=args.aa, num_aug_splits=num_aug_splits, interpolation=train_interpolation, mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, collate_fn=collate_fn, pin_memory=args.pin_mem, use_multi_epochs_loader=args.use_multi_epochs_loader ) eval_dir = os.path.join(args.data, 'val') if not os.path.isdir(eval_dir): eval_dir = os.path.join(args.data, 'validation') if not os.path.isdir(eval_dir): _logger.error('Validation folder does not exist at: {}'.format(eval_dir)) exit(1) dataset_eval = McDataset(args.data, './dataset/ILSVRC2012_name_val.txt', 'val') loader_eval = create_loader( dataset_eval, input_size=data_config['input_size'], batch_size=args.validation_batch_size_multiplier * args.batch_size, is_training=False, use_prefetcher=args.prefetcher, interpolation=data_config['interpolation'], mean=data_config['mean'], std=data_config['std'], num_workers=args.workers, distributed=args.distributed, crop_pct=data_config['crop_pct'], pin_memory=args.pin_mem, ) if args.jsd: assert num_aug_splits > 1 # JSD only valid with aug splits set train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing).cuda() elif mixup_active: # smoothing is handled with mixup target transform train_loss_fn = SoftTargetCrossEntropy().cuda() elif args.smoothing: train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing).cuda() else: train_loss_fn = nn.CrossEntropyLoss().cuda() validate_loss_fn = nn.CrossEntropyLoss().cuda() eval_metric = args.eval_metric best_metric = None best_epoch = None if args.eval_checkpoint: # evaluate the model load_checkpoint(model, args.eval_checkpoint, args.model_ema) val_metrics = validate(model, loader_eval, validate_loss_fn, args) print(f"Top-1 accuracy of the model is: {val_metrics['top1']:.1f}%") return saver = None output_dir = '' if args.local_rank == 0: output_base = args.output if args.output else './output' exp_name = '-'.join([ datetime.now().strftime("%Y%m%d-%H%M%S"), args.model, str(data_config['input_size'][-1]) ]) output_dir = get_outdir(output_base, 'finetune', exp_name) decreasing = True if eval_metric == 'loss' else False saver = CheckpointSaver( model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler, checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing) with open(os.path.join(output_dir, 'args.yaml'), 'w') as f: f.write(args_text) try: # train the model for epoch in range(start_epoch, num_epochs): if args.distributed: loader_train.sampler.set_epoch(epoch) train_metrics = train_epoch( epoch, model, loader_train, optimizer, train_loss_fn, args, lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir, amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn) if args.distributed and args.dist_bn in ('broadcast', 'reduce'): if args.local_rank == 0: _logger.info("Distributing BatchNorm running means and vars") distribute_bn(model, args.world_size, args.dist_bn == 'reduce') eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast) if model_ema is not None and not args.model_ema_force_cpu: if args.distributed and args.dist_bn in ('broadcast', 'reduce'): distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce') ema_eval_metrics = validate( model_ema.ema, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)') eval_metrics = ema_eval_metrics if lr_scheduler is not None: # step LR for next epoch lr_scheduler.step(epoch + 1, eval_metrics[eval_metric]) update_summary( epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'), write_header=best_metric is None) if saver is not None: # save proper checkpoint with eval metric save_metric = eval_metrics[eval_metric] best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric) except KeyboardInterrupt: pass if best_metric is not None: _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch)) def train_epoch( epoch, model, loader, optimizer, loss_fn, args, freeze=False, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None): if args.mixup_off_epoch and epoch >= args.mixup_off_epoch: if args.prefetcher and loader.mixup_enabled: loader.mixup_enabled = False elif mixup_fn is not None: mixup_fn.mixup_enabled = False second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order batch_time_m = AverageMeter() data_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.train() end = time.time() last_idx = len(loader) - 1 num_updates = epoch * len(loader) for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx data_time_m.update(time.time() - end) if not args.prefetcher: input, target = input.cuda(), target.cuda() if mixup_fn is not None: input, target = mixup_fn(input, target) if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) loss = loss_fn(output, target) if not args.distributed: losses_m.update(loss.item(), input.size(0)) #torch.cuda.synchronize() #end = time.time() optimizer.zero_grad() if loss_scaler is not None: loss_scaler( loss, optimizer, clip_grad=args.clip_grad, parameters=model.parameters(), create_graph=second_order) else: loss.backward(create_graph=second_order) if args.clip_grad is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad) optimizer.step() torch.cuda.synchronize() if model_ema is not None: model_ema.update(model) num_updates += 1 batch_time_m.update(time.time() - end) if last_batch or batch_idx % args.log_interval == 0: lrl = [param_group['lr'] for param_group in optimizer.param_groups] lr = sum(lrl) / len(lrl) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) losses_m.update(reduced_loss.item(), input.size(0)) if args.local_rank == 0: _logger.info( 'Train:{} [{:>4d}/{} ({:>3.0f}%)] ' 'Loss:{loss.val:>9.6f} ({loss.avg:>6.4f}) ' 'Time:' '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) ' 'LR:{lr1:.3e} {lr2:.3e} ' 'Data:({data_time.sum:.3f})'.format( epoch, batch_idx, len(loader), 100. * batch_idx / last_idx, loss=losses_m, batch_time=batch_time_m, rate=input.size(0) * args.world_size / batch_time_m.val, rate_avg=input.size(0) * args.world_size / batch_time_m.avg, lr1=lrl[0], lr2=lrl[1], data_time=data_time_m)) if args.save_images and output_dir: torchvision.utils.save_image( input, os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx), padding=0, normalize=True) if saver is not None and args.recovery_interval and ( last_batch or (batch_idx + 1) % args.recovery_interval == 0): saver.save_recovery(epoch, batch_idx=batch_idx) if lr_scheduler is not None: lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg) end = time.time() # end for if hasattr(optimizer, 'sync_lookahead'): optimizer.sync_lookahead() return OrderedDict([('loss', losses_m.avg)]) def validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''): batch_time_m = AverageMeter() losses_m = AverageMeter() top1_m = AverageMeter() top5_m = AverageMeter() model.eval() end = time.time() last_idx = len(loader) - 1 with torch.no_grad(): for batch_idx, (input, target) in enumerate(loader): last_batch = batch_idx == last_idx if not args.prefetcher: input = input.cuda() target = target.cuda() if args.channels_last: input = input.contiguous(memory_format=torch.channels_last) with amp_autocast(): output = model(input) if isinstance(output, (tuple, list)): output = output[0] # augmentation reduction reduce_factor = args.tta if reduce_factor > 1: output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2) target = target[0:target.size(0):reduce_factor] loss = loss_fn(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) if args.distributed: reduced_loss = reduce_tensor(loss.data, args.world_size) acc1 = reduce_tensor(acc1, args.world_size) acc5 = reduce_tensor(acc5, args.world_size) else: reduced_loss = loss.data torch.cuda.synchronize() losses_m.update(reduced_loss.item(), input.size(0)) top1_m.update(acc1.item(), output.size(0)) top5_m.update(acc5.item(), output.size(0)) batch_time_m.update(time.time() - end) end = time.time() if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0): log_name = 'Test' + log_suffix _logger.info( '{0}: [{1:>4d}/{2}] ' 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) ' 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) ' 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) ' 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format( log_name, batch_idx, last_idx, batch_time=batch_time_m, loss=losses_m, top1=top1_m, top5=top5_m)) metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)]) return metrics if __name__ == '__main__': main()
43,476
45.900755
134
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/checkpoint_saver.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import glob import operator import os import logging import torch from timm.utils.model import unwrap_model, get_state_dict import shutil _logger = logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts of self.model = model self.optimizer = optimizer self.args = args self.model_ema = model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files = [] # (filename, metric) tuples in order of decreasing betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file = '' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing # a lower metric is better if True self.cmp = operator.lt if decreasing else operator.gt # True if lhs better than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1 def save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): #os.unlink(last_save_path) # required for Windows support. os.remove(last_save_path) os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) #os.link(last_save_path, save_path) shutil.copyfile(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in descending order if a lower metric is not better checkpoints_str = "Current checkpoints:\n" for c in self.checkpoint_files: checkpoints_str += ' {}\n'.format(c) _logger.info(checkpoints_str) if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) #os.link(last_save_path, best_save_path) shutil.copyfile(last_save_path, best_save_path) return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2 increments epoch before save } if self.args is not None: save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if delete_index <= 0 or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug("Cleaning checkpoint: {}".format(d)) os.remove(d[0]) except Exception as e: _logger.error("Exception '{}' while deleting checkpoint".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug("Cleaning recovery: {}".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error("Exception '{}' while removing {}".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension) files = sorted(files) if len(files): return files[0] else: return ''
6,397
39.751592
104
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/backbone/cswin_transformer.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.resnet import resnet26d, resnet50d from timm.models.registry import register_model from einops.layers.torch import Rearrange import numpy as np import time from mmcv_custom import load_checkpoint from mmseg.utils import get_root_logger from ..builder import BACKBONES import torch.utils.checkpoint as checkpoint class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=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 LePEAttention(nn.Module): def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): """Not supported now, since we have cls_tokens now..... """ super().__init__() self.dim = dim self.dim_out = dim_out or dim self.resolution = resolution self.split_size = split_size self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 self.idx = idx if idx == -1: H_sp, W_sp = self.resolution, self.resolution elif idx == 0: H_sp, W_sp = self.resolution, self.split_size elif idx == 1: W_sp, H_sp = self.resolution, self.split_size else: print ("ERROR MODE", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp self.H_sp_ = self.H_sp self.W_sp_ = self.W_sp stride = 1 self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) self.attn_drop = nn.Dropout(attn_drop) def im2cswin(self, x): B, C, H, W = x.shape x = img2windows(x, self.H_sp, self.W_sp) x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous() return x def get_rpe(self, x, func): B, C, H, W = x.shape H_sp, W_sp = self.H_sp, self.W_sp x = x.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) x = x.permute(0, 2, 4, 1, 3, 5).contiguous().reshape(-1, C, H_sp, W_sp) ### B', C, H', W' rpe = func(x) ### B', C, H', W' rpe = rpe.reshape(-1, self.num_heads, C // self.num_heads, H_sp * W_sp).permute(0, 1, 3, 2).contiguous() x = x.reshape(-1, self.num_heads, C // self.num_heads, self.H_sp* self.W_sp).permute(0, 1, 3, 2).contiguous() return x, rpe def forward(self, temp): """ x: B N C mask: B N N """ B, _, C, H, W = temp.shape idx = self.idx if idx == -1: H_sp, W_sp = H, W elif idx == 0: H_sp, W_sp = H, self.split_size elif idx == 1: H_sp, W_sp = self.split_size, W else: print ("ERROR MODE in forward", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp ### padding for split window H_pad = (self.H_sp - H % self.H_sp) % self.H_sp W_pad = (self.W_sp - W % self.W_sp) % self.W_sp top_pad = H_pad//2 down_pad = H_pad - top_pad left_pad = W_pad//2 right_pad = W_pad - left_pad H_ = H + H_pad W_ = W + W_pad qkv = F.pad(temp, (left_pad, right_pad, top_pad, down_pad)) ### B,3,C,H',W' qkv = qkv.permute(1, 0, 2, 3, 4) q,k,v = qkv[0], qkv[1], qkv[2] q = self.im2cswin(q) k = self.im2cswin(k) v, rpe = self.get_rpe(v, self.get_v) ### Local attention q = q * self.scale attn = (q @ k.transpose(-2, -1)) # B head N C @ B head C N --> B head N N attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype) attn = self.attn_drop(attn) x = (attn @ v) + rpe x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C) # B head N N @ B head N C ### Window2Img x = windows2img(x, self.H_sp, self.W_sp, H_, W_) # B H_ W_ C x = x[:, top_pad:H+top_pad, left_pad:W+left_pad, :] x = x.reshape(B, -1, C) return x class CSWinBlock(nn.Module): def __init__(self, dim, patches_resolution, num_heads, split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, last_stage=False): super().__init__() self.dim = dim self.num_heads = num_heads self.patches_resolution = patches_resolution self.split_size = split_size self.mlp_ratio = mlp_ratio self.qkv = nn.Linear(dim, dim * 3, bias=True) self.norm1 = norm_layer(dim) if last_stage: self.branch_num = 1 else: self.branch_num = 2 self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(drop) if last_stage: self.attns = nn.ModuleList([ LePEAttention( dim, resolution=self.patches_resolution, idx = -1, split_size=split_size, num_heads=num_heads, dim_out=dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) else: self.attns = nn.ModuleList([ LePEAttention( dim//2, resolution=self.patches_resolution, idx = i, split_size=split_size, num_heads=num_heads//2, dim_out=dim//2, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) mlp_hidden_dim = int(dim * mlp_ratio) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop) self.norm2 = norm_layer(dim) atten_mask_matrix = None self.register_buffer("atten_mask_matrix", atten_mask_matrix) self.H = None self.W = None def forward(self, x): """ x: B, H*W, C """ B, L, C = x.shape H = self.H W = self.W assert L == H * W, "flatten img_tokens has wrong size" img = self.norm1(x) temp = self.qkv(img).reshape(B, H, W, 3, C).permute(0, 3, 4, 1, 2) if self.branch_num == 2: x1 = self.attns[0](temp[:,:,:C//2,:,:]) x2 = self.attns[1](temp[:,:,C//2:,:,:]) attened_x = torch.cat([x1,x2], dim=2) else: attened_x = self.attns[0](temp) attened_x = self.proj(attened_x) x = x + self.drop_path(attened_x) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def img2windows(img, H_sp, W_sp): """ img: B C H W """ B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C) return img_perm def windows2img(img_splits_hw, H_sp, W_sp, H, W): """ img_splits_hw: B' H W C """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img class Merge_Block(nn.Module): def __init__(self, dim, dim_out, norm_layer=nn.LayerNorm): super().__init__() self.conv = nn.Conv2d(dim, dim_out, 3, 2, 1) self.norm = norm_layer(dim_out) def forward(self, x, H, W): B, new_HW, C = x.shape x = x.transpose(-2, -1).contiguous().view(B, C, H, W) x = self.conv(x) B, C, H, W = x.shape x = x.view(B, C, -1).transpose(-2, -1).contiguous() x = self.norm(x) return x, H, W @BACKBONES.register_module() class CSWin(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=64, depth=[1,2,21,1], split_size = 7, num_heads=[1,2,4,8], mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, use_chk=False): super().__init__() self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models heads=num_heads self.use_chk = use_chk self.stage1_conv_embed = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 7, 4, 2), Rearrange('b c h w -> b (h w) c', h = img_size//4, w = img_size//4), nn.LayerNorm(embed_dim) ) self.norm1 = nn.LayerNorm(embed_dim) curr_dim = embed_dim dpr = [x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth))] # stochastic depth decay rule self.stage1 = nn.ModuleList([ CSWinBlock( dim=curr_dim, num_heads=heads[0], patches_resolution=224//4, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[0], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer) for i in range(depth[0])]) self.merge1 = Merge_Block(curr_dim, curr_dim*(heads[1]//heads[0])) curr_dim = curr_dim*(heads[1]//heads[0]) self.norm2 = nn.LayerNorm(curr_dim) self.stage2 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[1], patches_resolution=224//8, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:1])+i], norm_layer=norm_layer) for i in range(depth[1])]) self.merge2 = Merge_Block(curr_dim, curr_dim*(heads[2]//heads[1])) curr_dim = curr_dim*(heads[2]//heads[1]) self.norm3 = nn.LayerNorm(curr_dim) temp_stage3 = [] temp_stage3.extend( [CSWinBlock( dim=curr_dim, num_heads=heads[2], patches_resolution=224//16, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[2], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:2])+i], norm_layer=norm_layer) for i in range(depth[2])]) self.stage3 = nn.ModuleList(temp_stage3) self.merge3 = Merge_Block(curr_dim, curr_dim*(heads[3]//heads[2])) curr_dim = curr_dim*(heads[3]//heads[2]) self.stage4 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[3], patches_resolution=224//32, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[-1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:-1])+i], norm_layer=norm_layer, last_stage=True) for i in range(depth[-1])]) self.norm4 = norm_layer(curr_dim) def init_weights(self, pretrained=None): def _init_weights(m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) if isinstance(pretrained, str): self.apply(_init_weights) logger = get_root_logger() load_checkpoint(self, pretrained, strict=False, logger=logger) elif pretrained is None: self.apply(_init_weights) else: raise TypeError('pretrained must be a str or None') def save_out(self, x, norm, H, W): x = norm(x) B, N, C = x.shape x = x.view(B, H, W, C).permute(0, 3, 1, 2).contiguous() return x def forward_features(self, x): B = x.shape[0] x = self.stage1_conv_embed[0](x) ### B, C, H, W B, C, H, W = x.size() x = x.reshape(B, C, -1).transpose(-1,-2).contiguous() x = self.stage1_conv_embed[2](x) out = [] for blk in self.stage1: blk.H = H blk.W = W if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) out.append(self.save_out(x, self.norm1, H, W)) for pre, blocks, norm in zip([self.merge1, self.merge2, self.merge3], [self.stage2, self.stage3, self.stage4], [self.norm2 , self.norm3 , self.norm4 ]): x, H, W = pre(x, H, W) for blk in blocks: blk.H = H blk.W = W if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) out.append(self.save_out(x, norm, H, W)) return tuple(out) def forward(self, x): x = self.forward_features(x) return x def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict
14,811
35.126829
145
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/segmentation/mmcv_custom/checkpoint.py
# Copyright (c) Open-MMLab. All rights reserved. import io import os import os.path as osp import pkgutil import time import warnings from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory import torch import torchvision from torch.optim import Optimizer from torch.utils import model_zoo from torch.nn import functional as F import mmcv from mmcv.fileio import FileClient from mmcv.fileio import load as load_file from mmcv.parallel import is_module_wrapper from mmcv.utils import mkdir_or_exist from mmcv.runner import get_dist_info ENV_MMCV_HOME = 'MMCV_HOME' ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' DEFAULT_CACHE_DIR = '~/.cache' def _get_mmcv_home(): mmcv_home = os.path.expanduser( os.getenv( ENV_MMCV_HOME, os.path.join( os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv'))) mkdir_or_exist(mmcv_home) return mmcv_home def load_state_dict(module, state_dict, strict=False, logger=None): """Load state_dict to a module. This method is modified from :meth:`torch.nn.Module.load_state_dict`. Default value for ``strict`` is set to ``False`` and the message for param mismatch will be shown even if strict is False. Args: module (Module): Module that receives the state_dict. state_dict (OrderedDict): Weights. strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used. """ unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata # use _load_from_state_dict to enable checkpoint version control def load(module, prefix=''): # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module local_metadata = {} if metadata is None else metadata.get( prefix[:-1], {}) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + '.') load(module) load = None # break load->load reference cycle # ignore "num_batches_tracked" of BN layers missing_keys = [ key for key in all_missing_keys if 'num_batches_tracked' not in key ] if unexpected_keys: err_msg.append('unexpected key in source ' f'state_dict: {", ".join(unexpected_keys)}\n') if missing_keys: err_msg.append( f'missing keys in source state_dict: {", ".join(missing_keys)}\n') rank, _ = get_dist_info() if len(err_msg) > 0 and rank == 0: err_msg.insert( 0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif logger is not None: logger.warning(err_msg) else: print(err_msg) def load_url_dist(url, model_dir=None): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir) if world_size > 1: torch.distributed.barrier() if rank > 0: checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint def load_pavimodel_dist(model_path, map_location=None): """In distributed setting, this function only download checkpoint at local rank 0.""" try: from pavi import modelcloud except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if rank == 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load( downloaded_file, map_location=map_location) return checkpoint def load_fileclient_dist(filename, backend, map_location): """In distributed setting, this function only download checkpoint at local rank 0.""" rank, world_size = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if backend not in allowed_backends: raise ValueError(f'Load from Backend {backend} is not supported.') if rank == 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if world_size > 1: torch.distributed.barrier() if rank > 0: fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint def get_torchvision_models(): model_urls = dict() for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls') model_urls.update(_urls) return model_urls def get_external_models(): mmcv_home = _get_mmcv_home() default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') default_urls = load_file(default_json_path) assert isinstance(default_urls, dict) external_json_path = osp.join(mmcv_home, 'open_mmlab.json') if osp.exists(external_json_path): external_urls = load_file(external_json_path) assert isinstance(external_urls, dict) default_urls.update(external_urls) return default_urls def get_mmcls_models(): mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json') mmcls_urls = load_file(mmcls_json_path) return mmcls_urls def get_deprecated_model_names(): deprecate_json_path = osp.join(mmcv.__path__[0], 'model_zoo/deprecated.json') deprecate_urls = load_file(deprecate_json_path) assert isinstance(deprecate_urls, dict) return deprecate_urls def _process_mmcls_checkpoint(checkpoint): state_dict = checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): if k.startswith('backbone.'): new_state_dict[k[9:]] = v new_checkpoint = dict(state_dict=new_state_dict) return new_checkpoint def _load_checkpoint(filename, map_location=None): """Load checkpoint from somewhere (modelzoo, file, url). Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str | None): Same as :func:`torch.load`. Default: None. Returns: dict | OrderedDict: The loaded checkpoint. It can be either an OrderedDict storing model weights or a dict containing other information, which depends on the checkpoint. """ if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please ' 'use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if model_name in deprecated_urls: warnings.warn(f'open-mmlab://{model_name} is deprecated in favor ' f'of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] # check if is url if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist( filename, backend='ceph', map_location=map_location) else: if not osp.isfile(filename): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): """Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`logging.Logger` or None): The logger for error message. Returns: dict or OrderedDict: The loaded checkpoint. """ checkpoint = _load_checkpoint(filename, map_location) # OrderedDict is a subclass of dict if not isinstance(checkpoint, dict): raise RuntimeError( f'No state_dict found in checkpoint file {filename}') # get state_dict from checkpoint if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] elif 'state_dict_ema' in checkpoint: state_dict = checkpoint['state_dict_ema'] elif 'model' in checkpoint: state_dict = checkpoint['model'] else: state_dict = checkpoint # strip prefix of state_dict if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for k, v in state_dict.items()} # for MoBY, load model of online branch if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')} # reshape absolute position embedding if state_dict.get('absolute_pos_embed') is not None: absolute_pos_embed = state_dict['absolute_pos_embed'] N1, L, C1 = absolute_pos_embed.size() N2, C2, H, W = model.absolute_pos_embed.size() if N1 != N2 or C1 != C2 or L != H*W: logger.warning("Error in loading absolute_pos_embed, pass") else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) # interpolate position bias table if needed relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] L1, nH1 = table_pretrained.size() L2, nH2 = table_current.size() if nH1 != nH2: logger.warning(f"Error in loading {table_key}, pass") else: if L1 != L2: S1 = int(L1 ** 0.5) S2 = int(L2 ** 0.5) table_pretrained_resized = F.interpolate( table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) # load state_dict load_state_dict(model, state_dict, strict, logger) return checkpoint def weights_to_cpu(state_dict): """Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU. """ state_dict_cpu = OrderedDict() for key, val in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu def _save_to_state_dict(module, destination, prefix, keep_vars): """Saves module state to `destination` dictionary. This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. Args: module (nn.Module): The module to generate state_dict. destination (dict): A dict where state will be stored. prefix (str): The prefix for parameters and buffers used in this module. """ for name, param in module._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in module._buffers.items(): # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d if buf is not None: destination[prefix + name] = buf if keep_vars else buf.detach() def get_state_dict(module, destination=None, prefix='', keep_vars=False): """Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. This method is modified from :meth:`torch.nn.Module.state_dict` to recursively check parallel module in case that the model has a complicated structure, e.g., nn.Module(nn.Module(DDP)). Args: module (nn.Module): The module to generate state_dict. destination (OrderedDict): Returned dict for the state of the module. prefix (str): Prefix of the key. keep_vars (bool): Whether to keep the variable property of the parameters. Default: False. Returns: dict: A dictionary containing a whole state of the module. """ # recursively check parallel module in case that the model has a # complicated structure, e.g., nn.Module(nn.Module(DDP)) if is_module_wrapper(module): module = module.module # below is the same as torch.nn.Module.state_dict() if destination is None: destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:-1]] = local_metadata = dict( version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for name, child in module._modules.items(): if child is not None: get_state_dict( child, destination, prefix + name + '.', keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if hook_result is not None: destination = hook_result return destination def save_checkpoint(model, filename, optimizer=None, meta=None): """Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. meta (dict, optional): Metadata to be saved in checkpoint. """ if meta is None: meta = {} elif not isinstance(meta, dict): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if hasattr(model, 'CLASSES') and model.CLASSES is not None: # save class name to the meta meta.update(CLASSES=model.CLASSES) checkpoint = { 'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model)) } # save optimizer state dict in the checkpoint if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for name, optim in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelcloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError( 'Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() model_dir, model_name = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) # immediately flush buffer with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
19,055
36.884692
110
py
pytorch-boat
pytorch-boat-main/BOAT-CSWin/models/cswin_boat.py
# ------------------------------------------ # CSWin Transformer # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # written By Xiaoyi Dong # ------------------------------------------ import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from einops.layers.torch import Rearrange import torch.utils.checkpoint as checkpoint import numpy as np import time from einops import rearrange, repeat import math def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { 'cswin_224': _cfg(), 'cswin_384': _cfg( crop_pct=1.0 ), } class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=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 LePEAttention(nn.Module): def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8, attn_drop=0., proj_drop=0., qk_scale=None): super().__init__() self.dim = dim self.dim_out = dim_out or dim self.resolution = resolution self.split_size = split_size self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 if idx == -1: H_sp, W_sp = self.resolution, self.resolution elif idx == 0: H_sp, W_sp = self.resolution, self.split_size elif idx == 1: W_sp, H_sp = self.resolution, self.split_size else: print ("ERROR MODE", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp stride = 1 self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) self.attn_drop = nn.Dropout(attn_drop) def im2cswin(self, x): B, N, C = x.shape H = W = int(np.sqrt(N)) x = x.transpose(-2,-1).contiguous().view(B, C, H, W) x = img2windows(x, self.H_sp, self.W_sp) x = x.reshape(-1, self.H_sp* self.W_sp, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3).contiguous() return x def get_lepe(self, x, func): B, N, C = x.shape H = W = int(np.sqrt(N)) x = x.transpose(-2,-1).contiguous().view(B, C, H, W) H_sp, W_sp = self.H_sp, self.W_sp x = x.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) x = x.permute(0, 2, 4, 1, 3, 5).contiguous().reshape(-1, C, H_sp, W_sp) ### B', C, H', W' lepe = func(x) ### B', C, H', W' lepe = lepe.reshape(-1, self.num_heads, C // self.num_heads, H_sp * W_sp).permute(0, 1, 3, 2).contiguous() x = x.reshape(-1, self.num_heads, C // self.num_heads, self.H_sp* self.W_sp).permute(0, 1, 3, 2).contiguous() return x, lepe def forward(self, qkv): """ x: B L C """ q,k,v = qkv[0], qkv[1], qkv[2] ### Img2Window H = W = self.resolution B, L, C = q.shape assert L == H * W, "flatten img_tokens has wrong size" q = self.im2cswin(q) k = self.im2cswin(k) v, lepe = self.get_lepe(v, self.get_v) q = q * self.scale attn = (q @ k.transpose(-2, -1)) # B head N C @ B head C N --> B head N N attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype) attn = self.attn_drop(attn) x = (attn @ v) + lepe x = x.transpose(1, 2).reshape(-1, self.H_sp* self.W_sp, C) # B head N N @ B head N C ### Window2Img x = windows2img(x, self.H_sp, self.W_sp, H, W).view(B, -1, C) # B H' W' C return x class ContentAttention(nn.Module): def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.ws = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.softmax = nn.Softmax(dim=-1) self.get_v = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1,groups=dim) def forward(self, x, mask=None): #B_, W, H, C = x.shape #x = x.view(B_,W*H,C) B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)# 3, B_, self.num_heads,N,D if True: q_pre = qkv[0].reshape(B_*self.num_heads,N, C // self.num_heads).permute(0,2,1)#qkv_pre[:,0].reshape(b*self.num_heads,qkvhd//3//self.num_heads,hh*ww) ntimes = int(math.log(N//49,2)) q_idx_last = torch.arange(N).cuda().unsqueeze(0).expand(B_*self.num_heads,N) for i in range(ntimes): bh,d,n = q_pre.shape q_pre_new = q_pre.reshape(bh,d,2,n//2) q_avg = q_pre_new.mean(dim=-1)#.reshape(b*self.num_heads,qkvhd//3//self.num_heads,) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) iters = 2 for i in range(iters): q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg) soft_assign = torch.nn.functional.softmax(q_scores*100, dim=-1).detach() q_avg = q_pre.bmm(soft_assign) q_avg = torch.nn.functional.normalize(q_avg,dim=-2) q_scores = torch.nn.functional.normalize(q_pre.permute(0,2,1),dim=-1).bmm(q_avg).reshape(bh,n,2)#.unsqueeze(2) q_idx = (q_scores[:,:,0]+1)/(q_scores[:,:,1]+1) _,q_idx = torch.sort(q_idx,dim=-1) q_idx_last = q_idx_last.gather(dim=-1,index=q_idx).reshape(bh*2,n//2) q_idx = q_idx.unsqueeze(1).expand(q_pre.size()) q_pre = q_pre.gather(dim=-1,index=q_idx).reshape(bh,d,2,n//2).permute(0,2,1,3).reshape(bh*2,d,n//2) q_idx = q_idx_last.view(B_,self.num_heads,N) _,q_idx_rev = torch.sort(q_idx,dim=-1) q_idx = q_idx.unsqueeze(0).unsqueeze(4).expand(qkv.size()) qkv_pre = qkv.gather(dim=-2,index=q_idx) q, k, v = rearrange(qkv_pre, 'qkv b h (nw ws) c -> qkv (b nw) h ws c', ws=49) k = k.view(B_*((N//49))//2,2,self.num_heads,49,-1) k_over1 = k[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over2 = k[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) k_over = torch.cat([k_over1,k_over2],1) k = torch.cat([k,k_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) v = v.view(B_*((N//49))//2,2,self.num_heads,49,-1) v_over1 = v[:,1,:,:20].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over2 = v[:,0,:,29:].unsqueeze(1)#.expand(-1,2,-1,-1,-1) v_over = torch.cat([v_over1,v_over2],1) v = torch.cat([v,v_over],3).contiguous().view(B_*((N//49)),self.num_heads,49+20,-1) #v = rearrange(v[:,:,:49,:], '(b nw) h ws d -> b h d (nw ws)', h=self.num_heads, b=B_) #W = int(math.sqrt(N)) attn = (q @ k.transpose(-2, -1))*self.scale attn = self.softmax(attn) attn = self.attn_drop(attn) out = attn @ v out = rearrange(out, '(b nw) h ws d -> b (h d) nw ws', h=self.num_heads, b=B_) out = out.reshape(B_,self.num_heads,C//self.num_heads,-1) q_idx_rev = q_idx_rev.unsqueeze(2).expand(out.size()) x = out.gather(dim=-1,index=q_idx_rev).reshape(B_,C,N).permute(0,2,1) v = rearrange(v[:,:,:49,:], '(b nw) h ws d -> b h d (nw ws)', h=self.num_heads, b=B_) W = int(math.sqrt(N)) v = v.gather(dim=-1,index=q_idx_rev).reshape(B_,C,W,W) v = self.get_v(v) v = v.reshape(B_,C,N).permute(0,2,1) x = x + v x = self.proj(x) x = self.proj_drop(x) return x class CSWinBlock(nn.Module): def __init__(self, dim, reso, num_heads, split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, last_stage=False, content=False): super().__init__() self.dim = dim self.num_heads = num_heads self.patches_resolution = reso self.split_size = split_size self.mlp_ratio = mlp_ratio self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.norm1 = norm_layer(dim) if self.patches_resolution == split_size: last_stage = True if last_stage: self.branch_num = 1 else: self.branch_num = 2 self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(drop) self.content = content if last_stage: self.attns = nn.ModuleList([ LePEAttention( dim, resolution=self.patches_resolution, idx = -1, split_size=split_size, num_heads=num_heads, dim_out=dim, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) else: self.attns = nn.ModuleList([ LePEAttention( dim//2, resolution=self.patches_resolution, idx = i, split_size=split_size, num_heads=num_heads//2, dim_out=dim//2, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) for i in range(self.branch_num)]) if self.content: self.content_attn = ContentAttention(dim=dim, window_size=split_size, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qkv_bias, attn_drop=attn_drop, proj_drop=attn_drop) self.norm3 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop) self.norm2 = norm_layer(dim) def forward(self, x): """ x: B, H*W, C """ H = W = self.patches_resolution B, L, C = x.shape assert L == H * W, "flatten img_tokens has wrong size" img = self.norm1(x) qkv = self.qkv(img).reshape(B, -1, 3, C).permute(2, 0, 1, 3) if self.branch_num == 2: x1 = self.attns[0](qkv[:,:,:,:C//2]) x2 = self.attns[1](qkv[:,:,:,C//2:]) attened_x = torch.cat([x1,x2], dim=2) else: attened_x = self.attns[0](qkv) attened_x = self.proj(attened_x) x = x + self.drop_path(attened_x) if self.content: x = x + self.drop_path(self.content_attn(self.norm3(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def img2windows(img, H_sp, W_sp): """ img: B C H W """ B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp* W_sp, C) return img_perm def windows2img(img_splits_hw, H_sp, W_sp, H, W): """ img_splits_hw: B' H W C """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img class Merge_Block(nn.Module): def __init__(self, dim, dim_out, norm_layer=nn.LayerNorm): super().__init__() self.conv = nn.Conv2d(dim, dim_out, 3, 2, 1) self.norm = norm_layer(dim_out) def forward(self, x): B, new_HW, C = x.shape H = W = int(np.sqrt(new_HW)) x = x.transpose(-2, -1).contiguous().view(B, C, H, W) x = self.conv(x) B, C = x.shape[:2] x = x.view(B, C, -1).transpose(-2, -1).contiguous() x = self.norm(x) return x class CSWinTransformer(nn.Module): """ Vision Transformer with support for patch or hybrid CNN input stage """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=96, depth=[2,2,6,2], split_size = [3,5,7], num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, use_chk=False): super().__init__() self.use_chk = use_chk self.num_classes = num_classes self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models heads=num_heads self.stage1_conv_embed = nn.Sequential( nn.Conv2d(in_chans, embed_dim, 7, 4, 2), Rearrange('b c h w -> b (h w) c', h = img_size//4, w = img_size//4), nn.LayerNorm(embed_dim) ) curr_dim = embed_dim dpr = [x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth))] # stochastic depth decay rule self.stage1 = nn.ModuleList([ CSWinBlock( dim=curr_dim, num_heads=heads[0], reso=img_size//4, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[0], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, content=(i%2==0)) for i in range(depth[0])]) self.merge1 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 self.stage2 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[1], reso=img_size//8, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:1])+i], norm_layer=norm_layer,content=(i%2==0)) for i in range(depth[1])]) self.merge2 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 temp_stage3 = [] temp_stage3.extend( [CSWinBlock( dim=curr_dim, num_heads=heads[2], reso=img_size//16, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[2], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:2])+i], norm_layer=norm_layer,content=(i%2==0)) for i in range(depth[2])]) self.stage3 = nn.ModuleList(temp_stage3) self.merge3 = Merge_Block(curr_dim, curr_dim*2) curr_dim = curr_dim*2 self.stage4 = nn.ModuleList( [CSWinBlock( dim=curr_dim, num_heads=heads[3], reso=img_size//32, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[-1], drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[np.sum(depth[:-1])+i], norm_layer=norm_layer, last_stage=True,content=(i%2==0)) for i in range(depth[-1])]) self.norm = norm_layer(curr_dim) # Classifier head self.head = nn.Linear(curr_dim, num_classes) if num_classes > 0 else nn.Identity() trunc_normal_(self.head.weight, std=0.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def get_classifier(self): return self.head def reset_classifier(self, num_classes, global_pool=''): if self.num_classes != num_classes: print ('reset head to', num_classes) self.num_classes = num_classes self.head = nn.Linear(self.out_dim, num_classes) if num_classes > 0 else nn.Identity() self.head = self.head.cuda() trunc_normal_(self.head.weight, std=.02) if self.head.bias is not None: nn.init.constant_(self.head.bias, 0) def forward_features(self, x): B = x.shape[0] x = self.stage1_conv_embed(x) for blk in self.stage1: if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) for pre, blocks in zip([self.merge1, self.merge2, self.merge3], [self.stage2, self.stage3, self.stage4]): x = pre(x) for blk in blocks: if self.use_chk: x = checkpoint.checkpoint(blk, x) else: x = blk(x) x = self.norm(x) return torch.mean(x, dim=1) def forward(self, x): x = self.forward_features(x) x = self.head(x) return x def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v return out_dict ### 224 models @register_model def CSWin_64_12211_tiny_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=64, depth=[1,2,21,1], split_size=[1,2,7,7], num_heads=[2,4,8,16], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_64_24322_small_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=64, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[2,4,8,16], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_96_24322_base_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=96, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[4,8,16,32], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model @register_model def CSWin_144_24322_large_224(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=144, depth=[2,4,32,2], split_size=[1,2,7,7], num_heads=[6,12,24,24], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_224'] return model ### 384 models @register_model def CSWin_96_24322_base_384(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=96, depth=[2,4,32,2], split_size=[1,2,12,12], num_heads=[4,8,16,32], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_384'] return model @register_model def CSWin_144_24322_large_384(pretrained=False, **kwargs): model = CSWinTransformer(patch_size=4, embed_dim=144, depth=[2,4,32,2], split_size=[1,2,12,12], num_heads=[6,12,24,24], mlp_ratio=4., **kwargs) model.default_cfg = default_cfgs['cswin_384'] return model
20,463
38.353846
183
py
pytorch-boat
pytorch-boat-main/BOAT-Swin/main.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import time import random import argparse import datetime import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy, AverageMeter from config import get_config from models import build_model from data import build_loader from lr_scheduler import build_scheduler from optimizer import build_optimizer from logger import create_logger from utils import load_checkpoint, load_pretrained, save_checkpoint, get_grad_norm, auto_resume_helper, reduce_tensor try: # noinspection PyUnresolvedReferences from apex import amp except ImportError: amp = None def parse_option(): parser = argparse.ArgumentParser('Swin Transformer training and evaluation script', add_help=False) parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) parser.add_argument( "--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs='+', ) # easy config modification parser.add_argument('--batch-size', type=int, help="batch size for single GPU") parser.add_argument('--data-path', type=str, help='path to dataset') parser.add_argument('--zip', action='store_true', help='use zipped dataset instead of folder dataset') parser.add_argument('--cache-mode', type=str, default='part', choices=['no', 'full', 'part'], help='no: no cache, ' 'full: cache all data, ' 'part: sharding the dataset into nonoverlapping pieces and only cache one piece') parser.add_argument('--pretrained', help='pretrained weight from checkpoint, could be imagenet22k pretrained weight') parser.add_argument('--resume', help='resume from checkpoint') parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps") parser.add_argument('--use-checkpoint', action='store_true', help="whether to use gradient checkpointing to save memory") parser.add_argument('--amp-opt-level', type=str, default='O1', choices=['O0', 'O1', 'O2'], help='mixed precision opt level, if O0, no amp is used') parser.add_argument('--output', default='output', type=str, metavar='PATH', help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)') parser.add_argument('--tag', help='tag of experiment') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--throughput', action='store_true', help='Test throughput only') # distributed training parser.add_argument("--local_rank", type=int, required=True, help='local rank for DistributedDataParallel') args, unparsed = parser.parse_known_args() config = get_config(args) return args, config def main(config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader(config) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() logger.info(str(model)) optimizer = build_optimizer(config, model) if config.AMP_OPT_LEVEL != "O0": model, optimizer = amp.initialize(model, optimizer, opt_level=config.AMP_OPT_LEVEL) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, 'flops'): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len(data_loader_train)) if config.AUG.MIXUP > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME: resume_file = auto_resume_helper(config.OUTPUT) if resume_file: if config.MODEL.RESUME: logger.warning(f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}") config.defrost() config.MODEL.RESUME = resume_file config.freeze() logger.info(f'auto resuming from {resume_file}') else: logger.info(f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') if config.MODEL.RESUME: max_accuracy = load_checkpoint(config, model_without_ddp, optimizer, lr_scheduler, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.EVAL_MODE: return if config.MODEL.PRETRAINED and (not config.MODEL.RESUME): load_pretrained(config, model_without_ddp, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.THROUGHPUT_MODE: throughput(data_loader_val, model, logger) return logger.info("Start training") start_time = time.time() for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): data_loader_train.sampler.set_epoch(epoch) train_one_epoch(config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler) if dist.get_rank() == 0 and (epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1)): save_checkpoint(config, epoch, model_without_ddp, max_accuracy, optimizer, lr_scheduler, logger) acc1, acc5, loss = validate(config, data_loader_val, model) logger.info(f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") max_accuracy = max(max_accuracy, acc1) logger.info(f'Max accuracy: {max_accuracy:.2f}%') total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) logger.info('Training time {}'.format(total_time_str)) def train_one_epoch(config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler): model.train() optimizer.zero_grad() num_steps = len(data_loader) batch_time = AverageMeter() loss_meter = AverageMeter() norm_meter = AverageMeter() start = time.time() end = time.time() for idx, (samples, targets) in enumerate(data_loader): samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets) outputs = model(samples) if config.TRAIN.ACCUMULATION_STEPS > 1: loss = criterion(outputs, targets) loss = loss / config.TRAIN.ACCUMULATION_STEPS if config.AMP_OPT_LEVEL != "O0": with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(amp.master_params(optimizer)) else: loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(model.parameters()) if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0: optimizer.step() optimizer.zero_grad() lr_scheduler.step_update(epoch * num_steps + idx) else: loss = criterion(outputs, targets) optimizer.zero_grad() if config.AMP_OPT_LEVEL != "O0": with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(amp.master_params(optimizer)) else: loss.backward() if config.TRAIN.CLIP_GRAD: grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config.TRAIN.CLIP_GRAD) else: grad_norm = get_grad_norm(model.parameters()) optimizer.step() lr_scheduler.step_update(epoch * num_steps + idx) torch.cuda.synchronize() loss_meter.update(loss.item(), targets.size(0)) norm_meter.update(grad_norm) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: lr = optimizer.param_groups[0]['lr'] memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) logger.info( f'Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' f'mem {memory_used:.0f}MB') epoch_time = time.time() - start logger.info(f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}") @torch.no_grad() def validate(config, data_loader, model): criterion = torch.nn.CrossEntropyLoss() model.eval() batch_time = AverageMeter() loss_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() end = time.time() for idx, (images, target) in enumerate(data_loader): images = images.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # compute output output = model(images) # measure accuracy and record loss loss = criterion(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) acc1 = reduce_tensor(acc1) acc5 = reduce_tensor(acc5) loss = reduce_tensor(loss) loss_meter.update(loss.item(), target.size(0)) acc1_meter.update(acc1.item(), target.size(0)) acc5_meter.update(acc5.item(), target.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) logger.info( f'Test: [{idx}/{len(data_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' f'Mem {memory_used:.0f}MB') logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') return acc1_meter.avg, acc5_meter.avg, loss_meter.avg @torch.no_grad() def throughput(data_loader, model, logger): model.eval() for idx, (images, _) in enumerate(data_loader): images = images.cuda(non_blocking=True) batch_size = images.shape[0] for i in range(50): model(images) torch.cuda.synchronize() logger.info(f"throughput averaged with 30 times") tic1 = time.time() for i in range(30): model(images) torch.cuda.synchronize() tic2 = time.time() logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}") return if __name__ == '__main__': _, config = parse_option() if config.AMP_OPT_LEVEL != "O0": assert amp is not None, "amp not installed!" if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ['WORLD_SIZE']) print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 torch.cuda.set_device(config.LOCAL_RANK) torch.distributed.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=rank) torch.distributed.barrier() seed = config.SEED + dist.get_rank() torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True # linear scale the learning rate according to total batch size, may not be optimal linear_scaled_lr = config.TRAIN.BASE_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_min_lr = config.TRAIN.MIN_LR * config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 # gradient accumulation also need to scale the learning rate if config.TRAIN.ACCUMULATION_STEPS > 1: linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_warmup_lr = linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS config.defrost() config.TRAIN.BASE_LR = linear_scaled_lr config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr config.TRAIN.MIN_LR = linear_scaled_min_lr config.freeze() os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") if dist.get_rank() == 0: path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") # print config logger.info(config.dump()) main(config)
14,809
40.368715
117
py