import os
import numpy as np
import time
import copy
import random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from torchvision.datasets import OxfordIIITPet
import torchvision.transforms.functional as TF
import matplotlib.pyplot as plt
from PIL import Image
Check GPU availability
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
Using device: cuda
add Codeadd Markdown
Custom Dataset Class
class PetDataset(Dataset):
def init(self, root, transform=None, target_transform=None):
self.dataset = OxfordIIITPet(root=root, download=True, target_types='segmentation')
self.transform = transform
self.target_transform = target_transform
def len(self):
return len(self.dataset)
def getitem(self, idx):
# Unpack only two elements: image and mask
image, mask = self.dataset[idx]
# Convert mask to binary: pet vs. background
mask = np.array(mask)
# In Oxford-IIIT Pet Dataset:
# Pixel values:
# 1 = foreground (pet)
# 2 = background
# 3 = boundary
# We'll convert all non-pet pixels to background for binary segmentation
mask = np.where(mask == 1, 1, 0).astype(np.float32)
mask = Image.fromarray(mask)
if self.transform:
image = self.transform(image)
if self.target_transform:
mask = self.target_transform(mask)
Update Transforms for Validation Dataset (No Augmentations)
val_dataset.dataset.transform = val_transforms
Define DataLoaders with Reduced Batch Size
batch_size = 2 # Reduced from 8 to 2 to save memory
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=2, pin_memory=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True)
print(f"Number of training samples: {len(train_dataset)}")
print(f"Number of validation samples: {len(val_dataset)}")
Number of training samples: 2944
Number of validation samples: 736
add Codeadd Markdown
CBAM (Convolutional Block Attention Module)
class CBAM(nn.Module):
def init(self, channels, reduction=16, kernel_size=7):
super(CBAM, self).init()
# Channel Attention Module
self.channel_attention = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(channels, channels // reduction, 1, bias=False),
nn.ReLU(),
nn.Conv2d(channels // reduction, channels, 1, bias=False),
nn.Sigmoid()
)
# Spatial Attention Module
self.spatial_attention = nn.Sequential(
nn.Conv2d(2, 1, kernel_size=kernel_size, padding=kernel_size//2, bias=False),
nn.Sigmoid()
)
def forward(self, x):
# Channel Attention
ca = self.channel_attention(x)
x = x * ca
# Spatial Attention
max_pool, avg_pool = torch.max(x, dim=1, keepdim=True)[0], torch.mean(x, dim=1, keepdim=True)
sa = self.spatial_attention(torch.cat([max_pool, avg_pool], dim=1))
x = x * sa
return x
Self-Attention Module
class SelfAttention(nn.Module):
def init(self, in_dim):
super(SelfAttention, self).init()
self.channel_in = in_dim
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
"""
inputs:
x: input feature maps (B X C X W X H)
returns:
out: self attention value + input feature
attention: B X N X N (N = WH)
"""
m_batchsize, C, width, height = x.size()
proj_query = self.query_conv(x).view(m_batchsize, -1, widthheight).permute(0, 2, 1) # B X (WH) X C'
proj_key = self.key_conv(x).view(m_batchsize, -1, widthheight) # B X C' X (WH)
energy = torch.bmm(proj_query, proj_key) # B X (WH) X (WH)
attention = self.softmax(energy) # B X (WH) X (WH)
proj_value = self.value_conv(x).view(m_batchsize, -1, widthheight) # B X C X (WH)
out = torch.bmm(proj_value, attention.permute(0, 2, 1)) # B X C X (WH)
out = out.view(m_batchsize, C, width, height)
out = self.gamma * out + x
return out
add Codeadd Markdown
The error you’re encountering is due to an update in the torch.cuda.amp.autocast API. In recent versions of PyTorch, the autocast context manager now requires a device_type argument to specify whether you're using 'cuda' or 'cpu'. This change ensures that the mixed-precision operations are correctly applied based on the device type.
Here’s how you can resolve the TypeError and ensure your training loop works correctly:
1. Update the autocast Context Manager
Current Code with Error:
with autocast():
outputs = model(inputs)
loss = criterion(outputs, masks)
dice = dice_coefficient(outputs, masks)
Updated Code:
You need to specify the device_type by passing device.type, which dynamically sets it based on whether you're using GPU ('cuda') or CPU ('cpu').
with autocast(device_type=device.type):
outputs = model(inputs)
loss = criterion(outputs, masks)
dice = dice_coefficient(outputs, masks)
This change ensures that autocast is aware of the device you’re operating on and applies mixed precision accordingly.
2. Full train_model Function with Fix Applied
Here’s the complete train_model function with the necessary modification to the autocast context manager:
from torch.amp import autocast, GradScaler # Ensure these imports are present
def train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, num_epochs=50, patience=10, checkpoint_path='checkpoint.pth.tar'):
start_epoch = 0
best_model_wts = copy.deepcopy(model.state_dict())
best_loss = float('inf')
# Initialize Early Stopping
early_stopping = EarlyStopping(patience=patience, verbose=True)
# Initialize GradScaler for Mixed Precision Training
scaler = GradScaler()
# Check if checkpoint exists
if os.path.exists(checkpoint_path):
print("Loading checkpoint...")
checkpoint = torch.load(checkpoint_path, map_location=device)
start_epoch, best_loss_loaded = load_checkpoint(checkpoint, model, optimizer)
best_loss = best_loss_loaded
print(f"Resuming from epoch {start_epoch+1}")
for epoch in range(start_epoch, num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train()
dataloader = train_loader
else:
model.eval()
dataloader = val_loader
running_loss = 0.0
running_dice = 0.0
# Iterate over data
for inputs, masks in dataloader:
inputs = inputs.to(device, non_blocking=True)
masks = masks.to(device, non_blocking=True)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward with mixed precision
with autocast(device_type=device.type): # Updated line
outputs = model(inputs)
loss = criterion(outputs, masks)
dice = dice_coefficient(outputs, masks)
# Backward + optimize only if in training phase
if phase == 'train':
scaler.scale(loss).backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
running_loss += loss.item() * inputs.size(0)
running_dice += dice.item() * inputs.size(0)
epoch_loss = running_loss / len(dataloader.dataset)
epoch_dice = running_dice / len(dataloader.dataset)
print(f'{phase.capitalize()} Loss: {epoch_loss:.4f} Dice: {epoch_dice:.4f}')
# Deep copy the model
if phase == 'val':
scheduler.step(epoch_loss)
if epoch_loss < best_loss:
best_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
# Early Stopping
early_stopping(epoch_loss)
save_checkpoint({
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer' : optimizer.state_dict(),
'best_loss': best_loss
}, filename=checkpoint_path)
if early_stopping.early_stop:
print("Early stopping triggered!")
model.load_state_dict(best_model_wts)
return model
print()
# Load best model weights
model.load_state_dict(best_model_wts)
return model
3. Additional Recommendations
a. Verify Your PyTorch Version
Ensure that you're using a PyTorch version that supports the updated autocast API. You can check your PyTorch version using:
import torch
print(torch.__version__)
If you're not using the latest version, consider updating PyTorch:
pip install --upgrade torch torchvision
b. Dynamic Device Type Handling
To make the device_type assignment more robust, especially if you plan to run the code on both CPU and GPU, you can modify it as follows:
device_type = 'cuda' if torch.cuda.is_available() else 'cpu'
with autocast(device_type=device_type):
outputs = model(inputs)
loss = criterion(outputs, masks)
dice = dice_coefficient(outputs, masks)
Make sure to replace device.type with device_type if you choose this approach.
c. Full Training Script with the Fix
For clarity, here is the complete section of the training script incorporating the fix:
from torch.amp import autocast, GradScaler # Ensure these imports are present
def train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, num_epochs=50, patience=10, checkpoint_path='checkpoint.pth.tar'):
# ... [previous setup code remains unchanged] ...
for epoch in range(start_epoch, num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train()
dataloader = train_loader
else:
model.eval()
dataloader = val_loader
running_loss = 0.0
running_dice = 0.0
# Iterate over data
for inputs, masks in dataloader:
inputs = inputs.to(device, non_blocking=True)
masks = masks.to(device, non_blocking=True)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward with mixed precision
with autocast(device_type=device.type): # Updated here
outputs = model(inputs)
loss = criterion(outputs, masks)
dice = dice_coefficient(outputs, masks)
# Backward + optimize only if in training phase
if phase == 'train':
scaler.scale(loss).backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
running_loss += loss.item() * inputs.size(0)
running_dice += dice.item() * inputs.size(0)
epoch_loss = running_loss / len(dataloader.dataset)
epoch_dice = running_dice / len(dataloader.dataset)
print(f'{phase.capitalize()} Loss: {epoch_loss:.4f} Dice: {epoch_dice:.4f}')
# Deep copy the model
if phase == 'val':
scheduler.step(epoch_loss)
if epoch_loss < best_loss:
best_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
# Early Stopping
early_stopping(epoch_loss)
save_checkpoint({
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer' : optimizer.state_dict(),
'best_loss': best_loss
}, filename=checkpoint_path)
if early_stopping.early_stop:
print("Early stopping triggered!")
model.load_state_dict(best_model_wts)
return model
print()
# Load best model weights
model.load_state_dict(best_model_wts)
return model
4. Proceed with Training
After making the above changes, you can proceed to train your model:
# Initialize the U3Net Model with Reduced Features
model = U3Net(in_channels=3, out_channels=1, features=[32, 64, 128]).to(device)
# Define Loss Function and Optimizer
criterion = DiceLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-4, weight_decay=1e-5) # Added weight_decay for regularization
# Define Learning Rate Scheduler
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5)
# Define Training Parameters
num_epochs = 50
patience = 10
checkpoint_path = 'u3net_checkpoint.pth.tar'
# Start Training
trained_model = train_model(model, train_loader, val_loader, criterion, optimizer, scheduler,
num_epochs=num_epochs, patience=patience, checkpoint_path=checkpoint_path)
# Save the Best Model Weights
torch.save(trained_model.state_dict(), 'u3net_best_model.pth')
print("Training complete. Best model saved as 'u3net_best_model.pth'")
5. Final Notes
Mixed Precision Training: Utilizing mixed precision (autocast and GradScaler) can significantly speed up training and reduce GPU memory usage. However, ensure that your GPU supports mixed precision (most modern NVIDIA GPUs do).
Gradient Clipping: You've implemented gradient clipping (torch.nn.utils.clip_grad_norm_) which is beneficial for stabilizing training, especially in deep networks.
Early Stopping: This helps in preventing overfitting by stopping the training process once the validation loss stops improving.
Checkpointing: Regularly saving checkpoints allows you to resume training in case of interruptions and also keeps the best-performing model based on validation loss.
By applying the above fix and ensuring your environment is correctly set up, your training process should proceed without the TypeError related to autocast.