Shanmuk4622 commited on
Commit
9eadada
·
verified ·
1 Parent(s): 7c85344

Upload test1/Algo_CIFAR_10_MobileViTv3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test1/Algo_CIFAR_10_MobileViTv3.py +447 -0
test1/Algo_CIFAR_10_MobileViTv3.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data import Dataset, DataLoader
6
+ import torchvision.transforms as transforms
7
+ from codecarbon import EmissionsTracker
8
+ from carbontracker.tracker import CarbonTracker
9
+ from fvcore.nn import FlopCountAnalysis
10
+ from sklearn.metrics import precision_recall_fscore_support, accuracy_score
11
+ from einops import rearrange
12
+ from tqdm import tqdm
13
+ import pandas as pd
14
+ import numpy as np
15
+ import pickle
16
+ import os
17
+ import time
18
+ import logging
19
+ import warnings
20
+ import gc
21
+
22
+ # ==========================================
23
+ # 1. MOBILEVITV3 ARCHITECTURE DEFINITION
24
+ # ==========================================
25
+
26
+ def conv_1x1_bn(inp, oup):
27
+ return nn.Sequential(
28
+ nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
29
+ nn.BatchNorm2d(oup),
30
+ nn.SiLU()
31
+ )
32
+
33
+ def conv_nxn_bn(inp, oup, kernel_size=3, stride=1):
34
+ return nn.Sequential(
35
+ nn.Conv2d(inp, oup, kernel_size, stride, 1, bias=False),
36
+ nn.BatchNorm2d(oup),
37
+ nn.SiLU()
38
+ )
39
+
40
+ class PreNorm(nn.Module):
41
+ def __init__(self, dim, fn):
42
+ super().__init__()
43
+ self.norm = nn.LayerNorm(dim)
44
+ self.fn = fn
45
+ def forward(self, x, **kwargs):
46
+ return self.fn(self.norm(x), **kwargs)
47
+
48
+ class FeedForward(nn.Module):
49
+ def __init__(self, dim, hidden_dim, dropout=0.):
50
+ super().__init__()
51
+ self.net = nn.Sequential(
52
+ nn.Linear(dim, hidden_dim),
53
+ nn.SiLU(),
54
+ nn.Dropout(dropout),
55
+ nn.Linear(hidden_dim, dim),
56
+ nn.Dropout(dropout)
57
+ )
58
+ def forward(self, x):
59
+ return self.net(x)
60
+
61
+ # --- SPEED FIX 1: Hardware-Fused Attention Kernel ---
62
+ class Attention(nn.Module):
63
+ def __init__(self, dim, heads=8, dim_head=64, dropout=0.):
64
+ super().__init__()
65
+ inner_dim = dim_head * heads
66
+ project_out = not (heads == 1 and dim_head == dim)
67
+
68
+ self.heads = heads
69
+ self.dropout_rate = dropout
70
+
71
+ self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
72
+
73
+ self.to_out = nn.Sequential(
74
+ nn.Linear(inner_dim, dim),
75
+ nn.Dropout(dropout)
76
+ ) if project_out else nn.Identity()
77
+
78
+ def forward(self, x):
79
+ qkv = self.to_qkv(x).chunk(3, dim=-1)
80
+ q, k, v = map(lambda t: rearrange(t, 'b p n (h d) -> b p h n d', h=self.heads), qkv)
81
+
82
+ # PyTorch native SDPA triggers FlashAttention on supported hardware
83
+ out = F.scaled_dot_product_attention(
84
+ q, k, v,
85
+ dropout_p=self.dropout_rate if self.training else 0.0
86
+ )
87
+
88
+ out = rearrange(out, 'b p h n d -> b p n (h d)')
89
+ return self.to_out(out)
90
+
91
+ class Transformer(nn.Module):
92
+ def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.):
93
+ super().__init__()
94
+ self.layers = nn.ModuleList([])
95
+ for _ in range(depth):
96
+ self.layers.append(nn.ModuleList([
97
+ PreNorm(dim, Attention(dim, heads, dim_head, dropout)),
98
+ PreNorm(dim, FeedForward(dim, mlp_dim, dropout))
99
+ ]))
100
+ def forward(self, x):
101
+ for attn, ff in self.layers:
102
+ x = attn(x) + x
103
+ x = ff(x) + x
104
+ return x
105
+
106
+ class MV2Block(nn.Module):
107
+ def __init__(self, inp, oup, stride=1, expansion=4):
108
+ super().__init__()
109
+ self.stride = stride
110
+ hidden_dim = int(inp * expansion)
111
+ self.use_res_connect = self.stride == 1 and inp == oup
112
+
113
+ if expansion == 1:
114
+ self.conv = nn.Sequential(
115
+ nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
116
+ nn.BatchNorm2d(hidden_dim),
117
+ nn.SiLU(),
118
+ nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
119
+ nn.BatchNorm2d(oup),
120
+ )
121
+ else:
122
+ self.conv = nn.Sequential(
123
+ nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
124
+ nn.BatchNorm2d(hidden_dim),
125
+ nn.SiLU(),
126
+ nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
127
+ nn.BatchNorm2d(hidden_dim),
128
+ nn.SiLU(),
129
+ nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
130
+ nn.BatchNorm2d(oup),
131
+ )
132
+
133
+ def forward(self, x):
134
+ if self.use_res_connect:
135
+ return x + self.conv(x)
136
+ else:
137
+ return self.conv(x)
138
+
139
+ class MobileViTBlock(nn.Module):
140
+ def __init__(self, dim, depth, channel, kernel_size, patch_size, mlp_dim, dropout=0.):
141
+ super().__init__()
142
+ self.ph, self.pw = patch_size
143
+
144
+ self.conv1 = conv_nxn_bn(channel, channel, kernel_size)
145
+ self.conv2 = conv_1x1_bn(channel, dim)
146
+
147
+ self.transformer = Transformer(dim, depth, 1, 32, mlp_dim, dropout)
148
+
149
+ self.conv3 = conv_1x1_bn(dim, channel)
150
+ self.conv4 = conv_nxn_bn(2 * channel, channel, kernel_size)
151
+
152
+ def forward(self, x):
153
+ y = x.clone()
154
+
155
+ x = self.conv1(x)
156
+ x = self.conv2(x)
157
+
158
+ _, _, h, w = x.shape
159
+ pad_h = (self.ph - h % self.ph) % self.ph
160
+ pad_w = (self.pw - w % self.pw) % self.pw
161
+
162
+ if pad_h > 0 or pad_w > 0:
163
+ x = nn.functional.pad(x, (0, pad_w, 0, pad_h))
164
+
165
+ _, _, h_pad, w_pad = x.shape
166
+ x = rearrange(x, 'b d (h ph) (w pw) -> b (ph pw) (h w) d', ph=self.ph, pw=self.pw)
167
+ x = self.transformer(x)
168
+ x = rearrange(x, 'b (ph pw) (h w) d -> b d (h ph) (w pw)', h=h_pad//self.ph, w=w_pad//self.pw, ph=self.ph, pw=self.pw)
169
+
170
+ if pad_h > 0 or pad_w > 0:
171
+ x = x[:, :, :h, :w]
172
+
173
+ x = self.conv3(x)
174
+ x = torch.cat((x, y), 1)
175
+ x = self.conv4(x)
176
+ return x
177
+
178
+ class MobileViTv3_Small(nn.Module):
179
+ def __init__(self, image_size=(224, 224), num_classes=10):
180
+ super().__init__()
181
+ ih, iw = image_size
182
+ ph, pw = 2, 2
183
+
184
+ dims = [144, 192, 240]
185
+ channels = [16, 32, 64, 64, 96, 96, 128, 128, 160, 160, 640]
186
+
187
+ self.conv1 = conv_nxn_bn(3, channels[0], stride=2)
188
+
189
+ self.mv2 = nn.ModuleList([])
190
+ self.mv2.append(MV2Block(channels[0], channels[1], 1, 4))
191
+ self.mv2.append(MV2Block(channels[1], channels[2], 2, 4))
192
+ self.mv2.append(MV2Block(channels[2], channels[3], 1, 4))
193
+ self.mv2.append(MV2Block(channels[3], channels[4], 2, 4))
194
+
195
+ self.mvit = nn.ModuleList([])
196
+ self.mvit.append(MobileViTBlock(dims[0], 2, channels[5], 3, (ph, pw), int(dims[0]*2)))
197
+
198
+ self.mv2_2 = nn.ModuleList([])
199
+ self.mv2_2.append(MV2Block(channels[5], channels[6], 2, 4))
200
+
201
+ self.mvit_2 = nn.ModuleList([])
202
+ self.mvit_2.append(MobileViTBlock(dims[1], 4, channels[7], 3, (ph, pw), int(dims[1]*2)))
203
+
204
+ self.mv2_3 = nn.ModuleList([])
205
+ self.mv2_3.append(MV2Block(channels[7], channels[8], 2, 4))
206
+
207
+ self.mvit_3 = nn.ModuleList([])
208
+ self.mvit_3.append(MobileViTBlock(dims[2], 3, channels[9], 3, (ph, pw), int(dims[2]*2)))
209
+
210
+ self.conv2 = conv_1x1_bn(channels[9], channels[10])
211
+ self.pool = nn.AdaptiveAvgPool2d((1, 1))
212
+ self.fc = nn.Linear(channels[10], num_classes)
213
+
214
+ def forward(self, x):
215
+ x = self.conv1(x)
216
+ for conv in self.mv2: x = conv(x)
217
+ for m in self.mvit: x = m(x)
218
+ for conv in self.mv2_2: x = conv(x)
219
+ for m in self.mvit_2: x = m(x)
220
+ for conv in self.mv2_3: x = conv(x)
221
+ for m in self.mvit_3: x = m(x)
222
+ x = self.conv2(x)
223
+ x = self.pool(x).view(-1, x.shape[1])
224
+ return self.fc(x)
225
+
226
+ # ==========================================
227
+ # 2. EDEN EXPERIMENT & PROFILING
228
+ # ==========================================
229
+
230
+ warnings.filterwarnings("ignore", category=UserWarning)
231
+ logging.getLogger("codecarbon").setLevel(logging.ERROR)
232
+
233
+ # --- Configurations ---
234
+ DATA_DIR = r"C:\Users\shanm\Dataset Download\cifar-10-batches-py"
235
+ LOG_FILE = "eden_optimized_cifar10_custom_mobilevitv3.csv"
236
+ MODEL_SAVE_PATH = "eden_optimized_custom_mobilevitv3_cifar10.pth"
237
+
238
+ BATCH_SIZE = 32
239
+ ACCUMULATION_STEPS = 4
240
+ LEARNING_RATE = 1e-3
241
+ NUM_EPOCHS = 50
242
+ L1_LAMBDA = 1e-5
243
+
244
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
245
+
246
+ # --- SPEED FIX 2: Barebones CPU DataLoader ---
247
+ class CIFAR10Binary(Dataset):
248
+ def __init__(self, root, train=True):
249
+ self.data = []
250
+ self.labels = []
251
+
252
+ if train:
253
+ for i in range(1, 6):
254
+ file_path = os.path.join(root, f'data_batch_{i}')
255
+ with open(file_path, 'rb') as f:
256
+ entry = pickle.load(f, encoding='latin1')
257
+ self.data.append(entry['data'])
258
+ self.labels.extend(entry['labels'])
259
+ self.data = np.vstack(self.data).reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
260
+ else:
261
+ file_path = os.path.join(root, 'test_batch')
262
+ with open(file_path, 'rb') as f:
263
+ entry = pickle.load(f, encoding='latin1')
264
+ self.data = entry['data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
265
+ self.labels = entry['labels']
266
+
267
+ def __len__(self): return len(self.data)
268
+
269
+ def __getitem__(self, idx):
270
+ img, target = self.data[idx], self.labels[idx]
271
+ # Instantly convert raw numpy to tensor (no PIL conversion)
272
+ img = torch.from_numpy(img).permute(2, 0, 1).float() / 255.0
273
+ return img, target
274
+
275
+ def run_experiment():
276
+ # --- SPEED FIX 3: Enable CuDNN Benchmark ---
277
+ torch.backends.cudnn.benchmark = True
278
+ torch.cuda.empty_cache()
279
+ gc.collect()
280
+
281
+ print("\n[EDEN Setup] Loading Custom MobileViTv3-Small...")
282
+ model = MobileViTv3_Small(image_size=(224, 224), num_classes=10)
283
+ model = model.to(DEVICE)
284
+
285
+ optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
286
+
287
+ dummy_input = torch.randn(1, 3, 224, 224).to(DEVICE)
288
+ with warnings.catch_warnings():
289
+ warnings.simplefilter("ignore")
290
+ total_flops = FlopCountAnalysis(model, dummy_input).total()
291
+ total_params = sum(p.numel() for p in model.parameters())
292
+
293
+ # Load dataset with zero CPU preprocessing overhead
294
+ train_set = CIFAR10Binary(root=DATA_DIR, train=True)
295
+ loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)
296
+
297
+ criterion = nn.CrossEntropyLoss()
298
+ scaler = torch.cuda.amp.GradScaler()
299
+
300
+ cc_tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
301
+ ct_tracker = CarbonTracker(epochs=NUM_EPOCHS, monitor_epochs=NUM_EPOCHS, update_interval=1)
302
+
303
+ cc_tracker.start()
304
+ all_logs = []
305
+ total_iterations_counter = 0
306
+ session_start_time = time.time()
307
+
308
+ prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = 0.0, 0.0, 0.0
309
+
310
+ # Define the normalizer once, push it directly to the GPU
311
+ normalizer = transforms.Normalize(
312
+ (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
313
+ ).to(DEVICE)
314
+
315
+ print(f"\nEDEN PROFILING STARTED | DEVICE: {torch.cuda.get_device_name(0)}")
316
+ print(f"Dataset: CIFAR-10 (RAM Cached, GPU Resized) | Architecture: Custom MobileViTv3-Small")
317
+ print(f"Params: {total_params:,} | FLOPs: {total_flops:.2e}\n")
318
+
319
+ for epoch in range(NUM_EPOCHS):
320
+ ct_tracker.epoch_start()
321
+ torch.cuda.reset_peak_memory_stats()
322
+ epoch_start_time = time.time()
323
+ model.train()
324
+
325
+ running_loss = 0.0
326
+ all_preds, all_labels = [], []
327
+ epoch_grad_norms = []
328
+
329
+ optimizer.zero_grad()
330
+ pbar = tqdm(loader, desc=f"Epoch {epoch+1}/{NUM_EPOCHS}", unit="batch", leave=False)
331
+
332
+ for i, (images, labels) in enumerate(pbar):
333
+ # --- SPEED FIX 4: GPU-Accelerated Resizing and Normalization ---
334
+ images, labels = images.to(DEVICE), labels.to(DEVICE)
335
+
336
+ # Resize the entire batch simultaneously on the CUDA cores
337
+ images = F.interpolate(
338
+ images, size=(224, 224), mode='bilinear', align_corners=False
339
+ )
340
+ images = normalizer(images)
341
+ # ---------------------------------------------------------------
342
+
343
+ with torch.cuda.amp.autocast():
344
+ outputs = model(images)
345
+ loss = criterion(outputs, labels)
346
+
347
+ # Active Sparse Training (L1 Penalty)
348
+ l1_penalty = sum(p.abs().sum() for p in model.parameters())
349
+ total_loss = loss + (L1_LAMBDA * l1_penalty)
350
+ scaled_loss = total_loss / ACCUMULATION_STEPS
351
+
352
+ scaler.scale(scaled_loss).backward()
353
+
354
+ grad_norm = 0.0
355
+ for p in model.parameters():
356
+ if p.grad is not None:
357
+ grad_norm += p.grad.data.norm(2).item() ** 2
358
+ epoch_grad_norms.append(grad_norm ** 0.5)
359
+
360
+ if (i + 1) % ACCUMULATION_STEPS == 0:
361
+ scaler.step(optimizer)
362
+ scaler.update()
363
+ optimizer.zero_grad()
364
+
365
+ running_loss += loss.item() * ACCUMULATION_STEPS
366
+
367
+ _, preds = torch.max(outputs, 1)
368
+ all_preds.extend(preds.cpu().numpy())
369
+ all_labels.extend(labels.cpu().numpy())
370
+ total_iterations_counter += 1
371
+
372
+ pbar.set_postfix(loss=f"{(loss.item()*ACCUMULATION_STEPS):.4f}")
373
+
374
+ # --- A. Evaluation ---
375
+ ct_tracker.epoch_end()
376
+ epoch_end_time = time.time()
377
+ epoch_duration = epoch_end_time - epoch_start_time
378
+ avg_it_per_sec = len(loader) / epoch_duration
379
+
380
+ acc = accuracy_score(all_labels, all_preds)
381
+ p, r, f1, _ = precision_recall_fscore_support(all_labels, all_preds, average='macro', zero_division=0)
382
+
383
+ model.eval()
384
+ with torch.no_grad():
385
+ sample_img = torch.randn(1, 3, 224, 224).to(DEVICE)
386
+ _ = model(sample_img)
387
+ torch.cuda.synchronize()
388
+
389
+ starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
390
+ starter.record()
391
+ _ = model(sample_img)
392
+ ender.record()
393
+ torch.cuda.synchronize()
394
+ lat_ms = starter.elapsed_time(ender)
395
+
396
+ # --- B. Energy & Power Calculations ---
397
+ emissions_data = cc_tracker._prepare_emissions_data()
398
+
399
+ cum_gpu_j = emissions_data.gpu_energy * 3.6e6
400
+ cum_cpu_j = emissions_data.cpu_energy * 3.6e6
401
+ cum_ram_j = emissions_data.ram_energy * 3.6e6
402
+ cum_total_j = cum_gpu_j + cum_cpu_j + cum_ram_j
403
+
404
+ epoch_gpu_j = cum_gpu_j - prev_cum_gpu_j
405
+ epoch_cpu_j = cum_cpu_j - prev_cum_cpu_j
406
+ epoch_ram_j = cum_ram_j - prev_cum_ram_j
407
+ epoch_total_j = epoch_gpu_j + epoch_cpu_j + epoch_ram_j
408
+
409
+ prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = cum_gpu_j, cum_cpu_j, cum_ram_j
410
+
411
+ avg_gpu_w = epoch_gpu_j / epoch_duration if epoch_duration > 0 else 0
412
+ avg_cpu_w = epoch_cpu_j / epoch_duration if epoch_duration > 0 else 0
413
+ avg_ram_w = epoch_ram_j / epoch_duration if epoch_duration > 0 else 0
414
+
415
+ vram_peak = torch.cuda.max_memory_allocated(DEVICE) / (1024**3)
416
+
417
+ # --- C. Terminal Update ---
418
+ print(f"Epoch {epoch+1} Summary:")
419
+ print(f" > Acc: {acc:.4f} | F1: {f1:.4f} | Loss: {running_loss/len(loader):.4f}")
420
+ print(f" > Epoch Energy: {epoch_total_j:.1f}J")
421
+ print(f" > Avg Power: GPU {avg_gpu_w:.1f}W | VRAM: {vram_peak:.2f}GB | Latency: {lat_ms:.2f}ms")
422
+ print("-" * 65)
423
+
424
+ # --- D. Unified Verified CSV Logging ---
425
+ log_entry = {
426
+ "epoch": epoch + 1,
427
+ "loss": running_loss / len(loader),
428
+ "accuracy": acc, "f1_score": f1, "precision": p, "recall": r,
429
+ "epoch_energy_gpu_j": epoch_gpu_j, "epoch_energy_cpu_j": epoch_cpu_j,
430
+ "epoch_energy_ram_j": epoch_ram_j, "epoch_total_energy_j": epoch_total_j,
431
+ "cumulative_total_energy_j": cum_total_j, "carbon_emissions_kg": emissions_data.emissions,
432
+ "avg_power_gpu_w": avg_gpu_w, "avg_power_cpu_w": avg_cpu_w, "avg_power_ram_w": avg_ram_w,
433
+ "vram_peak_gb": vram_peak, "latency_ms": lat_ms, "avg_grad_norm": np.mean(epoch_grad_norms),
434
+ "it_per_sec": avg_it_per_sec, "total_iterations": total_iterations_counter,
435
+ "epoch_duration_sec": epoch_duration, "cumulative_time_sec": time.time() - session_start_time
436
+ }
437
+ all_logs.append(log_entry)
438
+ pd.DataFrame(all_logs).to_csv(LOG_FILE, index=False)
439
+
440
+ cc_tracker.stop()
441
+
442
+ # --- E. Save Optimized Model ---
443
+ torch.save(model.state_dict(), MODEL_SAVE_PATH)
444
+ print(f"\n[FINISH] Verified Optimization Complete.")
445
+
446
+ if __name__ == "__main__":
447
+ run_experiment()