DEBUG:rasterio.env:Entered env context: <rasterio.env.Env object at 0x316fec6d0>
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=6901, row_off=9339, width=512, height=512)
DEBUG:rasterio._io:IO window xoff=6901.0 yoff=9339.0 width=512.0 height=512.0
DEBUG:rasterio.env:Exiting env context: <rasterio.env.Env object at 0x316fec6d0>
DEBUG:rasterio.env:Cleared existing <rasterio._env.GDALEnv object at 0x3183b72b0> options
DEBUG:rasterio._env:Stopped GDALEnv <rasterio._env.GDALEnv object at 0x3183b72b0>.
DEBUG:rasterio.env:Exiting outermost env
DEBUG:rasterio.env:Exited env context: <rasterio.env.Env object at 0x316fec6d0>
[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:
(257.0, 263.0, 0.0) [<class 'float'>, <class 'float'>, <class 'float'>]
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 35, 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 35, 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 109, in evaluate_model
raise ValueError("Batch does not contain 'image/images' or 'targets/labels' keys.")
ValueError: Batch does not contain 'image/images' or 'targets/labels' keys.
(sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers %
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
here's full nas.py file as I think it's not fully correct
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from skopt import gp_minimize
from skopt.space import Real, Integer, Categorical
import random
import math
import copy
from torch import Tensor
from torch.optim import Adam
from torch.utils.data import DataLoader
from xview3.common import AdaptiveVesselDetectionModule
from xview3.centernet.bboxer.multilabel_circle_coder import MultilabelCircleNetCoder
The error you're encountering indicates that the batches from your train_loader or val_loader do not contain the keys 'image', 'images', 'targets', or 'labels', which your evaluate_model function expects. This mismatch often happens when the data loader is structured differently than your function assumes.
Here's how you can resolve this issue:
Inspect the Batch Structure:
First, use the debug statements you have in your evaluate_model function to print out the batch's structure. This will help you understand how to adjust your code to match the actual data format.
# Inside evaluate_model
print(f"[DEBUG] Batch type: {type(batch)}")
if isinstance(batch, dict):
print(f"[DEBUG] Batch keys: {list(batch.keys())}")
elif isinstance(batch, (list, tuple)):
print(f"[DEBUG] Batch length: {len(batch)}")
for i, item in enumerate(batch):
print(f"[DEBUG] Batch[{i}] type: {type(item)}")
else:
print("[DEBUG] Unrecognized batch format.")
Adjust the Key Extraction Logic:
Modify your key extraction logic in evaluate_model to accommodate the actual keys present in your batch. Here's how you can make your code more robust:
if isinstance(batch, dict):
# Possible keys that might contain input images
input_keys = ['image', 'images', 'input', 'inputs', 'data']
# Possible keys that might contain targets/labels
target_keys = ['targets', 'labels', 'target', 'label']
# Find the actual keys
inputs = next((batch[key] for key in input_keys if key in batch), None)
targets = next((batch[key] for key in target_keys if key in batch), None)
if inputs is None or targets is None:
raise ValueError(f"Batch does not contain expected keys. Batch keys: {list(batch.keys())}")
elif isinstance(batch, (list, tuple)):
if len(batch) >= 2:
inputs, targets = batch[0], batch[1]
else:
raise ValueError("Batch tuple does not have at least two elements (inputs and targets).")
else:
raise ValueError("Batch is in an unexpected format.")
Ensure Loss Function is Defined:
Your current code uses self.loss_fn, which hasn't been defined in your class. Replace self.loss_fn with your calculate_loss method or define self.loss_fn appropriately.
# Replace this line in evaluate_model
loss = self.loss_fn(outputs, targets)
# With this
loss = self.calculate_loss(outputs, targets)
Adapt the Loss Calculation:
Update your calculate_loss method to reflect the actual outputs and targets of your model. If your model outputs tensors directly and your targets are tensors, you might need a standard loss function like CrossEntropyLoss or MSELoss.
def calculate_loss(self, outputs, targets):
# Example with CrossEntropyLoss for classification tasks
loss_fn = nn.CrossEntropyLoss()
loss = loss_fn(outputs, targets)
return loss
Adjust this according to your specific task. For object detection or other tasks, you'll need an appropriate loss function.
Adjust Accuracy Calculation:
In evaluate_model, ensure that the method of calculating accuracy matches your task. For example, for multi-label classification, you might need a different approach.
# For multi-label classification or other tasks, adjust this part
_, predicted = outputs.max(1)
total_correct += predicted.eq(targets).sum().item()
If your task doesn't fit this simple classification paradigm, you'll need to calculate accuracy differently.
Verify Data Loader Output:
Make sure that your data loaders train_loader and val_loader are producing batches in the format your evaluate_model function expects. If not, you might need to adjust your dataset or data loader code.
Example of Adjusted evaluate_model Function:
Here's how your evaluate_model function might look after adjustments:
def evaluate_model(self, model, train_loader, val_loader):
model.eval()
total_loss = 0.0
total_correct = 0
total_samples = 0
with torch.no_grad():
for batch_idx, batch in enumerate(train_loader):
# Debug batch structure
print(f"[DEBUG] Batch index: {batch_idx}")
print(f"[DEBUG] Batch type: {type(batch)}")
if isinstance(batch, dict):
print(f"[DEBUG] Batch keys: {list(batch.keys())}")
# Extract inputs and targets
inputs = batch.get('inputs') or batch.get('images') or batch.get('image')
targets = batch.get('targets') or batch.get('labels') or batch.get('label')
if inputs is None or targets is None:
raise ValueError(f"Batch does not contain expected keys. Batch keys: {list(batch.keys())}")
elif isinstance(batch, (list, tuple)):
print(f"[DEBUG] Batch length: {len(batch)}")
if len(batch) >= 2:
inputs, targets = batch[0], batch[1]
else:
raise ValueError("Batch tuple does not have at least two elements (inputs and targets).")
else:
raise ValueError("Batch is in an unexpected format.")
# Proceed with evaluation as before
device = next(model.parameters()).device
inputs = inputs.to(device)
targets = targets.to(device)
outputs = model(inputs)
loss = self.calculate_loss(outputs, targets)
total_loss += loss.item() * inputs.size(0)
# Adjust accuracy calculation based on your task
# For example, for binary classification:
predicted = (outputs > 0.5).float()
total_correct += (predicted == targets).sum().item()
total_samples += inputs.size(0)
accuracy = total_correct / total_samples
return accuracy
Align with Your Task:
Since you mentioned you're working with SAR imagery and have parameters like 'heatmap_encoding' and 'labels_encoding', it's likely you're working on an object detection or segmentation task. Ensure that:
The loss function you use is appropriate for your task (e.g., FocalLoss, DiceLoss, etc.).
The way you calculate evaluation metrics corresponds to the task (e.g., IoU for segmentation, mAP for detection).
Review Your Data Pipeline:
Make sure that the dataset and data loaders are providing the data in the expected format. If you're using a custom dataset, check its __getitem__ method to see what it returns.
Consistent Naming in Code:
Ensure that variable names are consistent throughout your codebase. If your dataset returns 'input' and 'target', your evaluation code should look for these keys.
Test with a Single Batch:
Before running the full training loop, test your evaluation function with a single batch to ensure it works as expected.
By following these steps, you should be able to resolve the ValueError and adjust your evaluate_model function to correctly handle the batches from your data loaders. Remember to ensure that all components of your code (data loading, model, loss function, evaluation metrics) are aligned with your specific machine learning task.