|
Download model_checkpoints/Primitive_Extractor/FSD50k/training_script_part1.md from Hitelcy/WindoneRepo2: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/datasets/Hitelcy/WindoneRepo2/resolve/main/model_checkpoints/Primitive_Extractor/FSD50k/training_script_part1.md
- Command line
-
hf download hf://datasets/Hitelcy/WindoneRepo2/model_checkpoints/Primitive_Extractor/FSD50k/training_script_part1.md
-
curl -L -o training_script_part1.md https://huggingface.co/datasets/Hitelcy/WindoneRepo2/resolve/main/model_checkpoints/Primitive_Extractor/FSD50k/training_script_part1.md
15.2 kB
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
- Extract BEATs features for parts 2-5
- Retrain on the full 36,796 samples
- Evaluate on the separate FSD50K eval set (10,234 files)
- 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 resultstraining_script_part1.mdβ This file
Trained on October 06, 2026
Full Training Script
Below is the complete Python training script used for this experiment.
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}")