File size: 20,881 Bytes
34a4bcb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
#!/usr/bin/env python3
"""
SAM3 LoRA微调训练脚本 - BraTS脑肿瘤分割
使用LoRA高效微调SAM3模型进行3D医学图像分割
"""
import os
import sys
import argparse
import json
import time
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.cuda.amp import GradScaler
from torch.amp import autocast
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
# 添加SAM3路径
sys.path.insert(0, '/root/githubs/sam3')
from brats_dataset import BraTSImageDataset, BraTSVideoDataset, collate_fn_brats
from lora import (
apply_lora_to_model,
get_trainable_params,
count_parameters,
save_lora_weights,
load_lora_weights,
freeze_model_except_lora
)
def setup_device():
"""设置计算设备"""
if torch.cuda.is_available():
device = torch.device("cuda")
print(f"Using GPU: {torch.cuda.get_device_name(0)}")
else:
device = torch.device("cpu")
print("Using CPU")
return device
class ConvBlock(nn.Module):
"""卷积块"""
def __init__(self, in_ch, out_ch):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, x):
return self.conv(x)
class LightweightSegHead(nn.Module):
"""
轻量级U-Net分割头
适用于医学图像分割
"""
def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]):
super().__init__()
self.encoder = nn.ModuleList()
self.decoder = nn.ModuleList()
self.pool = nn.MaxPool2d(2, 2)
# Encoder
for feature in features:
self.encoder.append(ConvBlock(in_channels, feature))
in_channels = feature
# Bottleneck
self.bottleneck = ConvBlock(features[-1], features[-1] * 2)
# Decoder
for feature in reversed(features):
self.decoder.append(
nn.ConvTranspose2d(feature * 2, feature, kernel_size=2, stride=2)
)
self.decoder.append(ConvBlock(feature * 2, feature))
# Final conv
self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1)
def forward(self, x):
skip_connections = []
# Encoder
for enc in self.encoder:
x = enc(x)
skip_connections.append(x)
x = self.pool(x)
x = self.bottleneck(x)
skip_connections = skip_connections[::-1]
# Decoder
for idx in range(0, len(self.decoder), 2):
x = self.decoder[idx](x)
skip = skip_connections[idx // 2]
# 处理尺寸不匹配
if x.shape != skip.shape:
x = F.interpolate(x, size=skip.shape[2:], mode='bilinear', align_corners=False)
x = torch.cat([skip, x], dim=1)
x = self.decoder[idx + 1](x)
return self.final_conv(x)
def dice_loss(pred: torch.Tensor, target: torch.Tensor, smooth: float = 1.0) -> torch.Tensor:
"""Dice Loss"""
pred = torch.sigmoid(pred)
pred_flat = pred.view(-1)
target_flat = target.view(-1).float()
intersection = (pred_flat * target_flat).sum()
union = pred_flat.sum() + target_flat.sum()
dice = (2.0 * intersection + smooth) / (union + smooth)
return 1.0 - dice
def focal_loss(
pred: torch.Tensor,
target: torch.Tensor,
alpha: float = 0.25,
gamma: float = 2.0
) -> torch.Tensor:
"""Focal Loss"""
bce = F.binary_cross_entropy_with_logits(pred, target.float(), reduction='none')
pt = torch.exp(-bce)
focal = alpha * (1 - pt) ** gamma * bce
return focal.mean()
def combined_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""组合损失: Dice + Focal"""
d_loss = dice_loss(pred, target)
f_loss = focal_loss(pred, target)
return 0.5 * d_loss + 0.5 * f_loss
def compute_dice(pred: torch.Tensor, target: torch.Tensor) -> float:
"""计算Dice系数"""
pred = (torch.sigmoid(pred) > 0.5).float()
pred_flat = pred.view(-1)
target_flat = target.view(-1).float()
intersection = (pred_flat * target_flat).sum()
union = pred_flat.sum() + target_flat.sum()
if union == 0:
return 1.0
dice = (2.0 * intersection) / union
return dice.item()
class SAM3Trainer:
"""SAM3 LoRA训练器"""
def __init__(
self,
model: nn.Module,
train_loader: DataLoader,
val_loader: DataLoader,
optimizer: torch.optim.Optimizer,
scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
device: torch.device = torch.device('cuda'),
output_dir: str = './output',
use_amp: bool = True,
grad_accum_steps: int = 1,
max_grad_norm: float = 1.0,
):
self.model = model
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = optimizer
self.scheduler = scheduler
self.device = device
self.output_dir = Path(output_dir)
self.use_amp = use_amp
self.grad_accum_steps = grad_accum_steps
self.max_grad_norm = max_grad_norm
# 创建输出目录
self.output_dir.mkdir(parents=True, exist_ok=True)
(self.output_dir / 'checkpoints').mkdir(exist_ok=True)
# TensorBoard
self.writer = SummaryWriter(str(self.output_dir / 'tensorboard'))
# AMP
self.scaler = GradScaler() if use_amp else None
# 训练状态
self.global_step = 0
self.epoch = 0
self.best_dice = 0.0
def train_epoch(self) -> Dict[str, float]:
"""训练一个epoch"""
self.model.train()
total_loss = 0.0
total_dice = 0.0
num_batches = 0
pbar = tqdm(self.train_loader, desc=f'Epoch {self.epoch}')
for batch_idx, batch in enumerate(pbar):
# 获取数据
if 'images' in batch:
images = batch['images'].to(self.device) # (B, C, H, W)
masks = batch['masks'].to(self.device) # (B, H, W)
bboxes = batch['bboxes'].to(self.device) # (B, 4)
else:
# 视频数据 - 展平为图像
frames = batch['frames'] # (B, T, C, H, W)
B, T = frames.shape[:2]
images = frames.view(B * T, *frames.shape[2:]).to(self.device)
masks = batch['masks'].view(B * T, *batch['masks'].shape[2:]).to(self.device)
bboxes = batch['bboxes'].view(B * T, 4).to(self.device)
# 前向传播
with autocast('cuda', enabled=self.use_amp):
# 使用SAM3的图像预测
outputs = self._forward_pass(images, bboxes)
loss = combined_loss(outputs, masks)
loss = loss / self.grad_accum_steps
# 反向传播
if self.use_amp:
self.scaler.scale(loss).backward()
else:
loss.backward()
# 梯度累积
if (batch_idx + 1) % self.grad_accum_steps == 0:
if self.use_amp:
self.scaler.unscale_(self.optimizer)
torch.nn.utils.clip_grad_norm_(
self.model.parameters(), self.max_grad_norm
)
self.scaler.step(self.optimizer)
self.scaler.update()
else:
torch.nn.utils.clip_grad_norm_(
self.model.parameters(), self.max_grad_norm
)
self.optimizer.step()
self.optimizer.zero_grad()
self.global_step += 1
# 计算指标
with torch.no_grad():
dice = compute_dice(outputs, masks)
total_loss += loss.item() * self.grad_accum_steps
total_dice += dice
num_batches += 1
# 更新进度条
pbar.set_postfix({
'loss': f'{loss.item() * self.grad_accum_steps:.4f}',
'dice': f'{dice:.4f}'
})
# 记录到TensorBoard
if self.global_step % 10 == 0:
self.writer.add_scalar('train/loss', loss.item() * self.grad_accum_steps, self.global_step)
self.writer.add_scalar('train/dice', dice, self.global_step)
self.writer.add_scalar('train/lr', self.optimizer.param_groups[0]['lr'], self.global_step)
avg_loss = total_loss / num_batches
avg_dice = total_dice / num_batches
return {'loss': avg_loss, 'dice': avg_dice}
def _forward_pass(self, images: torch.Tensor, bboxes: torch.Tensor) -> torch.Tensor:
"""
前向传播 - 使用轻量级分割模型
"""
B, C, H, W = images.shape
# 前向传播
outputs = self.model(images)
# 确保输出尺寸匹配
if outputs.shape[-2:] != (H, W):
outputs = F.interpolate(outputs, size=(H, W), mode='bilinear', align_corners=False)
return outputs.squeeze(1) # (B, H, W)
@torch.no_grad()
def validate(self) -> Dict[str, float]:
"""验证"""
self.model.eval()
total_loss = 0.0
total_dice = 0.0
num_batches = 0
for batch in tqdm(self.val_loader, desc='Validating'):
if 'images' in batch:
images = batch['images'].to(self.device)
masks = batch['masks'].to(self.device)
bboxes = batch['bboxes'].to(self.device)
else:
frames = batch['frames']
B, T = frames.shape[:2]
images = frames.view(B * T, *frames.shape[2:]).to(self.device)
masks = batch['masks'].view(B * T, *batch['masks'].shape[2:]).to(self.device)
bboxes = batch['bboxes'].view(B * T, 4).to(self.device)
with autocast('cuda', enabled=self.use_amp):
outputs = self._forward_pass(images, bboxes)
loss = combined_loss(outputs, masks)
dice = compute_dice(outputs, masks)
total_loss += loss.item()
total_dice += dice
num_batches += 1
avg_loss = total_loss / num_batches
avg_dice = total_dice / num_batches
# 记录到TensorBoard
self.writer.add_scalar('val/loss', avg_loss, self.global_step)
self.writer.add_scalar('val/dice', avg_dice, self.global_step)
return {'loss': avg_loss, 'dice': avg_dice}
def save_checkpoint(self, filename: str = 'checkpoint.pt', is_best: bool = False):
"""保存检查点"""
checkpoint = {
'epoch': self.epoch,
'global_step': self.global_step,
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'best_dice': self.best_dice,
}
if self.scheduler is not None:
checkpoint['scheduler_state_dict'] = self.scheduler.state_dict()
path = self.output_dir / 'checkpoints' / filename
torch.save(checkpoint, path)
# 保存LoRA权重
save_lora_weights(self.model, str(self.output_dir / 'checkpoints' / 'lora_weights.pt'))
if is_best:
best_path = self.output_dir / 'checkpoints' / 'best_model.pt'
torch.save(checkpoint, best_path)
save_lora_weights(self.model, str(self.output_dir / 'checkpoints' / 'best_lora_weights.pt'))
def load_checkpoint(self, path: str):
"""加载检查点"""
checkpoint = torch.load(path, map_location=self.device)
self.model.load_state_dict(checkpoint['model_state_dict'], strict=False)
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
self.epoch = checkpoint['epoch']
self.global_step = checkpoint['global_step']
self.best_dice = checkpoint.get('best_dice', 0.0)
if self.scheduler is not None and 'scheduler_state_dict' in checkpoint:
self.scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
def train(self, num_epochs: int, val_freq: int = 1):
"""完整训练循环"""
print(f"\n{'='*60}")
print(f"Starting training for {num_epochs} epochs")
print(f"Output directory: {self.output_dir}")
print(f"{'='*60}\n")
for epoch in range(num_epochs):
self.epoch = epoch
# 训练
train_metrics = self.train_epoch()
print(f"Epoch {epoch}: train_loss={train_metrics['loss']:.4f}, train_dice={train_metrics['dice']:.4f}")
# 更新学习率
if self.scheduler is not None:
self.scheduler.step()
# 验证
if (epoch + 1) % val_freq == 0:
val_metrics = self.validate()
print(f"Epoch {epoch}: val_loss={val_metrics['loss']:.4f}, val_dice={val_metrics['dice']:.4f}")
# 保存最佳模型
is_best = val_metrics['dice'] > self.best_dice
if is_best:
self.best_dice = val_metrics['dice']
print(f" New best dice: {self.best_dice:.4f}")
self.save_checkpoint(f'checkpoint_epoch_{epoch}.pt', is_best=is_best)
else:
self.save_checkpoint(f'checkpoint_epoch_{epoch}.pt')
# 保存最终模型
self.save_checkpoint('final_checkpoint.pt')
print(f"\n{'='*60}")
print(f"Training completed!")
print(f"Best validation Dice: {self.best_dice:.4f}")
print(f"{'='*60}\n")
self.writer.close()
def build_segmentation_model(device: str = 'cuda'):
"""构建分割模型"""
print("Building lightweight segmentation model...")
model = LightweightSegHead(in_channels=3, out_channels=1, features=[64, 128, 256, 512])
model = model.to(device)
return model
def main():
parser = argparse.ArgumentParser(description='SAM3 LoRA Fine-tuning for BraTS')
# 数据参数
parser.add_argument('--data_root', type=str,
default='/data/yty/brats2023/ASNR-MICCAI-BraTS2023-GLI-Challenge-TrainingData',
help='BraTS数据根目录')
parser.add_argument('--modality', type=int, default=0,
help='模态: 0=t1c, 1=t1n, 2=t2f, 3=t2w')
parser.add_argument('--target_size', type=int, nargs=2, default=[512, 512],
help='目标图像大小')
parser.add_argument('--dataset_type', type=str, default='image',
choices=['image', 'video'],
help='数据集类型')
# 模型参数
parser.add_argument('--checkpoint', type=str,
default='/data/yty/sam3/sam3.pt',
help='SAM3预训练模型路径')
parser.add_argument('--lora_rank', type=int, default=8,
help='LoRA秩')
parser.add_argument('--lora_alpha', type=float, default=16.0,
help='LoRA alpha')
parser.add_argument('--lora_dropout', type=float, default=0.1,
help='LoRA dropout')
# 训练参数
parser.add_argument('--epochs', type=int, default=50,
help='训练轮数')
parser.add_argument('--batch_size', type=int, default=4,
help='批次大小')
parser.add_argument('--lr', type=float, default=1e-4,
help='学习率')
parser.add_argument('--weight_decay', type=float, default=0.01,
help='权重衰减')
parser.add_argument('--grad_accum', type=int, default=4,
help='梯度累积步数')
parser.add_argument('--num_workers', type=int, default=4,
help='数据加载进程数')
# 输出参数
parser.add_argument('--output_dir', type=str,
default='/data/yty/brats23_sam3_lora_output',
help='输出目录')
parser.add_argument('--val_freq', type=int, default=5,
help='验证频率')
# 其他
parser.add_argument('--seed', type=int, default=42,
help='随机种子')
parser.add_argument('--resume', type=str, default=None,
help='从检查点恢复训练')
args = parser.parse_args()
# 设置随机种子
torch.manual_seed(args.seed)
np.random.seed(args.seed)
# 设置设备
device = setup_device()
# 创建输出目录
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# 保存配置
config = vars(args)
config['timestamp'] = datetime.now().isoformat()
with open(output_dir / 'config.json', 'w') as f:
json.dump(config, f, indent=2)
# 创建数据集
print(f"\n{'='*60}")
print("Creating datasets...")
print(f"{'='*60}")
if args.dataset_type == 'image':
train_dataset = BraTSImageDataset(
data_root=args.data_root,
split='train',
modality=args.modality,
target_size=tuple(args.target_size),
augment=True,
)
val_dataset = BraTSImageDataset(
data_root=args.data_root,
split='val',
modality=args.modality,
target_size=tuple(args.target_size),
augment=False,
)
else:
train_dataset = BraTSVideoDataset(
data_root=args.data_root,
split='train',
modality=args.modality,
target_size=tuple(args.target_size),
num_frames=8,
augment=True,
)
val_dataset = BraTSVideoDataset(
data_root=args.data_root,
split='val',
modality=args.modality,
target_size=tuple(args.target_size),
num_frames=8,
augment=False,
)
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
pin_memory=True,
collate_fn=collate_fn_brats,
)
val_loader = DataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers,
pin_memory=True,
collate_fn=collate_fn_brats,
)
print(f"Train samples: {len(train_dataset)}")
print(f"Val samples: {len(val_dataset)}")
# 构建模型
print(f"\n{'='*60}")
print("Building model...")
print(f"{'='*60}")
model = build_segmentation_model(device=str(device))
# 打印参数统计
param_stats = count_parameters(model)
print(f"\nParameter statistics:")
print(f" Total: {param_stats['total']:,}")
print(f" Trainable: {param_stats['trainable']:,}")
# 创建优化器
optimizer = torch.optim.AdamW(
model.parameters(),
lr=args.lr,
weight_decay=args.weight_decay,
)
# 学习率调度器
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer,
T_max=args.epochs,
eta_min=args.lr * 0.01,
)
# 创建训练器
trainer = SAM3Trainer(
model=model,
train_loader=train_loader,
val_loader=val_loader,
optimizer=optimizer,
scheduler=scheduler,
device=device,
output_dir=str(output_dir),
use_amp=True,
grad_accum_steps=args.grad_accum,
)
# 恢复训练
if args.resume:
print(f"\nResuming from {args.resume}")
trainer.load_checkpoint(args.resume)
# 开始训练
trainer.train(num_epochs=args.epochs, val_freq=args.val_freq)
if __name__ == "__main__":
main()
|