Segmentation / code /scripts /test_medical_training.py
MaybeRichard's picture
Upload PixelGen code: cross-attention mask mode + multi-scale ablation configs
01fdb75 verified
raw
history blame
3.41 kB
#!/usr/bin/env python
"""
Quick test script for medical image training pipeline.
Runs a few steps to verify everything works.
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
# Test imports
print("Testing imports...")
from src.data.dataset.octa500 import OCTA500Dataset
from src.models.transformer.JiT_medical import JiTMedical_B_16
from src.diffusion.flow_matching.scheduling import LinearScheduler
import lpips
print("All imports successful!")
# Configuration
DATA_ROOT = "/data2/sichengli/Data/test/Segmentation/OCTA500"
BATCH_SIZE = 4
NUM_STEPS = 5
DEVICE = "cuda:0"
def main():
print("\n=== Testing Medical Image Training Pipeline ===\n")
# 1. Test dataset
print("1. Loading dataset...")
dataset = OCTA500Dataset(DATA_ROOT, resolution=256, split='train', max_samples=100)
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
print(f" Dataset size: {len(dataset)}")
# Get a batch
batch = next(iter(dataloader))
images, labels, metadata = batch
masks = metadata['mask']
raw_images = metadata['raw_image']
print(f" Images shape: {images.shape}, range: [{images.min():.2f}, {images.max():.2f}]")
print(f" Masks shape: {masks.shape}, range: [{masks.min():.2f}, {masks.max():.2f}]")
print(f" Raw images shape: {raw_images.shape}")
# 2. Test model
print("\n2. Creating model...")
model = JiTMedical_B_16(input_size=256, num_classes=1).to(DEVICE)
print(f" Model parameters: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")
# 3. Test LPIPS
print("\n3. Loading LPIPS...")
lpips_fn = lpips.LPIPS(net='vgg').to(DEVICE).eval()
print(" LPIPS loaded!")
# 4. Test scheduler
print("\n4. Creating scheduler...")
scheduler = LinearScheduler()
# 5. Test training step
print("\n5. Testing training steps...")
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
for step in range(NUM_STEPS):
# Get batch
images, labels, metadata = next(iter(dataloader))
images = images.to(DEVICE)
masks = metadata['mask'].to(DEVICE)
labels = labels.to(DEVICE)
# Sample timesteps
batch_size = images.shape[0]
t = torch.rand(batch_size, device=DEVICE)
# Add noise
noise = torch.randn_like(images)
alpha = scheduler.alpha(t)
sigma = scheduler.sigma(t)
x_t = alpha * images + noise * sigma
# Forward pass
pred = model(x_t, t, labels, mask=masks)
# Compute losses
v_t = (images - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(0.05)
pred_v = (pred - x_t) / (1 - t.view(-1, 1, 1, 1)).clamp_min(0.05)
fm_loss = ((pred_v - v_t) ** 2).mean()
lpips_loss = lpips_fn(pred, images).mean()
loss = fm_loss + 0.1 * lpips_loss
# Backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f" Step {step+1}/{NUM_STEPS}: fm_loss={fm_loss.item():.4f}, lpips_loss={lpips_loss.item():.4f}, total={loss.item():.4f}")
print("\n=== All tests PASSED! ===")
print("\nReady for full training with:")
print(" python main.py fit -c ./configs_medical/PixelGen_Medical_B16.yaml")
if __name__ == "__main__":
main()