File size: 8,402 Bytes
5b32206 | 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 | # Primitive Extractor - Clotho Reconstruction
## Overview
This checkpoint represents the **Clotho Reconstruction** fine-tuning of the WindOne Sound V3 Primitive Extractor.
Starting from the proven ESC-50 Baseline weights, this module was trained as an Autoencoder on the Clotho dataset. A temporary linear decoder (`512 -> 1024 -> 768`) was attached to the end of the Primitive Extractor.
### Why Reconstruction Loss?
We deliberately chose **L1 Reconstruction Loss** instead of Contrastive Loss (like CLIP) for this phase.
* **Acoustic Fidelity:** The downstream `VoiceHead` requires exact acoustic textures to generate clean mel-spectrograms. Contrastive loss forces the 512-dim space to prioritize text semantics, which can distort fine-grained audio details.
* **Separation of Concerns:** Reconstruction loss guarantees the 512-dim primitives retain the exact acoustic information of the 768-dim BEATs features. Semantic and temporal alignment is handled later by the `CausalGraphNetwork` and `COGENMemory`.
## Training Configuration
- **Base Model**: PrimitiveExtractor (ESC-50 Baseline) + Temporary Decoder
- **Dataset**: Clotho Development Set (3,631 audio files)
- **Train/Val Split**: 2,904 / 727
- **Input**: 768-dim BEATs features
- **Output**: 768-dim Reconstructed features (via 512-dim bottleneck)
- **Epochs**: 8
- **Batch Size**: 8
- **Optimizer**: AdamW (lr=1e-4, weight_decay=1e-2)
- **Loss**: L1 Reconstruction Loss
- **Checkpoint Metric**: Validation Reconstruction Loss (Lower is better)
## Results Summary
- **Best Val Loss**: 0.1251 (Epoch 8)
- **Best Val Similarity**: 91.94% (Cosine Similarity between original and reconstructed 768-dim vectors)
- **Verdict**: The 512-dim primitives successfully retain ~92% of the acoustic information from the original BEATs features.
## Training Script
```python
import os
import sys
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from huggingface_hub import hf_hub_download, HfApi
from google.colab import drive
from tqdm.auto import tqdm
# ==========================================
# 1. SETUP & PATHS
# ==========================================
drive.mount('/content/drive', force_remount=False)
CLOTHO_BEATS_768_CACHE = '/content/clotho_beats_768_cache'
repo_id = "Hitelcy/WindoneRepo2"
sys.path.append('/content/drive/MyDrive/WindOneSound_300M')
from model_v3.primitive_extractor import PrimitiveExtractor
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ==========================================
# 2. LOAD ESC-50 BASELINE WEIGHTS
# ==========================================
print("📥 Downloading ESC-50 Baseline Primitive Extractor from Hugging Face...")
esc50_ckpt_path = hf_hub_download(
repo_id=repo_id,
filename="model_checkpoints/Primitive_Extractor/esc50/primitive_extractor_esc50_best.pt",
repo_type="dataset",
local_dir="/tmp/hf_ckpt"
)
# ==========================================
# 3. DEFINE AUTOENCODER MODEL
# ==========================================
class PrimitiveAutoEncoder(nn.Module):
def __init__(self):
super().__init__()
self.extractor = PrimitiveExtractor(input_dim=768, hidden_dim=1728, output_dim=512)
self.decoder = nn.Sequential(
nn.Linear(512, 1024),
nn.GELU(),
nn.Linear(1024, 768)
)
def forward(self, x):
primitives = self.extractor(x)
reconstructed = self.decoder(primitives)
return reconstructed
model = PrimitiveAutoEncoder()
esc50_state = torch.load(esc50_ckpt_path, map_location='cpu', weights_only=False)
original_state_dict = esc50_state['model_state_dict']
# Strip 'extractor.' prefix to load into bare PrimitiveExtractor
extractor_state_dict = {}
for k, v in original_state_dict.items():
if k.startswith('extractor.'):
new_key = k.replace('extractor.', '')
extractor_state_dict[new_key] = v
model.extractor.load_state_dict(extractor_state_dict)
print("✅ ESC-50 weights successfully loaded into Extractor.")
model = model.to(device)
extractor_params = sum(p.numel() for p in model.extractor.parameters() if p.requires_grad)
decoder_params = sum(p.numel() for p in model.decoder.parameters() if p.requires_grad)
print(f" Params -> Extractor: {extractor_params:,} | Decoder: {decoder_params:,} | Total: {extractor_params + decoder_params:,}\n")
# ==========================================
# 4. DATASET & DATALOADER
# ==========================================
class ClothoBeatsDataset(torch.utils.data.Dataset):
def __init__(self, cache_dir, split='train', train_ratio=0.8):
self.cache_files = sorted([f for f in os.listdir(cache_dir) if f.endswith('.pt')])
split_idx = int(len(self.cache_files) * train_ratio)
self.files = self.cache_files[:split_idx] if split == 'train' else self.cache_files[split_idx:]
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
return torch.load(os.path.join(CLOTHO_BEATS_768_CACHE, self.files[idx]), weights_only=True)
train_dataset = ClothoBeatsDataset(CLOTHO_BEATS_768_CACHE, split='train')
val_dataset = ClothoBeatsDataset(CLOTHO_BEATS_768_CACHE, split='val')
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=2)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=8, shuffle=False, num_workers=2)
print(f"✅ Train size: {len(train_dataset)}, Val size: {len(val_dataset)}")
# ==========================================
# 5. TRAINING LOOP
# ==========================================
criterion = nn.L1Loss()
optimizer = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-2)
num_epochs = 8
best_val_loss = float('inf')
api = HfApi()
print("\n🚀 Starting Clotho Reconstruction Training (Max 8 Epochs)...")
for epoch in range(1, num_epochs + 1):
model.train()
train_losses = []
for features in tqdm(train_loader, desc=f"Epoch {epoch}/8 Train"):
features = features.to(device)
optimizer.zero_grad()
reconstructed = model(features)
loss = criterion(reconstructed, features)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
train_losses.append(loss.item())
model.eval()
val_losses = []
val_similarities = []
with torch.no_grad():
for features in tqdm(val_loader, desc=f"Epoch {epoch}/8 Val"):
features = features.to(device)
reconstructed = model(features)
loss = criterion(reconstructed, features)
val_losses.append(loss.item())
B, T, D = features.shape
flat_orig = features.view(B * T, D)
flat_recon = reconstructed.view(B * T, D)
sim = F.cosine_similarity(flat_orig, flat_recon, dim=1).mean().item()
val_similarities.append(sim)
avg_train_loss = sum(train_losses) / len(train_losses)
avg_val_loss = sum(val_losses) / len(val_losses)
avg_val_sim = (sum(val_similarities) / len(val_similarities)) * 100
print(f"\nEpoch {epoch}/{num_epochs} | Train Loss: {avg_train_loss:.4f} | Val Loss: {avg_val_loss:.4f} | Val Similarity: {avg_val_sim:.2f}%\n")
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
print(f" New best Val Loss! Saving checkpoint to Hugging Face...")
save_path = "model_checkpoints/Primitive_Extractor/clotho/primitive_extractor_clotho_recon_best.pt"
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'val_recon_loss': avg_val_loss,
'val_similarity_percent': avg_val_sim,
'train_recon_loss': avg_train_loss
}, '/tmp/primitive_clotho_best.pt')
try:
api.upload_file(
path_or_fileobj='/tmp/primitive_clotho_best.pt',
path_in_repo=save_path,
repo_id=repo_id,
repo_type="dataset"
)
print(f"✅ Successfully uploaded checkpoint to {repo_id}/{save_path}")
except Exception as e:
print(f"❌ HF Upload failed: {e}")
print("\n Clotho Reconstruction Training complete!")
print(f"Best Validation Loss: {best_val_loss:.4f}")
```
|