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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Primitive Extractor Training Script
|
| 2 |
+
|
| 3 |
+
## Training Configuration
|
| 4 |
+
- **Model**: PrimitiveExtractor + ClassifierHead
|
| 5 |
+
- **Dataset**: ESC-50 (2000 samples, 50 classes)
|
| 6 |
+
- **Train/Val Split**: 1600 / 400
|
| 7 |
+
- **Feature Extractor**: BEATs (frozen, 768-dim output)
|
| 8 |
+
- **Epochs**: 5
|
| 9 |
+
- **Batch Size**: 16
|
| 10 |
+
- **Optimizer**: AdamW (lr=1e-4, weight_decay=1e-2)
|
| 11 |
+
- **Loss**: Weighted BCEWithLogitsLoss
|
| 12 |
+
- **Checkpoint Metric**: Validation mAP
|
| 13 |
+
|
| 14 |
+
## Results Summary
|
| 15 |
+
- **Best Val mAP**: 98.29% (Epoch 5)
|
| 16 |
+
- **Best Val Acc**: 95.25% (Epoch 5)
|
| 17 |
+
- **Final Train Loss**: 0.0198
|
| 18 |
+
|
| 19 |
+
## Training Script
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import json
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.optim as optim
|
| 28 |
+
import torchaudio
|
| 29 |
+
import numpy as np
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from sklearn.metrics import accuracy_score, average_precision_score
|
| 32 |
+
from huggingface_hub import HfApi
|
| 33 |
+
from google.colab import drive
|
| 34 |
+
|
| 35 |
+
# ==========================================
|
| 36 |
+
# 1. SETUP & PATHS
|
| 37 |
+
# ==========================================
|
| 38 |
+
drive.mount('/content/drive', force_remount=False)
|
| 39 |
+
|
| 40 |
+
AUDIO_DIR = '/content/drive/MyDrive/esc50/audio'
|
| 41 |
+
JSON_PATH = '/content/drive/MyDrive/esc50/causal_labels.json'
|
| 42 |
+
BEATS_CKPT = '/content/drive/MyDrive/WindOneSound_300M/training_checkpoints/v2/beats_pretrained_as2m.pt'
|
| 43 |
+
BEATS_SRC = '/content/drive/MyDrive/WindOneSound_300M/model/beats_official'
|
| 44 |
+
CACHE_DIR = '/content/esc50_cache'
|
| 45 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 46 |
+
|
| 47 |
+
# Add BEATs source to path
|
| 48 |
+
sys.path.append(BEATS_SRC)
|
| 49 |
+
from BEATs import BEATs, BEATsConfig
|
| 50 |
+
|
| 51 |
+
# Add WindOne to path
|
| 52 |
+
sys.path.append('/content/drive/MyDrive/WindOneSound_300M')
|
| 53 |
+
from model_v3.primitive_extractor import PrimitiveExtractor
|
| 54 |
+
|
| 55 |
+
# ==========================================
|
| 56 |
+
# 2. LOAD JSON & BUILD LABEL MAP
|
| 57 |
+
# ==========================================
|
| 58 |
+
with open(JSON_PATH, 'r') as f:
|
| 59 |
+
label_data = json.load(f)
|
| 60 |
+
|
| 61 |
+
# Create mapping: clip_id -> integer label (0-49)
|
| 62 |
+
clip_to_label = {item['clip_id']: item['label'] for item in label_data}
|
| 63 |
+
unique_labels = sorted(list(set(clip_to_label.values())))
|
| 64 |
+
label_to_id = {label: idx for idx, label in enumerate(unique_labels)}
|
| 65 |
+
num_classes = len(unique_labels) # Should be 50
|
| 66 |
+
|
| 67 |
+
print(f"β
Loaded {len(label_data)} JSON entries. Found {num_classes} unique classes.")
|
| 68 |
+
|
| 69 |
+
# ==========================================
|
| 70 |
+
# 3. LOAD FROZEN BEATs
|
| 71 |
+
# ==========================================
|
| 72 |
+
print("π¦ Loading frozen BEATs...")
|
| 73 |
+
checkpoint = torch.load(BEATS_CKPT, map_location='cpu')
|
| 74 |
+
cfg = BEATsConfig(checkpoint['cfg'])
|
| 75 |
+
beats_model = BEATs(cfg)
|
| 76 |
+
beats_model.load_state_dict(checkpoint['model'])
|
| 77 |
+
beats_model.eval()
|
| 78 |
+
|
| 79 |
+
for param in beats_model.parameters():
|
| 80 |
+
param.requires_grad = False
|
| 81 |
+
|
| 82 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 83 |
+
beats_model = beats_model.to(device)
|
| 84 |
+
|
| 85 |
+
# ==========================================
|
| 86 |
+
# 4. FEATURE EXTRACTION & CACHING
|
| 87 |
+
# ==========================================
|
| 88 |
+
print("π Extracting and caching BEATs features (this runs once)...")
|
| 89 |
+
audio_files = [f for f in os.listdir(AUDIO_DIR) if f.endswith('.wav')]
|
| 90 |
+
cached_count = 0
|
| 91 |
+
|
| 92 |
+
for filename in audio_files:
|
| 93 |
+
cache_path = os.path.join(CACHE_DIR, f"{filename}.pt")
|
| 94 |
+
if os.path.exists(cache_path):
|
| 95 |
+
cached_count += 1
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
filepath = os.path.join(AUDIO_DIR, filename)
|
| 99 |
+
waveform, sr = torchaudio.load(filepath)
|
| 100 |
+
|
| 101 |
+
# Convert to mono and resample to 16kHz for BEATs
|
| 102 |
+
if waveform.shape[0] > 1:
|
| 103 |
+
waveform = torch.mean(waveform, dim=0, keepdim=True)
|
| 104 |
+
if sr != 16000:
|
| 105 |
+
waveform = torchaudio.functional.resample(waveform, sr, 16000)
|
| 106 |
+
|
| 107 |
+
# Pad or truncate to 5 seconds (80,000 samples)
|
| 108 |
+
target_len = 80000
|
| 109 |
+
if waveform.shape[1] < target_len:
|
| 110 |
+
waveform = torch.nn.functional.pad(waveform, (0, target_len - waveform.shape[1]))
|
| 111 |
+
else:
|
| 112 |
+
waveform = waveform[:, :target_len]
|
| 113 |
+
|
| 114 |
+
waveform = waveform.to(device)
|
| 115 |
+
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
features, _ = beats_model.extract_features(waveform)
|
| 118 |
+
|
| 119 |
+
# features shape: [1, T, 768]. Squeeze to [T, 768]
|
| 120 |
+
features = features.squeeze(0).cpu()
|
| 121 |
+
label_id = label_to_id[clip_to_label[filename]]
|
| 122 |
+
|
| 123 |
+
torch.save({'features': features, 'label': label_id}, cache_path)
|
| 124 |
+
cached_count += 1
|
| 125 |
+
|
| 126 |
+
print(f"β
Cached {cached_count} / {len(audio_files)} files to {CACHE_DIR}")
|
| 127 |
+
|
| 128 |
+
# ==========================================
|
| 129 |
+
# 5. DATASET & DATALOADER
|
| 130 |
+
# ==========================================
|
| 131 |
+
class ESC50CacheDataset(torch.utils.data.Dataset):
|
| 132 |
+
def __init__(self, cache_dir, split='train', train_ratio=0.8):
|
| 133 |
+
self.cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')]
|
| 134 |
+
self.cache_files.sort()
|
| 135 |
+
split_idx = int(len(self.cache_files) * train_ratio)
|
| 136 |
+
self.files = self.cache_files[:split_idx] if split == 'train' else self.cache_files[split_idx:]
|
| 137 |
+
|
| 138 |
+
def __len__(self):
|
| 139 |
+
return len(self.files)
|
| 140 |
+
|
| 141 |
+
def __getitem__(self, idx):
|
| 142 |
+
data = torch.load(os.path.join(CACHE_DIR, self.files[idx]), weights_only=True)
|
| 143 |
+
return data['features'], data['label']
|
| 144 |
+
|
| 145 |
+
train_dataset = ESC50CacheDataset(CACHE_DIR, split='train')
|
| 146 |
+
val_dataset = ESC50CacheDataset(CACHE_DIR, split='val')
|
| 147 |
+
|
| 148 |
+
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, shuffle=True, num_workers=2)
|
| 149 |
+
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=16, shuffle=False, num_workers=2)
|
| 150 |
+
|
| 151 |
+
print(f"β
Train size: {len(train_dataset)}, Val size: {len(val_dataset)}")
|
| 152 |
+
|
| 153 |
+
# ==========================================
|
| 154 |
+
# 6. MODEL DEFINITION & PARAM COUNT
|
| 155 |
+
# ==========================================
|
| 156 |
+
class PrimitiveTrainModel(nn.Module):
|
| 157 |
+
def __init__(self):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.extractor = PrimitiveExtractor(input_dim=768, hidden_dim=1728, output_dim=512)
|
| 160 |
+
self.classifier = nn.Linear(512, num_classes)
|
| 161 |
+
|
| 162 |
+
def forward(self, x):
|
| 163 |
+
primitives = self.extractor(x)
|
| 164 |
+
pooled = primitives.mean(dim=1)
|
| 165 |
+
logits = self.classifier(pooled)
|
| 166 |
+
return logits
|
| 167 |
+
|
| 168 |
+
model = PrimitiveTrainModel().to(device)
|
| 169 |
+
|
| 170 |
+
# --- PARAMETER COUNTING ---
|
| 171 |
+
extractor_params = sum(p.numel() for p in model.extractor.parameters() if p.requires_grad)
|
| 172 |
+
classifier_params = sum(p.numel() for p in model.classifier.parameters() if p.requires_grad)
|
| 173 |
+
total_trainable_params = extractor_params + classifier_params
|
| 174 |
+
|
| 175 |
+
print(f"\nπ PARAMETER COUNTS:")
|
| 176 |
+
print(f" ββ Primitive Extractor : {extractor_params:,} params")
|
| 177 |
+
print(f" ββ Classifier Head : {classifier_params:,} params")
|
| 178 |
+
print(f" ββ Total Trainable : {total_trainable_params:,} params\n")
|
| 179 |
+
|
| 180 |
+
# Weighted BCE
|
| 181 |
+
class_counts = np.zeros(num_classes)
|
| 182 |
+
for _, label in train_dataset:
|
| 183 |
+
class_counts[label] += 1
|
| 184 |
+
pos_weights = torch.tensor((len(train_dataset) - class_counts) / (class_counts + 1e-5), dtype=torch.float32).to(device)
|
| 185 |
+
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weights)
|
| 186 |
+
optimizer = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-2)
|
| 187 |
+
|
| 188 |
+
# ==========================================
|
| 189 |
+
# 7. TRAINING LOOP (MAX 5 EPOCHS)
|
| 190 |
+
# ==========================================
|
| 191 |
+
num_epochs = 5
|
| 192 |
+
best_val_map = -1.0
|
| 193 |
+
api = HfApi()
|
| 194 |
+
repo_id = "Hitelcy/WindoneRepo2"
|
| 195 |
+
|
| 196 |
+
print("π Starting Training (Max 5 Epochs)...")
|
| 197 |
+
|
| 198 |
+
for epoch in range(1, num_epochs + 1):
|
| 199 |
+
model.train()
|
| 200 |
+
train_losses = []
|
| 201 |
+
|
| 202 |
+
for features, labels in train_loader:
|
| 203 |
+
features = features.to(device)
|
| 204 |
+
labels = labels.to(device)
|
| 205 |
+
|
| 206 |
+
targets = torch.nn.functional.one_hot(labels, num_classes=num_classes).float()
|
| 207 |
+
|
| 208 |
+
optimizer.zero_grad()
|
| 209 |
+
logits = model(features)
|
| 210 |
+
loss = criterion(logits, targets)
|
| 211 |
+
loss.backward()
|
| 212 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 213 |
+
optimizer.step()
|
| 214 |
+
|
| 215 |
+
train_losses.append(loss.item())
|
| 216 |
+
|
| 217 |
+
# --- VALIDATION ---
|
| 218 |
+
model.eval()
|
| 219 |
+
val_preds = []
|
| 220 |
+
val_targets = []
|
| 221 |
+
|
| 222 |
+
with torch.no_grad():
|
| 223 |
+
for features, labels in val_loader:
|
| 224 |
+
features = features.to(device)
|
| 225 |
+
labels = labels.to(device)
|
| 226 |
+
|
| 227 |
+
logits = model(features)
|
| 228 |
+
probs = torch.sigmoid(logits).cpu().numpy()
|
| 229 |
+
|
| 230 |
+
val_preds.append(probs)
|
| 231 |
+
val_targets.append(torch.nn.functional.one_hot(labels, num_classes=num_classes).cpu().numpy())
|
| 232 |
+
|
| 233 |
+
val_preds = np.vstack(val_preds)
|
| 234 |
+
val_targets = np.vstack(val_targets)
|
| 235 |
+
|
| 236 |
+
# Calculate Metrics as percentages
|
| 237 |
+
val_acc = accuracy_score(np.argmax(val_targets, axis=1), np.argmax(val_preds, axis=1)) * 100
|
| 238 |
+
val_map = average_precision_score(val_targets, val_preds, average='macro') * 100
|
| 239 |
+
|
| 240 |
+
print(f"Epoch {epoch}/{num_epochs} | Train Loss: {np.mean(train_losses):.4f} | Val Acc: {val_acc:.2f}% | Val mAP: {val_map:.2f}%")
|
| 241 |
+
|
| 242 |
+
# --- CHECKPOINTING ---
|
| 243 |
+
if val_map > best_val_map:
|
| 244 |
+
best_val_map = val_map
|
| 245 |
+
print(f"π New best Val mAP! Saving checkpoint to Hugging Face...")
|
| 246 |
+
|
| 247 |
+
save_path = "model_checkpoints/Primitive_Extractor/esc50/primitive_extractor_esc50_best.pt"
|
| 248 |
+
|
| 249 |
+
torch.save({
|
| 250 |
+
'epoch': epoch,
|
| 251 |
+
'model_state_dict': model.state_dict(),
|
| 252 |
+
'val_map': val_map,
|
| 253 |
+
'val_acc': val_acc,
|
| 254 |
+
'label_to_id': label_to_id
|
| 255 |
+
}, '/tmp/primitive_best.pt')
|
| 256 |
+
|
| 257 |
+
try:
|
| 258 |
+
api.upload_file(
|
| 259 |
+
path_or_fileobj='/tmp/primitive_best.pt',
|
| 260 |
+
path_in_repo=save_path,
|
| 261 |
+
repo_id=repo_id,
|
| 262 |
+
repo_type="dataset"
|
| 263 |
+
)
|
| 264 |
+
print(f"β
Successfully uploaded checkpoint to {repo_id}/{save_path}")
|
| 265 |
+
except Exception as e:
|
| 266 |
+
print(f"β HF Upload failed: {e}")
|
| 267 |
+
|
| 268 |
+
print("\nπ Training complete!")
|
| 269 |
+
print(f"Best Validation mAP achieved: {best_val_map:.2f}%")
|
| 270 |
+
```
|