File size: 10,470 Bytes
6ed45c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# WindOneSound 300M: FSD50K Part 4 Training

## Overview
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.

## Methodology & Configuration
- **Base Checkpoint:** `best_fsd50k_part3.pt`
- **Dataset:** FSD50K Part 4 (7,379 training samples, 815 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

```python
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_part4"
os.makedirs(work_dir, exist_ok=True)

print("\nโฌ‡๏ธ Downloading Part 4 assets and Part 3 checkpoint...")

# Download Part 4 Features Zip
zip_path = hf_hub_download(
    repo_id=repo_id, repo_type="dataset",
    filename="datasets/FSD50K/part4_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 the Part 3 Checkpoint
ckpt_path = hf_hub_download(
    repo_id=repo_id, repo_type="dataset",
    filename="model_checkpoints/Primitive_Extractor/FSD50k/best_fsd50k_part3.pt",
    local_dir=work_dir, token=HF_TOKEN
)

print("๐Ÿ“ฆ Unzipping Part 4 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 4...")
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)

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 4 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.\n")

# 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 = 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")

print("\n๐Ÿง  Loading Part 3 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
batch_size = 16

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

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"\n{'='*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)
    
    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()

    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(f"\n{'='*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}")
    
    if val_map > best_val_map:
        best_val_map = val_map
        save_path = "/content/best_fsd50k_primitive_part1_to_4.pt"
        torch.save(model.state_dict(), save_path)
        print(f"  ๐Ÿ† NEW BEST! Checkpoint saved (mAP: {best_val_map:.4f})\n")
    else:
        print(f"  (Best mAP remains: {best_val_map:.4f})\n")

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

---
**Date:** Wednesday, 8th of October