MamaPearl commited on
Commit
ead010f
·
verified ·
1 Parent(s): 6fca20a

Update augmented_train.py

Browse files
Files changed (1) hide show
  1. augmented_train.py +121 -0
augmented_train.py CHANGED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ NUM_EPOCHS = 50
3
+ AUG_PROB = 0.5
4
+ GRAD_CLIP = 1.0
5
+ SAVE_EVERY = 5
6
+ CHECKPOINT_DIR = "./checkpoints"
7
+ BEST_MODEL_DIR = "./nula-best-model"
8
+
9
+ MEAN = pt.tensor([0.5,0.5,0.5], device=DEVICE).view(1,3,1,1)
10
+ STD = pt.tensor([0.5,0.5,0.5], device=DEVICE).view(1,3,1,1)
11
+
12
+ GLOBAL_POOL_BLUR = BlurPool2d(channels=cfg.in_channels, stride=2).to(DEVICE)
13
+
14
+ def train_one_epoch(model, loader, optimizer, device, grad_clip=1.0):
15
+ model.train()
16
+
17
+ total_loss = 0.0
18
+ total_correct = 0
19
+ total_examples = 0
20
+
21
+ pbar = tqdm(loader, desc="training...", leave=False)
22
+
23
+ for batch in pbar:
24
+ x = batch["pixel_values"].to(device, non_blocking=True)
25
+ y = batch["labels"].to(device, non_blocking=True)
26
+ optimizer.zero_grad(set_to_none=True)
27
+
28
+ B = x.size(0)
29
+ mask_aug = pt.rand(B, device=x.device) < AUG_PROB
30
+
31
+ if mask_aug.any():
32
+ with pt.no_grad():
33
+ x_image = x * STD + MEAN
34
+ choices = pt.randint(0, 3, (B,), device=x.device)
35
+ mask_resize = mask_aug & (choices == 0)
36
+ if mask_resize.any():
37
+ scales = pt.empty(mask_resize.sum(), device=x.device).uniform_(0.2, 0.6)
38
+ x_subset = x_image[mask_resize]
39
+
40
+ resize_out = []
41
+ for i in range(x_subset.size(0)):
42
+ resize_out.append(resize_down_up(x_subset[i:i+1], scale=scales[i].item()))
43
+ x_image[mask_resize] = pt.cat(resize_out, dim=0)
44
+ mask_decimate = mask_aug & (choices == 1)
45
+ if mask_decimate.any():
46
+ factors = pt.randint(2, 5, (mask_decimate.sum(),), device=x.device)
47
+ x_subset = x_image[mask_decimate]
48
+
49
+ decimate_out = []
50
+ for i in range(x_subset.size(0)):
51
+ decimate_out.append(decimate(x_subset[i:i+1], factor=int(factors[i].item())))
52
+ x_image[mask_decimate] = pt.cat(decimate_out, dim=0)
53
+
54
+ mask_blur = mask_aug & (choices == 2)
55
+ if mask_blur.any():
56
+ x_subset = x_image[mask_blur]
57
+ x_down = GLOBAL_POOL_BLUR(x_subset)
58
+ x_up = F.interpolate(x_down, size=x_subset.shape[-2:], mode="bilinear", align_corners=False)
59
+ x_image[mask_blur] = x_up
60
+
61
+ x = (x_image - MEAN) / STD
62
+
63
+ out = model(pixel_values=x, labels=y)
64
+ loss = out.loss
65
+ logits = out.logits
66
+ preds = logits.argmax(dim=1)
67
+ loss.backward()
68
+ pt.nn.utils.clip_grad_norm_(model.parameters(), max_norm=GRAD_CLIP)
69
+ optimizer.step()
70
+
71
+ total_loss += loss.item() * y.size(0)
72
+ total_correct += (preds == y).sum().item()
73
+ total_examples += y.size(0)
74
+
75
+ pbar.set_postfix(loss=f"{loss.item():.4f}", acc=f"{100 * total_correct / total_examples:.2f}%")
76
+
77
+ return total_loss / total_examples, total_correct / total_examples
78
+
79
+ @pt.no_grad()
80
+ def evaluate(model, loader, device):
81
+ model.eval()
82
+ total_loss = 0.0
83
+ total_correct = 0
84
+ total_examples = 0
85
+ for batch in loader:
86
+ x = batch["pixel_values"].to(device, non_blocking=True)
87
+ y = batch["labels"].to(device, non_blocking=True)
88
+ out = model(pixel_values=x, labels=y)
89
+ loss = out.loss
90
+ logits = out.logits
91
+
92
+ total_loss += loss.item() * y.size(0)
93
+ total_correct += (logits.argmax(dim=1) == y).sum().item()
94
+ total_examples += y.size(0)
95
+ return total_loss / total_examples, total_correct / total_examples
96
+
97
+ best_val_acc = 0.0
98
+
99
+ for epoch in range(1, NUM_EPOCHS + 1):
100
+ train_loss, train_acc = train_one_epoch(model, train_loader, optimizer, DEVICE)
101
+ val_loss, val_acc = evaluate(model, test_loader, DEVICE)
102
+ scheduler.step()
103
+
104
+ if epoch % SAVE_EVERY == 0:
105
+ model.save_pretrained(f"{CHECKPOINT_DIR}/epoch{epoch}")
106
+
107
+ if val_acc > best_val_acc:
108
+ best_val_acc = val_acc
109
+ model.save_pretrained(BEST_MODEL_DIR)
110
+ print(f"new best: {100 * best_val_acc:.2f}%")
111
+
112
+ current_lr = optimizer.param_groups[0]["lr"]
113
+ print("=", "-"*60, "=")
114
+ print(f"Epoch [{epoch}/{NUM_EPOCHS}]")
115
+ print(f"lr : {current_lr:.6f}")
116
+ print(f"train_loss : {train_loss:.4f}")
117
+ print(f"train_acc : {train_acc * 100:.2f}%")
118
+ print(f"val_loss : {val_loss:4f}")
119
+ print(f"val_acc : {val_acc * 100:.2f}%")
120
+ print(f"best_val_acc : {100 * best_val_acc:.2f}%")
121
+ print()