after these modifications I think I receive 5 layer which makes 5 * 256 = 1280
so review these files to help modify the give group weight of size which gives 1024 only and help fix the error at the end of the question
#first file centernet_unet.py
from functools import partial
from typing import List, Dict
from omegaconf import DictConfig
from pytorch_toolbelt.modules import (
ACT_RELU,
decoders as D,
EncoderModule,
ResidualDeconvolutionUpsample2d,
)
from torch import nn
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
from .unet_blocks import IRBlock, get_unet_block, SqueezeExcitation
from .necks import FPNNeck
from xview3.nas import NAS as NeuralArchitectureSearch
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,
)
all = ["CenterNetUNetModel"]
if hasattr(encoder, 'channels'):
encoder_channels = list(encoder.channels)
else:
encoder_channels = [32, 24, 40, 112, 320] # Default for EfficientNet
encoder_channels += [encoder_channels[-1]] * num_extra_blocks
#self.neck = FPNNeck(self.decoder_channels, neck_out_channels)
#self.neck_conv = nn.Conv2d(self.neck_output_channels, neck_out_channels, kernel_size=1)
self.head = head
self.head_output_channels = head.out_channels # Ensure your head module defines 'out_channels'
# Ensure self.nas is a module that can be called during forward
self.nas = NeuralArchitectureSearch(
search_space={
'num_layers': (2, 5),
'num_filters': (32, 128),
'kernel_size': (3, 5),
'activation': ['relu', 'leaky_relu']
},
evaluation_function=self.evaluate_architecture
)
self.nas_output_channels = self.nas.output_channels # Define this in your NAS module
self.yolo_head = YOLOHead(num_classes=num_classes, anchors=anchors)
self.yolo_output_channels = self.yolo_head.num_anchors * (num_classes + 5) # Adjust as per YOLO implementation
self.classifier = ConvolutionalClassifier(in_channels=neck_out_channels, num_classes=num_classes)
self.classifier_output_channels = self.classifier.out_channels
self.box_coder = box_coder
self.head_output_channels = getattr(self.head, 'out_channels', 256)
self.nas_output_channels = getattr(self.nas, 'output_channels', 256)
self.yolo_output_channels = self.yolo_head.num_anchors * (num_classes + 5)
self.classifier_output_channels = getattr(self.classifier, 'out_channels', num_classes)
# Ensure all channel values are integers
total_input_channels = (
int(self.head_output_channels) +
int(self.nas_output_channels) +
int(self.yolo_output_channels) +
int(self.classifier_output_channels)
)
self.fusion = nn.Conv2d(total_input_channels, self.head_output_channels, kernel_size=1)
self.dropout = nn.Dropout(p=0.5)
#self.decoder_channels = decoder_features
#encoder_channels = list(encoder.channels)
self.num_decoded_features = len(encoder_channels)
num_decoder_stages = self.num_decoded_features
self.neck_output_channels = neck_out_channels * self.num_decoded_features
print(f"[DEBUG] neck_output_channels: {self.neck_output_channels}")
num_decoder_stages = self.num_decoded_features
# Adjust decoder_channels if necessary
self.decoder_channels = decoder_features
encoder_channels = list(encoder.channels)
num_blocks = len(encoder_channels) - 1 # UNetDecoder expects decoder_features of length len(encoder_channels) - 1
# Adjust decoder_channels to match num_blocks
if len(self.decoder_channels) < num_blocks:
# Extend decoder_channels by repeating the last value
self.decoder_channels.extend(
[self.decoder_channels[-1]] * (num_blocks - len(self.decoder_channels))
)
elif len(self.decoder_channels) > num_blocks:
# Trim decoder_channels to the required length
self.decoder_channels = self.decoder_channels[:num_blocks]
print(f"[DEBUG] encoder_channels: {encoder_channels}") # Should be of length 5
print(f"[DEBUG] decoder_channels: {self.decoder_channels}") # Should be of length 4
print(f"[DEBUG] num_blocks: {num_blocks}")
self.decoder = D.UNetDecoder(
encoder_channels,
self.decoder_channels,
unet_block=unet_block,
upsample_block=upsample_block,
)
self.neck = FPNNeck(self.decoder_channels, neck_out_channels)
self.neck_conv = nn.Conv2d(
in_channels=self.neck_output_channels,
out_channels=neck_out_channels,
kernel_size=1
)
print(f"[DEBUG] neck_output_channels: {self.neck_output_channels}")
self.batch_norm = FilterResponseNormalization(self.neck_output_channels)
def evaluate_architecture(self, architecture):
# Implement a simple evaluation function
return random.random() # Replace with actual evaluation logic
def forward(self, x):
x = self.initial_upsample(x)
print(f"[DEBUG] x shape after initial_upsample: {x.shape}")
feature_maps = self.encoder(x)
print(f"[DEBUG] feature_maps type: {type(feature_maps)}")
if isinstance(feature_maps, list):
for idx, fmap in enumerate(feature_maps):
print(f"[DEBUG] feature_maps[{idx}] shape: {fmap.shape}")
else:
print("[ERROR] feature_maps is not a list")
print(f"feature_maps shape: {feature_maps.shape}")
print(f"feature_maps type: {type(feature_maps)}")
# Convert feature_maps to a list if needed
feature_maps = [feature_maps]
for extra_block in self.extra_encoder_blocks:
feature_maps.append(extra_block(feature_maps[-1]))
decoded_features = self.decoder(feature_maps)
print(f"[DEBUG] decoded_features type: {type(decoded_features)}")
if isinstance(decoded_features, list):
for idx, fmap in enumerate(decoded_features):
print(f"[DEBUG] decoded_features[{idx}] shape: {fmap.shape}")
else:
print("[ERROR] decoded_features is not a list")
print(f"decoded_features shape: {decoded_features.shape}")
print(f"decoded_features type: {type(decoded_features)}")
# Convert decoded_features to a list if needed
decoded_features = [decoded_features]
neck_features = self.neck(decoded_features)
print(f"[DEBUG] neck_features shape before batch_norm: {neck_features.shape}")
print(f"[DEBUG] neck_features channels: {neck_features.size(1)}")
print(f"[DEBUG] neck_features shape before batch_norm: {neck_features.shape}")
neck_features = self.batch_norm(neck_features)
print(f"[DEBUG] neck_features shape after batch_norm: {neck_features.shape}")
neck_features = self.dropout(neck_features)
neck_features = self.neck_conv(neck_features)
#self.head.channels = self.nas_output_channels # Assuming self.nas_output_channels is the correct channel size
head_output = self.head(neck_features)
nas_output = self.nas(neck_features)
yolo_output = self.yolo_head(neck_features)
classification_output = self.classifier(neck_features)
# Fusion layer
fused_output = self.fusion(torch.cat([head_output, nas_output, yolo_output, classification_output], dim=1))
return {
CENTERNET_OUTPUT_OBJECTNESS_MAP: fused_output[:, :1],
CENTERNET_OUTPUT_VESSEL_MAP: fused_output[:, 1:2],
CENTERNET_OUTPUT_FISHING_MAP: fused_output[:, 2:3],
CENTERNET_OUTPUT_SIZE: fused_output[:, 3:4],
CENTERNET_OUTPUT_OFFSET: fused_output[:, 4:6],
}
@classmethod
def from_config(cls, **config):
# Extract and pop the encoder configuration
encoder_config = config.pop('encoder')
num_channels = config.pop('num_channels', 3)
model_name = encoder_config.get('model_name', 'tf_efficientnet_b5_ns')
pretrained = encoder_config.get('pretrained', False)
# Instantiate the custom encoder
encoder_module = CustomTimmEncoder(
model_name=model_name,
num_channels=num_channels,
features_only=True,
pretrained=pretrained
)
# Pop other configurations
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)])
# Pop decoder configuration
decoder_config = config.pop('decoder')
decoder_features = decoder_config['channels']
block_type = decoder_config.get("block_type", "UnetBlock")
upsample_type = decoder_config.get("upsample_type", "bilinear")
neck_out_channels = config.get('neck_out_channels', 256)
neck_output_channels = neck_out_channels * len(decoder_features)
print(f"Neck output channels: {neck_output_channels}")
# Instantiate head and box_coder
head_config = config.pop('head')
head = instantiate(head_config, channels=neck_output_channels)
box_coder_config = config.pop('box_coder')
box_coder = instantiate(
box_coder_config,
output_stride=encoder_module.strides[0] // (head.upsample_factor * input_upsample_factor),
)
# Now initialize the model instance with the remaining config
return cls(
encoder=encoder_module,
decoder_features=decoder_features,
head=head,
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
)
def adjust_encoder_input_channels(encoder_module, in_chans):
# Access the underlying encoder model
if hasattr(encoder_module, 'encoder'):
base_encoder = encoder_module.encoder
else:
base_encoder = encoder_module
code
if hasattr(base_encoder, 'conv_stem'):
old_conv = base_encoder.conv_stem
print(f"[DEBUG] Before adjustment, encoder.conv_stem.in_channels: {old_conv.in_channels}")
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
)
# Initialize new_conv weights
with torch.no_grad():
# Copy weights for existing channels
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:
# Initialize added 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]])
code
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)
def forward(self, x):
print(f"[DEBUG] x shape in YOLOHead before fpn: {x.shape}")
x = self.fpn(x)
print(f"[DEBUG] x shape in YOLOHead after fpn: {x.shape}")
batch_size, _, height, width = x.shape
# Continue with the rest of the code
return self.conv(x).view(batch_size, len(self.anchors), 5 + self.num_classes, height, width).permute(0, 1, 3, 4, 2)
#the next file is the decoupled_head.py contains the ceneternet head
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,
)
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import numpy as np
from skopt import gp_minimize
from skopt.space import Real, Integer, Categorical
import math
import copy
from torch import Tensor
from torch.optim import Adam
from torch.utils.data import DataLoader
from xview3.centernet.bboxer.multilabel_circle_coder import MultilabelCircleNetCoder
#andhere's the train script which is train_mutlilabel.py
import sys
import traceback
import warnings
from typing import Dict, Any, OrderedDict, Tuple, Optional, List
import catalyst
import os
import numpy as np
import pandas as pd
import torch
import hydra
from torch.optim import Optimizer
from torch.utils.data import Dataset, Sampler, DataLoader
from torch import nn
from omegaconf import DictConfig
from functools import partial
import albumentations as A
from catalyst.callbacks import ControlFlowCallback, CriterionCallback, SchedulerCallback, TimerCallback
from catalyst.core import Callback
from pytorch_toolbelt.utils.catalyst import (
ShowPolarBatchesCallback,
BestMetricCheckpointCallback,
HyperParametersCallback,
MixupCriterionCallback,
MixupInputCallback,
)
from pytorch_toolbelt.optimization.functional import freeze_model, get_lr_decay_parameters, get_optimizable_parameters
from pytorch_toolbelt.utils import fs, transfer_weights, count_parameters
from pytorch_toolbelt.utils.distributed import is_main_process
from xview3.centernet.bboxer import MultilabelCircleNetCoder
from xview3.early_stopping import EarlyStoppingCallback
from xview3.nas import ProgressiveNAS
from xview3.centernet.models.heads.yolo_head import YOLOHead
from xview3.centernet.models.transformer_classifier import ConvolutionalClassifier
from xview3.centernet.losses.circlenet_loss import CircleNetLoss, YOLOLoss
from xview3.centernet import *
from xview3.pipeline import *
from xview3.factory import *
from xview3.augmentations import *
from xview3.samplers import *
from xview3.dataset import *
from xview3.ema import *
from xview3.evaluation import *
from xview3.inference import *
from xview3.metric import *
from xview3.constants import INPUT_SCENE_ID_KEY
import logging
torch.set_anomaly_enabled(cfg.torch.detect_anomaly)
torch.backends.cudnn.deterministic = cfg.torch.deterministic
torch.backends.cudnn.benchmark = cfg.torch.benchmark
# The flag below controls whether to allow TF32 on matmul. This flag defaults to True.
torch.backends.cuda.matmul.allow_tf32 = cfg.torch.cuda_allow_tf32
# The flag below controls whether to allow TF32 on cuDNN. This flag defaults to True.
torch.backends.cudnn.allow_tf32 = cfg.torch.cudnn.allow_tf32
if cfg.dataset.data_dir is None:
raise ValueError("--data-dir must be set")
CenternetPipeline(cfg).train()
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x340aad760>
DEBUG:rasterio._io:Output nodata value read from file: -32768.0
DEBUG:rasterio._io:Output nodata values: [-32768.0]
DEBUG:rasterio._io:all_valid: False
DEBUG:rasterio._io:mask_flags: ([<MaskFlags.nodata: 8>],)
DEBUG:rasterio._io:Jump straight to _read()
DEBUG:rasterio._io:Window: Window(col_off=17028, row_off=8790, width=512, height=512)
DEBUG:rasterio._io:IO window xoff=17028.0 yoff=8790.0 width=512.0 height=512.0
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x340aad760>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x340aada30> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x340aada30>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x340aad760>
[DEBUG] Channel 'vh' image shape before transformations: (512, 512)
[DEBUG] Channel 'vh' image shape after individual_transforms: (512, 512)
[DEBUG] Channel 'vh' image shape after normalization: (512, 512)
[DEBUG] Channel 'vv' image shape before transformations: (512, 512)
[DEBUG] Channel 'vv' image shape after individual_transforms: (512, 512)
[DEBUG] Channel 'vv' image shape after normalization: (512, 512)
[DEBUG] Number of channels: 2
[DEBUG] Channel 0 shape: (512, 512)
[DEBUG] Channel 1 shape: (512, 512)
[DEBUG] Combined image shape after np.dstack: (512, 512, 2)
[DEBUG] Keypoints being passed to albumentations:
Error executing job with overrides: ['+config=configs/multilabel_circle_net.yaml']
Traceback (most recent call last):
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 529, 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 525, in main
CenternetPipeline(cfg).train()
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 416, in train
model = self.build_model(config, self.loaders)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 207, in build_model
model = nas.search(config.nas.num_iterations, loaders['train'], loaders['valid'])
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/nas.py", line 36, in search
scores = [self.evaluate_model(model, train_loader, val_loader) for model in population]
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/nas.py", line 36, in
scores = [self.evaluate_model(model, train_loader, val_loader) for model in population]
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/nas.py", line 115, in evaluate_model
outputs = model(inputs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/models/centernet_unet.py", line 193, in forward
neck_features = self.neck(decoded_features)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/models/necks.py", line 47, in forward
return self.out_conv(fpn_output)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/conv.py", line 458, in forward
return self._conv_forward(input, self.weight, self.bias)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/nn/modules/conv.py", line 454, in _conv_forward
return F.conv2d(input, weight, bias, self.stride,
RuntimeError: Given groups=1, weight of size [256, 1024, 1, 1], expected input[8, 1280, 256, 256] to have 1024 channels, but got 1280 channels instead
(sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers %
The error you're encountering stems from a mismatch between the expected input channels of a convolutional layer and the actual number of channels in the input tensor. Specifically, the convolutional layer expects 1024 input channels, but the input tensor has 1280 channels.
Here's the relevant part of the error message:
code
RuntimeError: Given groups=1, weight of size [256, 1024, 1, 1], expected input[8, 1280, 256, 256] to have 1024 channels, but got 1280 channels instead
This indicates that the convolutional layer (nn.Conv2d) is initialized with in_channels=1024, but it's receiving an input tensor with channels=1280.
Root Cause:
The inconsistency arises from how self.neck_output_channels is calculated in your CenterNetUNetModel. Currently, self.neck_output_channels is computed based on len(encoder_channels), but it should be based on len(self.decoder_channels). Here's the specific section of your code where the issue occurs:
Since you have modified your model to have five layers (which results in 5 * 256 = 1280 channels), self.num_decoded_features should be set to the length of self.decoder_channels, not encoder_channels.
Solution:
Modify your CenterNetUNetModel class to calculate self.num_decoded_features based on the number of decoder channels (self.decoder_channels) instead of encoder channels (encoder_channels). This ensures that self.neck_output_channels correctly reflects the actual number of channels being passed through the network.
Here's how you can fix it:
python
# Replace this line
self.num_decoded_features = len(encoder_channels)
# With this line
self.num_decoded_features = len(self.decoder_channels)
Adjusted Code Snippet:
In your centernet_unet.py, update the __init__ method of CenterNetUNetModel as follows:
python
# ... previous code ...
# Determine number of decoder stages (features) after adjusting decoder_channels
self.num_decoded_features = len(self.decoder_channels)
num_decoder_stages = self.num_decoded_features
self.neck_output_channels = neck_out_channels * self.num_decoded_features
print(f"[DEBUG] neck_output_channels: {self.neck_output_channels}")
# Adjust decoder_channels if necessary
# (this code remains the same)
encoder_channels = list(encoder.channels)
num_blocks = len(encoder_channels) - 1 # UNetDecoder expects decoder_features of length len(encoder_channels) - 1
# Adjust decoder_channels to match num_blocks
if len(self.decoder_channels) < num_blocks:
# Extend decoder_channels by repeating the last value
self.decoder_channels.extend(
[self.decoder_channels[-1]] * (num_blocks - len(self.decoder_channels))
)
elif len(self.decoder_channels) > num_blocks:
# Trim decoder_channels to the required length
self.decoder_channels = self.decoder_channels[:num_blocks]
print(f"[DEBUG] encoder_channels: {encoder_channels}") # Should be of length 5 or 6
print(f"[DEBUG] decoder_channels: {self.decoder_channels}") # Should match num_blocks
print(f"[DEBUG] num_blocks: {num_blocks}")
self.decoder = D.UNetDecoder(
encoder_channels,
self.decoder_channels,
unet_block=unet_block,
upsample_block=upsample_block,
)
self.neck = FPNNeck(self.decoder_channels, neck_out_channels)
Explanation:
By setting self.num_decoded_features = len(self.decoder_channels), you ensure that the calculation of self.neck_output_channels (which is neck_out_channels * self.num_decoded_features) correctly represents the actual number of channels output by the decoder stages.
This change ensures that when the FPNNeck and its self.out_conv layer are initialized, they have the correct in_channels that match the actual input tensor's number of channels.
After making this change, your model should correctly handle the increased number of layers, and the convolutional layer will expect 1280 input channels, matching the actual input tensor.
Additional Notes:
Be sure to check any other parts of your code where self.num_decoded_features, self.decoder_channels, or related variables are used to ensure consistency throughout your model.
The debug prints will help you verify that the shapes and lengths of your channel lists match your expectations, which can be invaluable when troubleshooting similar issues in the future.
Updated centernet_unet.py Snippet:
python
Validating the Fix:
After making this change, rerun your training script. You should see that the error about mismatched channels has been resolved.
Debug Output:
The debug statements you've included (print(f"[DEBUG] ...")) will help confirm that the number of channels matches expectations:
encoder_channels: List of channels from the encoder.
decoder_channels: Should match num_blocks after adjustment.
num_blocks: Number of blocks in your decoder.
neck_output_channels: Should now correctly reflect neck_out_channels * len(self.decoder_channels).
Conclusion:
By adjusting how self.num_decoded_features is calculated, you ensure that all subsequent operations that depend on the number of decoder features are consistent with the actual model architecture. This change aligns the expected input channels of the convolutional layers with the actual number of channels in the tensors they receive, resolving the runtime error.