Hitelcy commited on
Commit
900e0db
ยท
verified ยท
1 Parent(s): 6e22561

Add detailed training script and documentation for FSD50K Part 3

Browse files
model_checkpoints/Primitive_Extractor/FSD50k/training_script_part3.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WindOneSound 300M: FSD50K Part 3 Training
2
+
3
+ ## Overview
4
+ This script fine-tunes the existing Part 1 + Part 2 Primitive Extractor checkpoint on the newly processed FSD50K Part 3 dataset. The goal is to expand the model's acoustic knowledge base and improve its generalization without catastrophic forgetting of previously learned environmental sounds.
5
+
6
+ ## Methodology & Configuration
7
+ - **Base Checkpoint:** `best_fsd50k_primitive_part1_and_2.pt`
8
+ - **Dataset:** FSD50K Part 3 (7,353 training samples, 841 validation samples)
9
+ - **Dual-Loss Objective:**
10
+ - **Weighted BCE Loss:** Handles multi-label classification with dynamically calculated class weights to balance rare and common sounds.
11
+ - **MSE Reconstruction Loss:** Forces the model to rebuild the input BEATs features from the primitives, preserving the acoustic feature space and preventing representation collapse.
12
+ - **Total Loss:** `BCE_Loss + (0.1 * MSE_Loss)`
13
+ - **Optimizer & Scheduler:** AdamW (lr=2e-4, weight_decay=1e-4) with a 10% Linear Warmup followed by Cosine Annealing decay.
14
+ - **Epochs:** 10
15
+ - **Mobile Optimization:** Harmless PyTorch warnings are suppressed at runtime. The training loop outputs a clean, structured table after each epoch to prevent scrolling spam on mobile devices.
16
+
17
+ ## Training Script
18
+
19
+ ```python
20
+ import os
21
+ import warnings
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.optim as optim
25
+ import pandas as pd
26
+ import numpy as np
27
+ import getpass
28
+ import zipfile
29
+ from tqdm.auto import tqdm
30
+ from sklearn.metrics import average_precision_score
31
+ from huggingface_hub import HfApi, hf_hub_download
32
+
33
+ # ==========================================
34
+ # 1. SUPPRESS HARMLESS PYTORCH WARNINGS
35
+ # ==========================================
36
+ warnings.filterwarnings("ignore", category=FutureWarning)
37
+ warnings.filterwarnings("ignore", category=UserWarning)
38
+
39
+ # ==========================================
40
+ # 2. AUTHENTICATION & SETUP
41
+ # ==========================================
42
+ HF_TOKEN = getpass.getpass("Enter your Hugging Face API token (hidden): ")
43
+ api = HfApi(token=HF_TOKEN)
44
+ repo_id = "Hitelcy/WindoneRepo2"
45
+ work_dir = "/content/training_part3"
46
+ os.makedirs(work_dir, exist_ok=True)
47
+
48
+ print("
49
+ โฌ‡๏ธ Downloading Part 3 assets from Hugging Face...")
50
+
51
+ # Download Part 3 Features Zip
52
+ zip_path = hf_hub_download(
53
+ repo_id=repo_id, repo_type="dataset",
54
+ filename="datasets/FSD50K/part3_beats_features.zip",
55
+ local_dir=work_dir, token=HF_TOKEN
56
+ )
57
+
58
+ # Download Labels
59
+ dev_csv = hf_hub_download(
60
+ repo_id=repo_id, repo_type="dataset",
61
+ filename="datasets/FSD50K/labels/ground_truth/dev.csv",
62
+ local_dir=work_dir, token=HF_TOKEN
63
+ )
64
+ vocab_csv = hf_hub_download(
65
+ repo_id=repo_id, repo_type="dataset",
66
+ filename="datasets/FSD50K/labels/ground_truth/vocabulary.csv",
67
+ local_dir=work_dir, token=HF_TOKEN
68
+ )
69
+
70
+ # Download Checkpoint
71
+ ckpt_path = hf_hub_download(
72
+ repo_id=repo_id, repo_type="dataset",
73
+ filename="model_checkpoints/Primitive_Extractor/FSD50k/best_fsd50k_primitive_part1_and_2.pt",
74
+ local_dir=work_dir, token=HF_TOKEN
75
+ )
76
+
77
+ print("๐Ÿ“ฆ Unzipping Part 3 features...")
78
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
79
+ zip_ref.extractall(work_dir)
80
+ features_dir = work_dir
81
+
82
+ # ==========================================
83
+ # 3. MATCH FEATURES TO LABELS
84
+ # ==========================================
85
+ print("๐Ÿท๏ธ Processing Labels & Matching Part 3...")
86
+ dev_df = pd.read_csv(dev_csv)
87
+ vocab_df = pd.read_csv(vocab_csv)
88
+
89
+ class_names = vocab_df.iloc[:, 1].tolist()
90
+ class_to_idx = {name: idx for idx, name in enumerate(class_names)}
91
+ num_classes = len(class_to_idx)
92
+
93
+ # Get all extracted .pt filenames
94
+ pt_files_set = set(f.replace('.pt', '') for f in os.listdir(features_dir) if f.endswith('.pt'))
95
+
96
+ train_set = []
97
+ val_set = []
98
+
99
+ print("๐Ÿ”— Matching Part 3 files to ground truth...")
100
+ for _, row in tqdm(dev_df.iterrows(), total=len(dev_df), desc="Matching", leave=False):
101
+ fname = str(row['fname'])
102
+ if fname in pt_files_set:
103
+ labels = str(row['labels']).split(',')
104
+ targets = torch.zeros(num_classes)
105
+ for lbl in labels:
106
+ if lbl in class_to_idx:
107
+ targets[class_to_idx[lbl]] = 1.0
108
+
109
+ item = {'file': os.path.join(features_dir, f"{fname}.pt"), 'target': targets}
110
+ if row['split'] == 'train':
111
+ train_set.append(item)
112
+ elif row['split'] == 'val':
113
+ val_set.append(item)
114
+
115
+ print(f"โœ… Matched {len(train_set)} training and {len(val_set)} validation samples.
116
+ ")
117
+
118
+ # Calculate Class Weights for Weighted BCE
119
+ all_targets = torch.stack([d['target'] for d in train_set])
120
+ pos_counts = all_targets.sum(dim=0)
121
+ neg_counts = len(train_set) - pos_counts
122
+ weights = (neg_counts / (pos_counts + 1e-5)).clamp(max=50.0)
123
+
124
+ # ==========================================
125
+ # 4. DEFINE & LOAD MODEL
126
+ # ==========================================
127
+ class ConvNormGELU(nn.Module):
128
+ def __init__(self, in_channels, out_channels, kernel_size, padding):
129
+ super().__init__()
130
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, padding=padding)
131
+ self.norm = nn.LayerNorm(out_channels)
132
+ self.act = nn.GELU()
133
+ def forward(self, x):
134
+ x = self.conv(x)
135
+ x = x.transpose(1, 2)
136
+ x = self.norm(x)
137
+ x = x.transpose(1, 2)
138
+ return self.act(x)
139
+
140
+ class PrimitiveExtractor(nn.Module):
141
+ def __init__(self, input_dim=768, hidden_dim=512, num_classes=200):
142
+ super().__init__()
143
+ self.conv_stack = nn.Sequential(
144
+ ConvNormGELU(input_dim, 1728, 7, 3),
145
+ ConvNormGELU(1728, 1728, 5, 2),
146
+ ConvNormGELU(1728, 1728, 3, 1)
147
+ )
148
+ self.proj = nn.Sequential(nn.Linear(1728, hidden_dim), nn.LayerNorm(hidden_dim))
149
+ self.attn = nn.MultiheadAttention(hidden_dim, num_heads=8, batch_first=True)
150
+ self.norm = nn.LayerNorm(hidden_dim)
151
+ self.decoder = nn.Sequential(nn.Linear(hidden_dim, 1024), nn.GELU(), nn.Linear(1024, input_dim))
152
+ self.classifier = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.GELU(), nn.Dropout(0.2), nn.Linear(hidden_dim, num_classes))
153
+
154
+ def forward(self, x):
155
+ x_conv = x.transpose(1, 2)
156
+ features = self.conv_stack(x_conv).transpose(1, 2)
157
+ features = self.proj(features)
158
+ attn_out, _ = self.attn(features, features, features)
159
+ primitives = self.norm(features + attn_out)
160
+
161
+ # Reconstruction output
162
+ reconstruction_output = self.decoder(primitives)
163
+
164
+ # Classification output
165
+ pooled = primitives.mean(dim=1)
166
+ logits = self.classifier(pooled)
167
+
168
+ return reconstruction_output, logits
169
+
170
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
171
+
172
+ print("
173
+ ๐Ÿง  Loading Part 1 + Part 2 Checkpoint...")
174
+ state_dict = torch.load(ckpt_path, map_location=device)
175
+ actual_num_classes = state_dict['classifier.3.weight'].shape[0]
176
+ model = PrimitiveExtractor(input_dim=768, hidden_dim=512, num_classes=actual_num_classes).to(device)
177
+ model.load_state_dict(state_dict)
178
+ print(f"โœ… Model loaded successfully ({actual_num_classes} classes).")
179
+
180
+ # ==========================================
181
+ # 5. TRAINING SETUP (DUAL LOSS + WARMUP)
182
+ # ==========================================
183
+ epochs = 10
184
+ alpha = 0.1 # Weight for MSE Reconstruction loss
185
+ batch_size = 16
186
+
187
+ optimizer = optim.AdamW(model.parameters(), lr=2e-4, weight_decay=1e-4)
188
+
189
+ # Calculate true optimizer steps for accurate warmup
190
+ steps_per_epoch = int(np.ceil(len(train_set) / batch_size))
191
+ total_steps = steps_per_epoch * epochs
192
+ warmup_steps = int(total_steps * 0.1)
193
+
194
+ def lr_lambda(step):
195
+ if step < warmup_steps:
196
+ return float(step) / float(max(1, warmup_steps))
197
+ return 0.5 * (1 + np.cos(np.pi * (step - warmup_steps) / (total_steps - warmup_steps)))
198
+
199
+ scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
200
+ bce_loss_fn = nn.BCEWithLogitsLoss(pos_weight=weights.to(device))
201
+ mse_loss_fn = nn.MSELoss()
202
+
203
+ best_val_map = 0.0
204
+ global_step = 0
205
+
206
+ # ==========================================
207
+ # 6. TRAINING LOOP (MOBILE OPTIMIZED)
208
+ # ==========================================
209
+ print(f"
210
+ {'='*65}")
211
+ print(f" STARTING TRAINING: {epochs} Epochs | Target Metric: Val mAP")
212
+ print(f"{'='*65}")
213
+
214
+ for epoch in range(1, epochs + 1):
215
+ model.train()
216
+ epoch_bce = 0.0
217
+ epoch_mse = 0.0
218
+
219
+ np.random.shuffle(train_set)
220
+
221
+ # leave=False keeps the progress bar on one line, updating in place
222
+ pbar = tqdm(range(0, len(train_set), batch_size), desc=f"Epoch {epoch}/{epochs}", leave=False, ncols=80)
223
+ for i in pbar:
224
+ batch = train_set[i:i+batch_size]
225
+ optimizer.zero_grad()
226
+
227
+ batch_bce = 0.0
228
+ batch_mse = 0.0
229
+
230
+ for item in batch:
231
+ x = torch.load(item['file'], map_location=device).unsqueeze(0)
232
+ y = item['target'].unsqueeze(0).to(device)
233
+
234
+ recon_out, logits = model(x)
235
+
236
+ loss_bce = bce_loss_fn(logits, y)
237
+ loss_mse = mse_loss_fn(recon_out, x)
238
+ loss = loss_bce + (alpha * loss_mse)
239
+
240
+ loss.backward()
241
+
242
+ batch_bce += loss_bce.item()
243
+ batch_mse += loss_mse.item()
244
+
245
+ optimizer.step()
246
+ scheduler.step()
247
+ global_step += 1
248
+
249
+ epoch_bce += batch_bce / len(batch)
250
+ epoch_mse += batch_mse / len(batch)
251
+ pbar.set_postfix({'LR': f"{scheduler.get_last_lr()[0]:.2e}"})
252
+ pbar.close() # Close the bar cleanly before printing the table
253
+
254
+ # Evaluation
255
+ model.eval()
256
+ all_preds = []
257
+ all_targets = []
258
+ with torch.no_grad():
259
+ for item in val_set:
260
+ x = torch.load(item['file'], map_location=device).unsqueeze(0)
261
+ y = item['target']
262
+ _, logits = model(x)
263
+ preds = torch.sigmoid(logits).cpu().squeeze()
264
+ all_preds.append(preds.numpy())
265
+ all_targets.append(y.numpy())
266
+
267
+ val_map = average_precision_score(np.array(all_targets), np.array(all_preds), average='macro')
268
+
269
+ # Print Clean Epoch Table
270
+ print(f"
271
+ {'='*65}")
272
+ print(f" Epoch | BCE Loss | MSE Loss | Val mAP | LR ")
273
+ print(f"{'-'*65}")
274
+ print(f" {epoch:02d} | {epoch_bce/steps_per_epoch:.4f} | {epoch_mse/steps_per_epoch:.4f} | {val_map:.4f} | {scheduler.get_last_lr()[0]:.2e}")
275
+ print(f"{'='*65}")
276
+
277
+ # Checkpointing
278
+ if val_map > best_val_map:
279
+ best_val_map = val_map
280
+ save_path = "/content/best_fsd50k_primitive_part1_2_and_3.pt"
281
+ torch.save(model.state_dict(), save_path)
282
+ print(f" ๐Ÿ† NEW BEST! Checkpoint saved (mAP: {best_val_map:.4f})
283
+ ")
284
+ else:
285
+ print(f" (Best mAP remains: {best_val_map:.4f})
286
+ ")
287
+
288
+ print(f"{'='*65}")
289
+ print(f" ๐ŸŽ‰ TRAINING COMPLETE!")
290
+ print(f" ๐Ÿ’พ Best model saved at: /content/best_fsd50k_primitive_part1_2_and_3.pt")
291
+ print(f"{'='*65}")
292
+ ```
293
+
294
+ ---
295
+ **Date:** Wednesday, 7th of October