here's my log, which my multilabel_dataset.py gives as errors I think on running my train_multilabel.py with configs
please as a professional machine learning software engineer review those logs and deeply detect each error and what cause it and how to fix these errors professionally,
here;s my original then my upgraded multilabel_dataset.py then the error
original multilabel_dataset.py
import os
from functools import partial
from typing import List, Tuple, Optional, Callable, Dict, Any, Union
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from pytorch_toolbelt.datasets import INPUT_IMAGE_KEY, INPUT_INDEX_KEY
from pytorch_toolbelt.utils.torch_utils import image_to_tensor
from sklearn.neighbors import BallTree
from sklearn.utils import compute_sample_weight
from torch.utils.data import Sampler, WeightedRandomSampler
from torch.utils.data.dataloader import default_collate
from tqdm import tqdm
from .bboxer import (
MultilabelCircleNetCoder,
MultilabelCircleNetEncodeResult,
)
from .constants import *
from ..constants import *
all = [
"MultilabelCircleNetDataModule",
"MultilabelCircleNetFixedCropDataset",
"MultilabelCircleNetRandomCropDataset",
"centernet_collate",
]
from ..dataset import (
RandomCropFromImageDataset,
RandomCropAroundEachObjectDataset,
XView3DataModule,
KeypointsDataset,
FixedCropFromImageDataset,
read_multichannel_image,
)
from ..dataset.random_crop_dataset import encode_labels
from ..metric import get_shoreline_shoreline_contours
def centernet_collate(batch, channels_last=False):
skip_keys = [
TARGET_CENTERS_KEY,
TARGET_FISHING_KEY,
TARGET_VESSEL_KEY,
TARGET_LABELS_KEY,
TARGET_LENGTHS_KEY,
INPUT_SCENE_ID_KEY,
INPUT_SCENE_CROP_KEY,
INPUT_CONFIDENCE_KEY,
INPUT_LOCATION_ID_KEY,
INPUT_IS_NEAR_SHORE_KEY,
]
excluded_items = [dict((k, v) for k, v in b.items() if k in skip_keys) for b in batch]
included_items = [dict((k, v) for k, v in b.items() if k not in skip_keys) for b in batch]
batch: dict = default_collate(included_items)
for k in skip_keys:
out = [item[k] for item in excluded_items if k in item]
if len(out):
batch[k] = out
# for key in [
# INPUT_IMAGE_KEY,
# CENTERNET_TARGET_OBJECTNESS_MAP,
# CENTERNET_OUTPUT_CLASS_MAP,
# CENTERNET_TARGET_OFFSET,
# CENTERNET_TARGET_SIZE,
# CENTERNET_TARGET_FISHING_MAP,
# CENTERNET_TARGET_VESSEL_MAP,
# ]:
# if key in batch:
# batch[key] = batch[key].to(memory_format=torch.contiguous_format)
if channels_last:
batch[INPUT_IMAGE_KEY] = batch[INPUT_IMAGE_KEY].to(memory_format=torch.channels_last)
return batch
class MultilabelCircleNetTargetsMixin:
box_coder: MultilabelCircleNetCoder
upgraded multilabel_dataset.py which gives the current error
import os
from functools import partial
from typing import List, Tuple, Optional, Callable, Dict, Any, Union
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from pytorch_toolbelt.datasets import INPUT_IMAGE_KEY, INPUT_INDEX_KEY
from pytorch_toolbelt.utils.torch_utils import image_to_tensor
from sklearn.neighbors import BallTree
from sklearn.utils import compute_sample_weight
from torch.utils.data import Sampler, WeightedRandomSampler
from torch.utils.data.dataloader import default_collate
from tqdm import tqdm
from .bboxer import (
MultilabelCircleNetCoder,
MultilabelCircleNetEncodeResult,
)
from .constants import *
from ..constants import *
all = [
"MultilabelCircleNetDataModule",
"MultilabelCircleNetFixedCropDataset",
"MultilabelCircleNetRandomCropDataset",
"centernet_collate",
]
from ..dataset import (
RandomCropFromImageDataset,
RandomCropAroundEachObjectDataset,
XView3DataModule,
KeypointsDataset,
FixedCropFromImageDataset,
read_multichannel_image,
)
from ..dataset.random_crop_dataset import encode_labels
from ..metric import get_shoreline_shoreline_contours
# Separate included and excluded items
included_items = [
{k: v for k, v in b.items() if k not in skip_keys}
for b in batch
]
excluded_items = {
k: [b[k] for b in batch if k in b]
for k in skip_keys
}
# Use default_collate for included items
batch_dict = default_collate(included_items)
# Process excluded items
for k, v in excluded_items.items():
# Find the max number of objects in the batch for this key
max_num = max([item.shape[0] for item in v])
padded = []
for item in v:
pad_size = max_num - item.shape[0]
if pad_size > 0:
if item.ndim == 1:
# Item is 1D: shape (N,)
pad = torch.zeros(pad_size, dtype=item.dtype)
padded_item = torch.cat([item, pad], dim=0)
elif item.ndim == 2:
# Item is 2D: shape (N, D)
pad = torch.zeros((pad_size, item.shape[1]), dtype=item.dtype)
padded_item = torch.cat([item, pad], dim=0)
else:
raise ValueError(f"Unsupported tensor shape: {item.shape}")
else:
# No padding needed
padded_item = item
padded.append(padded_item)
# Stack into a single tensor
batch_dict[k] = torch.stack(padded, dim=0)
# Handle channels_last if necessary
if channels_last and INPUT_IMAGE_KEY in batch_dict:
batch_dict[INPUT_IMAGE_KEY] = batch_dict[INPUT_IMAGE_KEY].to(memory_format=torch.channels_last)
return batch_dict
class MultilabelCircleNetTargetsMixin:
box_coder: MultilabelCircleNetCoder
def build_centernet_sample(
self,
image,
centers,
confidences, # Expected: List or 1D array of strings
lengths,
is_vessel,
is_fishing,
index,
image_id,
is_near_shore,
location,
folder: str,
crop_coords: Tuple[Tuple[int, int], Tuple[int, int]],
) -> Dict[str, Any]:
# Mask NaN values in the image
image[~np.isfinite(image)] = 0
# Debug: Examine confidences
print(f"[DEBUG] Build Sample - Confidences Type: {type(confidences)}")
if isinstance(confidences, np.ndarray):
print(f"[DEBUG] Confidences Dtype: {confidences.dtype}")
print(f"[DEBUG] Confidences Shape: {confidences.shape}")
else:
print(f"[DEBUG] Confidences: {confidences}")
# Ensure confidences are strings and 1D
if isinstance(confidences, list):
confidences = np.array(confidences, dtype=str)
elif isinstance(confidences, np.ndarray):
if confidences.dtype.kind in {'U', 'S', 'O'}:
confidences = confidences.astype(str)
else:
raise ValueError(f"Confidences array should contain strings, but got dtype {confidences.dtype}")
else:
raise TypeError(f"Unexpected type for confidences: {type(confidences)}")
# Reshape to 1D if necessary
if confidences.ndim == 1:
pass # Already 1D
elif confidences.ndim == 2 and confidences.shape[1] == 1:
confidences = confidences.reshape(-1)
else:
raise ValueError(f"Confidences should be 1D or 2D with single column, but got shape {confidences.shape}")
# Convert to list for encoding
confidences_list = confidences.tolist()
# Validate consistency in lengths
num_objects = len(confidences_list)
if not all([
len(centers) == num_objects,
len(lengths) == num_objects,
len(is_vessel) == num_objects,
len(is_fishing) == num_objects,
]):
raise ValueError("Mismatch in number of objects across targets")
# Encode targets using string confidences
centernet_targets: MultilabelCircleNetEncodeResult = self.box_coder.encode(
centers=centers,
confidences=confidences_list,
lengths=lengths,
is_vessel=is_vessel,
is_fishing=is_fishing
)
# Convert encoded targets to PyTorch tensors
yolo_heatmap = torch.from_numpy(centernet_targets.heatmap).float()
yolo_is_vessel = torch.from_numpy(centernet_targets.is_vessel).float()
yolo_is_fishing = torch.from_numpy(centernet_targets.is_fishing).float()
yolo_length = torch.from_numpy(centernet_targets.lengths).float()
yolo_offset = torch.from_numpy(centernet_targets.offset).float()
# Convert other fields to tensors
centers_tensor = torch.from_numpy(centers.astype(np.float32)).float()
lengths_tensor = torch.tensor(lengths, dtype=torch.float32)
is_vessel_tensor = torch.tensor(is_vessel, dtype=torch.float32)
is_fishing_tensor = torch.tensor(is_fishing, dtype=torch.float32)
is_near_shore_tensor = torch.tensor(is_near_shore, dtype=torch.float32)
# Construct the result dictionary without INPUT_CONFIDENCE_KEY
result = {
INPUT_INDEX_KEY: index,
INPUT_IMAGE_KEY: image_to_tensor(image),
TARGET_CENTERS_KEY: centers_tensor, # [N, 2]
TARGET_VESSEL_KEY: is_vessel_tensor, # [N]
TARGET_FISHING_KEY: is_fishing_tensor, # [N]
TARGET_LENGTHS_KEY: lengths_tensor, # [N]
INPUT_IS_NEAR_SHORE_KEY: is_near_shore_tensor, # [N]
INPUT_LOCATION_ID_KEY: location,
INPUT_SCENE_ID_KEY: image_id,
TARGET_SAMPLE_WEIGHT: {
"train": 0.25,
"validation": 1.0,
"valid": 1.0,
"test": 0.1
}[folder],
}
if crop_coords is not None:
# Convert crop_coords to tensor
crop_coords_tensor = torch.tensor(crop_coords, dtype=torch.float32)
result[INPUT_SCENE_CROP_KEY] = crop_coords_tensor
# Add encoded target maps to the result
result[CENTERNET_TARGET_OBJECTNESS_MAP] = yolo_heatmap
result[CENTERNET_TARGET_VESSEL_MAP] = yolo_is_vessel
result[CENTERNET_TARGET_FISHING_MAP] = yolo_is_fishing
result[CENTERNET_TARGET_SIZE] = yolo_length
result[CENTERNET_TARGET_OFFSET] = yolo_offset
return result
#the error log
sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers % 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, 692.95it/s]
[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, 552.19it/s]
Train instances 13933 dataset 35 sampler 8192
Valid instances 3655 dataset 1039
[DEBUG] After adjustment, encoder.conv_stem.in_channels: 2
head_output_channels: 6
yolo_output_channels: 21
classifier_output_channels: 2
total_input_channels: 29
head_output_channels: 6
yolo_output_channels: 21
classifier_output_channels: 2
total_input_channels: 29
[DEBUG] model.box_coder after initialization: MultilabelCircleNetCoder(image_size=[768, 768], stride=1, max_objects=512, labels_encoding=circle, heatmap_encoding=umich, fixed_radius=None, ignore_index=-1, ignore_low_confidence_detections=False)
BoxCoder
MultilabelCircleNetCoder(image_size=[768, 768], stride=1, max_objects=512, labels_encoding=circle, heatmap_encoding=umich, fixed_radius=None, ignore_index=-1, ignore_low_confidence_detections=False)
DEBUG:rasterio.session:Could not import boto3, continuing with reduced functionality.
...
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x335636c40> created
DEBUG:rasterio._base:Nodata success: 1, Nodata value: -32768.000000
DEBUG:rasterio._base:Dataset is started.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x335636c40>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x335636cd0>
DEBUG:rasterio._io:Output nodata value read from file: -32768.0
DEBUG:rasterio._io:Output nodata values: [-32768.0]
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x333eb2be0>
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=14694, row_off=9082, width=512, height=512)
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x333eb2c10> options
DEBUG:rasterio._io:IO window xoff=14694.0 yoff=9082.0 width=512.0 height=512.0
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x333eb2c10>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x333eb2be0>
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x333eb2ca0>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x333eb2c10> created
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x333eb2c10>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x333eb2ca0>
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=23404, row_off=11820, width=512, height=512)
DEBUG:rasterio._io:IO window xoff=23404.0 yoff=11820.0 width=512.0 height=512.0
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x329345d60>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x329345cd0> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x329345cd0>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x329345d60>
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x33a501c70>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x33a501d00> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x33a501d00>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x33a501c70>
[DEBUG] Channel 0 shape: (512, 512)
[DEBUG] Channel 1 shape: (512, 512)
[DEBUG] Channel 0 shape: (512, 512)
(73.0, 407.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
[DEBUG] Channel 1 shape: (512, 512)
(259.0, 272.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(245.0, 273.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(144.0, 377.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(249.0, 271.0, 3.5621795654296875) [<class 'float'>, <class 'float'>, <class 'float'>]
(224.0, 166.0, 1.5832922458648682) [<class 'float'>, <class 'float'>, <class 'float'>]
[DEBUG] Build Sample - Confidences Type: <class 'numpy.ndarray'>
[DEBUG] Confidences Dtype: object
[DEBUG] Confidences Shape: (5,)
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x335636cd0>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x335636c40> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x335636c40>.
DEBUG:rasterio.env:Exiting outermost env
...
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x333eb2c10> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x333eb2c10>.
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:Exiting outermost env
[DEBUG] Channel 0 shape: (512, 512)
[DEBUG] Channel 1 shape: (512, 512)
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x32d681d90> created
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x333eb2ca0>
[DEBUG] Build Sample - Confidences Type: <class 'numpy.ndarray'>
[DEBUG] Confidences Dtype: object
[DEBUG] Confidences Shape: (1,)
DEBUG:rasterio._env:GDAL_DATA found in environment.
[DEBUG] Channel 0 shape: (512, 512)
[DEBUG] Channel 1 shape: (512, 512)
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x32d681d90>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x32d681610>
(168.0, 45.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(229.0, 264.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(238.0, 285.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(236.0, 271.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(244.0, 276.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(252.0, 281.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(175.0, 49.0, 1.8786169290542603) [<class 'float'>, <class 'float'>, <class 'float'>]
(183.0, 53.0, 1.8199727535247803) [<class 'float'>, <class 'float'>, <class 'float'>]
(190.0, 54.0, 2.3164262771606445) [<class 'float'>, <class 'float'>, <class 'float'>]
DEBUG:rasterio._base:Sharing flag: 0
(182.0, 36.0, 1.0649999380111694) [<class 'float'>, <class 'float'>, <class 'float'>]
(45.0, 333.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
(267.0, 241.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
Error executing job with overrides: ['+config=configs/multilabel_circle_net.yaml']
[DEBUG] Build Sample - Confidences Type: <class 'numpy.ndarray'>
[DEBUG] Confidences Dtype: object
[DEBUG] Confidences Shape: (2,)
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x33dcdca00>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x33dcdc2b0> created
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:PROJ_DATA found in environment.
...
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x33dcdc2b0>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x33dcdca00>
DEBUG:rasterio._base:Sharing flag: 0
[DEBUG] Build Sample - Confidences Type: <class 'numpy.ndarray'>
[DEBUG] Confidences Dtype: object
[DEBUG] Confidences Shape: (10,)
DEBUG:rasterio._base:Nodata success: 1, Nodata value: -32768.000000
DEBUG:rasterio._base:Dataset is started.
Traceback (most recent call last):
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 717, 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 713, in main
CenternetPipeline(cfg).train()
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 496, in train
model = self.build_model(config, self.loaders)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel.py", line 211, in build_model
logger.debug(f"Train loader sample: {next(iter(loaders['train']))}")
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 630, in next
data = self._next_data()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 1344, in _next_data
return self._process_data(data)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 1370, in _process_data
data.reraise()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/_utils.py", line 706, in reraise
raise exception
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/worker.py", line 309, in _worker_loop
data = fetcher.fetch(index) # type: ignore[possibly-undefined]
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 52, in
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/random_crop_dataset.py", line 191, in getitem
return self.build_sample(
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/multilabel_dataset.py", line 366, in build_sample
return self.build_centernet_sample(
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/multilabel_dataset.py", line 166, in build_centernet_sample
centernet_targets: MultilabelCircleNetEncodeResult = self.box_coder.encode(
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/bboxer/multilabel_circle_coder.py", line 153, in encode
confidences = rearrange(confidences, order, lengths)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/bboxer/multilabel_circle_coder.py", line 149, in rearrange
sorted_sub_arrays.append(subsampled_elements[order])
TypeError: only integer scalar arrays can be converted to a scalar index
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x32d681610>
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x339932d30>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x32d681d90> options
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x32d681d90>.
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x339932d00> created
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x32d681610>
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x329345d30>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x32d681d90> created
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x337651df0>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x337651250> created
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x339932d00>.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x339932d30>
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._base:Sharing flag: 0
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x32d681d90>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x329345d30>
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x337651250>.
DEBUG:rasterio._io:Output nodata value read from file: -32768.0
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x337651df0>
DEBUG:rasterio._base:Sharing flag: 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._base:Nodata success: 1, Nodata value: -32768.000000
DEBUG:rasterio._io:Window: Window(col_off=19067, row_off=19797, width=512, height=512)
DEBUG:rasterio._io:IO window xoff=19067.0 yoff=19797.0 width=512.0 height=512.0
DEBUG:rasterio._base:Dataset is started.
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x33dcdca00>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x33dcdc2b0> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x33dcdc2b0>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x33dcdca00>
DEBUG:rasterio.env:Entering env context: <rasterio.env.Env object at 0x33dcdc7f0>
DEBUG:rasterio.env:Starting outermost env
DEBUG:rasterio.env:No GDAL environment exists
DEBUG:rasterio.env:New GDAL environment <rasterio._env.GDALEnv object at 0x33dcdc2b0> created
DEBUG:rasterio._env:GDAL_DATA found in environment.
DEBUG:rasterio._env:PROJ_DATA found in environment.
DEBUG:rasterio._env:Started GDALEnv: self=<rasterio._env.GDALEnv object at 0x33dcdc2b0>.
DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x33dcdc7f0>
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=22205, row_off=10815, width=512, height=512)
DEBUG:rasterio._io:IO window xoff=22205.0 yoff=10815.0 width=512.0 height=512.0
(sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers %
The error you're encountering stems from a type mismatch in the handling of the confidences variable within your upgraded multilabel_dataset.py. Specifically, the confidences are being processed as strings (dtype=object), but the downstream box_coder.encode function expects them to be numerical values. This discrepancy leads to the TypeError: only integer scalar arrays can be converted to a scalar index.
Let's break down the issue, identify its root cause, and provide a comprehensive solution to resolve it.
1. Understanding the Error
Error Summary:
Error Message:
TypeError: only integer scalar arrays can be converted to a scalar index
Cause Location:
The error occurs in multilabel_circle_coder.py within the rearrange function:
Here, order is expected to be an integer or an array of integers used for indexing. However, it's receiving non-integer types (likely strings), leading to the TypeError.
Detailed Traceback:
Data Loading and Preparation:
train_multilabel.py initiates the training process.
In build_centernet_sample, confidences are being converted to strings.
Encoding Targets:
box_coder.encode is invoked with the modified confidences.
Inside box_coder.encode, the rearrange function is called, which fails due to incorrect indexing.
2. Identifying the Root Cause
Key Observations:
Modification in build_centernet_sample:
# Ensure confidences are strings and 1D
if isinstance(confidences, list):
confidences = np.array(confidences, dtype=str)
elif isinstance(confidences, np.ndarray):
if confidences.dtype.kind in {'U', 'S', 'O'}:
confidences = confidences.astype(str)
else:
raise ValueError(f"Confidences array should contain strings, but got dtype {confidences.dtype}")
# Reshape to 1D if necessary
if confidences.ndim == 1:
pass # Already 1D
elif confidences.ndim == 2 and confidences.shape[1] == 1:
confidences = confidences.reshape(-1)
else:
raise ValueError(f"Confidences should be 1D or 2D with single column, but got shape {confidences.shape}")
# Convert to list for encoding
confidences_list = confidences.tolist()
Here, order contains string values instead of integers, causing the TypeError.
Cause Analysis:
Type Conversion of confidences:
The upgraded code explicitly converts confidences to strings.
The box_coder.encode function likely expects numerical values (e.g., class indices or probabilities) for confidences, not strings.
Indexing Mismatch:
When box_coder.encode tries to use confidences as indices for array manipulation, the presence of strings leads to invalid indexing, triggering the TypeError.
3. Professional Solution
Step 1: Revert Unnecessary Type Conversion
Unless there's a compelling reason to handle confidences as strings (which is uncommon in numerical encoding for machine learning models), it's advisable to maintain confidences as numerical values. Here's how to adjust the code:
Modified build_centernet_sample:
def build_centernet_sample(
self,
image,
centers,
confidences, # Expected: List or 1D array of numerical values
lengths,
is_vessel,
is_fishing,
index,
image_id,
is_near_shore,
location,
folder: str,
crop_coords: Tuple[Tuple[int, int], Tuple[int, int]],
) -> Dict[str, Any]:
# Mask NaN values in the image
image[~np.isfinite(image)] = 0
# Debug: Examine confidences
print(f"[DEBUG] Build Sample - Confidences Type: {type(confidences)}")
if isinstance(confidences, np.ndarray):
print(f"[DEBUG] Confidences Dtype: {confidences.dtype}")
print(f"[DEBUG] Confidences Shape: {confidences.shape}")
else:
print(f"[DEBUG] Confidences: {confidences}")
# Remove or comment out the string conversion
# Ensure confidences are numerical and 1D
if isinstance(confidences, list):
confidences = np.array(confidences, dtype=float) # Use float or appropriate numerical dtype
elif isinstance(confidences, np.ndarray):
if confidences.dtype.kind in {'f', 'i'}: # 'f' for float, 'i' for integer
pass # Already numerical
else:
raise ValueError(f"Confidences array should contain numerical values, but got dtype {confidences.dtype}")
else:
raise TypeError(f"Unexpected type for confidences: {type(confidences)}")
# Reshape to 1D if necessary
if confidences.ndim == 1:
pass # Already 1D
elif confidences.ndim == 2 and confidences.shape[1] == 1:
confidences = confidences.reshape(-1)
else:
raise ValueError(f"Confidences should be 1D or 2D with single column, but got shape {confidences.shape}")
# Convert to list for encoding
confidences_list = confidences.tolist()
# Validate consistency in lengths
num_objects = len(confidences_list)
if not all([
len(centers) == num_objects,
len(lengths) == num_objects,
len(is_vessel) == num_objects,
len(is_fishing) == num_objects,
]):
raise ValueError("Mismatch in number of objects across targets")
# Encode targets using numerical confidences
centernet_targets: MultilabelCircleNetEncodeResult = self.box_coder.encode(
centers=centers,
confidences=confidences_list,
lengths=lengths,
is_vessel=is_vessel,
is_fishing=is_fishing
)
# Proceed with encoding as before...
Step 2: Ensure Consistent Data Types Across the Pipeline
Dataset Preparation:
Make sure that during dataset preparation, confidences are consistently treated as numerical values.
Avoid any transformations that may inadvertently convert numerical confidences to strings or object types.
Collate Function:
Verify that the centernet_collate function and any other collate-related transformations do not alter the data types of confidences.
Since INPUT_CONFIDENCE_KEY has been removed from skip_keys in the upgraded version, ensure that confidences are still correctly processed elsewhere.
Step 3: Update the centernet_collate Function if Necessary
If there's a specific reason to handle confidences differently in the collate function, ensure that it's done in a type-consistent manner.
Revised centernet_collate:
def centernet_collate(batch, channels_last=False):
skip_keys = [
TARGET_CENTERS_KEY,
TARGET_FISHING_KEY,
TARGET_VESSEL_KEY,
TARGET_LABELS_KEY,
TARGET_LENGTHS_KEY,
INPUT_SCENE_ID_KEY,
INPUT_SCENE_CROP_KEY,
# INPUT_CONFIDENCE_KEY, # Removed since confidences are handled internally
INPUT_LOCATION_ID_KEY,
INPUT_IS_NEAR_SHORE_KEY,
]
# Separate included and excluded items
included_items = [
{k: v for k, v in b.items() if k not in skip_keys}
for b in batch
]
excluded_items = {
k: [b[k] for b in batch if k in b]
for k in skip_keys
}
# Use default_collate for included items
batch_dict = default_collate(included_items)
# Process excluded items
for k, v in excluded_items.items():
# Find the max number of objects in the batch for this key
max_num = max([item.shape[0] for item in v])
padded = []
for item in v:
pad_size = max_num - item.shape[0]
if pad_size > 0:
if item.ndim == 1:
# Item is 1D: shape (N,)
pad = torch.zeros(pad_size, dtype=item.dtype)
padded_item = torch.cat([item, pad], dim=0)
elif item.ndim == 2:
# Item is 2D: shape (N, D)
pad = torch.zeros((pad_size, item.shape[1]), dtype=item.dtype)
padded_item = torch.cat([item, pad], dim=0)
else:
raise ValueError(f"Unsupported tensor shape: {item.shape}")
else:
# No padding needed
padded_item = item
padded.append(padded_item)
# Stack into a single tensor
batch_dict[k] = torch.stack(padded, dim=0)
# Handle channels_last if necessary
if channels_last and INPUT_IMAGE_KEY in batch_dict:
batch_dict[INPUT_IMAGE_KEY] = batch_dict[INPUT_IMAGE_KEY].to(memory_format=torch.channels_last)
return batch_dict
Note: Since INPUT_CONFIDENCE_KEY is removed, ensure that confidences are handled exclusively within build_centernet_sample and not expected elsewhere.
Step 4: Validate the Changes
Add Comprehensive Debugging:
Enhance debugging in build_centernet_sample to log the types and contents of all relevant variables, especially after significant transformations.
Example:
print(f"[DEBUG] Confidences List Type: {type(confidences_list)}")
print(f"[DEBUG] Confidences List Contents: {confidences_list}")
Run Unit Tests:
Create or update unit tests for build_centernet_sample and box_coder.encode to ensure they handle various input scenarios correctly.
Test cases should include:
Valid numerical confidences.
Empty confidences.
Mismatched lengths between confidences and other target arrays.
Monitor Batch Processing:
Ensure that during batch processing, all batches have confidences as numerical tensors without any object or string types.
Step 5: Review the Box Coder Implementation
Ensure that the MultilabelCircleNetCoder.encode function and any related utilities are designed to handle the numerical confidences appropriately.
Example of Expected Usage in encode:
class MultilabelCircleNetCoder:
def encode(self, centers, confidences, lengths, is_vessel, is_fishing):
# Ensure confidences are numerical
confidences = np.array(confidences, dtype=float)
# Proceed with encoding logic
order = np.argsort(confidences)[::-1] # Example: sorting by confidence
sampled_elements = centers[:self.max_objects]
# Ensure 'order' is numerical
sorted_sub_arrays = []
sorted_sub_arrays.append(sampled_elements[order])
# Continue encoding...
Key Points:
Numerical Operations: Ensure that confidences are used in numerical operations like sorting, thresholding, etc.
Indexing: When using confidences for indexing, they should be converted to integers if necessary or used as boolean masks.
4. Additional Recommendations
Data Integrity Checks:
Consistency Across Datasets:
Ensure that both training and validation datasets handle confidences consistently.
Check for any anomalies or inconsistencies in the dataset files that might introduce unexpected data types.
Documentation and Code Comments:
Maintain Clear Documentation:
Document the expected data types and shapes for each parameter in your dataset classes and functions.
Clearly state the purpose and expected format of confidences.
Modular Code Design:
Separation of Concerns:
Ensure that data preprocessing (like type conversions) is handled in dedicated functions or methods, making it easier to manage and debug.
Avoid embedding type conversions within data sample building unless absolutely necessary.
Error Handling:
Graceful Failures:
Implement try-except blocks where type conversions or critical operations happen to catch and log errors more gracefully.
Provide informative error messages to facilitate quicker debugging in the future.
5. Final Steps
After implementing the above changes:
Revert confidences to Numerical Types:
Ensure confidences are maintained as numerical values throughout the data pipeline.
Run the Training Script:
Execute train_multilabel.py again to verify that the TypeError is resolved.
Monitor the debug logs to confirm that confidences are correctly processed.
Verify Model Behavior:
After successful training initiation, monitor the model's performance to ensure that it is learning as expected.
By ensuring that confidences remain numerical throughout your data pipeline and are handled consistently by all components, you should be able to resolve the TypeError. This approach not only fixes the immediate issue but also reinforces the robustness and reliability of your data processing pipeline.
If you continue to encounter issues or if confidences must indeed be handled as strings for specific reasons, further adjustments to the box_coder.encode method and related components will be necessary to accommodate string-based operations. However, given the nature of machine learning models and encoding mechanisms, numerical confidences are typically the standard and recommended approach.
Feel free to reach out with more details or follow-up questions if the issue persists after applying these changes.