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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# WindOneSound 300M: FSD50K Part 4 Training
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
This script fine-tunes the existing Part 3 Primitive Extractor checkpoint on the newly processed FSD50K Part 4 dataset. The goal is to continue expanding 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_part3.pt`
|
| 8 |
+
- **Dataset:** FSD50K Part 4 (7,379 training samples, 815 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_part4"
|
| 46 |
+
os.makedirs(work_dir, exist_ok=True)
|
| 47 |
+
|
| 48 |
+
print("\nโฌ๏ธ Downloading Part 4 assets and Part 3 checkpoint...")
|
| 49 |
+
|
| 50 |
+
# Download Part 4 Features Zip
|
| 51 |
+
zip_path = hf_hub_download(
|
| 52 |
+
repo_id=repo_id, repo_type="dataset",
|
| 53 |
+
filename="datasets/FSD50K/part4_beats_features.zip",
|
| 54 |
+
local_dir=work_dir, token=HF_TOKEN
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Download Labels
|
| 58 |
+
dev_csv = hf_hub_download(
|
| 59 |
+
repo_id=repo_id, repo_type="dataset",
|
| 60 |
+
filename="datasets/FSD50K/labels/ground_truth/dev.csv",
|
| 61 |
+
local_dir=work_dir, token=HF_TOKEN
|
| 62 |
+
)
|
| 63 |
+
vocab_csv = hf_hub_download(
|
| 64 |
+
repo_id=repo_id, repo_type="dataset",
|
| 65 |
+
filename="datasets/FSD50K/labels/ground_truth/vocabulary.csv",
|
| 66 |
+
local_dir=work_dir, token=HF_TOKEN
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Download the Part 3 Checkpoint
|
| 70 |
+
ckpt_path = hf_hub_download(
|
| 71 |
+
repo_id=repo_id, repo_type="dataset",
|
| 72 |
+
filename="model_checkpoints/Primitive_Extractor/FSD50k/best_fsd50k_part3.pt",
|
| 73 |
+
local_dir=work_dir, token=HF_TOKEN
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
print("๐ฆ Unzipping Part 4 features...")
|
| 77 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 78 |
+
zip_ref.extractall(work_dir)
|
| 79 |
+
features_dir = work_dir
|
| 80 |
+
|
| 81 |
+
# ==========================================
|
| 82 |
+
# 3. MATCH FEATURES TO LABELS
|
| 83 |
+
# ==========================================
|
| 84 |
+
print("๐ท๏ธ Processing Labels & Matching Part 4...")
|
| 85 |
+
dev_df = pd.read_csv(dev_csv)
|
| 86 |
+
vocab_df = pd.read_csv(vocab_csv)
|
| 87 |
+
|
| 88 |
+
class_names = vocab_df.iloc[:, 1].tolist()
|
| 89 |
+
class_to_idx = {name: idx for idx, name in enumerate(class_names)}
|
| 90 |
+
num_classes = len(class_to_idx)
|
| 91 |
+
|
| 92 |
+
pt_files_set = set(f.replace('.pt', '') for f in os.listdir(features_dir) if f.endswith('.pt'))
|
| 93 |
+
|
| 94 |
+
train_set = []
|
| 95 |
+
val_set = []
|
| 96 |
+
|
| 97 |
+
print("๐ Matching Part 4 files to ground truth...")
|
| 98 |
+
for _, row in tqdm(dev_df.iterrows(), total=len(dev_df), desc="Matching", leave=False):
|
| 99 |
+
fname = str(row['fname'])
|
| 100 |
+
if fname in pt_files_set:
|
| 101 |
+
labels = str(row['labels']).split(',')
|
| 102 |
+
targets = torch.zeros(num_classes)
|
| 103 |
+
for lbl in labels:
|
| 104 |
+
if lbl in class_to_idx:
|
| 105 |
+
targets[class_to_idx[lbl]] = 1.0
|
| 106 |
+
|
| 107 |
+
item = {'file': os.path.join(features_dir, f"{fname}.pt"), 'target': targets}
|
| 108 |
+
if row['split'] == 'train':
|
| 109 |
+
train_set.append(item)
|
| 110 |
+
elif row['split'] == 'val':
|
| 111 |
+
val_set.append(item)
|
| 112 |
+
|
| 113 |
+
print(f"โ
Matched {len(train_set)} training and {len(val_set)} validation samples.\n")
|
| 114 |
+
|
| 115 |
+
# Calculate Class Weights for Weighted BCE
|
| 116 |
+
all_targets = torch.stack([d['target'] for d in train_set])
|
| 117 |
+
pos_counts = all_targets.sum(dim=0)
|
| 118 |
+
neg_counts = len(train_set) - pos_counts
|
| 119 |
+
weights = (neg_counts / (pos_counts + 1e-5)).clamp(max=50.0)
|
| 120 |
+
|
| 121 |
+
# ==========================================
|
| 122 |
+
# 4. DEFINE & LOAD MODEL
|
| 123 |
+
# ==========================================
|
| 124 |
+
class ConvNormGELU(nn.Module):
|
| 125 |
+
def __init__(self, in_channels, out_channels, kernel_size, padding):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, padding=padding)
|
| 128 |
+
self.norm = nn.LayerNorm(out_channels)
|
| 129 |
+
self.act = nn.GELU()
|
| 130 |
+
def forward(self, x):
|
| 131 |
+
x = self.conv(x)
|
| 132 |
+
x = x.transpose(1, 2)
|
| 133 |
+
x = self.norm(x)
|
| 134 |
+
x = x.transpose(1, 2)
|
| 135 |
+
return self.act(x)
|
| 136 |
+
|
| 137 |
+
class PrimitiveExtractor(nn.Module):
|
| 138 |
+
def __init__(self, input_dim=768, hidden_dim=512, num_classes=200):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.conv_stack = nn.Sequential(
|
| 141 |
+
ConvNormGELU(input_dim, 1728, 7, 3),
|
| 142 |
+
ConvNormGELU(1728, 1728, 5, 2),
|
| 143 |
+
ConvNormGELU(1728, 1728, 3, 1)
|
| 144 |
+
)
|
| 145 |
+
self.proj = nn.Sequential(nn.Linear(1728, hidden_dim), nn.LayerNorm(hidden_dim))
|
| 146 |
+
self.attn = nn.MultiheadAttention(hidden_dim, num_heads=8, batch_first=True)
|
| 147 |
+
self.norm = nn.LayerNorm(hidden_dim)
|
| 148 |
+
self.decoder = nn.Sequential(nn.Linear(hidden_dim, 1024), nn.GELU(), nn.Linear(1024, input_dim))
|
| 149 |
+
self.classifier = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.GELU(), nn.Dropout(0.2), nn.Linear(hidden_dim, num_classes))
|
| 150 |
+
|
| 151 |
+
def forward(self, x):
|
| 152 |
+
x_conv = x.transpose(1, 2)
|
| 153 |
+
features = self.conv_stack(x_conv).transpose(1, 2)
|
| 154 |
+
features = self.proj(features)
|
| 155 |
+
attn_out, _ = self.attn(features, features, features)
|
| 156 |
+
primitives = self.norm(features + attn_out)
|
| 157 |
+
|
| 158 |
+
reconstruction_output = self.decoder(primitives)
|
| 159 |
+
pooled = primitives.mean(dim=1)
|
| 160 |
+
logits = self.classifier(pooled)
|
| 161 |
+
|
| 162 |
+
return reconstruction_output, logits
|
| 163 |
+
|
| 164 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 165 |
+
|
| 166 |
+
print("\n๐ง Loading Part 3 Checkpoint...")
|
| 167 |
+
state_dict = torch.load(ckpt_path, map_location=device)
|
| 168 |
+
actual_num_classes = state_dict['classifier.3.weight'].shape[0]
|
| 169 |
+
model = PrimitiveExtractor(input_dim=768, hidden_dim=512, num_classes=actual_num_classes).to(device)
|
| 170 |
+
model.load_state_dict(state_dict)
|
| 171 |
+
print(f"โ
Model loaded successfully ({actual_num_classes} classes).")
|
| 172 |
+
|
| 173 |
+
# ==========================================
|
| 174 |
+
# 5. TRAINING SETUP (DUAL LOSS + WARMUP)
|
| 175 |
+
# ==========================================
|
| 176 |
+
epochs = 10
|
| 177 |
+
alpha = 0.1
|
| 178 |
+
batch_size = 16
|
| 179 |
+
|
| 180 |
+
optimizer = optim.AdamW(model.parameters(), lr=2e-4, weight_decay=1e-4)
|
| 181 |
+
|
| 182 |
+
steps_per_epoch = int(np.ceil(len(train_set) / batch_size))
|
| 183 |
+
total_steps = steps_per_epoch * epochs
|
| 184 |
+
warmup_steps = int(total_steps * 0.1)
|
| 185 |
+
|
| 186 |
+
def lr_lambda(step):
|
| 187 |
+
if step < warmup_steps:
|
| 188 |
+
return float(step) / float(max(1, warmup_steps))
|
| 189 |
+
return 0.5 * (1 + np.cos(np.pi * (step - warmup_steps) / (total_steps - warmup_steps)))
|
| 190 |
+
|
| 191 |
+
scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 192 |
+
bce_loss_fn = nn.BCEWithLogitsLoss(pos_weight=weights.to(device))
|
| 193 |
+
mse_loss_fn = nn.MSELoss()
|
| 194 |
+
|
| 195 |
+
best_val_map = 0.0
|
| 196 |
+
global_step = 0
|
| 197 |
+
|
| 198 |
+
# ==========================================
|
| 199 |
+
# 6. TRAINING LOOP (MOBILE OPTIMIZED)
|
| 200 |
+
# ==========================================
|
| 201 |
+
print(f"\n{'='*65}")
|
| 202 |
+
print(f" STARTING TRAINING: {epochs} Epochs | Target Metric: Val mAP")
|
| 203 |
+
print(f"{'='*65}")
|
| 204 |
+
|
| 205 |
+
for epoch in range(1, epochs + 1):
|
| 206 |
+
model.train()
|
| 207 |
+
epoch_bce = 0.0
|
| 208 |
+
epoch_mse = 0.0
|
| 209 |
+
|
| 210 |
+
np.random.shuffle(train_set)
|
| 211 |
+
|
| 212 |
+
pbar = tqdm(range(0, len(train_set), batch_size), desc=f"Epoch {epoch}/{epochs}", leave=False, ncols=80)
|
| 213 |
+
for i in pbar:
|
| 214 |
+
batch = train_set[i:i+batch_size]
|
| 215 |
+
optimizer.zero_grad()
|
| 216 |
+
|
| 217 |
+
batch_bce = 0.0
|
| 218 |
+
batch_mse = 0.0
|
| 219 |
+
|
| 220 |
+
for item in batch:
|
| 221 |
+
x = torch.load(item['file'], map_location=device).unsqueeze(0)
|
| 222 |
+
y = item['target'].unsqueeze(0).to(device)
|
| 223 |
+
|
| 224 |
+
recon_out, logits = model(x)
|
| 225 |
+
|
| 226 |
+
loss_bce = bce_loss_fn(logits, y)
|
| 227 |
+
loss_mse = mse_loss_fn(recon_out, x)
|
| 228 |
+
loss = loss_bce + (alpha * loss_mse)
|
| 229 |
+
|
| 230 |
+
loss.backward()
|
| 231 |
+
|
| 232 |
+
batch_bce += loss_bce.item()
|
| 233 |
+
batch_mse += loss_mse.item()
|
| 234 |
+
|
| 235 |
+
optimizer.step()
|
| 236 |
+
scheduler.step()
|
| 237 |
+
global_step += 1
|
| 238 |
+
|
| 239 |
+
epoch_bce += batch_bce / len(batch)
|
| 240 |
+
epoch_mse += batch_mse / len(batch)
|
| 241 |
+
pbar.set_postfix({'LR': f"{scheduler.get_last_lr()[0]:.2e}"})
|
| 242 |
+
pbar.close()
|
| 243 |
+
|
| 244 |
+
model.eval()
|
| 245 |
+
all_preds = []
|
| 246 |
+
all_targets = []
|
| 247 |
+
with torch.no_grad():
|
| 248 |
+
for item in val_set:
|
| 249 |
+
x = torch.load(item['file'], map_location=device).unsqueeze(0)
|
| 250 |
+
y = item['target']
|
| 251 |
+
_, logits = model(x)
|
| 252 |
+
preds = torch.sigmoid(logits).cpu().squeeze()
|
| 253 |
+
all_preds.append(preds.numpy())
|
| 254 |
+
all_targets.append(y.numpy())
|
| 255 |
+
|
| 256 |
+
val_map = average_precision_score(np.array(all_targets), np.array(all_preds), average='macro')
|
| 257 |
+
|
| 258 |
+
print(f"\n{'='*65}")
|
| 259 |
+
print(f" Epoch | BCE Loss | MSE Loss | Val mAP | LR ")
|
| 260 |
+
print(f"{'-'*65}")
|
| 261 |
+
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}")
|
| 262 |
+
print(f"{'='*65}")
|
| 263 |
+
|
| 264 |
+
if val_map > best_val_map:
|
| 265 |
+
best_val_map = val_map
|
| 266 |
+
save_path = "/content/best_fsd50k_primitive_part1_to_4.pt"
|
| 267 |
+
torch.save(model.state_dict(), save_path)
|
| 268 |
+
print(f" ๐ NEW BEST! Checkpoint saved (mAP: {best_val_map:.4f})\n")
|
| 269 |
+
else:
|
| 270 |
+
print(f" (Best mAP remains: {best_val_map:.4f})\n")
|
| 271 |
+
|
| 272 |
+
print(f"{'='*65}")
|
| 273 |
+
print(f" ๐ TRAINING COMPLETE!")
|
| 274 |
+
print(f" ๐พ Best model saved at: /content/best_fsd50k_primitive_part1_to_4.pt")
|
| 275 |
+
print(f"{'='*65}")
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
---
|
| 279 |
+
**Date:** Wednesday, 8th of October
|