LH-Tech-AI commited on
Commit
4f4e7db
Β·
verified Β·
1 Parent(s): 80e4e04

Create train.py

Browse files
Files changed (1) hide show
  1. train.py +239 -0
train.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ================================================================
2
+ # πŸ”„ IMAGE ROTATION PREDICTION β€” From-Scratch ResNet-18
3
+ # Dataset: ImageNet-1k Β· Hardware: Kaggle T4 GPU
4
+ # ================================================================
5
+
6
+ !pip install -q transformers datasets
7
+
8
+ # ────────────────────── Imports ──────────────────────
9
+ import os, random, math, time
10
+ import numpy as np
11
+ from PIL import Image
12
+ import torch
13
+ import torch.nn as nn
14
+ from torch.utils.data import Dataset, DataLoader
15
+ from torchvision import transforms
16
+ from transformers import ResNetConfig, ResNetForImageClassification
17
+ from datasets import load_dataset
18
+ from tqdm.auto import tqdm
19
+
20
+ # ────────────────────── Config ───────────────────────
21
+ HF_TOKEN = "hf_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
22
+ NUM_TRAIN = 50_000
23
+ NUM_VAL = 5_000
24
+ IMG_SIZE = 224
25
+ BATCH_SIZE = 128
26
+ EPOCHS = 12
27
+ LR = 1e-3
28
+ WARMUP_EPOCHS = 1
29
+ WEIGHT_DECAY = 0.05
30
+ LABEL_SMOOTHING = 0.1
31
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
32
+ TRAIN_DIR = "/kaggle/working/data/train"
33
+ VAL_DIR = "/kaggle/working/data/val"
34
+ MODEL_DIR = "/kaggle/working/rotation_model"
35
+
36
+ print(f"πŸ–₯️ Device: {DEVICE}")
37
+ if DEVICE.type == "cuda":
38
+ print(f" GPU: {torch.cuda.get_device_name()}")
39
+ print(f" VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
40
+
41
+ # ──────────── Download ImageNet-1k (Streaming) ──────────────
42
+ from huggingface_hub import login
43
+ login(token=HF_TOKEN)
44
+
45
+ def download_images(split, save_dir, num_images):
46
+ os.makedirs(save_dir, exist_ok=True)
47
+ existing = len([f for f in os.listdir(save_dir) if f.endswith(".jpg")])
48
+ if existing >= num_images:
49
+ print(f" βœ“ {save_dir}: {existing} images already exist β†’ skipping.")
50
+ return
51
+ ds = load_dataset("ILSVRC/imagenet-1k", split=split,
52
+ streaming=True, trust_remote_code=True, token=HF_TOKEN)
53
+ count = 0
54
+ for ex in tqdm(ds, total=num_images, desc=f" ↓ {split}"):
55
+ if count >= num_images:
56
+ break
57
+ try:
58
+ img = ex["image"].convert("RGB")
59
+ w, h = img.size
60
+ if min(w, h) > 480:
61
+ s = 480 / min(w, h)
62
+ img = img.resize((int(w*s), int(h*s)), Image.BILINEAR)
63
+ img.save(os.path.join(save_dir, f"{count}.jpg"), quality=90)
64
+ count += 1
65
+ except Exception:
66
+ continue
67
+ print(f" βœ“ {count} Images β†’ {save_dir}")
68
+
69
+ print("\nπŸ“₯ Loading images from ImageNet-1k …")
70
+ download_images("train", TRAIN_DIR, NUM_TRAIN)
71
+ download_images("validation", VAL_DIR, NUM_VAL)
72
+
73
+ # ──────────────────── Rotation-Dataset ───────────────────────
74
+ ANGLES = [0, 90, 180, 270]
75
+ ANGLE_NAMES = ["0Β° (original)", "90Β° CCW", "180Β°", "270Β° CCW (=90Β° CW)"]
76
+
77
+ class RotationDataset(Dataset):
78
+ def __init__(self, img_dir, num_imgs, transform, all_rotations=False):
79
+ self.img_dir = img_dir
80
+ self.num_imgs = num_imgs
81
+ self.transform = transform
82
+ self.all_rot = all_rotations
83
+
84
+ def __len__(self):
85
+ return self.num_imgs * 4 if self.all_rot else self.num_imgs
86
+
87
+ def __getitem__(self, idx):
88
+ if self.all_rot:
89
+ img_idx, label = idx // 4, idx % 4
90
+ else:
91
+ img_idx, label = idx, random.randint(0, 3)
92
+
93
+ img = Image.open(os.path.join(self.img_dir, f"{img_idx}.jpg")).convert("RGB")
94
+
95
+ angle = ANGLES[label]
96
+ if angle == 90: img = img.transpose(Image.ROTATE_90)
97
+ elif angle == 180: img = img.transpose(Image.ROTATE_180)
98
+ elif angle == 270: img = img.transpose(Image.ROTATE_270)
99
+
100
+ return self.transform(img), label
101
+
102
+ train_tf = transforms.Compose([
103
+ transforms.Resize(256),
104
+ transforms.RandomCrop(IMG_SIZE),
105
+ transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.2, hue=0.05),
106
+ transforms.RandomGrayscale(p=0.05),
107
+ transforms.ToTensor(),
108
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
109
+ transforms.RandomErasing(p=0.1),
110
+ ])
111
+ val_tf = transforms.Compose([
112
+ transforms.Resize(256),
113
+ transforms.CenterCrop(IMG_SIZE),
114
+ transforms.ToTensor(),
115
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
116
+ ])
117
+
118
+ train_ds = RotationDataset(TRAIN_DIR, NUM_TRAIN, train_tf, all_rotations=True)
119
+ val_ds = RotationDataset(VAL_DIR, NUM_VAL, val_tf, all_rotations=True)
120
+
121
+ train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True,
122
+ num_workers=2, pin_memory=True, drop_last=True)
123
+ val_loader = DataLoader(val_ds, batch_size=BATCH_SIZE, shuffle=False,
124
+ num_workers=2, pin_memory=True)
125
+
126
+ print(f"\nπŸ“Š Dataset size:")
127
+ print(f" Train: {len(train_ds):>8,} ({NUM_TRAIN:,} images Γ— 4 rotations)")
128
+ print(f" Val: {len(val_ds):>8,} ({NUM_VAL:,} images Γ— 4 rotations)")
129
+
130
+ # ────────────────── Modell: ResNet-18 from scratch ───────────────
131
+ config = ResNetConfig(
132
+ num_channels=3,
133
+ embedding_size=64,
134
+ hidden_sizes=[64, 128, 256, 512], # 4 Stages
135
+ depths=[2, 2, 2, 2], # β†’ ResNet-18
136
+ layer_type="basic",
137
+ hidden_act="relu",
138
+ num_labels=4, # 0Β°, 90Β°, 180Β°, 270Β°
139
+ )
140
+ model = ResNetForImageClassification(config).to(DEVICE)
141
+ n_params = sum(p.numel() for p in model.parameters())
142
+ print(f"\nπŸ—οΈ Model: ResNet-18 from scratch β€” {n_params:,} parameters")
143
+
144
+ # ────────────────────── Training-Setup ───────────────────────
145
+ optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)
146
+
147
+ total_steps = len(train_loader) * EPOCHS
148
+ warmup_steps = len(train_loader) * WARMUP_EPOCHS
149
+
150
+ def lr_lambda(step):
151
+ if step < warmup_steps:
152
+ return step / max(warmup_steps, 1)
153
+ progress = (step - warmup_steps) / max(total_steps - warmup_steps, 1)
154
+ return 0.5 * (1.0 + math.cos(math.pi * progress))
155
+
156
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
157
+ scaler = torch.cuda.amp.GradScaler()
158
+ criterion = nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING)
159
+
160
+ # ────────────────────── Training-Loop ────────────────────────
161
+ best_val_acc = 0.0
162
+ print(f"\nπŸš€ Starting training: {EPOCHS} epochs, {total_steps:,} steps\n")
163
+
164
+ for epoch in range(EPOCHS):
165
+ t0 = time.time()
166
+
167
+ # ---- Train ----
168
+ model.train()
169
+ run_loss = correct = total = 0
170
+
171
+ pbar = tqdm(train_loader, desc=f"Ep {epoch+1:2d}/{EPOCHS} [Train]", leave=False)
172
+ for imgs, labels in pbar:
173
+ imgs = imgs.to(DEVICE, non_blocking=True)
174
+ labels = labels.to(DEVICE, non_blocking=True)
175
+
176
+ with torch.cuda.amp.autocast():
177
+ logits = model(pixel_values=imgs).logits
178
+ loss = criterion(logits, labels)
179
+
180
+ optimizer.zero_grad(set_to_none=True)
181
+ scaler.scale(loss).backward()
182
+ scaler.unscale_(optimizer)
183
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
184
+ scaler.step(optimizer)
185
+ scaler.update()
186
+ scheduler.step()
187
+
188
+ bs = labels.size(0)
189
+ run_loss += loss.item() * bs
190
+ correct += (logits.argmax(1) == labels).sum().item()
191
+ total += bs
192
+ pbar.set_postfix(loss=f"{run_loss/total:.4f}", acc=f"{100*correct/total:.1f}%")
193
+
194
+ train_acc = 100 * correct / total
195
+
196
+ # ---- Validate ----
197
+ model.eval()
198
+ v_correct = v_total = 0
199
+ v_loss = 0.0
200
+ cls_correct = [0]*4
201
+ cls_total = [0]*4
202
+
203
+ with torch.no_grad():
204
+ for imgs, labels in tqdm(val_loader, desc=f"Ep {epoch+1:2d}/{EPOCHS} [Val] ", leave=False):
205
+ imgs = imgs.to(DEVICE, non_blocking=True)
206
+ labels = labels.to(DEVICE, non_blocking=True)
207
+ with torch.cuda.amp.autocast():
208
+ logits = model(pixel_values=imgs).logits
209
+ loss = criterion(logits, labels)
210
+ preds = logits.argmax(1)
211
+ bs = labels.size(0)
212
+ v_loss += loss.item() * bs
213
+ v_correct += (preds == labels).sum().item()
214
+ v_total += bs
215
+ for c in range(4):
216
+ mask = (labels == c)
217
+ cls_correct[c] += (preds[mask] == labels[mask]).sum().item()
218
+ cls_total[c] += mask.sum().item()
219
+
220
+ val_acc = 100 * v_correct / v_total
221
+ dt = time.time() - t0
222
+
223
+ print(f"Epoch {epoch+1:2d}/{EPOCHS} β”‚ "
224
+ f"Train {train_acc:.1f}% β”‚ Val {val_acc:.2f}% β”‚ "
225
+ f"LR {scheduler.get_last_lr()[0]:.6f} β”‚ {dt:.0f}s")
226
+ for c in range(4):
227
+ ca = 100*cls_correct[c]/max(cls_total[c],1)
228
+ print(f" {ANGLE_NAMES[c]:>25s}: {ca:.1f}%")
229
+
230
+ if val_acc > best_val_acc:
231
+ best_val_acc = val_acc
232
+ model.save_pretrained(MODEL_DIR)
233
+ print(f" βœ… New best model saved β†’ {MODEL_DIR}")
234
+ print()
235
+
236
+ # ── Fertig ──
237
+ print("=" * 60)
238
+ print(f"πŸ† Training finished! Best Val-Accuracy: {best_val_acc:.2f}%")
239
+ print(f" Model: {MODEL_DIR}")