Hitelcy's picture
Add detailed training script and documentation for FSD50K Part 3
900e0db verified
|
Raw History Blame Contribute Delete
10.9 kB

WindOneSound 300M: FSD50K Part 3 Training

Overview

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.

Methodology & Configuration

  • Base Checkpoint: best_fsd50k_primitive_part1_and_2.pt
  • Dataset: FSD50K Part 3 (7,353 training samples, 841 validation samples)
  • Dual-Loss Objective:
    • Weighted BCE Loss: Handles multi-label classification with dynamically calculated class weights to balance rare and common sounds.
    • MSE Reconstruction Loss: Forces the model to rebuild the input BEATs features from the primitives, preserving the acoustic feature space and preventing representation collapse.
    • Total Loss: BCE_Loss + (0.1 * MSE_Loss)
  • Optimizer & Scheduler: AdamW (lr=2e-4, weight_decay=1e-4) with a 10% Linear Warmup followed by Cosine Annealing decay.
  • Epochs: 10
  • 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.

Training Script

import os
import warnings
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
import getpass
import zipfile
from tqdm.auto import tqdm
from sklearn.metrics import average_precision_score
from huggingface_hub import HfApi, hf_hub_download

# ==========================================
# 1. SUPPRESS HARMLESS PYTORCH WARNINGS
# ==========================================
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)

# ==========================================
# 2. AUTHENTICATION & SETUP
# ==========================================
HF_TOKEN = getpass.getpass("Enter your Hugging Face API token (hidden): ")
api = HfApi(token=HF_TOKEN)
repo_id = "Hitelcy/WindoneRepo2"
work_dir = "/content/training_part3"
os.makedirs(work_dir, exist_ok=True)

print("
โฌ‡๏ธ Downloading Part 3 assets from Hugging Face...")

# Download Part 3 Features Zip
zip_path = hf_hub_download(
    repo_id=repo_id, repo_type="dataset",
    filename="datasets/FSD50K/part3_beats_features.zip",
    local_dir=work_dir, token=HF_TOKEN
)

# Download Labels
dev_csv = hf_hub_download(
    repo_id=repo_id, 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=repo_id, repo_type="dataset",
    filename="datasets/FSD50K/labels/ground_truth/vocabulary.csv",
    local_dir=work_dir, token=HF_TOKEN
)

# Download Checkpoint
ckpt_path = hf_hub_download(
    repo_id=repo_id, repo_type="dataset",
    filename="model_checkpoints/Primitive_Extractor/FSD50k/best_fsd50k_primitive_part1_and_2.pt",
    local_dir=work_dir, token=HF_TOKEN
)

print("๐Ÿ“ฆ Unzipping Part 3 features...")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
    zip_ref.extractall(work_dir)
features_dir = work_dir 

# ==========================================
# 3. MATCH FEATURES TO LABELS
# ==========================================
print("๐Ÿท๏ธ Processing Labels & Matching Part 3...")
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)

# Get all extracted .pt filenames
pt_files_set = set(f.replace('.pt', '') for f in os.listdir(features_dir) if f.endswith('.pt'))

train_set = []
val_set = []

print("๐Ÿ”— Matching Part 3 files to ground truth...")
for _, row in tqdm(dev_df.iterrows(), total=len(dev_df), desc="Matching", leave=False):
    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
        
        item = {'file': os.path.join(features_dir, f"{fname}.pt"), 'target': targets}
        if row['split'] == 'train':
            train_set.append(item)
        elif row['split'] == 'val':
            val_set.append(item)

print(f"โœ… Matched {len(train_set)} training and {len(val_set)} validation samples.
")

# Calculate Class Weights for Weighted BCE
all_targets = torch.stack([d['target'] for d in train_set])
pos_counts = all_targets.sum(dim=0)
neg_counts = len(train_set) - pos_counts
weights = (neg_counts / (pos_counts + 1e-5)).clamp(max=50.0)

# ==========================================
# 4. DEFINE & LOAD MODEL
# ==========================================
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)
        return self.act(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).transpose(1, 2)
        features = self.proj(features)
        attn_out, _ = self.attn(features, features, features)
        primitives = self.norm(features + attn_out)
        
        # Reconstruction output
        reconstruction_output = self.decoder(primitives)
        
        # Classification output
        pooled = primitives.mean(dim=1)
        logits = self.classifier(pooled)
        
        return reconstruction_output, logits

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

print("
๐Ÿง  Loading Part 1 + Part 2 Checkpoint...")
state_dict = torch.load(ckpt_path, map_location=device)
actual_num_classes = state_dict['classifier.3.weight'].shape[0] 
model = PrimitiveExtractor(input_dim=768, hidden_dim=512, num_classes=actual_num_classes).to(device)
model.load_state_dict(state_dict)
print(f"โœ… Model loaded successfully ({actual_num_classes} classes).")

# ==========================================
# 5. TRAINING SETUP (DUAL LOSS + WARMUP)
# ==========================================
epochs = 10
alpha = 0.1  # Weight for MSE Reconstruction loss
batch_size = 16

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

# Calculate true optimizer steps for accurate warmup
steps_per_epoch = int(np.ceil(len(train_set) / batch_size))
total_steps = steps_per_epoch * epochs
warmup_steps = int(total_steps * 0.1)

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()

best_val_map = 0.0
global_step = 0

# ==========================================
# 6. TRAINING LOOP (MOBILE OPTIMIZED)
# ==========================================
print(f"
{'='*65}")
print(f" STARTING TRAINING: {epochs} Epochs | Target Metric: Val mAP")
print(f"{'='*65}")

for epoch in range(1, epochs + 1):
    model.train()
    epoch_bce = 0.0
    epoch_mse = 0.0
    
    np.random.shuffle(train_set)
    
    # leave=False keeps the progress bar on one line, updating in place
    pbar = tqdm(range(0, len(train_set), batch_size), desc=f"Epoch {epoch}/{epochs}", leave=False, ncols=80)
    for i in pbar:
        batch = train_set[i:i+batch_size]
        optimizer.zero_grad()
        
        batch_bce = 0.0
        batch_mse = 0.0
        
        for item in batch:
            x = torch.load(item['file'], map_location=device).unsqueeze(0)
            y = item['target'].unsqueeze(0).to(device)
            
            recon_out, logits = model(x)
            
            loss_bce = bce_loss_fn(logits, y)
            loss_mse = mse_loss_fn(recon_out, x)
            loss = loss_bce + (alpha * loss_mse)
            
            loss.backward()
            
            batch_bce += loss_bce.item()
            batch_mse += loss_mse.item()
            
        optimizer.step()
        scheduler.step()
        global_step += 1
        
        epoch_bce += batch_bce / len(batch)
        epoch_mse += batch_mse / len(batch)
        pbar.set_postfix({'LR': f"{scheduler.get_last_lr()[0]:.2e}"})
    pbar.close() # Close the bar cleanly before printing the table

    # Evaluation
    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())
            
    val_map = average_precision_score(np.array(all_targets), np.array(all_preds), average='macro')
    
    # Print Clean Epoch Table
    print(f"
{'='*65}")
    print(f"  Epoch  |  BCE Loss  |  MSE Loss  |  Val mAP   |    LR    ")
    print(f"{'-'*65}")
    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}")
    print(f"{'='*65}")
    
    # Checkpointing
    if val_map > best_val_map:
        best_val_map = val_map
        save_path = "/content/best_fsd50k_primitive_part1_2_and_3.pt"
        torch.save(model.state_dict(), save_path)
        print(f"  ๐Ÿ† NEW BEST! Checkpoint saved (mAP: {best_val_map:.4f})
")
    else:
        print(f"  (Best mAP remains: {best_val_map:.4f})
")

print(f"{'='*65}")
print(f" ๐ŸŽ‰ TRAINING COMPLETE!")
print(f" ๐Ÿ’พ Best model saved at: /content/best_fsd50k_primitive_part1_2_and_3.pt")
print(f"{'='*65}")

Date: Wednesday, 7th of October