Add comprehensive debugging and tensor error handling

- Enhanced tensor shape verification with detailed logging
- Added failsafe tensor interpolation for shape mismatches
- Comprehensive error handling with fallback options
- Added reload_node.py script for development
- Created TROUBLESHOOTING.md with step-by-step fixes
- Detailed console output for debugging tensor issues
- Prevents crashes by returning single object as fallback
This commit is contained in:
Eduardo Ottone
2025-08-22 13:21:36 -07:00
parent c6176beaf5
commit e331af2a48
3 changed files with 145 additions and 2 deletions
+79
View File
@@ -0,0 +1,79 @@
# Troubleshooting Guide
## ❌ "Sizes of tensors must match" Error
If you're getting this error:
```
Error in object detection: Sizes of tensors must match except in dimension 0. Expected size 732 but got size 450 for tensor number 1 in the list.
```
### 🔧 Solution Steps:
#### 1. **Restart ComfyUI** (Most Important)
ComfyUI needs to be completely restarted to load updated custom nodes:
- Close ComfyUI completely
- Restart ComfyUI
- Load your workflow again
#### 2. **Update from GitHub**
Make sure you have the latest version:
```bash
cd ComfyUI/custom_nodes/ComfyUI_Detection_List
git pull origin main
```
#### 3. **Check Debug Output**
After restarting, you should see these debug messages in the console:
```
YOLOv8 Detection: Model inference complete
YOLOv8 Detection: Found X objects, resizing to (width, height)
Object 1 tensor shape: torch.Size([1, height, width, 3])
Object 2 tensor shape: torch.Size([1, height, width, 3])
Successfully created batch tensor with shape: torch.Size([X, height, width, 3])
```
If you **don't see these messages**, ComfyUI is still using the old version.
#### 4. **Manual Reload** (Alternative)
If restarting doesn't work, try:
```bash
cd ComfyUI/custom_nodes/ComfyUI_Detection_List
python reload_node.py
```
### 🎯 What Was Fixed:
- **Tensor Standardization**: All cropped objects are now resized to the same dimensions
- **Shape Verification**: Added checks to ensure all tensors match before concatenating
- **Fallback Handling**: If concatenation still fails, returns single object instead of crashing
- **Debug Logging**: Added detailed console output to track the process
### 🔍 Verification:
The node is working correctly when you see:
1. ✅ Objects detected (e.g., "1 person, 1 tie")
2. ✅ Debug messages showing tensor shapes
3. ✅ "Successfully created batch tensor" message
4. ✅ Multiple images output in the batch
### 🚫 Common Issues:
1. **Old Node Version**: ComfyUI not restarted after update
2. **Installation Issues**: Node not properly installed in custom_nodes folder
3. **Dependencies**: Missing ultralytics or torch packages
### 📞 Still Having Issues?
1. Check the [GitHub Issues](https://github.com/mangobyed/ComfyUI_Detection_List/issues)
2. Create a new issue with:
- ComfyUI console output
- Your workflow JSON
- Python/ComfyUI versions
- Full error message
### 💡 Pro Tips:
- Always restart ComfyUI after updating custom nodes
- Use lower confidence thresholds (0.1-0.3) to detect more objects
- Increase max_size parameter for higher quality crops
- Check console output for debug information
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""
Simple script to help reload the YOLOv8 detection node in ComfyUI
Run this script after making changes to the node code.
"""
import importlib
import sys
import os
def reload_node():
"""Attempt to reload the YOLOv8 detection node"""
try:
# Add current directory to Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
# Try to reload the module
module_name = 'yolov8_object_detection_node'
if module_name in sys.modules:
print(f"Reloading {module_name}...")
importlib.reload(sys.modules[module_name])
print("✅ Module reloaded successfully!")
else:
print(f"Module {module_name} not found in sys.modules")
print("Available modules:", [m for m in sys.modules.keys() if 'yolo' in m.lower()])
# Also try reloading the main init module
init_module = '__init__'
if init_module in sys.modules:
importlib.reload(sys.modules[init_module])
print("✅ Init module reloaded!")
except Exception as e:
print(f"❌ Error reloading module: {e}")
print("You may need to restart ComfyUI to load the updated node.")
if __name__ == "__main__":
print("🔄 Attempting to reload YOLOv8 detection node...")
reload_node()
print("\n📝 If this doesn't work, please restart ComfyUI completely.")
+24 -2
View File
@@ -189,12 +189,34 @@ class YOLOv8ObjectDetectionNode:
print(f"YOLOv8 Detection: Found {len(cropped_objects)} objects, resizing to {target_size}")
# Second pass: resize all objects to the same size and convert to tensors
for cropped_object in cropped_objects:
for i, cropped_object in enumerate(cropped_objects):
object_tensor = self.pil_to_tensor(cropped_object, target_size)
print(f"Object {i+1} tensor shape: {object_tensor.shape}")
detected_images.append(object_tensor)
# Verify all tensors have the same shape before concatenating
if len(detected_images) > 1:
first_shape = detected_images[0].shape
for i, tensor in enumerate(detected_images):
if tensor.shape != first_shape:
print(f"WARNING: Tensor {i} shape mismatch: {tensor.shape} vs expected {first_shape}")
# Force resize the tensor to match
detected_images[i] = torch.nn.functional.interpolate(
tensor.permute(0, 3, 1, 2),
size=(first_shape[1], first_shape[2]),
mode='bilinear',
align_corners=False
).permute(0, 2, 3, 1)
# Concatenate all detected objects into a batch
batch_tensor = torch.cat(detected_images, dim=0)
try:
batch_tensor = torch.cat(detected_images, dim=0)
print(f"Successfully created batch tensor with shape: {batch_tensor.shape}")
except Exception as cat_error:
print(f"Error concatenating tensors: {cat_error}")
# Fallback: return first detected object only
batch_tensor = detected_images[0]
print(f"Fallback: returning single object with shape: {batch_tensor.shape}")
class_names_str = ", ".join(class_names)
detection_info_str = "; ".join(detection_info_list)
object_count = len(detected_images)