2019-10-24 19:37:21 +00:00
|
|
|
import argparse
|
|
|
|
import logging
|
2021-08-16 00:53:00 +00:00
|
|
|
from pathlib import Path
|
2018-04-09 03:15:24 +00:00
|
|
|
|
2022-06-28 07:36:21 +00:00
|
|
|
import albumentations as A
|
2017-08-17 19:16:19 +00:00
|
|
|
import torch
|
2017-08-19 08:59:51 +00:00
|
|
|
import torch.nn as nn
|
2021-08-16 00:53:00 +00:00
|
|
|
import torch.nn.functional as F
|
2022-06-28 07:36:21 +00:00
|
|
|
from albumentations.pytorch import ToTensorV2
|
2018-04-09 03:15:24 +00:00
|
|
|
from torch import optim
|
2022-06-28 07:36:21 +00:00
|
|
|
from torch.utils.data import DataLoader
|
2019-10-24 19:37:21 +00:00
|
|
|
from tqdm import tqdm
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2022-06-28 07:36:21 +00:00
|
|
|
import wandb
|
2021-08-16 00:53:00 +00:00
|
|
|
from evaluate import evaluate
|
2022-06-28 07:36:21 +00:00
|
|
|
from src.utils.dataset import SphereDataset
|
2022-06-27 14:41:03 +00:00
|
|
|
from src.utils.dice import dice_loss
|
2022-06-28 07:36:21 +00:00
|
|
|
from unet import UNet
|
|
|
|
from utils.paste import RandomPaste
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2022-06-28 07:36:21 +00:00
|
|
|
CHECKPOINT_DIR = Path("./checkpoints/")
|
|
|
|
DIR_TRAIN_IMG = Path("/home/lilian/data_disk/lfainsin/train2017")
|
|
|
|
DIR_VALID_IMG = Path("/home/lilian/data_disk/lfainsin/val2017/")
|
|
|
|
# DIR_VALID_MASK = Path("/home/lilian/data_disk/lfainsin/val2017mask/")
|
|
|
|
DIR_SPHERE_IMG = Path("/home/lilian/data_disk/lfainsin/spheres/Images/")
|
|
|
|
DIR_SPHERE_MASK = Path("/home/lilian/data_disk/lfainsin/spheres/Masks/")
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
def train_net(
|
|
|
|
net,
|
|
|
|
device,
|
|
|
|
epochs: int = 5,
|
|
|
|
batch_size: int = 1,
|
|
|
|
learning_rate: float = 1e-5,
|
|
|
|
save_checkpoint: bool = True,
|
|
|
|
amp: bool = False,
|
|
|
|
):
|
2022-06-28 07:36:21 +00:00
|
|
|
# 1. Create transforms
|
|
|
|
tf_train = A.Compose(
|
|
|
|
[
|
|
|
|
A.Flip(),
|
|
|
|
A.ColorJitter(),
|
|
|
|
RandomPaste(5, 0.2, DIR_SPHERE_IMG, DIR_SPHERE_MASK),
|
|
|
|
A.ISONoise(),
|
|
|
|
A.ToFloat(max_value=255),
|
|
|
|
A.pytorch.ToTensorV2(),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
|
|
|
|
tf_valid = A.Compose(
|
|
|
|
[
|
|
|
|
RandomPaste(5, 0.2, DIR_SPHERE_IMG, DIR_SPHERE_MASK),
|
|
|
|
A.ToFloat(max_value=255),
|
|
|
|
ToTensorV2(),
|
|
|
|
],
|
|
|
|
)
|
2021-08-16 00:53:00 +00:00
|
|
|
|
2022-06-28 07:36:21 +00:00
|
|
|
# 2. Create datasets
|
|
|
|
ds_train = SphereDataset(images_dir=DIR_TRAIN_IMG, transform=tf_train)
|
|
|
|
# ds_valid = SphereDataset(images_dir=DIR_VALID_IMG, masks_dir=DIR_VALID_MASK, transform=tf_valid)
|
|
|
|
ds_valid = SphereDataset(images_dir=DIR_VALID_IMG, transform=tf_valid)
|
2019-11-23 16:56:14 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
# 3. Create data loaders
|
|
|
|
loader_args = dict(batch_size=batch_size, num_workers=4, pin_memory=True)
|
2022-06-28 07:36:21 +00:00
|
|
|
train_loader = DataLoader(ds_train, shuffle=True, **loader_args)
|
|
|
|
val_loader = DataLoader(ds_valid, shuffle=False, drop_last=True, **loader_args)
|
2021-08-16 00:53:00 +00:00
|
|
|
|
2021-08-16 14:54:06 +00:00
|
|
|
# (Initialize logging)
|
2022-06-28 07:36:21 +00:00
|
|
|
experiment = wandb.init(
|
|
|
|
project="U-Net",
|
|
|
|
config=dict(
|
2022-06-27 13:39:44 +00:00
|
|
|
epochs=epochs,
|
|
|
|
batch_size=batch_size,
|
|
|
|
learning_rate=learning_rate,
|
|
|
|
save_checkpoint=save_checkpoint,
|
|
|
|
amp=amp,
|
2022-06-28 07:36:21 +00:00
|
|
|
),
|
2022-06-27 13:39:44 +00:00
|
|
|
)
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.info(
|
|
|
|
f"""Starting training:
|
2019-10-24 19:37:21 +00:00
|
|
|
Epochs: {epochs}
|
|
|
|
Batch size: {batch_size}
|
2021-08-16 00:53:00 +00:00
|
|
|
Learning rate: {learning_rate}
|
2022-06-28 07:36:21 +00:00
|
|
|
Training size: {len(ds_train)}
|
|
|
|
Validation size: {len(ds_valid)}
|
2021-08-16 00:53:00 +00:00
|
|
|
Checkpoints: {save_checkpoint}
|
2019-10-24 19:37:21 +00:00
|
|
|
Device: {device.type}
|
2021-08-16 00:53:00 +00:00
|
|
|
Mixed Precision: {amp}
|
2022-06-28 07:36:21 +00:00
|
|
|
"""
|
2022-06-27 13:39:44 +00:00
|
|
|
)
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
# 4. Set up the optimizer, the loss, the learning rate scheduler and the loss scaling for AMP
|
|
|
|
optimizer = optim.RMSprop(net.parameters(), lr=learning_rate, weight_decay=1e-8, momentum=0.9)
|
2022-06-27 13:39:44 +00:00
|
|
|
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, "max", patience=2) # goal: maximize Dice score
|
2021-08-16 00:53:00 +00:00
|
|
|
grad_scaler = torch.cuda.amp.GradScaler(enabled=amp)
|
|
|
|
criterion = nn.CrossEntropyLoss()
|
|
|
|
global_step = 0
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
# 5. Begin training
|
2022-06-27 13:39:44 +00:00
|
|
|
for epoch in range(1, epochs + 1):
|
2018-09-26 06:58:49 +00:00
|
|
|
net.train()
|
2017-08-17 19:16:19 +00:00
|
|
|
epoch_loss = 0
|
2022-06-28 07:36:21 +00:00
|
|
|
|
|
|
|
with tqdm(total=len(ds_train), desc=f"Epoch {epoch}/{epochs}", unit="img") as pbar:
|
2019-11-23 13:22:42 +00:00
|
|
|
for batch in train_loader:
|
2022-06-27 13:39:44 +00:00
|
|
|
images = batch["image"]
|
|
|
|
true_masks = batch["mask"]
|
2021-08-16 00:53:00 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
assert images.shape[1] == net.n_channels, (
|
|
|
|
f"Network has been defined with {net.n_channels} input channels, "
|
|
|
|
f"but loaded images have {images.shape[1]} channels. Please check that "
|
|
|
|
"the images are loaded correctly."
|
|
|
|
)
|
2019-11-23 13:22:42 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
images = images.to(device=device, dtype=torch.float32)
|
|
|
|
true_masks = true_masks.to(device=device, dtype=torch.long)
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
with torch.cuda.amp.autocast(enabled=amp):
|
|
|
|
masks_pred = net(images)
|
2022-06-27 13:39:44 +00:00
|
|
|
loss = criterion(masks_pred, true_masks) + dice_loss(
|
|
|
|
F.softmax(masks_pred, dim=1).float(),
|
|
|
|
F.one_hot(true_masks, net.n_classes).permute(0, 3, 1, 2).float(),
|
|
|
|
multiclass=True,
|
|
|
|
)
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
optimizer.zero_grad(set_to_none=True)
|
|
|
|
grad_scaler.scale(loss).backward()
|
|
|
|
grad_scaler.step(optimizer)
|
|
|
|
grad_scaler.update()
|
2017-08-19 08:59:51 +00:00
|
|
|
|
2021-08-16 00:53:00 +00:00
|
|
|
pbar.update(images.shape[0])
|
2019-11-23 16:56:14 +00:00
|
|
|
global_step += 1
|
2021-08-16 00:53:00 +00:00
|
|
|
epoch_loss += loss.item()
|
2022-06-27 13:39:44 +00:00
|
|
|
experiment.log({"train loss": loss.item(), "step": global_step, "epoch": epoch})
|
|
|
|
pbar.set_postfix(**{"loss (batch)": loss.item()})
|
2021-08-16 00:53:00 +00:00
|
|
|
|
|
|
|
# Evaluation round
|
2022-06-28 07:36:21 +00:00
|
|
|
division_step = len(ds_train) // (10 * batch_size)
|
2021-10-24 21:14:18 +00:00
|
|
|
if division_step > 0:
|
2021-10-24 21:07:54 +00:00
|
|
|
if global_step % division_step == 0:
|
|
|
|
histograms = {}
|
|
|
|
for tag, value in net.named_parameters():
|
2022-06-27 13:39:44 +00:00
|
|
|
tag = tag.replace("/", ".")
|
|
|
|
histograms["Weights/" + tag] = wandb.Histogram(value.data.cpu())
|
|
|
|
histograms["Gradients/" + tag] = wandb.Histogram(value.grad.data.cpu())
|
2021-10-24 21:07:54 +00:00
|
|
|
|
|
|
|
val_score = evaluate(net, val_loader, device)
|
|
|
|
scheduler.step(val_score)
|
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.info("Validation Dice score: {}".format(val_score))
|
|
|
|
experiment.log(
|
|
|
|
{
|
|
|
|
"learning rate": optimizer.param_groups[0]["lr"],
|
|
|
|
"validation Dice": val_score,
|
|
|
|
"images": wandb.Image(images[0].cpu()),
|
|
|
|
"masks": {
|
|
|
|
"true": wandb.Image(true_masks[0].float().cpu()),
|
|
|
|
"pred": wandb.Image(
|
|
|
|
torch.softmax(masks_pred, dim=1).argmax(dim=1)[0].float().cpu()
|
|
|
|
),
|
|
|
|
},
|
|
|
|
"step": global_step,
|
|
|
|
"epoch": epoch,
|
|
|
|
**histograms,
|
|
|
|
}
|
|
|
|
)
|
2021-08-16 00:53:00 +00:00
|
|
|
|
|
|
|
if save_checkpoint:
|
2022-06-28 07:36:21 +00:00
|
|
|
Path(CHECKPOINT_DIR).mkdir(parents=True, exist_ok=True)
|
|
|
|
torch.save(net.state_dict(), str(CHECKPOINT_DIR / "checkpoint_epoch{}.pth".format(epoch)))
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.info(f"Checkpoint {epoch} saved!")
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2018-06-08 17:27:32 +00:00
|
|
|
|
|
|
|
def get_args():
|
2022-06-27 13:39:44 +00:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description="Train the UNet on images and target masks",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--epochs",
|
|
|
|
"-e",
|
|
|
|
metavar="E",
|
|
|
|
type=int,
|
|
|
|
default=5,
|
|
|
|
help="Number of epochs",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--batch-size",
|
|
|
|
"-b",
|
|
|
|
dest="batch_size",
|
|
|
|
metavar="B",
|
|
|
|
type=int,
|
2022-06-28 07:36:21 +00:00
|
|
|
default=32,
|
2022-06-27 13:39:44 +00:00
|
|
|
help="Batch size",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--learning-rate",
|
|
|
|
"-l",
|
|
|
|
metavar="LR",
|
|
|
|
type=float,
|
|
|
|
default=1e-5,
|
|
|
|
help="Learning rate",
|
|
|
|
dest="lr",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--load",
|
|
|
|
"-f",
|
|
|
|
type=str,
|
|
|
|
default=False,
|
|
|
|
help="Load model from a .pth file",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--amp",
|
|
|
|
action="store_true",
|
2022-06-27 14:40:04 +00:00
|
|
|
default=True,
|
2022-06-27 13:39:44 +00:00
|
|
|
help="Use mixed precision",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--classes",
|
|
|
|
"-c",
|
|
|
|
type=int,
|
2022-06-27 14:40:04 +00:00
|
|
|
default=1,
|
2022-06-27 13:39:44 +00:00
|
|
|
help="Number of classes",
|
|
|
|
)
|
2019-10-24 19:37:21 +00:00
|
|
|
|
|
|
|
return parser.parse_args()
|
|
|
|
|
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
if __name__ == "__main__":
|
2018-06-08 17:27:32 +00:00
|
|
|
args = get_args()
|
2021-08-16 00:53:00 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
2022-06-28 07:36:21 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
logging.info(f"Using device {device}")
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2022-06-27 14:13:38 +00:00
|
|
|
net = UNet(n_channels=3, n_classes=args.classes)
|
2021-08-16 00:53:00 +00:00
|
|
|
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.info(
|
2022-06-28 07:36:21 +00:00
|
|
|
f"""Network:
|
|
|
|
\t{net.n_channels} input channels
|
|
|
|
\t{net.n_classes} output channels (classes)
|
2022-06-27 14:13:38 +00:00
|
|
|
"""
|
2022-06-27 13:39:44 +00:00
|
|
|
)
|
2017-08-19 08:59:51 +00:00
|
|
|
|
2018-06-08 17:27:32 +00:00
|
|
|
if args.load:
|
2021-08-16 00:53:00 +00:00
|
|
|
net.load_state_dict(torch.load(args.load, map_location=device))
|
2022-06-27 13:39:44 +00:00
|
|
|
logging.info(f"Model loaded from {args.load}")
|
2019-10-24 19:37:21 +00:00
|
|
|
|
|
|
|
net.to(device=device)
|
2022-06-28 07:36:21 +00:00
|
|
|
|
2017-08-19 08:59:51 +00:00
|
|
|
try:
|
2022-06-27 13:39:44 +00:00
|
|
|
train_net(
|
|
|
|
net=net,
|
|
|
|
epochs=args.epochs,
|
|
|
|
batch_size=args.batch_size,
|
|
|
|
learning_rate=args.lr,
|
|
|
|
device=device,
|
|
|
|
amp=args.amp,
|
|
|
|
)
|
2019-12-21 21:04:23 +00:00
|
|
|
except KeyboardInterrupt:
|
2022-06-27 13:39:44 +00:00
|
|
|
torch.save(net.state_dict(), "INTERRUPTED.pth")
|
|
|
|
logging.info("Saved interrupt")
|
2022-04-06 11:35:02 +00:00
|
|
|
raise
|