File size: 3,414 Bytes
01fdb75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()