Shanmuk4622 commited on
Commit
adfd7fd
·
verified ·
1 Parent(s): 13b1d85

Upload test1/Algo_CIFAR_100_MobileViTv3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test1/Algo_CIFAR_100_MobileViTv3.py +433 -0
test1/Algo_CIFAR_100_MobileViTv3.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Hardware-Fused Attention Kernel for Maximum Speed
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
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=100): # Updated Default to 100
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\CIFAR100"
235
+ LOG_FILE = "eden_optimized_cifar100_custom_mobilevitv3.csv"
236
+ MODEL_SAVE_PATH = "eden_optimized_custom_mobilevitv3_cifar100.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
+ # --- CPU-Bypass DataLoader for CIFAR-100 ---
247
+ class CIFAR100Binary(Dataset):
248
+ def __init__(self, root, train=True):
249
+ file_name = 'train' if train else 'test'
250
+ file_path = os.path.join(root, file_name)
251
+ with open(file_path, 'rb') as f:
252
+ entry = pickle.load(f, encoding='latin1')
253
+ self.data = entry['data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
254
+ self.labels = entry['fine_labels']
255
+
256
+ def __len__(self): return len(self.data)
257
+
258
+ def __getitem__(self, idx):
259
+ img, target = self.data[idx], self.labels[idx]
260
+ # Instantly convert raw numpy to tensor (no CPU PIL conversion)
261
+ img = torch.from_numpy(img).permute(2, 0, 1).float() / 255.0
262
+ return img, target
263
+
264
+ def run_experiment():
265
+ # Enable CuDNN Benchmark for Custom Architecture Acceleration
266
+ torch.backends.cudnn.benchmark = True
267
+ torch.cuda.empty_cache()
268
+ gc.collect()
269
+
270
+ print("\n[EDEN Setup] Loading Custom MobileViTv3-Small (100 Classes)...")
271
+ model = MobileViTv3_Small(image_size=(224, 224), num_classes=100) # Updated to 100
272
+ model = model.to(DEVICE)
273
+
274
+ optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
275
+
276
+ dummy_input = torch.randn(1, 3, 224, 224).to(DEVICE)
277
+ with warnings.catch_warnings():
278
+ warnings.simplefilter("ignore")
279
+ total_flops = FlopCountAnalysis(model, dummy_input).total()
280
+ total_params = sum(p.numel() for p in model.parameters())
281
+
282
+ train_set = CIFAR100Binary(root=DATA_DIR, train=True)
283
+ loader = DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True)
284
+
285
+ criterion = nn.CrossEntropyLoss()
286
+ scaler = torch.cuda.amp.GradScaler()
287
+
288
+ cc_tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
289
+ ct_tracker = CarbonTracker(epochs=NUM_EPOCHS, monitor_epochs=NUM_EPOCHS, update_interval=1)
290
+
291
+ cc_tracker.start()
292
+ all_logs = []
293
+ total_iterations_counter = 0
294
+ session_start_time = time.time()
295
+
296
+ prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = 0.0, 0.0, 0.0
297
+
298
+ # Updated Normalizer tuned specifically for CIFAR-100 image data
299
+ normalizer = transforms.Normalize(
300
+ (0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)
301
+ ).to(DEVICE)
302
+
303
+ print(f"\nEDEN PROFILING STARTED | DEVICE: {torch.cuda.get_device_name(0)}")
304
+ print(f"Dataset: CIFAR-100 (RAM Cached, GPU Resized) | Architecture: Custom MobileViTv3-Small")
305
+ print(f"Params: {total_params:,} | FLOPs: {total_flops:.2e}\n")
306
+
307
+ for epoch in range(NUM_EPOCHS):
308
+ ct_tracker.epoch_start()
309
+ torch.cuda.reset_peak_memory_stats()
310
+ epoch_start_time = time.time()
311
+ model.train()
312
+
313
+ running_loss = 0.0
314
+ all_preds, all_labels = [], []
315
+ epoch_grad_norms = []
316
+
317
+ optimizer.zero_grad()
318
+ pbar = tqdm(loader, desc=f"Epoch {epoch+1}/{NUM_EPOCHS}", unit="batch", leave=False)
319
+
320
+ for i, (images, labels) in enumerate(pbar):
321
+ # GPU-Accelerated Resizing and Normalization
322
+ images, labels = images.to(DEVICE), labels.to(DEVICE)
323
+ images = F.interpolate(
324
+ images, size=(224, 224), mode='bilinear', align_corners=False
325
+ )
326
+ images = normalizer(images)
327
+
328
+ with torch.cuda.amp.autocast():
329
+ outputs = model(images)
330
+ loss = criterion(outputs, labels)
331
+
332
+ # Active Sparse Training (L1 Penalty) applied natively
333
+ l1_penalty = sum(p.abs().sum() for p in model.parameters())
334
+ total_loss = loss + (L1_LAMBDA * l1_penalty)
335
+ scaled_loss = total_loss / ACCUMULATION_STEPS
336
+
337
+ scaler.scale(scaled_loss).backward()
338
+
339
+ grad_norm = 0.0
340
+ for p in model.parameters():
341
+ if p.grad is not None:
342
+ grad_norm += p.grad.data.norm(2).item() ** 2
343
+ epoch_grad_norms.append(grad_norm ** 0.5)
344
+
345
+ if (i + 1) % ACCUMULATION_STEPS == 0:
346
+ scaler.step(optimizer)
347
+ scaler.update()
348
+ optimizer.zero_grad()
349
+
350
+ # Track pure classification loss for clean logging
351
+ running_loss += loss.item() * ACCUMULATION_STEPS
352
+
353
+ _, preds = torch.max(outputs, 1)
354
+ all_preds.extend(preds.cpu().numpy())
355
+ all_labels.extend(labels.cpu().numpy())
356
+ total_iterations_counter += 1
357
+
358
+ pbar.set_postfix(loss=f"{(loss.item()*ACCUMULATION_STEPS):.4f}")
359
+
360
+ # --- A. Evaluation ---
361
+ ct_tracker.epoch_end()
362
+ epoch_end_time = time.time()
363
+ epoch_duration = epoch_end_time - epoch_start_time
364
+ avg_it_per_sec = len(loader) / epoch_duration
365
+
366
+ acc = accuracy_score(all_labels, all_preds)
367
+ p, r, f1, _ = precision_recall_fscore_support(all_labels, all_preds, average='macro', zero_division=0)
368
+
369
+ model.eval()
370
+ with torch.no_grad():
371
+ sample_img = torch.randn(1, 3, 224, 224).to(DEVICE)
372
+ _ = model(sample_img)
373
+ torch.cuda.synchronize()
374
+
375
+ starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
376
+ starter.record()
377
+ _ = model(sample_img)
378
+ ender.record()
379
+ torch.cuda.synchronize()
380
+ lat_ms = starter.elapsed_time(ender)
381
+
382
+ # --- B. Energy & Power Calculations ---
383
+ emissions_data = cc_tracker._prepare_emissions_data()
384
+
385
+ cum_gpu_j = emissions_data.gpu_energy * 3.6e6
386
+ cum_cpu_j = emissions_data.cpu_energy * 3.6e6
387
+ cum_ram_j = emissions_data.ram_energy * 3.6e6
388
+ cum_total_j = cum_gpu_j + cum_cpu_j + cum_ram_j
389
+
390
+ epoch_gpu_j = cum_gpu_j - prev_cum_gpu_j
391
+ epoch_cpu_j = cum_cpu_j - prev_cum_cpu_j
392
+ epoch_ram_j = cum_ram_j - prev_cum_ram_j
393
+ epoch_total_j = epoch_gpu_j + epoch_cpu_j + epoch_ram_j
394
+
395
+ prev_cum_gpu_j, prev_cum_cpu_j, prev_cum_ram_j = cum_gpu_j, cum_cpu_j, cum_ram_j
396
+
397
+ avg_gpu_w = epoch_gpu_j / epoch_duration if epoch_duration > 0 else 0
398
+ avg_cpu_w = epoch_cpu_j / epoch_duration if epoch_duration > 0 else 0
399
+ avg_ram_w = epoch_ram_j / epoch_duration if epoch_duration > 0 else 0
400
+
401
+ vram_peak = torch.cuda.max_memory_allocated(DEVICE) / (1024**3)
402
+
403
+ # --- C. Terminal Update ---
404
+ print(f"Epoch {epoch+1} Summary:")
405
+ print(f" > Acc: {acc:.4f} | F1: {f1:.4f} | Loss: {running_loss/len(loader):.4f}")
406
+ print(f" > Epoch Energy: {epoch_total_j:.1f}J")
407
+ print(f" > Avg Power: GPU {avg_gpu_w:.1f}W | VRAM: {vram_peak:.2f}GB | Latency: {lat_ms:.2f}ms")
408
+ print("-" * 65)
409
+
410
+ # --- D. Unified Verified CSV Logging ---
411
+ log_entry = {
412
+ "epoch": epoch + 1,
413
+ "loss": running_loss / len(loader),
414
+ "accuracy": acc, "f1_score": f1, "precision": p, "recall": r,
415
+ "epoch_energy_gpu_j": epoch_gpu_j, "epoch_energy_cpu_j": epoch_cpu_j,
416
+ "epoch_energy_ram_j": epoch_ram_j, "epoch_total_energy_j": epoch_total_j,
417
+ "cumulative_total_energy_j": cum_total_j, "carbon_emissions_kg": emissions_data.emissions,
418
+ "avg_power_gpu_w": avg_gpu_w, "avg_power_cpu_w": avg_cpu_w, "avg_power_ram_w": avg_ram_w,
419
+ "vram_peak_gb": vram_peak, "latency_ms": lat_ms, "avg_grad_norm": np.mean(epoch_grad_norms),
420
+ "it_per_sec": avg_it_per_sec, "total_iterations": total_iterations_counter,
421
+ "epoch_duration_sec": epoch_duration, "cumulative_time_sec": time.time() - session_start_time
422
+ }
423
+ all_logs.append(log_entry)
424
+ pd.DataFrame(all_logs).to_csv(LOG_FILE, index=False)
425
+
426
+ cc_tracker.stop()
427
+
428
+ # --- E. Save Optimized Model ---
429
+ torch.save(model.state_dict(), MODEL_SAVE_PATH)
430
+ print(f"\n[FINISH] Verified Optimization Complete.")
431
+
432
+ if __name__ == "__main__":
433
+ run_experiment()