##I've applied precisely your suggestions , I want to remind you that my model uses input images TIFF SAR VV+VH and train, validation csv labels to detect vessels and If fishing or not
it uses CenterNetUNet model and I'm integrating with it YOLO, NAS, FAN, FBN, Swin transformer , Optuna let's just focus on the error rise from the integration of yolo
DEBUG:rasterio._base:Sharing flag: 0
Traceback (most recent call last):
File "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel3.py", line 934, 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 "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel3.py", line 930, in main
pipeline.train()
File "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel3.py", line 647, in train
train_loader, valid_loader, _, dataset_callbacks = self.build_datasets(config)
File "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel3.py", line 311, in build_datasets
sample_batch = next(iter(train_loader))
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
UnboundLocalError: Caught UnboundLocalError 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 "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/random_crop_dataset.py", line 191, in
return self.build_sample(
File "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/multilabel_dataset.py", line 339, in build_sample
return self.build_centernet_sample(
File "/Volumes/Crucial/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/centernet/multilabel_dataset.py", line 141, in build_centernet_sample
yolo_targets = centernet_targets.yolo_targets
UnboundLocalError: local variable 'centernet_targets' referenced before assignment
here's my original reference multilabel_dataset followed by my upgraded multilabel dataset to find and fix the errors
##original
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
import os
from functools import partial
from typing import List, Tuple, Optional, Callable, Dict, Any, Union
from xview3.centernet.models.heads.yolo_head import generate_yolo_targets
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from torch import nn
from omegaconf import DictConfig
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 omegaconf import OmegaConf
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
excluded_items = {k: [] for k in skip_keys}
included_items = []
for b in batch:
included = {k: v for k, v in b.items() if k not in skip_keys and v is not None}
included_items.append(included)
for k in skip_keys:
if k in b:
excluded_items[k].append(b[k])
# Use default_collate for included items (numerical tensors)
batch_dict = default_collate(included_items)
for k in skip_keys:
if k == CENTERNET_TARGET_YOLO:
# Handle CENTERNET_TARGET_YOLO appropriately
# For example, you might want to stack the tensors
batch_dict[CENTERNET_TARGET_YOLO] = torch.stack(excluded_items[CENTERNET_TARGET_YOLO])
else:
batch_dict[k] = excluded_items[k]
# 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 __init__(
self,
stride=32,
confidence_mapping=None,
vessel_mapping=None,
fishing_mapping=None,
ignore_value=-1,
):
self.stride = stride
self.confidence_mapping = {
'NONE': 0.0,
'LOW': 0.33,
'MEDIUM': 0.66,
'HIGH': 1.0,
}
self.vessel_mapping = vessel_mapping or {0: 0, 1: 1}
self.fishing_mapping = fishing_mapping or {0: 0, 1: 1}
self.ignore_value = ignore_value
def build_centernet_sample(
self,
image,
centers,
confidences,
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
image[~np.isfinite(image)] = 0
box_coder = self.box_coder.create_box_coder_for_image_size(image.shape[:2])
# Convert numerical fields to NumPy arrays with explicit dtypes
centers_np = np.array(centers, dtype=np.float32)
lengths_np = np.array(lengths, dtype=np.float32)
# Ensure 'is_vessel' and 'is_fishing' are the correct data type (strings or numerical labels)
# Adjust accordingly
# Keep 'is_vessel' and 'is_fishing' as lists of strings
is_vessel_list = is_vessel # List of strings
is_fishing_list = is_fishing # List of strings
is_near_shore_np = np.array(is_near_shore, dtype=np.float32)
yolo_targets = centernet_targets.yolo_targets
if yolo_targets is None:
# Initialize yolo_targets appropriately, e.g., with zeros
yolo_targets = torch.zeros((1, grid_height, grid_width, num_channels)) # Adjust dimensions as needed
# Validate consistency in lengths
num_objects = len(centers_np)
if not all([
len(confidences) == num_objects,
len(lengths_np) == num_objects,
len(is_vessel_list) == num_objects,
len(is_fishing_list) == num_objects,
]):
raise ValueError("Mismatch in number of objects across targets")
result = {
INPUT_INDEX_KEY: index,
INPUT_IMAGE_KEY: image_to_tensor(image),
TARGET_CENTERS_KEY: torch.from_numpy(centers_np),
TARGET_VESSEL_KEY: is_vessel_list, # Keep as is if they are strings
TARGET_FISHING_KEY: is_fishing_list, # Keep as is if they are strings
TARGET_LENGTHS_KEY: torch.from_numpy(lengths_np),
INPUT_CONFIDENCE_KEY: confidences, # Keep as list of strings
INPUT_IS_NEAR_SHORE_KEY: torch.from_numpy(is_near_shore_np),
INPUT_LOCATION_ID_KEY: location,
INPUT_FOLDER_KEY: folder,
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:
result[INPUT_SCENE_CROP_KEY] = crop_coords
# Encode targets using the box coder
centernet_targets: MultilabelCircleNetEncodeResult = box_coder.encode(
centers=centers_np,
confidences=confidences,
lengths=lengths_np,
is_vessel=is_vessel_list,
is_fishing=is_fishing_list,
)
# Extract and assign the targets
result[CENTERNET_TARGET_OBJECTNESS_MAP] = torch.from_numpy(centernet_targets.heatmap).float()
result[CENTERNET_TARGET_VESSEL_MAP] = torch.from_numpy(centernet_targets.is_vessel).float()
result[CENTERNET_TARGET_FISHING_MAP] = torch.from_numpy(centernet_targets.is_fishing).float()
result[CENTERNET_TARGET_SIZE] = torch.from_numpy(centernet_targets.lengths).float()
result[CENTERNET_TARGET_OFFSET] = torch.from_numpy(centernet_targets.offset).float()
result[CENTERNET_TARGET_YOLO] = centernet_targets.yolo_targets # Already a torch.Tensor (from coder)
sample_weight_dict = {"train": 0.25, "validation": 1.0, "valid": 1.0, "test": 0.1}
result[TARGET_SAMPLE_WEIGHT] = sample_weight_dict.get(folder, 1.0) # Default to 1.0 if folder is not found
for key, value in result.items():
if value is None:
print(f"Warning: Key '{key}' has a None value in result for index {index}")
return result
The error you're encountering, UnboundLocalError: local variable 'centernet_targets' referenced before assignment, arises because the variable centernet_targets is being used before it has been assigned a value. This is likely due to an issue with the initialization and assignment of self.box_coder in your class hierarchy after integrating YOLO.
Here's the issue: In your upgraded MultilabelCircleNetTargetsMixin, you've introduced an __init__ method that doesn't set self.box_coder. Moreover, this __init__ method is overriding the base class's __init__ without calling super().__init__(), which means any initialization in the base classes (like setting self.box_coder) isn't happening.
In Python, when a subclass defines its own __init__ method, it needs to explicitly call the __init__ method of its parent class if it wants to ensure proper initialization. Since self.box_coder is crucial for encoding the targets and it's not being set, when you call box_coder.encode(), it fails to assign centernet_targets, leading to the UnboundLocalError when you try to access it.
Solution:
To fix this error, you need to ensure that self.box_coder is properly initialized. There are a couple of ways to achieve this:
Remove the __init__ method from MultilabelCircleNetTargetsMixin:
Since MultilabelCircleNetTargetsMixin is a mixin class that provides methods but shouldn't interfere with the initialization chain, you should remove the __init__ method from it. This way, the initialization of self.box_coder in the subclasses will proceed correctly.
# Remove __init__ method from MultilabelCircleNetTargetsMixin
class MultilabelCircleNetTargetsMixin:
box_coder: MultilabelCircleNetCoder
# Remove this __init__ method
# def __init__(self, stride=32, confidence_mapping=None, vessel_mapping=None, fishing_mapping=None, ignore_value=-1):
# # Initialization code
Ensure Proper Initialization in the Subclasses:
If you need to keep the __init__ method in MultilabelCircleNetTargetsMixin (e.g., to set mapping dictionaries), you must make sure to call super().__init__() so that the initialization chain is maintained, and self.box_coder is set.
Then, ensure that when you initialize your dataset classes, you're passing the necessary arguments, and the __init__ methods are properly chaining.
Recommendation:
Given that mixin classes typically don't have an __init__ method (unless absolutely necessary), and to keep things simple, it's best to remove the __init__ method from the MultilabelCircleNetTargetsMixin. This will allow the initialization in your dataset classes to proceed as expected, ensuring that self.box_coder is properly set, and that box_coder.encode() can be called without issues.
Revised Code Snippet:
# Remove __init__ method from MultilabelCircleNetTargetsMixin
class MultilabelCircleNetTargetsMixin:
box_coder: MultilabelCircleNetCoder
# Do not define an __init__ method
def build_centernet_sample(
self,
image,
centers,
confidences,
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]:
# ... rest of your method ...
By making this change, self.box_coder will be correctly initialized in your dataset classes (MultilabelCircleNetFixedCropDataset, MultilabelCircleNetRandomCropDataset, etc.), and your build_centernet_sample method will have access to a valid box_coder, preventing the UnboundLocalError.