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
+
Key training features:
|
| 11 |
+
- Mixed precision (fp16/bf16) for memory efficiency
|
| 12 |
+
- Gradient accumulation for large effective batch sizes
|
| 13 |
+
- EMA for stable generation quality
|
| 14 |
+
- Physics-informed loss with warmup
|
| 15 |
+
- Cosine learning rate schedule with warmup
|
| 16 |
+
- Checkpoint saving/resuming
|
| 17 |
+
- Wandb/Trackio logging support
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
import math
|
| 23 |
+
import time
|
| 24 |
+
import json
|
| 25 |
+
import argparse
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn as nn
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from torch.utils.data import DataLoader, Dataset
|
| 32 |
+
from torch.cuda.amp import autocast, GradScaler
|
| 33 |
+
import torchvision
|
| 34 |
+
import torchvision.transforms as transforms
|
| 35 |
+
from PIL import Image
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
# Add parent to path
|
| 39 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 40 |
+
|
| 41 |
+
from model import (
|
| 42 |
+
LiquidFlowNet, liquidflow_tiny, liquidflow_small,
|
| 43 |
+
liquidflow_base, liquidflow_512
|
| 44 |
+
)
|
| 45 |
+
from losses import PhysicsInformedFlowLoss, EMAModel
|
| 46 |
+
from sampling import euler_sample, heun_sample, make_grid_image
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ============================================================
|
| 50 |
+
# DATASET UTILITIES
|
| 51 |
+
# ============================================================
|
| 52 |
+
|
| 53 |
+
class ImageFolderDataset(Dataset):
|
| 54 |
+
"""Simple image dataset from folder."""
|
| 55 |
+
|
| 56 |
+
def __init__(self, root, img_size=128, transform=None):
|
| 57 |
+
self.root = Path(root)
|
| 58 |
+
self.img_size = img_size
|
| 59 |
+
|
| 60 |
+
# Find all images
|
| 61 |
+
self.files = []
|
| 62 |
+
for ext in ['*.png', '*.jpg', '*.jpeg', '*.webp', '*.bmp']:
|
| 63 |
+
self.files.extend(self.root.rglob(ext))
|
| 64 |
+
self.files = sorted(self.files)
|
| 65 |
+
|
| 66 |
+
if transform is None:
|
| 67 |
+
self.transform = transforms.Compose([
|
| 68 |
+
transforms.Resize(img_size),
|
| 69 |
+
transforms.CenterCrop(img_size),
|
| 70 |
+
transforms.RandomHorizontalFlip(),
|
| 71 |
+
transforms.ToTensor(),
|
| 72 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 73 |
+
])
|
| 74 |
+
else:
|
| 75 |
+
self.transform = transform
|
| 76 |
+
|
| 77 |
+
def __len__(self):
|
| 78 |
+
return len(self.files)
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, idx):
|
| 81 |
+
img = Image.open(self.files[idx]).convert('RGB')
|
| 82 |
+
return self.transform(img)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_cifar10_dataset(img_size=32, data_dir='./data'):
|
| 86 |
+
"""CIFAR-10 for quick experiments."""
|
| 87 |
+
transform = transforms.Compose([
|
| 88 |
+
transforms.Resize(img_size) if img_size != 32 else transforms.Lambda(lambda x: x),
|
| 89 |
+
transforms.RandomHorizontalFlip(),
|
| 90 |
+
transforms.ToTensor(),
|
| 91 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 92 |
+
])
|
| 93 |
+
dataset = torchvision.datasets.CIFAR10(
|
| 94 |
+
root=data_dir, train=True, download=True, transform=transform
|
| 95 |
+
)
|
| 96 |
+
return dataset
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_celeba_dataset(img_size=128, data_dir='./data'):
|
| 100 |
+
"""CelebA for face generation."""
|
| 101 |
+
transform = transforms.Compose([
|
| 102 |
+
transforms.Resize(img_size),
|
| 103 |
+
transforms.CenterCrop(img_size),
|
| 104 |
+
transforms.RandomHorizontalFlip(),
|
| 105 |
+
transforms.ToTensor(),
|
| 106 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 107 |
+
])
|
| 108 |
+
dataset = torchvision.datasets.CelebA(
|
| 109 |
+
root=data_dir, split='train', download=True, transform=transform
|
| 110 |
+
)
|
| 111 |
+
return dataset
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def get_flowers_dataset(img_size=128, data_dir='./data'):
|
| 115 |
+
"""Oxford Flowers 102 - small but beautiful dataset."""
|
| 116 |
+
transform = transforms.Compose([
|
| 117 |
+
transforms.Resize(img_size + img_size // 8),
|
| 118 |
+
transforms.CenterCrop(img_size),
|
| 119 |
+
transforms.RandomHorizontalFlip(),
|
| 120 |
+
transforms.ToTensor(),
|
| 121 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 122 |
+
])
|
| 123 |
+
dataset = torchvision.datasets.Flowers102(
|
| 124 |
+
root=data_dir, split='train', download=True, transform=transform
|
| 125 |
+
)
|
| 126 |
+
return dataset
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ============================================================
|
| 130 |
+
# LEARNING RATE SCHEDULE
|
| 131 |
+
# ============================================================
|
| 132 |
+
|
| 133 |
+
def get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps, min_lr_ratio=0.1):
|
| 134 |
+
"""Cosine annealing with linear warmup."""
|
| 135 |
+
def lr_lambda(step):
|
| 136 |
+
if step < warmup_steps:
|
| 137 |
+
return step / max(1, warmup_steps)
|
| 138 |
+
progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
|
| 139 |
+
return min_lr_ratio + (1 - min_lr_ratio) * 0.5 * (1 + math.cos(math.pi * progress))
|
| 140 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ============================================================
|
| 144 |
+
# TRAINING LOOP
|
| 145 |
+
# ============================================================
|
| 146 |
+
|
| 147 |
+
def train(args):
|
| 148 |
+
"""Main training function."""
|
| 149 |
+
|
| 150 |
+
# Setup device
|
| 151 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 152 |
+
use_amp = device.type == 'cuda' and args.use_amp
|
| 153 |
+
print(f"Device: {device}, AMP: {use_amp}")
|
| 154 |
+
|
| 155 |
+
# Create output directory
|
| 156 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 157 |
+
os.makedirs(os.path.join(args.output_dir, 'samples'), exist_ok=True)
|
| 158 |
+
os.makedirs(os.path.join(args.output_dir, 'checkpoints'), exist_ok=True)
|
| 159 |
+
|
| 160 |
+
# ---- Model ----
|
| 161 |
+
model_factories = {
|
| 162 |
+
'tiny': liquidflow_tiny,
|
| 163 |
+
'small': liquidflow_small,
|
| 164 |
+
'base': liquidflow_base,
|
| 165 |
+
'512': liquidflow_512,
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
if args.model_size in model_factories:
|
| 169 |
+
model = model_factories[args.model_size](img_size=args.img_size)
|
| 170 |
+
else:
|
| 171 |
+
model = liquidflow_small(img_size=args.img_size)
|
| 172 |
+
|
| 173 |
+
model = model.to(device)
|
| 174 |
+
num_params = model.count_params()
|
| 175 |
+
print(f"Model: LiquidFlow-{args.model_size}, Params: {num_params/1e6:.2f}M")
|
| 176 |
+
print(f"Image size: {args.img_size}x{args.img_size}")
|
| 177 |
+
|
| 178 |
+
# ---- Dataset ----
|
| 179 |
+
if args.dataset == 'cifar10':
|
| 180 |
+
dataset = get_cifar10_dataset(args.img_size, args.data_dir)
|
| 181 |
+
elif args.dataset == 'flowers':
|
| 182 |
+
dataset = get_flowers_dataset(args.img_size, args.data_dir)
|
| 183 |
+
elif args.dataset == 'celeba':
|
| 184 |
+
dataset = get_celeba_dataset(args.img_size, args.data_dir)
|
| 185 |
+
elif args.dataset == 'folder':
|
| 186 |
+
dataset = ImageFolderDataset(args.data_dir, args.img_size)
|
| 187 |
+
else:
|
| 188 |
+
raise ValueError(f"Unknown dataset: {args.dataset}")
|
| 189 |
+
|
| 190 |
+
print(f"Dataset: {args.dataset}, Size: {len(dataset)}")
|
| 191 |
+
|
| 192 |
+
dataloader = DataLoader(
|
| 193 |
+
dataset,
|
| 194 |
+
batch_size=args.batch_size,
|
| 195 |
+
shuffle=True,
|
| 196 |
+
num_workers=args.num_workers,
|
| 197 |
+
pin_memory=True,
|
| 198 |
+
drop_last=True,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# ---- Optimizer ----
|
| 202 |
+
optimizer = torch.optim.AdamW(
|
| 203 |
+
model.parameters(),
|
| 204 |
+
lr=args.lr,
|
| 205 |
+
betas=(0.9, 0.999),
|
| 206 |
+
weight_decay=args.weight_decay,
|
| 207 |
+
eps=1e-8,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# ---- Schedule ----
|
| 211 |
+
total_steps = args.epochs * len(dataloader) // args.grad_accum
|
| 212 |
+
warmup_steps = min(args.warmup_steps, total_steps // 10)
|
| 213 |
+
scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)
|
| 214 |
+
|
| 215 |
+
# ---- Loss ----
|
| 216 |
+
criterion = PhysicsInformedFlowLoss(
|
| 217 |
+
lambda_smooth=args.lambda_smooth,
|
| 218 |
+
lambda_tv=args.lambda_tv,
|
| 219 |
+
use_adaptive_weights=True,
|
| 220 |
+
).to(device)
|
| 221 |
+
|
| 222 |
+
# ---- EMA ----
|
| 223 |
+
ema = EMAModel(model, decay=args.ema_decay)
|
| 224 |
+
|
| 225 |
+
# ---- AMP ----
|
| 226 |
+
scaler = GradScaler(enabled=use_amp)
|
| 227 |
+
|
| 228 |
+
# ---- Resume ----
|
| 229 |
+
start_epoch = 0
|
| 230 |
+
global_step = 0
|
| 231 |
+
|
| 232 |
+
if args.resume and os.path.exists(args.resume):
|
| 233 |
+
print(f"Resuming from {args.resume}")
|
| 234 |
+
ckpt = torch.load(args.resume, map_location=device)
|
| 235 |
+
model.load_state_dict(ckpt['model'])
|
| 236 |
+
optimizer.load_state_dict(ckpt['optimizer'])
|
| 237 |
+
scheduler.load_state_dict(ckpt['scheduler'])
|
| 238 |
+
ema.load_state_dict(ckpt['ema'])
|
| 239 |
+
start_epoch = ckpt['epoch'] + 1
|
| 240 |
+
global_step = ckpt['global_step']
|
| 241 |
+
print(f"Resumed at epoch {start_epoch}, step {global_step}")
|
| 242 |
+
|
| 243 |
+
# ---- Training Config ----
|
| 244 |
+
config = {
|
| 245 |
+
'model_size': args.model_size,
|
| 246 |
+
'img_size': args.img_size,
|
| 247 |
+
'dataset': args.dataset,
|
| 248 |
+
'batch_size': args.batch_size,
|
| 249 |
+
'lr': args.lr,
|
| 250 |
+
'epochs': args.epochs,
|
| 251 |
+
'num_params': num_params,
|
| 252 |
+
'lambda_smooth': args.lambda_smooth,
|
| 253 |
+
'lambda_tv': args.lambda_tv,
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
with open(os.path.join(args.output_dir, 'config.json'), 'w') as f:
|
| 257 |
+
json.dump(config, f, indent=2)
|
| 258 |
+
|
| 259 |
+
print(f"\n{'='*60}")
|
| 260 |
+
print(f"Training for {args.epochs} epochs, {total_steps} steps")
|
| 261 |
+
print(f"Batch size: {args.batch_size} x {args.grad_accum} = {args.batch_size * args.grad_accum}")
|
| 262 |
+
print(f"Learning rate: {args.lr}")
|
| 263 |
+
print(f"{'='*60}\n")
|
| 264 |
+
|
| 265 |
+
# ---- Training ----
|
| 266 |
+
best_loss = float('inf')
|
| 267 |
+
log_losses = []
|
| 268 |
+
|
| 269 |
+
for epoch in range(start_epoch, args.epochs):
|
| 270 |
+
model.train()
|
| 271 |
+
epoch_loss = 0.0
|
| 272 |
+
epoch_flow_loss = 0.0
|
| 273 |
+
epoch_physics_loss = 0.0
|
| 274 |
+
num_batches = 0
|
| 275 |
+
|
| 276 |
+
for batch_idx, batch_data in enumerate(dataloader):
|
| 277 |
+
# Handle different dataset formats
|
| 278 |
+
if isinstance(batch_data, (list, tuple)):
|
| 279 |
+
x1 = batch_data[0].to(device) # images only, ignore labels
|
| 280 |
+
else:
|
| 281 |
+
x1 = batch_data.to(device)
|
| 282 |
+
|
| 283 |
+
B = x1.shape[0]
|
| 284 |
+
|
| 285 |
+
# Sample noise (x0) and timestep (t)
|
| 286 |
+
x0 = torch.randn_like(x1)
|
| 287 |
+
t = torch.rand(B, device=device)
|
| 288 |
+
|
| 289 |
+
# Interpolate: x_t = t * x_1 + (1-t) * x_0
|
| 290 |
+
t_expand = t.view(B, 1, 1, 1)
|
| 291 |
+
x_t = t_expand * x1 + (1.0 - t_expand) * x0
|
| 292 |
+
|
| 293 |
+
# Forward pass with AMP
|
| 294 |
+
with autocast(enabled=use_amp):
|
| 295 |
+
v_pred = model(x_t, t)
|
| 296 |
+
loss, loss_dict = criterion(
|
| 297 |
+
v_pred, x0, x1, t,
|
| 298 |
+
step=global_step,
|
| 299 |
+
)
|
| 300 |
+
loss = loss / args.grad_accum
|
| 301 |
+
|
| 302 |
+
# Backward
|
| 303 |
+
scaler.scale(loss).backward()
|
| 304 |
+
|
| 305 |
+
# Gradient accumulation step
|
| 306 |
+
if (batch_idx + 1) % args.grad_accum == 0:
|
| 307 |
+
# Gradient clipping (critical for stability)
|
| 308 |
+
scaler.unscale_(optimizer)
|
| 309 |
+
grad_norm = nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
|
| 310 |
+
|
| 311 |
+
scaler.step(optimizer)
|
| 312 |
+
scaler.update()
|
| 313 |
+
optimizer.zero_grad()
|
| 314 |
+
scheduler.step()
|
| 315 |
+
ema.update(model)
|
| 316 |
+
global_step += 1
|
| 317 |
+
|
| 318 |
+
# Logging
|
| 319 |
+
epoch_loss += loss_dict['total'].item()
|
| 320 |
+
epoch_flow_loss += loss_dict['flow'].item()
|
| 321 |
+
epoch_physics_loss += (loss_dict['smooth'].item() + loss_dict['tv'].item())
|
| 322 |
+
num_batches += 1
|
| 323 |
+
|
| 324 |
+
if global_step % args.log_every == 0:
|
| 325 |
+
avg_loss = epoch_loss / max(1, num_batches)
|
| 326 |
+
avg_flow = epoch_flow_loss / max(1, num_batches)
|
| 327 |
+
avg_phys = epoch_physics_loss / max(1, num_batches)
|
| 328 |
+
lr_current = scheduler.get_last_lr()[0]
|
| 329 |
+
|
| 330 |
+
print(
|
| 331 |
+
f"[Epoch {epoch+1}/{args.epochs}] "
|
| 332 |
+
f"Step {global_step}/{total_steps} | "
|
| 333 |
+
f"Loss: {avg_loss:.4f} | "
|
| 334 |
+
f"Flow: {avg_flow:.4f} | "
|
| 335 |
+
f"Physics: {avg_phys:.6f} | "
|
| 336 |
+
f"LR: {lr_current:.2e} | "
|
| 337 |
+
f"GradNorm: {grad_norm:.2f}"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
log_losses.append({
|
| 341 |
+
'step': global_step,
|
| 342 |
+
'epoch': epoch,
|
| 343 |
+
'loss': avg_loss,
|
| 344 |
+
'flow_loss': avg_flow,
|
| 345 |
+
'physics_loss': avg_phys,
|
| 346 |
+
'lr': lr_current,
|
| 347 |
+
'grad_norm': grad_norm.item() if isinstance(grad_norm, torch.Tensor) else grad_norm,
|
| 348 |
+
})
|
| 349 |
+
|
| 350 |
+
# ---- End of Epoch ----
|
| 351 |
+
avg_epoch_loss = epoch_loss / max(1, num_batches)
|
| 352 |
+
print(f"\n[Epoch {epoch+1}] Average Loss: {avg_epoch_loss:.4f}\n")
|
| 353 |
+
|
| 354 |
+
# Sample images with EMA
|
| 355 |
+
if (epoch + 1) % args.sample_every == 0 or epoch == 0:
|
| 356 |
+
print("Generating samples...")
|
| 357 |
+
model.eval()
|
| 358 |
+
ema.apply_shadow(model)
|
| 359 |
+
|
| 360 |
+
with torch.no_grad():
|
| 361 |
+
shape = (min(16, args.batch_size), 3, args.img_size, args.img_size)
|
| 362 |
+
samples = euler_sample(model, shape, num_steps=args.sample_steps, device=device)
|
| 363 |
+
samples = samples.clamp(-1, 1) * 0.5 + 0.5
|
| 364 |
+
|
| 365 |
+
grid = make_grid_image(samples, nrow=4)
|
| 366 |
+
grid.save(os.path.join(args.output_dir, 'samples', f'epoch_{epoch+1:04d}.png'))
|
| 367 |
+
print(f" Saved samples to samples/epoch_{epoch+1:04d}.png")
|
| 368 |
+
|
| 369 |
+
ema.restore(model)
|
| 370 |
+
model.train()
|
| 371 |
+
|
| 372 |
+
# Save checkpoint
|
| 373 |
+
if (epoch + 1) % args.save_every == 0 or avg_epoch_loss < best_loss:
|
| 374 |
+
best_loss = min(best_loss, avg_epoch_loss)
|
| 375 |
+
ckpt = {
|
| 376 |
+
'model': model.state_dict(),
|
| 377 |
+
'optimizer': optimizer.state_dict(),
|
| 378 |
+
'scheduler': scheduler.state_dict(),
|
| 379 |
+
'ema': ema.state_dict(),
|
| 380 |
+
'epoch': epoch,
|
| 381 |
+
'global_step': global_step,
|
| 382 |
+
'loss': avg_epoch_loss,
|
| 383 |
+
'config': config,
|
| 384 |
+
}
|
| 385 |
+
ckpt_path = os.path.join(args.output_dir, 'checkpoints', f'epoch_{epoch+1:04d}.pt')
|
| 386 |
+
torch.save(ckpt, ckpt_path)
|
| 387 |
+
print(f" Saved checkpoint: {ckpt_path}")
|
| 388 |
+
|
| 389 |
+
# Also save "latest" and "best"
|
| 390 |
+
torch.save(ckpt, os.path.join(args.output_dir, 'checkpoints', 'latest.pt'))
|
| 391 |
+
if avg_epoch_loss <= best_loss:
|
| 392 |
+
torch.save(ckpt, os.path.join(args.output_dir, 'checkpoints', 'best.pt'))
|
| 393 |
+
|
| 394 |
+
# Save final model (EMA weights)
|
| 395 |
+
ema.apply_shadow(model)
|
| 396 |
+
final_state = {
|
| 397 |
+
'model': model.state_dict(),
|
| 398 |
+
'config': config,
|
| 399 |
+
}
|
| 400 |
+
torch.save(final_state, os.path.join(args.output_dir, 'liquidflow_final.pt'))
|
| 401 |
+
ema.restore(model)
|
| 402 |
+
|
| 403 |
+
# Save training log
|
| 404 |
+
with open(os.path.join(args.output_dir, 'training_log.json'), 'w') as f:
|
| 405 |
+
json.dump(log_losses, f, indent=2)
|
| 406 |
+
|
| 407 |
+
print(f"\n{'='*60}")
|
| 408 |
+
print(f"Training complete! Final model saved to {args.output_dir}/liquidflow_final.pt")
|
| 409 |
+
print(f"{'='*60}")
|
| 410 |
+
|
| 411 |
+
return model
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def main():
|
| 415 |
+
parser = argparse.ArgumentParser(description='LiquidFlow Training')
|
| 416 |
+
|
| 417 |
+
# Model
|
| 418 |
+
parser.add_argument('--model_size', type=str, default='small',
|
| 419 |
+
choices=['tiny', 'small', 'base', '512'])
|
| 420 |
+
parser.add_argument('--img_size', type=int, default=128)
|
| 421 |
+
|
| 422 |
+
# Dataset
|
| 423 |
+
parser.add_argument('--dataset', type=str, default='cifar10',
|
| 424 |
+
choices=['cifar10', 'flowers', 'celeba', 'folder'])
|
| 425 |
+
parser.add_argument('--data_dir', type=str, default='./data')
|
| 426 |
+
|
| 427 |
+
# Training
|
| 428 |
+
parser.add_argument('--epochs', type=int, default=100)
|
| 429 |
+
parser.add_argument('--batch_size', type=int, default=32)
|
| 430 |
+
parser.add_argument('--lr', type=float, default=3e-4)
|
| 431 |
+
parser.add_argument('--weight_decay', type=float, default=0.01)
|
| 432 |
+
parser.add_argument('--grad_accum', type=int, default=1)
|
| 433 |
+
parser.add_argument('--max_grad_norm', type=float, default=1.0)
|
| 434 |
+
parser.add_argument('--warmup_steps', type=int, default=500)
|
| 435 |
+
parser.add_argument('--ema_decay', type=float, default=0.9999)
|
| 436 |
+
|
| 437 |
+
# Physics loss
|
| 438 |
+
parser.add_argument('--lambda_smooth', type=float, default=0.01)
|
| 439 |
+
parser.add_argument('--lambda_tv', type=float, default=0.001)
|
| 440 |
+
|
| 441 |
+
# AMP
|
| 442 |
+
parser.add_argument('--use_amp', action='store_true', default=True)
|
| 443 |
+
parser.add_argument('--no_amp', action='store_true')
|
| 444 |
+
|
| 445 |
+
# Logging & Saving
|
| 446 |
+
parser.add_argument('--output_dir', type=str, default='./outputs')
|
| 447 |
+
parser.add_argument('--log_every', type=int, default=50)
|
| 448 |
+
parser.add_argument('--sample_every', type=int, default=5)
|
| 449 |
+
parser.add_argument('--save_every', type=int, default=10)
|
| 450 |
+
parser.add_argument('--sample_steps', type=int, default=50)
|
| 451 |
+
parser.add_argument('--num_workers', type=int, default=2)
|
| 452 |
+
|
| 453 |
+
# Resume
|
| 454 |
+
parser.add_argument('--resume', type=str, default=None)
|
| 455 |
+
|
| 456 |
+
args = parser.parse_args()
|
| 457 |
+
|
| 458 |
+
if args.no_amp:
|
| 459 |
+
args.use_amp = False
|
| 460 |
+
|
| 461 |
+
train(args)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
if __name__ == '__main__':
|
| 465 |
+
main()
|