HYDRA_FULL_ERROR=1 python train_multilabel.py +config=configs/multilabel_circle_net.yaml
DEBUG:hydra.core.utils:Setting JobRuntime:name=UNKNOWN_NAME
DEBUG:hydra.core.utils:Setting JobRuntime:name=train_multilabel
Dataset valid_sar_cv
ignore_low_confidence_detections False
ignore_low_confidence_labels False
filter_low_confidence_objects False
Train dataset
Unknown vessels 90
Unknown fishing 11242
Valid dataset
Unknown vessels 20
Unknown fishing 2778
Preparing training dataset: 100%|█| 35/35 [00:00<00:00, 691.59it/
[DEBUG] self.box_coder in dataset.init: MultilabelCircleNetCoder(image_size=(512, 512), stride=4, max_objects=512, labels_encoding=circle, heatmap_encoding=umich, fixed_radius=None, ignore_index=-1, ignore_low_confidence_detections=False)
Preparing validation dataset: 100%|█| 7/7 [00:00<00:00, 539.78it/
Train instances 13933 dataset 35 sampler 8192
Valid instances 3655 dataset 1039
Losses
losses/ MultilabelCenterTrimmedLoss weight 1.0
target ['CENTERNET_TARGET_OBJECTNESS_MAP', 'CENTERNET_TARGET_VESSEL_MAP', 'CENTERNET_TARGET_FISHING_MAP', 'CENTERNET_TARGET_SIZE', 'CENTERNET_TARGET_OFFSET']
output ['CENTERNET_OUTPUT_OBJECTNESS_MAP', 'CENTERNET_OUTPUT_VESSEL_MAP', 'CENTERNET_OUTPUT_FISHING_MAP', 'CENTERNET_OUTPUT_SIZE', 'CENTERNET_OUTPUT_OFFSET']
[DEBUG] After adjustment, encoder.conv_stem.in_channels: 2
Error executing job with overrides: ['+config=configs/multilabel_circle_net.yaml']
Traceback (most recent call last):
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 92, in _call_target
return target(*args, **kwargs)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/models/centernet_unet.py", line 318, in from_config
base_model=cls(
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/models/centernet_unet.py", line 104, in init
self.yolo_output_channels = self.yolo_head.num_anchors * (5 + self.num_classes) # Adjust as per YOLO implementation
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1729, in getattr
raise AttributeError(f"'{type(self).name}' object has no attribute '{name}'")
AttributeError: 'CenterNetUNetModel' object has no attribute 'num_classes'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 829, in
main()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/main.py", line 94, in decorated_main
_run_hydra(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 394, in _run_hydra
_run_app(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 457, in _run_app
run_and_report(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 223, in run_and_report
raise ex
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 220, in run_and_report
return func()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 458, in
lambda: hydra.run(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/hydra.py", line 132, in run
_ = ret.return_value
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/core/utils.py", line 260, in return_value
raise self._return_value
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/core/utils.py", line 186, in run_job
ret.return_value = task_function(task_cfg)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 826, in main
CenternetPipeline(cfg).train()
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 708, in train
model = self.build_model(config, self.loaders)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 212, in build_model
model = super().build_model(config)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/pipeline.py", line 395, in build_model
model = self.get_model(config["model"])
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 421, in get_model
model: nn.Module = get_detection_model(model_config)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/factory.py", line 27, in get_detection_model
return instantiate(model_config, recursive=False)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 226, in instantiate
return instantiate_node(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 347, in instantiate_node
return _call_target(target, partial, args, kwargs, full_key)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 97, in _call_target
raise InstantiationException(msg) from e
hydra.errors.InstantiationException: Error in call to target 'xview3.centernet.models.centernet_unet.CenterNetUNetModel.from_config':
AttributeError("'CenterNetUNetModel' object has no attribute 'num_classes'")
full_key: model
(sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers %
#I think you ruined my model as ruined num_classes and CENTERNET_OUTPUT_YOLO,
CENTERNET_TARGET_YOLO
here's my files
#centernet_unet.py
centernet_unet.py
from functools import partial
from typing import List, Dict, Any
from omegaconf import DictConfig
from pytorch_toolbelt.modules import (
ACT_RELU,
decoders as D,
EncoderModule,
ResidualDeconvolutionUpsample2d,
)
from torch import nn, Tensor
import torch
import timm
from hydra.utils import instantiate
import random
import torch.nn.functional as F
from xview3.centernet.models.custom_encoder import CustomTimmEncoder, DebugUNetDecoder
from .unet_blocks import IRBlock, get_unet_block, SqueezeExcitation
from .necks import FPNNeck
from xview3.nas import ProgressiveNAS
from .heads.yolo_head import YOLOHead
from .transformer_classifier import ConvolutionalClassifier
from xview3.common import FilterResponseNormalization, ResidualBlock, FeaturePyramidNetwork
from ..constants import (
CENTERNET_OUTPUT_CLASS_MAP,
CENTERNET_OUTPUT_OBJECTNESS_MAP,
CENTERNET_OUTPUT_OFFSET,
CENTERNET_OUTPUT_SIZE,
CENTERNET_OUTPUT_VESSEL_MAP,
CENTERNET_OUTPUT_FISHING_MAP,
CENTERNET_OUTPUT_YOLO,
)
from xview3.centernet.models.heads.decoupled_head import DecoupledHeadGroupNormLateShuffle
from xview3.centernet.models.heads.yolo_head import YOLOHead
from ..losses.circlenet_loss import CircleNetLoss, YOLOLoss
all = ["CenterNetUNetModel"]
from xview3.utils import TorchDevice
device = TorchDevice.choose_torch_device()
class CenterNetUNetModel(nn.Module):
def init(
self,
encoder: EncoderModule,
decoder_features: List[int],
heads: List[nn.Module], # Add heads argument
box_coder,
neck_out_channels: int = 256,
input_upsample_factor: int = 1,
activation=ACT_RELU,
num_extra_blocks=0,
block_type="UnetBlock",
upsample_type="bilinear",
extra_block=partial(IRBlock, stride=2),
num_classes=2,
anchors=[(10, 13), (16, 30), (33, 23)],
nas=None, # Add nas as a parameter
):
super().init()
# Initial Setup
self.output_stride = getattr(encoder, 'strides', [32])[0]
self.initial_upsample = (
nn.UpsamplingBilinear2d(scale_factor=input_upsample_factor)
if input_upsample_factor != 1 else nn.Identity()
)
unet_block = get_unet_block(block_type, activation=activation)
self.encoder = encoder
self.extra_encoder_blocks = nn.ModuleList(
[extra_block(encoder.channels[-1], encoder.channels[-1]) for _ in range(num_extra_blocks)]
)
# Upsample Block Selection
if upsample_type in ['nearest', 'bilinear']:
upsample_block_cls = partial(
nn.Upsample,
scale_factor=2,
mode=upsample_type,
align_corners=False
)
elif upsample_type == 'rdtsc':
upsample_block_cls = partial(ResidualDeconvolutionUpsample2d, scale_factor=2)
elif upsample_type == 'shuffle':
upsample_block_cls = partial(nn.PixelShuffle, upscale_factor=2)
else:
raise ValueError(f"Unknown upsample_type {upsample_type}")
# Encoder Channels
if hasattr(encoder, 'channels'):
encoder_channels = list(encoder.channels)
else:
encoder_channels = [32, 24, 40, 112, 320] # Default channels if not provided
encoder_channels += [encoder_channels[-1]] * num_extra_blocks
# Head, NAS, YOLO Head, Classifier Initialization
self.heads = nn.ModuleList(heads) # Initialize heads
self.head_output_channels = getattr(self.heads[0], 'out_channels', 256)
self.output_channels = self.head_output_channels # **Added**
self.nas = nas # Initialize nas
self.yolo_head = YOLOHead(num_classes=num_classes, anchors=anchors)
self.yolo_output_channels = self.yolo_head.num_anchors * (5 + self.num_classes) # Adjust as per YOLO implementation
self.classifier = ConvolutionalClassifier(in_channels=neck_out_channels, num_classes=num_classes)
self.classifier_output_channels = getattr(self.classifier, 'out_channels', num_classes)
self.box_coder = box_coder
# Set neck_output_channels directly without multiplication
self.neck_output_channels = neck_out_channels
# Decoder Channels Assignment
self.decoder_channels = decoder_features
num_encoder_blocks = len(encoder_channels) - 1
if len(self.decoder_channels) < num_encoder_blocks:
self.decoder_channels.extend(
[self.decoder_channels[-1]] * (num_encoder_blocks - len(self.decoder_channels))
)
elif len(self.decoder_channels) > num_encoder_blocks:
self.decoder_channels = self.decoder_channels[:num_encoder_blocks]
self.num_decoded_features = len(encoder_channels)
# Initialize Decoder
self.decoder = DebugUNetDecoder(
encoder_channels=encoder_channels,
decoder_channels=self.decoder_channels,
unet_block=unet_block,
upsample_block=upsample_block_cls,
center=False,
)
# Initialize Neck with correct decoder_channels
self.neck = FPNNeck(channels=self.decoder_channels, out_channels=neck_out_channels)
# self.neck_output_channels is already set to neck_out_channels
# Initialize neck_conv with the correct in_channels
self.neck_conv = nn.Conv2d(
in_channels=self.neck_output_channels, # 256
out_channels=neck_out_channels, # 256
kernel_size=1
)
self.batch_norm = FilterResponseNormalization(self.neck_output_channels)
# Calculate total_input_channels based on the corrected neck_output_channels
self.total_input_channels = (
int(self.head_output_channels) +
int(self.yolo_output_channels) +
int(self.classifier_output_channels)
)
print(f"head_output_channels: {self.head_output_channels}")
print(f"yolo_output_channels: {self.yolo_output_channels}")
print(f"classifier_output_channels: {self.classifier_output_channels}")
print(f"total_input_channels: {self.total_input_channels}")
# Adjust channels if necessary
self.yolo_adjust = nn.Conv2d(self.yolo_output_channels, self.head_output_channels, kernel_size=1)
self.classifier_adjust = nn.Conv2d(self.classifier_output_channels, self.head_output_channels, kernel_size=1)
#self.fusion = nn.Conv2d(self.head_output_channels * 3, self.head_output_channels, kernel_size=1)
# Assuming total_input_channels should be 13 (based on your concatenation)
self.fusion = nn.Conv2d(13, self.head_output_channels, kernel_size=1)
self.dropout = nn.Dropout(p=0.5)
# Initialize Loss Functions
self.circle_net_loss = CircleNetLoss()
self.yolo_loss = YOLOLoss(num_classes=num_classes, anchors=anchors)
self.criterion = YOLOLoss(num_classes, anchors)
def forward(self, x):
x = self.initial_upsample(x)
feature_maps = self.encoder(x)
decoded_features = self.decoder(feature_maps)
neck_features = self.neck(decoded_features)
neck_features = self.batch_norm(neck_features)
neck_features = self.dropout(neck_features)
neck_features = self.neck_conv(neck_features)
head_output = self.heads[0](neck_features)
yolo_output = self.yolo_head(neck_features)
classification_output = self.classifier(neck_features)
# Print shapes for debugging
print(f"yolo_output shape: {yolo_output.shape}")
# Extract tensors from the head_output dictionary
objectness_map = head_output[CENTERNET_OUTPUT_OBJECTNESS_MAP]
vessel_map = head_output[CENTERNET_OUTPUT_VESSEL_MAP]
fishing_map = head_output[CENTERNET_OUTPUT_FISHING_MAP]
size_map = head_output[CENTERNET_OUTPUT_SIZE]
offset_map = head_output[CENTERNET_OUTPUT_OFFSET]
# Adjust indexing for yolo_output
if len(yolo_output.shape) == 4:
yolo_output = yolo_output.squeeze(1) # Remove the extra dimension if it's of size 1
# Print shapes for debugging
print(f"objectness_map shape: {objectness_map.shape}")
print(f"vessel_map shape: {vessel_map.shape}")
print(f"fishing_map shape: {fishing_map.shape}")
print(f"size_map shape: {size_map.shape}")
print(f"offset_map shape: {offset_map.shape}")
print(f"yolo_output shape: {yolo_output.shape}")
print(f"classification_output shape: {classification_output.shape}")
# Determine the target spatial size from the primary outputs
target_size = objectness_map.size()[-2:] # (H, W)
# **Upsample YOLO Output**
if yolo_output.size()[-2:] != target_size:
yolo_output = F.interpolate(yolo_output, size=target_size, mode='bilinear', align_corners=False)
print(f"yolo_output upsampled to: {yolo_output.shape}")
# **Upsample Classification Output**
if classification_output.size()[-2:] != target_size:
classification_output = F.interpolate(classification_output, size=target_size, mode='bilinear', align_corners=False)
print(f"classification_output upsampled to: {classification_output.shape}")
# Adjust channels if necessary
yolo_output = self.yolo_adjust(yolo_output)
classification_output = self.classifier_adjust(classification_output)
# **Concatenate all outputs along the channel dimension**
fused_output = self.fusion(torch.cat([
objectness_map,
yolo_output,
classification_output
], dim=1))
return {
CENTERNET_OUTPUT_OBJECTNESS_MAP: objectness_map,
CENTERNET_OUTPUT_SIZE: size_map,
CENTERNET_OUTPUT_OFFSET: offset_map,
CENTERNET_OUTPUT_VESSEL_MAP: vessel_map,
CENTERNET_OUTPUT_FISHING_MAP: fishing_map,
CENTERNET_OUTPUT_YOLO: yolo_output, # Include YOLO output
}
def calculate_loss(self, outputs, targets):
circle_net_loss = self.circle_net_loss(**outputs, **targets)
# Calculate YOLO loss
yolo_loss = self.yolo_loss(outputs[CENTERNET_OUTPUT_YOLO], targets[CENTERNET_OUTPUT_YOLO])
# Combine losses
total_loss = circle_net_loss['objectness'] + circle_net_loss['vessel'] + circle_net_loss['fishing'] + circle_net_loss['size'] + yolo_loss
return total_loss
@classmethod
def from_config(cls, **config):
# Extract and remove 'encoder' from config
encoder_config = config.pop('encoder')
num_channels = config.pop('num_channels', 3)
# Extract 'model_name' from encoder_config
model_name = encoder_config.pop('model_name', 'tf_efficientnet_b5_ns')
pretrained = encoder_config.pop('pretrained', False)
# Initialize the encoder module
encoder_module = CustomTimmEncoder(
model_name=model_name,
num_channels=num_channels,
features_only=True,
pretrained=pretrained
)
# Adjust encoder input channels
encoder_module = adjust_encoder_input_channels(encoder_module, num_channels)
# Extract other parameters with pop to remove them from config
input_upsample_factor = config.pop("input_upsample_factor", 1)
activation = config.pop('activation', ACT_RELU)
num_extra_blocks = config.pop('num_extra_blocks', 0)
num_classes = config.pop("num_classes", 2)
anchors = config.pop("anchors", [(10, 13), (16, 30), (33, 23)])
# Extract decoder configuration
decoder_config = config.pop('decoder')
decoder_features = decoder_config.pop('channels')
block_type = decoder_config.pop("block_type", "UnetBlock")
upsample_type = decoder_config.pop("upsample_type", "bilinear")
# Extract neck_out_channels
neck_out_channels = config.pop('neck_out_channels', 256)
# Extract heads configuration and initialize
heads_config = config.pop('heads')
heads = []
for head_config in heads_config:
if head_config._target_ == 'xview3.centernet.models.heads.yolo_head.YOLOHead':
head = instantiate(head_config, num_classes=num_classes, anchors=anchors)
else:
head = instantiate(head_config, channels=neck_out_channels)
heads.append(head)
# Extract box_coder configuration and initialize
box_coder_config = config.pop('box_coder')
box_coder = instantiate(
box_coder_config,
output_stride=encoder_module.strides[0] // (heads[0].upsample_factor * input_upsample_factor),
)
# **Define the evaluation function**
def evaluate_architecture(model, train_loader, val_loader):
return model.evaluate_architecture(model, train_loader, val_loader)
# **Initialize ProgressiveNAS with the evaluation function**
nas_config = config.pop('nas', {}) # Extract nas configuration
nas = ProgressiveNAS(
base_model=cls(
encoder=encoder_module,
decoder_features=decoder_features,
heads=heads,
box_coder=box_coder,
neck_out_channels=neck_out_channels,
input_upsample_factor=input_upsample_factor,
activation=activation,
block_type=block_type,
upsample_type=upsample_type,
num_extra_blocks=num_extra_blocks,
num_classes=num_classes,
anchors=anchors,
**config # Remaining config without 'neck_out_channels'
),
search_space=nas_config.get('search_space', {}), # Access search_space from nas_config
evaluation_function=evaluate_architecture # Pass the evaluation function
)
return cls(
encoder=encoder_module,
decoder_features=decoder_features,
heads=heads,
box_coder=box_coder,
nas=nas, # Pass nas to the class
neck_out_channels=neck_out_channels,
input_upsample_factor=input_upsample_factor,
activation=activation,
block_type=block_type,
upsample_type=upsample_type,
num_extra_blocks=num_extra_blocks,
num_classes=num_classes,
anchors=anchors,
**config # Remaining config without 'neck_out_channels'
)
def adjust_encoder_input_channels(encoder_module, in_chans):
# [Existing code...]
if hasattr(encoder_module, 'encoder'):
base_encoder = encoder_module.encoder
else:
base_encoder = encoder_module
if hasattr(base_encoder, 'conv_stem'):
old_conv = base_encoder.conv_stem
new_conv = nn.Conv2d(
in_channels=in_chans,
out_channels=old_conv.out_channels,
kernel_size=old_conv.kernel_size,
stride=old_conv.stride,
padding=old_conv.padding,
bias=old_conv.bias is not None
)
with torch.no_grad():
num_existing_in_channels = min(old_conv.in_channels, in_chans)
new_conv.weight[:, :num_existing_in_channels, ...] = old_conv.weight[:, :num_existing_in_channels, ...]
if in_chans > old_conv.in_channels:
torch.nn.init.kaiming_normal_(new_conv.weight[:, old_conv.in_channels:, ...])
base_encoder.conv_stem = new_conv
print(f"[DEBUG] After adjustment, encoder.conv_stem.in_channels: {base_encoder.conv_stem.in_channels}")
else:
raise NotImplementedError("Adjusting input channels for this encoder is not implemented.")
return encoder_module
class EnhancedCenterNetUNet(nn.Module):
def init(self, in_channels, num_classes):
super().init()
self.backbone = CenterNetUNetModel(in_channels, num_classes)
self.fpn = FeaturePyramidNetwork([64, 128, 256, 512], 256)
self.se_blocks = nn.ModuleList([SqueezeExcitation(c) for c in [64, 128, 256, 512]])
def forward(self, x):
features = self.backbone(x)
for i, feature in enumerate(features):
features[i] = self.se_blocks[i](feature)
return self.fpn(features)
#yolo_head.py
from torch import nn, Tensor
import torch
#from pytorch_toolbelt.modules import FPNFuse
from typing import List, Tuple, Union
from ..necks import FPNFuse
class AnchorFreeHead(nn.Module):
def init(self, in_channels, num_classes):
super().init()
self.cls_conv = nn.Conv2d(in_channels, num_classes, 1)
self.reg_conv = nn.Conv2d(in_channels, 4, 1)
self.obj_conv = nn.Conv2d(in_channels, 1, 1)
def forward(self, x):
cls_pred = self.cls_conv(x)
reg_pred = self.reg_conv(x)
obj_pred = self.obj_conv(x)
return torch.cat([reg_pred, obj_pred, cls_pred], dim=1)
class YOLOHead(nn.Module):
def init(self, num_classes: int, anchors: List[Tuple[int, int]]):
super(YOLOHead, self).init()
self.num_classes = num_classes
self.anchors = anchors
self.num_anchors = len(anchors)
self.out_channels = self.num_anchors * (5 + self.num_classes) # (4 bbox + 1 confidence + classes)
# Define a 1x1 convolutional layer to generate YOLO output
self.conv = nn.Conv2d(256, self.out_channels, kernel_size=1)
def forward(self, x: Tensor) -> Tensor:
"""Forward pass for YOLOHead."""
return self.conv(x) # Output shape: [N, num_anchors * (5 + num_classes), H, W]
def generate_yolo_targets(gt_boxes, gt_confidences, gt_classes, grid_size, device):
batch_size = gt_boxes.size(0)
num_objects = gt_boxes.size(1)
yolo_targets = torch.zeros(batch_size, 6, grid_size, grid_size, device=device)
for i in range(batch_size):
for j in range(num_objects):
box = gt_boxes[i, j]
confidence = gt_confidences[i, j]
class_label = gt_classes[i, j]
if box[2] == 0 or box[3] == 0:
continue
grid_x = int(box[0] * grid_size)
grid_y = int(box[1] * grid_size)
grid_x = min(grid_x, grid_size - 1)
grid_y = min(grid_y, grid_size - 1)
box_w = box[2]
box_h = box[3]
yolo_targets[i, 0:4, grid_y, grid_x] = torch.tensor([box[0], box[1], box_w, box_h], device=device)
yolo_targets[i, 4, grid_y, grid_x] = confidence
yolo_targets[i, 5, grid_y, grid_x] = class_label
print(f"[DEBUG] Generated YOLO targets shape: {yolo_targets.shape}")
unique_confidences = yolo_targets[4].unique()
unique_classes = yolo_targets[5].unique()
print(f"[DEBUG] Unique confidence values in targets: {unique_confidences}")
print(f"[DEBUG] Unique class labels in targets: {unique_classes}")
return yolo_targets
#decoupled_head.py
from collections import OrderedDict
from typing import Dict, Tuple, List
from pytorch_toolbelt.modules import ACT_RELU, get_activation_block, conv1x1
from torch import nn, Tensor
from ...constants import (
CENTERNET_OUTPUT_VESSEL_MAP,
CENTERNET_OUTPUT_FISHING_MAP,
CENTERNET_OUTPUT_OBJECTNESS_MAP,
CENTERNET_OUTPUT_SIZE,
CENTERNET_OUTPUT_OFFSET,
)
all = ["DecoupledHeadGroupNormLateShuffle"]
class FeatureRecombination(nn.Module):
def init(self, channels, modulating_features):
super().init()
self.project = conv1x1(modulating_features, channels)
def forward(self, x, modulation):
return x * self.project(modulation).sigmoid()
def build_regression_block(
input_channels: int,
embedding_size: int,
dropout_rate: float,
num_blocks: int,
activation: str,
extra_final_layers: List[Tuple[str, nn.Module]],
num_groups=16,
):
activation_block = get_activation_block(activation)
layers = [
(
"project",
nn.Conv2d(input_channels, embedding_size, kernel_size=(1, 1), padding=0, bias=False),
),
]
for layer_index in range(num_blocks):
layers += [
(
f"conv{layer_index}",
nn.Conv2d(embedding_size, embedding_size, kernel_size=(3, 3), padding=1, bias=False),
),
(f"bn{layer_index}", nn.GroupNorm(num_groups, embedding_size)),
(f"act{layer_index}", activation_block(inplace=True)),
]
layers += [
("drop", nn.Dropout2d(dropout_rate, inplace=False)),
("conv1", nn.Conv2d(embedding_size, embedding_size, kernel_size=(1, 1), padding=0, bias=False)),
] + extra_final_layers
return nn.Sequential(OrderedDict(layers))
class DecoupledHeadGroupNormLateShuffle(nn.Module):
upsample_factor: int = 2
def __init__(
self,
channels: int,
classifier_dim: int,
dropout_rate=0.25,
objectness_dim: int = 32,
size_dim: int = 32,
offset_dim: int = 32,
num_blocks: int = 3,
activation: str = ACT_RELU,
num_groups=16,
):
super().__init__()
self.objectness = build_regression_block(
channels,
embedding_size=objectness_dim,
dropout_rate=dropout_rate,
activation=activation,
num_groups=num_groups,
num_blocks=num_blocks,
extra_final_layers=[
(("shuffle"), nn.PixelShuffle(2)),
("final", nn.Conv2d(objectness_dim // 4, 1, kernel_size=(3, 3), padding=1)),
],
)
self.classifier = build_regression_block(
channels,
embedding_size=classifier_dim,
dropout_rate=dropout_rate,
num_groups=num_groups,
activation=activation,
num_blocks=num_blocks,
extra_final_layers=[],
)
self.size = build_regression_block(
channels,
embedding_size=size_dim,
dropout_rate=dropout_rate,
activation=activation,
num_groups=num_groups,
num_blocks=num_blocks,
extra_final_layers=[],
)
self.classifier_recombination = FeatureRecombination(classifier_dim, size_dim)
self.classifier_up = nn.Sequential(
OrderedDict(
[
("conv1", nn.Conv2d(classifier_dim, classifier_dim, kernel_size=(3, 3), padding=1)),
("shuffle", nn.PixelShuffle(2)),
("final", nn.Conv2d(classifier_dim // 4, 2, kernel_size=(3, 3), padding=1)),
]
)
)
self.size_recombination = FeatureRecombination(size_dim, classifier_dim)
self.size_up = nn.Sequential(
OrderedDict(
[
("conv1", nn.Conv2d(size_dim, size_dim, kernel_size=(3, 3), padding=1)),
("shuffle", nn.PixelShuffle(2)),
("final", nn.Conv2d(size_dim // 4, 1, kernel_size=(3, 3), padding=1)),
("activation", nn.Softplus()),
]
)
)
if offset_dim:
self.offset = build_regression_block(
channels,
embedding_size=offset_dim,
dropout_rate=dropout_rate,
activation=activation,
num_groups=num_groups,
num_blocks=num_blocks,
extra_final_layers=[
(("shuffle"), nn.PixelShuffle(2)),
("final", nn.Conv2d(offset_dim // 4, 2, kernel_size=(3, 3), padding=1)),
],
)
else:
self.offset = None
# Determine if offset is included
if self.offset is not None:
self.out_channels = 6 # Total output channels
else:
self.out_channels = 4 # Exclude offset channels
self._init_weights()
def _init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# self.classifier_up.final.bias.data.fill_(0)
# self.objectness.final.bias.data.fill_(-4)
self.objectness.final.bias.data.fill_(-5)
self.classifier_up.final.bias.data.fill_(-1)
self.size_up.final.bias.data.fill_(2)
def forward(self, features: Tensor) -> Dict[str, Tensor]:
class_features = self.classifier(features)
length_features = self.size(features)
new_class_features = self.classifier_recombination(class_features, length_features)
new_length_features = self.size_recombination(length_features, class_features)
predicted_classes = self.classifier_up(new_class_features)
predicted_length = self.size_up(new_length_features)
output = {
CENTERNET_OUTPUT_OBJECTNESS_MAP: self.objectness(features),
CENTERNET_OUTPUT_VESSEL_MAP: predicted_classes[:, 0:1],
CENTERNET_OUTPUT_FISHING_MAP: predicted_classes[:, 1:2],
CENTERNET_OUTPUT_SIZE: predicted_length,
}
if self.offset is not None:
output[CENTERNET_OUTPUT_OFFSET] = self.offset(features).clip(0, 1)
return output
#multilabel_trimmed_loss.py
from functools import partial
from typing import Dict, Tuple
import torch
from pytorch_toolbelt.losses import SoftBCEWithLogitsLoss, BinaryBiTemperedLogisticLoss, BinaryFocalLoss, BalancedBCEWithLogitsLoss
from torch import nn, Tensor
from torch.nn import functional as F
from .functional import binary_shannon_entropy_loss
from ..constants import (
CENTERNET_OUTPUT_SIZE,
CENTERNET_OUTPUT_OFFSET,
CENTERNET_OUTPUT_OBJECTNESS_MAP,
CENTERNET_TARGET_SIZE,
CENTERNET_TARGET_OFFSET,
CENTERNET_TARGET_FISHING_MAP,
CENTERNET_OUTPUT_FISHING_MAP,
CENTERNET_OUTPUT_VESSEL_MAP,
CENTERNET_TARGET_VESSEL_MAP,
CENTERNET_TARGET_OBJECTNESS_MAP,
CENTERNET_OUTPUT_YOLO,
CENTERNET_TARGET_YOLO
)
from ...constants import IGNORE_LABEL
all = ["MultilabelCenterTrimmedLoss"]
class MultilabelCenterTrimmedLoss(nn.Module):
fraction: int
samplewise: bool
regularize_ignored: bool
def __init__(
self,
fraction: int,
samplewise: bool = True,
objectness_loss: str = "rfl",
classifier_loss="bce",
size_loss: str = "mse",
offset_loss: str = "mse",
regularize_ignored: bool = False,
regularization_weight: float = 1.0,
ignore_index: int = IGNORE_LABEL,
):
super().__init__()
self.fraction = fraction
self.objectness_loss = objectness_loss
self.samplewise = samplewise
self.regularize_ignored = regularize_ignored
self.regularization_weight = regularization_weight
self.ignore_index = ignore_index
if objectness_loss == "rfl":
self.objectness_loss = partial(self.reduced_focal_loss, alpha=2, beta=4, eps=0)
elif objectness_loss == "l1":
self.objectness_loss = self.objectness_l1_loss
elif objectness_loss == "mse":
self.objectness_loss = self.objectness_mse_loss
elif objectness_loss == "focal_mse":
self.objectness_loss = self.objectness_focal_mse_loss
else:
raise KeyError(objectness_loss)
if classifier_loss == "bce":
self.classifier_loss = SoftBCEWithLogitsLoss(ignore_index=ignore_index, reduction="none")
elif classifier_loss == "bbce":
self.classifier_loss = BalancedBCEWithLogitsLoss(ignore_index=ignore_index, reduction="none")
elif classifier_loss == "soft_bce":
self.classifier_loss = SoftBCEWithLogitsLoss(ignore_index=ignore_index, reduction="none", smooth_factor=0.05)
elif classifier_loss == "bitempered":
self.classifier_loss = BinaryBiTemperedLogisticLoss(t1=0.5, t2=4.0, ignore_index=ignore_index, reduction="none")
elif classifier_loss == "focal":
self.classifier_loss = BinaryFocalLoss(ignore_index=ignore_index, alpha=None, reduction="none")
else:
raise KeyError(classifier_loss)
if size_loss == "huber":
self.size_loss = self.huber_loss
elif size_loss == "mse":
self.size_loss = self.mse_loss
elif size_loss == "smooth_l1":
self.size_loss = self.smooth_l1_loss
elif size_loss == "rel_error":
self.size_loss = self.relative_length_error
else:
raise KeyError(size_loss)
if offset_loss == "mse":
self.offset_loss = self.mse_loss
elif offset_loss == "l1":
self.offset_loss = self.l1_loss
elif offset_loss == "smooth_l1":
self.offset_loss = self.smooth_l1_loss
elif offset_loss == "huber":
self.offset_loss = self.huber_loss
elif offset_loss is None:
self.offset_loss = None
else:
raise KeyError(offset_loss)
def objectness_mse_loss(self, pred: Tensor, gt: Tensor, pos_mask) -> Tuple[Tensor, Tensor]:
ign_mask = gt.eq(self.ignore_index)
pt = pred.sigmoid()
neg_mask = ~pos_mask
loss = F.mse_loss(pt, gt, reduction="none")
pos_loss: Tensor = loss * pos_mask
neg_loss: Tensor = loss * neg_mask
return torch.masked_fill(pos_loss, ign_mask, 0), torch.masked_fill(neg_loss, ign_mask, 0)
def objectness_focal_mse_loss(self, pred: Tensor, gt: Tensor, pos_mask: Tensor, alpha=2.0, beta=2.0) -> Tuple[Tensor, Tensor]:
pt = pred.sigmoid()
neg_mask = ~pos_mask
loss = F.mse_loss(pt, gt, reduction="none")
pos_loss: Tensor = loss * pos_mask
neg_loss: Tensor = loss * neg_mask * torch.pow(pt, alpha) * torch.pow(1.0 - gt, beta)
return pos_loss, neg_loss
def objectness_l1_loss(self, pred: Tensor, gt: Tensor, pos_mask):
pt = pred.sigmoid()
ign_mask = gt.eq(self.ignore_index)
neg_mask = ~pos_mask
loss = F.l1_loss(pt, gt, reduction="none")
pos_loss: Tensor = loss * pos_mask
neg_loss: Tensor = (loss * neg_mask) ** 4
return torch.masked_fill(pos_loss, ign_mask, 0), torch.masked_fill(neg_loss, ign_mask, 0)
def reduced_focal_loss(self, pred: Tensor, gt: Tensor, pos_mask, alpha: float, beta: float, eps: float = 1e-4):
neg_mask = ~pos_mask
ign_mask = gt.eq(self.ignore_index)
pt = pred.sigmoid().clamp(eps, 1 - eps)
pos_loss: Tensor = -torch.pow(1 - pt, alpha) * F.logsigmoid(pred) * pos_mask
neg_loss: Tensor = -torch.pow(1.0 - gt, beta) * torch.pow(pt, alpha) * F.logsigmoid(-pred) * neg_mask
return torch.masked_fill(pos_loss, ign_mask, 0), torch.masked_fill(neg_loss, ign_mask, 0)
def mse_loss(self, prediction, target, pos_mask):
loss = F.mse_loss(prediction, target, reduction="none") * pos_mask
return loss
def l1_loss(self, prediction, target, pos_mask):
loss = F.l1_loss(prediction, target, reduction="none") * pos_mask
return loss
def smooth_l1_loss(self, prediction, target, pos_mask):
loss = F.smooth_l1_loss(prediction, target, reduction="none") * pos_mask
return loss
def huber_loss(self, prediction, target, pos_mask):
loss = F.huber_loss(prediction, target, reduction="none", delta=1) * pos_mask
return loss
def relative_length_error(self, prediction, target, pos_mask, eps=1e-4):
loss = pos_mask * F.smooth_l1_loss(prediction, target, reduction="none") / (target + eps)
return loss
# @torch.cuda.amp.autocast(False)
def forward(self, **kwargs) -> Dict[str, Tensor]:
gt_objectness: Tensor = kwargs[CENTERNET_TARGET_OBJECTNESS_MAP]
gt_is_vessel: Tensor = kwargs[CENTERNET_TARGET_VESSEL_MAP]
gt_is_fishing: Tensor = kwargs[CENTERNET_TARGET_FISHING_MAP]
gt_size: Tensor = kwargs[CENTERNET_TARGET_SIZE]
gt_yolo: Tensor = kwargs[CENTERNET_TARGET_YOLO]
pred_objectness: Tensor = kwargs[CENTERNET_OUTPUT_OBJECTNESS_MAP]
pred_is_vessel: Tensor = kwargs[CENTERNET_OUTPUT_VESSEL_MAP]
pred_is_fishing: Tensor = kwargs[CENTERNET_OUTPUT_FISHING_MAP]
pred_size: Tensor = kwargs[CENTERNET_OUTPUT_SIZE]
pred_yolo: Tensor = kwargs[CENTERNET_OUTPUT_YOLO]
peaks_mask = gt_objectness.eq(1)
true_vessels_mask = gt_is_vessel.eq(1)
num_objects = peaks_mask.sum(dtype=torch.float32).clamp_min(1.0)
num_vessels = (true_vessels_mask & peaks_mask).sum(dtype=torch.float32).clamp_min(1.0)
uncertain_objectness_mask = gt_objectness.eq(self.ignore_index)
certain_objectness_mask = ~uncertain_objectness_mask
# Returns unreduced losses
pos_objectness_loss, neg_objectness_loss = self.objectness_loss(pred_objectness, gt_objectness, pos_mask=peaks_mask)
# Weight classification loss by objectness (This make sense for target encoding=center).
# This way pixels closer to the center of the keypoint will have bigger influence than ones on the periphery
vessel_loss = self.classifier_loss(pred_is_vessel, gt_is_vessel) * gt_objectness * certain_objectness_mask
fishing_loss = self.classifier_loss(pred_is_fishing, gt_is_fishing) * gt_objectness * certain_objectness_mask
yolo_loss = self.yolo_loss(pred_yolo, gt_yolo)
if self.regularize_ignored:
uncertain_vessel_mask = gt_is_vessel.eq(self.ignore_index)
uncertain_fishing_mask = gt_is_fishing.eq(self.ignore_index)
# Plus regularization loss for ignored values in the objectness heatmap
objectness_reg_loss = binary_shannon_entropy_loss(pred_objectness) * uncertain_objectness_mask
vsl_reg_loss = binary_shannon_entropy_loss(pred_is_vessel) * certain_objectness_mask * uncertain_vessel_mask * gt_objectness
fsh_reg_loss = (
binary_shannon_entropy_loss(pred_is_fishing)
* certain_objectness_mask
* uncertain_fishing_mask
* true_vessels_mask
* gt_objectness
)
pos_objectness_loss += objectness_reg_loss * self.regularization_weight
vessel_loss += vsl_reg_loss * self.regularization_weight
fishing_loss += fsh_reg_loss * self.regularization_weight
valid_size_mask = peaks_mask * (gt_size > 0) # Size loss only for positive lengths
num_objects_with_length = valid_size_mask.sum(dtype=torch.float32).clamp_min(1.0)
size_loss = self.size_loss(pred_size, gt_size, valid_size_mask)
if self.offset_loss is not None:
offset_loss = self.offset_loss(kwargs[CENTERNET_OUTPUT_OFFSET], kwargs[CENTERNET_TARGET_OFFSET], peaks_mask).sum(
dim=1, keepdim=True
)
else:
offset_loss = torch.zeros_like(size_loss)
if self.fraction > 0:
if self.samplewise:
(pos_objectness_loss, neg_objectness_loss, vessel_loss, fishing_loss, offset_loss, size_loss,) = samplewise_trimming(
pred_objectness,
pred_is_vessel,
pred_is_fishing,
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
)
else:
(pos_objectness_loss, neg_objectness_loss, vessel_loss, fishing_loss, offset_loss, size_loss,) = batchwise_trimming(
pred_objectness,
pred_is_vessel,
pred_is_fishing,
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
)
mean_obj_loss = (neg_objectness_loss.sum(dtype=torch.float32) + pos_objectness_loss.sum(dtype=torch.float32)) / num_objects
mean_vessel_loss = (vessel_loss.sum(dtype=torch.float32)) / num_objects
mean_fishing_loss = (fishing_loss.sum(dtype=torch.float32)) / num_vessels
mean_siz_loss = size_loss.sum(dtype=torch.float32) / num_objects_with_length
losses = {
"objectness": mean_obj_loss.type_as(pred_objectness),
"vessel": mean_vessel_loss.type_as(pred_objectness),
"fishing": mean_fishing_loss.type_as(pred_objectness),
"size": mean_siz_loss.type_as(pred_objectness),
}
if self.offset_loss is not None:
mean_off_loss = offset_loss.sum(dtype=torch.float32) / num_objects
losses["offset"] = mean_off_loss.type_as(pred_objectness)
return losses
def samplewise_trimming(
pred_objectness,
pred_is_vessel,
pred_is_fishing,
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
num_elements_to_ignore,
):
pred_objectness = pred_objectness.flatten(2) # [B, 1, N]
pred_is_vessel = pred_is_vessel.flatten(2) # [B, 1, N]
pred_is_fishing = pred_is_fishing.flatten(2) # [B, 1, N]
pos_objectness_loss = pos_objectness_loss.flatten(2) # [B, 1, N]
neg_objectness_loss = neg_objectness_loss.flatten(2) # [B, 1, N]
vessel_loss = vessel_loss.flatten(2) # [B, 1, N]
fishing_loss = fishing_loss.flatten(2) # [B, 1, N]
offset_loss = offset_loss.flatten(2) # [B, 1, N]
size_loss = size_loss.flatten(2) # [B, 1, N]
# Here we ignore top-N negative losses for negative objectness loss (E.g target is predicted, but groundtruth is negative).
# Since some objects may be missing in gt, and we don't want to include those wrong false-positives in the training signal
# And use keep indexes to propagate ignored pixels in other losses
_, indices = torch.topk(neg_objectness_loss, k=num_elements_to_ignore, dim=2, largest=True, sorted=False)
non_ignored_mask = torch.ones_like(neg_objectness_loss).scatter_(2, indices, 0)
# Instead of just setting loss to zeros in those hard example predictions, we minimize entropy loss
# for objectness & classification to push the predictions to either 0 or 1
neg_objectness_loss = neg_objectness_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_objectness) * (1 - non_ignored_mask)
vessel_loss = vessel_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_is_vessel) * (1 - non_ignored_mask)
fishing_loss = fishing_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_is_fishing) * (1 - non_ignored_mask)
# For offset & size there is no regularization, so we exclude corresponding pixels from the grad. contribution
offset_loss = offset_loss * non_ignored_mask
size_loss = size_loss * non_ignored_mask
return (
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
)
def batchwise_trimming(
pred_objectness,
pred_is_vessel,
pred_is_fishing,
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
num_elements_to_ignore,
):
pred_objectness = pred_objectness.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
pred_is_vessel = pred_is_vessel.permute(1, 0, 2, 3).flatten(1) # [C, BxN]
pred_is_fishing = pred_is_fishing.permute(1, 0, 2, 3).flatten(1) # [C, BxN]
pos_objectness_loss = pos_objectness_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
neg_objectness_loss = neg_objectness_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
vessel_loss = vessel_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
fishing_loss = fishing_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
offset_loss = offset_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
size_loss = size_loss.permute(1, 0, 2, 3).flatten(1) # [1, BxN]
# Here we ignore top-N negative losses for negative objectness loss (E.g target is predicted, but groundtruth is negative).
# Since some objects may be missing in gt, and we don't want to include those wrong false-positives in the training signal
# And use keep indexes to propagate ignored pixels in other losses
_, indices = torch.topk(neg_objectness_loss, k=num_elements_to_ignore, dim=1, largest=True, sorted=False)
non_ignored_mask = torch.ones_like(neg_objectness_loss).scatter_(1, indices, 0)
# Instead of just setting loss to zeros in those hard example predictions, we minimize entropy loss
# for objectness & classification to push the predictions to either 0 or 1
neg_objectness_loss = neg_objectness_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_objectness) * (1 - non_ignored_mask)
vessel_loss = vessel_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_is_vessel) * (1 - non_ignored_mask)
fishing_loss = fishing_loss * non_ignored_mask + binary_shannon_entropy_loss(pred_is_fishing) * (1 - non_ignored_mask)
# For offset & size there is no regularization, so we exclude corresponding pixels from the grad. contribution
offset_loss = offset_loss * non_ignored_mask
size_loss = size_loss * non_ignored_mask
return (
pos_objectness_loss,
neg_objectness_loss,
vessel_loss,
fishing_loss,
offset_loss,
size_loss,
)