File size: 7,764 Bytes
016eee7 | 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | """
train_mnist_1k_tqdm.py
Trains a tiny MNIST model (<1000 params) until convergence,
using tqdm progress bars and early stopping.
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, random_split
from tqdm import tqdm
import numpy as np
import os
import sys
# -------------------------------
# 0. Automatic device fallback
# -------------------------------
def get_device():
if torch.cuda.is_available():
try:
test_tensor = torch.randn(1, 1, 28, 28).cuda()
_ = torch.nn.functional.avg_pool2d(test_tensor, 4)
return torch.device('cuda')
except Exception as e:
print(f"GPU error: {e}\nFalling back to CPU.")
return torch.device('cpu')
return torch.device('cpu')
device = get_device()
print(f"Using device: {device}")
# -------------------------------
# 1. Model (970 parameters)
# -------------------------------
class TinyMNISTModel(nn.Module):
def __init__(self):
super().__init__()
self.pool = nn.AvgPool2d(4, 4)
self.fc1 = nn.Linear(7*7, 16)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.2)
self.fc2 = nn.Linear(16, 10)
def forward(self, x):
x = self.pool(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.fc2(x)
return x
# -------------------------------
# 2. Data
# -------------------------------
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
full_train = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
# Split 90% train, 10% validation
val_size = int(0.1 * len(full_train))
train_size = len(full_train) - val_size
train_dataset, val_dataset = random_split(full_train, [train_size, val_size])
batch_size = 64
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# -------------------------------
# 3. Training with early stopping + tqdm
# -------------------------------
model = TinyMNISTModel().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
patience = 5
best_val_loss = float('inf')
epochs_no_improve = 0
best_model_state = None
print("\nποΈ Training until convergence (early stopping patience = 5)\n")
epoch = 0
while True:
# Training phase with tqdm
model.train()
train_loss = 0.0
train_bar = tqdm(train_loader, desc=f"Epoch {epoch+1} [Train]", leave=False)
for images, labels in train_bar:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_bar.set_postfix(loss=loss.item())
train_loss /= len(train_loader)
# Validation phase
model.eval()
val_loss = 0.0
correct = 0
total = 0
val_bar = tqdm(val_loader, desc=f"Epoch {epoch+1} [Val]", leave=False)
with torch.no_grad():
for images, labels in val_bar:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
val_loss += loss.item()
_, pred = torch.max(outputs, 1)
total += labels.size(0)
correct += (pred == labels).sum().item()
val_bar.set_postfix(loss=loss.item())
val_loss /= len(val_loader)
val_acc = 100.0 * correct / total
# Print progress line (outside tqdm to keep clean)
print(f"Epoch {epoch+1:3d} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.2f}%")
# Early stopping logic
if val_loss < best_val_loss:
best_val_loss = val_loss
epochs_no_improve = 0
best_model_state = model.state_dict().copy()
else:
epochs_no_improve += 1
if epochs_no_improve >= patience:
print(f"\nπ Early stopping after {epoch+1} epochs (no improvement for {patience} epochs).")
break
epoch += 1
# Restore best model
model.load_state_dict(best_model_state)
# -------------------------------
# 4. Final evaluation on full test set
# -------------------------------
def evaluate(loader, name="Test"):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in tqdm(loader, desc=f"Evaluating on {name}", leave=False):
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, pred = torch.max(outputs, 1)
total += labels.size(0)
correct += (pred == labels).sum().item()
acc = 100.0 * correct / total
print(f"{name} accuracy: {acc:.2f}%")
return acc
test_acc = evaluate(test_loader, "full test set")
total_params = sum(p.numel() for p in model.parameters())
# -------------------------------
# 5. TL;DR summary
# -------------------------------
tldr = f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TL;DR β Tiny MNIST β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
β Parameters: {total_params:<48}β
β Training epochs until convergence: {epoch+1:<31}β
β Best validation loss: {best_val_loss:.4f}<40 spaces>β -- actually align manually
β Final test accuracy: {test_acc:.2f}%<39 spaces>β
β Early stopping patience: {patience} epochs<36 spaces>β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
print(tldr)
# Save model
torch.save(model.state_dict(), "mnist_1k_best.pth")
# -------------------------------
# 6. Generate README.md (HF style)
# -------------------------------
readme_content = f"""---
language: en
license: apache-2.0
tags:
- mnist
- tiny-model
- tqdm
- early-stopping
---
# Tiny MNIST Classifier β with tqdm progress bars
- **Parameters**: {total_params} (<1000)
- **Test accuracy**: {test_acc:.2f}%
- **Epochs trained**: {epoch+1} (early stopping after {patience} epochs without improvement)
This script trains until convergence and shows **tqdm** progress bars for each batch.
## TL;DR
```bash
python train_mnist_1k_tqdm.py
```
## Full results
| Metric | Value |
|---------------------------|-----------------|
| Total parameters | {total_params} |
| Best validation loss | {best_val_loss:.4f} |
| Final test accuracy | {test_acc:.2f}% |
| Early stopping patience | {patience} |
| Training epochs | {epoch+1} |
## Model architecture
AvgPool(4x4) β Linear(49β16) β ReLU β Dropout(0.2) β Linear(16β10)
## How to use
```python
import torch
from train_mnist_1k_tqdm import TinyMNISTModel
model = TinyMNISTModel()
model.load_state_dict(torch.load("mnist_1k_best.pth"))
model.eval()
```
"""
with open("README.md", "w") as f:
f.write(readme_content)
print("β
README.md generated. Model saved as mnist_1k_best.pth")
|