File size: 15,176 Bytes
7dfadf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b15ca6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# FSD50K Primitive Extractor Training - Part 1

## Overview
This document describes the training of a **Primitive Extractor** on the FSD50K dataset (Part 1 only), using transfer learning from a pretrained Clotho checkpoint.

## Architecture
The model is a **36.7M parameter** Primitive Extractor with three main components:

### 1. Extractor (Encoder) - From Clotho
- **Conv Stack**: 3 Γ— (Conv1d β†’ Transpose β†’ LayerNorm β†’ Transpose β†’ GELU)
  - Conv1d(768 β†’ 1728, k=7)
  - Conv1d(1728 β†’ 1728, k=5)
  - Conv1d(1728 β†’ 1728, k=3)
- **Projection**: Linear(1728 β†’ 512) + LayerNorm
- **Self-Attention**: MultiheadAttention(512, 8 heads) + residual + LayerNorm
- **Output**: 512-dimensional primitive vectors (seq_len, 512)

### 2. Decoder - From Clotho
- Linear(512 β†’ 1024) + GELU
- Linear(1024 β†’ 768)
- **Purpose**: Reconstruct the original 768-dim BEATs features for the reconstruction_loss

### 3. Classifier Head - NEW for FSD50K
- Linear(512 β†’ 512) + GELU + Dropout(0.2)
- Linear(512 β†’ 200)
- **Purpose**: Predict the 200 FSD50K sound classes

## Training Configuration
- **Dataset**: FSD50K Part 1 (7,343 matched samples)
  - Train: 6,608 samples
  - Validation: 735 samples
- **Features**: 768-dim BEATs features (variable length per clip)
- **Pretrained weights**: `primitive_extractor_clotho_recon_best.pt` (26 parameter tensors transferred)
- **Epochs**: 8
- **Optimizer**: AdamW (lr=2e-4, weight_decay=1e-4)
- **Scheduler**: Cosine decay with 10% warmup (5,286 steps)
- **Loss function**:
  - Classification: Weighted BCE (pos_weight handles class imbalance)
  - reconstruction_loss: MSE (between input BEATs and decoder output)
  - Total: `weighted_bce_loss + 0.1 * reconstruction_loss`
- **Checkpoint metric**: Validation mAP (macro) β€” saved only when improved

## Loss Strategy
- **Weighted BCE** (optimization loss): Handles FSD50K's multi-label nature and class imbalance. Rare classes get higher penalty.
- **reconstruction_loss** (regularization): Forces the 512-dim bottleneck to preserve acoustic details, not just collapse into a classifier.
- **mAP** (checkpoint metric): Non-differentiable ranking metric that measures real classification quality.

## Results

| Epoch | weighted_bce_loss | reconstruction_loss | total_loss | val_mAP |
|-------|-------------------|---------------------|------------|---------|
| 1     | 0.4938            | 0.1174              | 0.5055     | 24.24%  |
| 2     | 0.3081            | 0.1301              | 0.3211     | 30.68%  |
| 3     | 0.2400            | 0.1259              | 0.2526     | 37.76%  |
| 4     | 0.1911            | 0.1227              | 0.2034     | 41.97%  |
| 5     | 0.1486            | 0.1197              | 0.1605     | 47.50%  |
| 6     | 0.1161            | 0.1173              | 0.1278     | 50.70%  |
| 7     | 0.0964            | 0.1154              | 0.1079     | 52.41%  |
| 8     | 0.0860            | 0.1145              | 0.0974     | **52.72%** |

### Best Result
- **Validation mAP**: **52.72%** (achieved at epoch 8)
- **Checkpoint**: `best_fsd50k_primitive.pt`

## Notes
- The sklearn warnings about "No positive class found in y_true" are expected. With only 735 validation samples across 200 classes, many rare classes have zero examples in the validation split. This does not affect the macro mAP calculation.
- reconstruction_loss stayed stable (~0.11-0.13) throughout training, confirming the bottleneck preserves acoustic information while learning to classify.

## Limitations
- Only trained on **Part 1** (7,343 samples). Full FSD50K has **36,796 training samples** across parts 1-5.
- The 52.72% mAP is a strong baseline but expected to improve significantly with the full dataset.

## Next Steps
1. Extract BEATs features for parts 2-5
2. Retrain on the full 36,796 samples
3. Evaluate on the separate FSD50K eval set (10,234 files)
4. Consider longer training (15-20 epochs) with full data

## Files
- `best_fsd50k_primitive.pt` β€” Best checkpoint (52.72% mAP)
- `training_result_part1.json` β€” Machine-readable results
- `training_script_part1.md` β€” This file

---
*Trained on October 06, 2026*


---

## Full Training Script

Below is the complete Python training script used for this experiment.

```python
import os
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
import glob
import getpass
import shutil
from tqdm.auto import tqdm
from sklearn.metrics import average_precision_score
from huggingface_hub import snapshot_download, hf_hub_download

# ==========================================
# 0. AUTHENTICATION
# ==========================================
HF_TOKEN = getpass.getpass("Enter your Hugging Face API token (hidden): ")

# ==========================================
# 1. SETUP PATHS & DOWNLOAD DATA
# ==========================================
work_dir = "/content/training_data"
os.makedirs(work_dir, exist_ok=True)

print("\n⬇️ Downloading Part 1 Features...")
features_zip = hf_hub_download(
    repo_id="Hitelcy/WindoneRepo2", repo_type="dataset",
    filename="datasets/FSD50K/part1_beats_features.zip",
    local_dir=work_dir, token=HF_TOKEN
)

print("⬇️ Downloading Labels...")
dev_csv = hf_hub_download(
    repo_id="Hitelcy/WindoneRepo2", repo_type="dataset",
    filename="datasets/FSD50K/labels/ground_truth/dev.csv",
    local_dir=work_dir, token=HF_TOKEN
)

vocab_csv = hf_hub_download(
    repo_id="Hitelcy/WindoneRepo2", repo_type="dataset",
    filename="datasets/FSD50K/labels/ground_truth/vocabulary.csv",
    local_dir=work_dir, token=HF_TOKEN
)

print("⬇️ Downloading Clotho Primitive Extractor Checkpoint...")
snapshot_download(
    repo_id="Hitelcy/WindoneRepo2", repo_type="dataset",
    allow_patterns="model_checkpoints/Primitive_Extractor/clotho/**",
    local_dir=work_dir, token=HF_TOKEN
)

# ==========================================
# 2. EXTRACT & PREPARE DATA
# ==========================================
print("\nπŸ“¦ Extracting features...")
shutil.unpack_archive(features_zip, work_dir)
features_dir = os.path.join(work_dir, "fsd50k_beats_768_cache")

print("🏷️ Processing Labels...")
dev_df = pd.read_csv(dev_csv)
vocab_df = pd.read_csv(vocab_csv)

class_names = vocab_df.iloc[:, 1].tolist()
class_to_idx = {name: idx for idx, name in enumerate(class_names)}
num_classes = len(class_to_idx)

train_df = dev_df[dev_df['split'] == 'train'].copy()
pt_files_set = set(f.replace('.pt', '') for f in os.listdir(features_dir) if f.endswith('.pt'))

valid_data = []
print("πŸ”— Matching features to labels...")
for _, row in tqdm(train_df.iterrows(), total=len(train_df), desc="Matching"):
    fname = str(row['fname'])
    if fname in pt_files_set:
        labels = str(row['labels']).split(',')
        targets = torch.zeros(num_classes)
        for lbl in labels:
            if lbl in class_to_idx:
                targets[class_to_idx[lbl]] = 1.0
        valid_data.append({'file': os.path.join(features_dir, f"{fname}.pt"), 'target': targets})

print(f"βœ… Matched {len(valid_data)} training samples.")

all_targets = torch.stack([d['target'] for d in valid_data])
pos_counts = all_targets.sum(dim=0)
neg_counts = len(valid_data) - pos_counts
weights = (neg_counts / (pos_counts + 1e-5)).clamp(max=50.0)

# ==========================================
# 3. DEFINE ARCHITECTURE (36.7M parameters)
# ==========================================
class ConvNormGELU(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, padding):
        super().__init__()
        self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, padding=padding)
        self.norm = nn.LayerNorm(out_channels)
        self.act = nn.GELU()

    def forward(self, x):
        x = self.conv(x)
        x = x.transpose(1, 2)
        x = self.norm(x)
        x = x.transpose(1, 2)
        x = self.act(x)
        return x

class PrimitiveExtractor(nn.Module):
    def __init__(self, input_dim=768, hidden_dim=512, num_classes=200):
        super().__init__()
        self.conv_stack = nn.Sequential(
            ConvNormGELU(input_dim, 1728, 7, 3),
            ConvNormGELU(1728, 1728, 5, 2),
            ConvNormGELU(1728, 1728, 3, 1)
        )
        self.proj = nn.Sequential(
            nn.Linear(1728, hidden_dim),
            nn.LayerNorm(hidden_dim)
        )
        self.attn = nn.MultiheadAttention(hidden_dim, num_heads=8, batch_first=True)
        self.norm = nn.LayerNorm(hidden_dim)
        self.decoder = nn.Sequential(
            nn.Linear(hidden_dim, 1024),
            nn.GELU(),
            nn.Linear(1024, input_dim)
        )
        self.classifier = nn.Sequential(
            nn.Linear(hidden_dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(0.2),
            nn.Linear(hidden_dim, num_classes)
        )

    def forward(self, x):
        x_conv = x.transpose(1, 2)
        features = self.conv_stack(x_conv)
        features = features.transpose(1, 2)
        features = self.proj(features)
        attn_out, _ = self.attn(features, features, features)
        primitives = self.norm(features + attn_out)
        reconstruction_output = self.decoder(primitives)
        pooled = primitives.mean(dim=1)
        logits = self.classifier(pooled)
        return reconstruction_output, logits

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = PrimitiveExtractor(input_dim=768, hidden_dim=512, num_classes=num_classes).to(device)

# ==========================================
# 4. LOAD CLOTHO WEIGHTS (ALL 26 LAYERS)
# ==========================================
print("\n🧠 Loading Clotho weights...")
ckpt_files = glob.glob(os.path.join(work_dir, "**/*.pt"), recursive=True)
clotho_ckpt_path = [f for f in ckpt_files if "clotho" in f.lower()][0]

clotho_state = torch.load(clotho_ckpt_path, map_location=device)
if 'model_state_dict' in clotho_state:
    clotho_state = clotho_state['model_state_dict']

model_dict = model.state_dict()
pretrained_dict = {}

for i in range(3):
    clotho_conv_idx = i * 3
    clotho_norm_idx = clotho_conv_idx + 1
    pretrained_dict[f'conv_stack.{i}.conv.weight'] = clotho_state[f'extractor.conv_stack.{clotho_conv_idx}.weight']
    pretrained_dict[f'conv_stack.{i}.conv.bias'] = clotho_state[f'extractor.conv_stack.{clotho_conv_idx}.bias']
    pretrained_dict[f'conv_stack.{i}.norm.weight'] = clotho_state[f'extractor.conv_stack.{clotho_norm_idx}.weight']
    pretrained_dict[f'conv_stack.{i}.norm.bias'] = clotho_state[f'extractor.conv_stack.{clotho_norm_idx}.bias']

pretrained_dict['proj.0.weight'] = clotho_state['extractor.proj.0.weight']
pretrained_dict['proj.0.bias'] = clotho_state['extractor.proj.0.bias']
pretrained_dict['proj.1.weight'] = clotho_state['extractor.proj.1.weight']
pretrained_dict['proj.1.bias'] = clotho_state['extractor.proj.1.bias']
pretrained_dict['attn.in_proj_weight'] = clotho_state['extractor.attn.in_proj_weight']
pretrained_dict['attn.in_proj_bias'] = clotho_state['extractor.attn.in_proj_bias']
pretrained_dict['attn.out_proj.weight'] = clotho_state['extractor.attn.out_proj.weight']
pretrained_dict['attn.out_proj.bias'] = clotho_state['extractor.attn.out_proj.bias']
pretrained_dict['norm.weight'] = clotho_state['extractor.norm.weight']
pretrained_dict['norm.bias'] = clotho_state['extractor.norm.bias']
pretrained_dict['decoder.0.weight'] = clotho_state['decoder.0.weight']
pretrained_dict['decoder.0.bias'] = clotho_state['decoder.0.bias']
pretrained_dict['decoder.2.weight'] = clotho_state['decoder.2.weight']
pretrained_dict['decoder.2.bias'] = clotho_state['decoder.2.bias']

model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)
print(f"βœ… Successfully transferred {len(pretrained_dict)} / {len(clotho_state)} layers from Clotho.")

# ==========================================
# 5. TRAINING SETUP WITH WARMUP
# ==========================================
epochs = 8
total_steps = int(len(valid_data) * 0.9 * epochs)
warmup_steps = int(total_steps * 0.1)

optimizer = optim.AdamW(model.parameters(), lr=2e-4, weight_decay=1e-4)

def lr_lambda(step):
    if step < warmup_steps:
        return float(step) / float(max(1, warmup_steps))
    return 0.5 * (1 + np.cos(np.pi * (step - warmup_steps) / (total_steps - warmup_steps)))

scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
bce_loss_fn = nn.BCEWithLogitsLoss(pos_weight=weights.to(device))
mse_loss_fn = nn.MSELoss()
alpha = 0.1
best_mAP = 0.0

np.random.shuffle(valid_data)
split_idx = int(0.9 * len(valid_data))
train_set = valid_data[:split_idx]
val_set = valid_data[split_idx:]

print(f"\nπŸš€ Ready to train! Train: {len(train_set)}, Val: {len(val_set)}")
print(f"πŸ“ˆ Warmup steps: {warmup_steps}")

# ==========================================
# 6. TRAINING LOOP
# ==========================================
def train_epoch():
    model.train()
    total_bce = 0
    total_reconstruction_loss = 0
    total_loss = 0
    for item in tqdm(train_set, desc="Training", leave=False):
        optimizer.zero_grad()
        x = torch.load(item['file'], map_location=device).unsqueeze(0)
        y = item['target'].unsqueeze(0).to(device)
        reconstruction_output, logits = model(x)
        loss_bce = bce_loss_fn(logits, y)
        loss_reconstruction = mse_loss_fn(reconstruction_output, x)
        loss = loss_bce + (alpha * loss_reconstruction)
        loss.backward()
        optimizer.step()
        scheduler.step()
        total_bce += loss_bce.item()
        total_reconstruction_loss += loss_reconstruction.item()
        total_loss += loss.item()
    return total_bce / len(train_set), total_reconstruction_loss / len(train_set), total_loss / len(train_set)

def evaluate():
    model.eval()
    all_preds = []
    all_targets = []
    with torch.no_grad():
        for item in val_set:
            x = torch.load(item['file'], map_location=device).unsqueeze(0)
            y = item['target']
            _, logits = model(x)
            preds = torch.sigmoid(logits).cpu().squeeze()
            all_preds.append(preds.numpy())
            all_targets.append(y.numpy())
    mAP = average_precision_score(np.array(all_targets), np.array(all_preds), average='macro')
    return mAP

print(f"\n{'='*70}")
print(f"STARTING TRAINING FOR {epochs} EPOCHS")
print(f"{'='*70}\n")

for epoch in range(1, epochs + 1):
    print(f"\nπŸ”„ Epoch {epoch}/{epochs}")
    bce_loss, reconstruction_loss, total_loss = train_epoch()
    val_mAP = evaluate()
    current_lr = scheduler.get_last_lr()[0]
    print(f"   Weighted BCE Loss:   {bce_loss:.4f}")
    print(f"   Reconstruction Loss: {reconstruction_loss:.4f}")
    print(f"   Total Loss:          {total_loss:.4f}")
    print(f"   Validation mAP:      {val_mAP:.4f}")
    print(f"   Learning Rate:       {current_lr:.6f}")
    if val_mAP > best_mAP:
        best_mAP = val_mAP
        save_path = "/content/best_fsd50k_primitive.pt"
        torch.save(model.state_dict(), save_path)
        print(f"   πŸ† NEW BEST! Checkpoint saved (mAP: {best_mAP:.4f})")

print(f"\n{'='*70}")
print(f"πŸŽ‰ TRAINING COMPLETE!")
print(f"Best Validation mAP: {best_mAP:.4f}")
print(f"πŸ’Ύ Best model saved at: /content/best_fsd50k_primitive.pt")
print(f"{'='*70}")
```