File size: 8,109 Bytes
0919d3c aa9090e 7831472 0919d3c 7831472 aa9dfd4 0919d3c 0337262 18eb21d 0337262 0919d3c 7831472 0919d3c 7831472 0919d3c 7831472 e0ebeb3 0919d3c aa9dfd4 0919d3c 7831472 0919d3c 7831472 0919d3c 2adcf7c 0919d3c 2adcf7c 0919d3c 2adcf7c 0919d3c 2adcf7c 0919d3c 2adcf7c 0919d3c | 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 | import json
import torch
import torch.nn as nn
import numpy as np
import soundfile as sf
import torchaudio.functional as TAF
from transformers import PreTrainedModel, AutoProcessor, AutoModel
from .configuration_apex import APEXConfig
# BUILDING BLOCKS
class SharedBlock(nn.Module):
def __init__(self, in_dim, out_dim, dropout):
super().__init__()
self.block = nn.Sequential(
nn.Linear(in_dim, out_dim),
nn.BatchNorm1d(out_dim),
nn.GELU(),
nn.Dropout(dropout)
)
def forward(self, x):
return self.block(x)
class BranchBlock(nn.Module):
def __init__(self, in_dim, out_dim, dropout, use_bn=True):
super().__init__()
layers = [nn.Linear(in_dim, out_dim)]
if use_bn:
layers.append(nn.BatchNorm1d(out_dim))
layers += [nn.GELU(), nn.Dropout(dropout)]
self.block = nn.Sequential(*layers)
def forward(self, x):
return self.block(x)
class TaskBranch(nn.Module):
def __init__(self, in_dim, branch_dims, dropout, scale, shift):
super().__init__()
layers = []
prev = in_dim
for dim in branch_dims:
layers.append(BranchBlock(prev, dim, dropout=dropout, use_bn=True))
prev = dim
layers.append(nn.Linear(prev, 1))
self.branch = nn.Sequential(*layers)
self.scale = scale
self.shift = shift
def forward(self, x):
return torch.sigmoid(self.branch(x)) * self.scale + self.shift
# APEX MODEL
class APEXModel(PreTrainedModel):
config_class = APEXConfig
_keys_to_ignore_on_load_missing = [r"mert\..*", r"mert_processor\..*"]
_tied_weights_keys = []
@property
def all_tied_weights_keys(self):
return {}
def _init_weights(self, module):
pass
def __init__(self, config: APEXConfig):
super().__init__(config)
# Load MERT processor and encoder fresh from HuggingFace
self.mert_processor = AutoProcessor.from_pretrained(
config.mert_model_name,
trust_remote_code = True
)
with torch.device("cpu"):
self.mert = AutoModel.from_pretrained(
config.mert_model_name,
trust_remote_code = True,
device_map = None,
low_cpu_mem_usage = False
)
self.mert.eval()
for param in self.mert.parameters():
param.requires_grad = False
self.target_sr = self.mert_processor.sampling_rate
# Conv1d aggregator with fixed seed
torch.manual_seed(config.seed)
self.aggregator = nn.Conv1d(
in_channels = len(config.layer_indices),
out_channels = 1,
kernel_size = 1
)
# Shared layers: 768 → 512 → 256
shared_layers = []
prev_dim = config.input_dim
for dim in config.shared_dims:
shared_layers.append(SharedBlock(prev_dim, dim, dropout=config.dropout_shared))
prev_dim = dim
self.shared = nn.Sequential(*shared_layers)
out_dim = config.shared_dims[-1] # 256
# Task branches: 256 → 128 → 64 → 1
self.branch_score_streams = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=100, shift=0)
self.branch_score_likes = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=100, shift=0)
self.branch_coherence = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=4, shift=1)
self.branch_musicality = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=4, shift=1)
self.branch_memorability = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=4, shift=1)
self.branch_clarity = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=4, shift=1)
self.branch_naturalness = TaskBranch(out_dim, config.branch_dims, config.dropout_branch, scale=4, shift=1)
def _init_weights(self, module):
pass
def forward(self, embedding):
shared = self.shared(embedding)
return {
"score_streams": self.branch_score_streams(shared).squeeze(1),
"score_likes" : self.branch_score_likes(shared).squeeze(1),
"coherence" : self.branch_coherence(shared).squeeze(1),
"musicality" : self.branch_musicality(shared).squeeze(1),
"memorability" : self.branch_memorability(shared).squeeze(1),
"clarity" : self.branch_clarity(shared).squeeze(1),
"naturalness" : self.branch_naturalness(shared).squeeze(1),
}
def _load_audio(self, audio_path):
waveform, sr = sf.read(audio_path, dtype="float32")
waveform = torch.from_numpy(waveform)
if len(waveform.shape) > 1 and waveform.shape[1] > 1:
waveform = waveform.mean(dim=1)
waveform = waveform.to(self.device)
if sr != self.target_sr:
waveform = TAF.resample(waveform, sr, self.target_sr)
return waveform
def _extract_embedding(self, waveform):
segment_len = self.config.segment_sec * self.target_sr
segment_embeddings = []
for start in range(0, waveform.shape[0], segment_len):
segment = waveform[start:start + segment_len]
if segment.numel() == 0:
break
if segment.shape[0] < segment_len:
pad_len = segment_len - segment.shape[0]
segment = torch.nn.functional.pad(segment, (0, pad_len))
inputs = self.mert_processor(
segment.cpu().numpy(),
sampling_rate = self.target_sr,
return_tensors = "pt"
)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = self.mert(**inputs, output_hidden_states=True)
all_hidden = torch.stack([
outputs.hidden_states[i].mean(dim=1)
for i in self.config.layer_indices
])
all_hidden = all_hidden.squeeze(1)
pooled = self.aggregator(
all_hidden.unsqueeze(0)
).squeeze()
segment_embeddings.append(pooled)
del segment, inputs, outputs, all_hidden, pooled
song_embedding = torch.stack(segment_embeddings).mean(dim=0)
return song_embedding
@torch.no_grad()
def predict(self, audio_path, save_json=None):
self.eval()
print(f"\nProcessing: {audio_path}")
waveform = self._load_audio(audio_path)
duration = waveform.shape[0] / self.target_sr
n_segs = int(np.ceil(duration / self.config.segment_sec))
print(f"Duration: {duration:.1f}s | Segments: {n_segs}")
print("Extracting MERT embeddings...")
embedding = self._extract_embedding(waveform)
print("Running APEX model...")
preds = self.forward(embedding.unsqueeze(0))
results = {
task: float(preds[task].squeeze().cpu())
for task in preds
}
print(f"\n{'─'*50}")
print(f" APEX Predictions")
print(f"{'─'*50}")
print(f"\n Popularity:")
print(f" {'-'*40}")
print(f" {'Streams Score':<20} {results['score_streams']:>8.2f} / 100")
print(f" {'Likes Score':<20} {results['score_likes']:>8.2f} / 100")
print(f"\n Aesthetic Quality:")
print(f" {'-'*40}")
for dim in ["coherence", "musicality", "memorability", "clarity", "naturalness"]:
print(f" {dim.capitalize():<20} {results[dim]:>8.2f} / 5.00")
if save_json:
with open(save_json, "w") as f:
json.dump({
"audio_path" : audio_path,
"predictions": results
}, f, indent=2)
print(f"Results saved to {save_json}")
return results |