Spaces:
Runtime error
Runtime error
File size: 20,121 Bytes
90cacdf 1b6bb59 7ac8557 90cacdf 7ac8557 ff526b3 1e53a02 90cacdf 7ac8557 634cc2a f3350b1 0e3a05d 652f240 32701af 5945136 133e1dc 90cacdf 652f240 133e1dc 652f240 9eba2f5 eae60a9 133e1dc 7fc4de1 133e1dc 652f240 a559a3b 652f240 9eba2f5 eae60a9 be8f3b0 568c3f1 be8f3b0 133e1dc 7902946 133e1dc a559a3b 7902946 652f240 e8eaf47 652f240 f13cb8e fb9ce8b 9eba2f5 fb9ce8b 9eba2f5 fb9ce8b 652f240 133e1dc fb9ce8b 652f240 fb9ce8b 652f240 943f213 652f240 f13cb8e 652f240 90cacdf 7d6f241 90cacdf 7d6f241 ff526b3 1e53a02 ff526b3 f73ffe0 d2155c7 7fc4de1 90cacdf 9a9a2c9 d8d3e30 90cacdf 9a9a2c9 90cacdf 9a9a2c9 90cacdf 8125531 9a9a2c9 8125531 90cacdf 7d6f241 6448f47 106ab10 aecaaea 106ab10 aecaaea 90cacdf ff526b3 b99be38 e8a69d9 b99be38 aecaaea b99be38 aecaaea f13cb8e 90cacdf 7d6f241 90cacdf 1e53a02 90cacdf 7d6f241 90cacdf 6448f47 90cacdf 1ff07dc 90cacdf ff526b3 90cacdf 7d6f241 1dd1464 1e53a02 b676040 1dd1464 7d6f241 1dd1464 6448f47 1dd1464 1ff07dc 1dd1464 7d6f241 9a9a2c9 7d6f241 5945136 9a9a2c9 7d6f241 7ac8557 7d6f241 7ac8557 7d6f241 9a9a2c9 7d6f241 7ac8557 7d6f241 9a9a2c9 7ac8557 f8fea2a f3350b1 0e3a05d f3350b1 1b6bb59 29f23c3 1b6bb59 29f23c3 1b6bb59 568c3f1 7ac8557 1b6bb59 4d2eb76 7ac8557 1b6bb59 4d2eb76 32701af 29f23c3 32701af 29f23c3 32701af 29f23c3 4d2eb76 32701af c756b1d 1b6bb59 7ac8557 c756b1d 7ac8557 1b6bb59 29f23c3 1b6bb59 29f23c3 32701af 1b6bb59 7ac8557 32701af c756b1d 32701af c756b1d 32701af 4d2eb76 32701af 7ac8557 568c3f1 |
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
import torch
import numpy as np
import torchmetrics
import pytorch_lightning as pl
from torch import Tensor, nn
from torchaudio.models import HDemucs
from auraloss.time import SISDRLoss
from auraloss.freq import MultiResolutionSTFTLoss
from umx.openunmix.model import OpenUnmix, Separator
from remfx.utils import spectrogram
from remfx.tcn import TCN
from remfx.utils import causal_crop
from remfx import effects
from remfx.classifier import Cnn14
import asteroid
import random
ALL_EFFECTS = effects.Pedalboard_Effects
class RemFXChainInference(pl.LightningModule):
def __init__(
self,
models,
sample_rate,
num_bins,
effect_order,
classifier=None,
shuffle_effect_order=False,
use_all_effect_models=False,
):
super().__init__()
self.model = models
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=num_bins, sample_rate=sample_rate
)
self.l1loss = nn.L1Loss()
self.metrics = nn.ModuleDict(
{
"SISDR": SISDRLoss(),
"STFT": MultiResolutionSTFTLoss(),
}
)
self.sample_rate = sample_rate
self.effect_order = effect_order
self.classifier = classifier
self.shuffle_effect_order = shuffle_effect_order
self.output_str = "IN_SISDR,OUT_SISDR,IN_STFT,OUT_STFT\n"
self.use_all_effect_models = use_all_effect_models
def forward(self, batch, batch_idx, order=None, verbose=False):
x, y, _, rem_fx_labels = batch
# Use chain of effects defined in config
if order:
effects_order = order
else:
effects_order = self.effect_order
# Use classifier labels
if self.classifier:
threshold = 0.5
with torch.no_grad():
labels = torch.hstack(self.classifier(x))
rem_fx_labels = torch.where(labels > threshold, 1.0, 0.0)
if self.use_all_effect_models:
effects_present = [
[ALL_EFFECTS[i] for i, effect in enumerate(effect_label)]
for effect_label in rem_fx_labels
]
else:
effects_present = [
[
ALL_EFFECTS[i]
for i, effect in enumerate(effect_label)
if effect == 1.0
]
for effect_label in rem_fx_labels
]
effects_present_name = [
[
ALL_EFFECTS[i].__name__
for i, effect in enumerate(effect_label)
if effect == 1.0
]
for effect_label in rem_fx_labels
]
if verbose:
print("Detected effects:", effects_present_name[0])
print("Removing effects...")
output = []
with torch.no_grad():
for i, (elem, effects_list) in enumerate(zip(x, effects_present)):
elem = elem.unsqueeze(0) # Add batch dim
# Get the correct effect by search for names in effects_order
effect_list_names = [effect.__name__ for effect in effects_list]
effects = [
effect for effect in effects_order if effect in effect_list_names
]
for effect in effects:
# Sample the model
elem = self.model[effect].model.sample(elem)
output.append(elem.squeeze(0))
output = torch.stack(output)
loss = self.mrstftloss(output, y) + self.l1loss(output, y) * 100
return loss, output
def test_step(self, batch, batch_idx):
x, y, _, _ = batch # x, y = (B, C, T), (B, C, T)
if self.shuffle_effect_order:
# Random order
random.shuffle(self.effect_order)
loss, output = self.forward(batch, batch_idx, order=self.effect_order)
# Crop target to match output
if output.shape[-1] < y.shape[-1]:
y = causal_crop(y, output.shape[-1])
self.log("test_loss", loss)
# Metric logging
with torch.no_grad():
for metric in self.metrics:
# SISDR returns negative values, so negate them
if metric == "SISDR":
negate = -1
else:
negate = 1
self.log(
f"test_{metric}", # + "".join(self.effect_order).replace("RandomPedalboard", ""),
negate * self.metrics[metric](output, y),
on_step=False,
on_epoch=True,
logger=True,
prog_bar=True,
sync_dist=True,
)
self.log(
f"Input_{metric}",
negate * self.metrics[metric](x, y),
on_step=False,
on_epoch=True,
logger=True,
prog_bar=True,
sync_dist=True,
)
return loss
def sample(self, batch):
return self.forward(batch, 0)[1]
class RemFX(pl.LightningModule):
def __init__(
self,
lr: float,
lr_beta1: float,
lr_beta2: float,
lr_eps: float,
lr_weight_decay: float,
sample_rate: float,
network: nn.Module,
):
super().__init__()
self.lr = lr
self.lr_beta1 = lr_beta1
self.lr_beta2 = lr_beta2
self.lr_eps = lr_eps
self.lr_weight_decay = lr_weight_decay
self.sample_rate = sample_rate
self.model = network
self.metrics = nn.ModuleDict(
{
"SISDR": SISDRLoss(),
"STFT": MultiResolutionSTFTLoss(),
}
)
# Log first batch metrics input vs output only once
self.log_train_audio = True
self.output_str = "IN_SISDR,OUT_SISDR,IN_STFT,OUT_STFT\n"
@property
def device(self):
return next(self.model.parameters()).device
def configure_optimizers(self):
optimizer = torch.optim.AdamW(
list(self.model.parameters()),
lr=self.lr,
betas=(self.lr_beta1, self.lr_beta2),
eps=self.lr_eps,
weight_decay=self.lr_weight_decay,
)
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer,
[0.8 * self.trainer.max_steps, 0.95 * self.trainer.max_steps],
gamma=0.1,
)
return {
"optimizer": optimizer,
"lr_scheduler": {
"scheduler": lr_scheduler,
"monitor": "val_loss",
"interval": "step",
"frequency": 1,
},
}
def training_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="train")
def validation_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="valid")
def test_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="test")
def common_step(self, batch, batch_idx, mode: str = "train"):
x, y, _, _ = batch # x, y = (B, C, T), (B, C, T)
loss, output = self.model((x, y))
# Crop target to match output
target = y
if output.shape[-1] < y.shape[-1]:
target = causal_crop(y, output.shape[-1])
self.log(f"{mode}_loss", loss)
# Metric logging
with torch.no_grad():
for metric in self.metrics:
# SISDR returns negative values, so negate them
if metric == "SISDR":
negate = -1
else:
negate = 1
# Only Log FAD on test set
if metric == "FAD" and mode != "test":
continue
self.log(
f"{mode}_{metric}",
negate * self.metrics[metric](output, target),
on_step=False,
on_epoch=True,
logger=True,
prog_bar=True,
sync_dist=True,
)
self.log(
f"Input_{metric}",
negate * self.metrics[metric](x, y),
on_step=False,
on_epoch=True,
logger=True,
prog_bar=True,
sync_dist=True,
)
return loss
class OpenUnmixModel(nn.Module):
def __init__(
self,
n_fft: int = 2048,
hop_length: int = 512,
n_channels: int = 1,
alpha: float = 0.3,
sample_rate: int = 22050,
):
super().__init__()
self.n_channels = n_channels
self.n_fft = n_fft
self.hop_length = hop_length
self.alpha = alpha
window = torch.hann_window(n_fft)
self.register_buffer("window", window)
self.num_bins = self.n_fft // 2 + 1
self.sample_rate = sample_rate
self.model = OpenUnmix(
nb_channels=self.n_channels,
nb_bins=self.num_bins,
)
self.separator = Separator(
target_models={"other": self.model},
nb_channels=self.n_channels,
sample_rate=self.sample_rate,
n_fft=self.n_fft,
n_hop=self.hop_length,
)
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=self.num_bins, sample_rate=self.sample_rate
)
self.l1loss = nn.L1Loss()
def forward(self, batch):
x, target = batch
X = spectrogram(x, self.window, self.n_fft, self.hop_length, self.alpha)
Y = self.model(X)
sep_out = self.separator(x).squeeze(1)
loss = self.mrstftloss(sep_out, target) + self.l1loss(sep_out, target) * 100
return loss, sep_out
def sample(self, x: Tensor) -> Tensor:
return self.separator(x).squeeze(1)
class DemucsModel(nn.Module):
def __init__(self, sample_rate, **kwargs) -> None:
super().__init__()
self.model = HDemucs(**kwargs)
self.num_bins = kwargs["nfft"] // 2 + 1
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=self.num_bins, sample_rate=sample_rate
)
self.l1loss = nn.L1Loss()
def forward(self, batch):
x, target = batch
output = self.model(x).squeeze(1)
loss = self.mrstftloss(output, target) + self.l1loss(output, target) * 100
return loss, output
def sample(self, x: Tensor) -> Tensor:
return self.model(x).squeeze(1)
class DPTNetModel(nn.Module):
def __init__(self, sample_rate, num_bins, **kwargs):
super().__init__()
self.model = asteroid.models.dptnet.DPTNet(**kwargs)
self.num_bins = num_bins
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=self.num_bins, sample_rate=sample_rate
)
self.l1loss = nn.L1Loss()
def forward(self, batch):
x, target = batch
output = self.model(x.squeeze(1))
loss = self.mrstftloss(output, target) + self.l1loss(output, target) * 100
return loss, output
def sample(self, x: Tensor) -> Tensor:
return self.model(x.squeeze(1))
class DCUNetModel(nn.Module):
def __init__(self, sample_rate, num_bins, **kwargs):
super().__init__()
self.model = asteroid.models.DCUNet(**kwargs)
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=num_bins, sample_rate=sample_rate
)
self.l1loss = nn.L1Loss()
def forward(self, batch):
x, target = batch
output = self.model(x.squeeze(1)) # B x T
# Crop target to match output
if output.shape[-1] < target.shape[-1]:
target = causal_crop(target, output.shape[-1])
loss = self.mrstftloss(output, target) + self.l1loss(output, target) * 100
return loss, output
def sample(self, x: Tensor) -> Tensor:
output = self.model(x.squeeze(1)) # B x T
return output
class TCNModel(nn.Module):
def __init__(self, sample_rate, num_bins, **kwargs):
super().__init__()
self.model = TCN(**kwargs)
self.mrstftloss = MultiResolutionSTFTLoss(
n_bins=num_bins, sample_rate=sample_rate
)
self.l1loss = nn.L1Loss()
def forward(self, batch):
x, target = batch
output = self.model(x) # B x 1 x T
# Crop target to match output
if output.shape[-1] < target.shape[-1]:
target = causal_crop(target, output.shape[-1])
loss = self.mrstftloss(output, target) + self.l1loss(output, target) * 100
return loss, output
def sample(self, x: Tensor) -> Tensor:
output = self.model(x) # B x 1 x T
return output
def mixup(x: torch.Tensor, y: torch.Tensor, alpha: float = 1.0):
"""Mixup data augmentation for time-domain signals.
Args:
x (torch.Tensor): Batch of time-domain signals, shape [batch, 1, time].
y (torch.Tensor): Batch of labels, shape [batch, n_classes].
alpha (float): Beta distribution parameter.
Returns:
torch.Tensor: Mixed time-domain signals, shape [batch, 1, time].
torch.Tensor: Mixed labels, shape [batch, n_classes].
torch.Tensor: Lambda
"""
batch_size = x.size(0)
if alpha > 0:
# lam = np.random.beta(alpha, alpha)
lam = np.random.uniform(0.25, 0.75, batch_size)
lam = torch.from_numpy(lam).float().to(x.device).view(batch_size, 1, 1)
else:
lam = 1
if np.random.rand() > 0.5:
index = torch.randperm(batch_size).to(x.device)
mixed_x = lam * x + (1 - lam) * x[index, :]
mixed_y = torch.logical_or(y, y[index, :]).float()
else:
mixed_x = x
mixed_y = y
return mixed_x, mixed_y, lam
class FXClassifier(pl.LightningModule):
def __init__(
self,
lr: float,
lr_weight_decay: float,
sample_rate: float,
network: nn.Module,
mixup: bool = False,
label_smoothing: float = 0.0,
):
super().__init__()
self.lr = lr
self.lr_weight_decay = lr_weight_decay
self.sample_rate = sample_rate
self.network = network
self.effects = ["Reverb", "Chorus", "Delay", "Distortion", "Compressor"]
self.mixup = mixup
self.label_smoothing = label_smoothing
if isinstance(self.network, Cnn14):
self.loss_fn = torch.nn.BCELoss()
self.metrics = torch.nn.ModuleDict()
for effect in self.effects:
self.metrics[
f"train_{effect}_acc"
] = torchmetrics.classification.Accuracy(task="binary")
self.metrics[
f"valid_{effect}_acc"
] = torchmetrics.classification.Accuracy(task="binary")
self.metrics[
f"test_{effect}_acc"
] = torchmetrics.classification.Accuracy(task="binary")
else:
self.loss_fn = torch.nn.CrossEntropyLoss(label_smoothing=label_smoothing)
self.train_f1 = torchmetrics.classification.MultilabelF1Score(
5, average="none", multidim_average="global"
)
self.val_f1 = torchmetrics.classification.MultilabelF1Score(
5, average="none", multidim_average="global"
)
self.test_f1 = torchmetrics.classification.MultilabelF1Score(
5, average="none", multidim_average="global"
)
self.train_f1_avg = torchmetrics.classification.MultilabelF1Score(
5, threshold=0.5, average="macro", multidim_average="global"
)
self.val_f1_avg = torchmetrics.classification.MultilabelF1Score(
5, threshold=0.5, average="macro", multidim_average="global"
)
self.test_f1_avg = torchmetrics.classification.MultilabelF1Score(
5, threshold=0.5, average="macro", multidim_average="global"
)
self.metrics = {
"train": self.train_f1,
"valid": self.val_f1,
"test": self.test_f1,
}
self.avg_metrics = {
"train": self.train_f1_avg,
"valid": self.val_f1_avg,
"test": self.test_f1_avg,
}
def forward(self, x: torch.Tensor, train: bool = False):
return self.network(x, train=train)
def common_step(self, batch, batch_idx, mode: str = "train"):
train = True if mode == "train" else False
x, y, dry_label, wet_label = batch
if mode == "train" and self.mixup:
x_mixed, label_mixed, lam = mixup(x, wet_label)
outputs = self(x_mixed, train)
loss = 0
for idx, output in enumerate(outputs):
loss += self.loss_fn(output.squeeze(-1), label_mixed[..., idx])
else:
outputs = self(x, train)
loss = 0
# Multi-head binary loss
if isinstance(self.network, Cnn14):
for idx, output in enumerate(outputs):
loss += self.loss_fn(output.squeeze(-1), wet_label[..., idx])
else:
# Output is a 2d tensor
loss = self.loss_fn(outputs, wet_label)
self.log(
f"{mode}_loss",
loss,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
if isinstance(self.network, Cnn14):
acc_metrics = []
for idx, effect_name in enumerate(self.effects):
acc_metric = self.metrics[f"{mode}_{effect_name}_acc"](
outputs[idx].squeeze(-1), wet_label[..., idx]
)
self.log(
f"{mode}_{effect_name}_acc",
acc_metric,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
acc_metrics.append(acc_metric)
self.log(
f"{mode}_avg_acc",
torch.mean(torch.stack(acc_metrics)),
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
else:
metrics = self.metrics[mode](torch.sigmoid(outputs), wet_label.long())
for idx, effect_name in enumerate(self.effects):
self.log(
f"{mode}_f1_{effect_name}",
metrics[idx],
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
avg_metrics = self.avg_metrics[mode](
torch.sigmoid(outputs), wet_label.long()
)
self.log(
f"{mode}_avg_acc",
avg_metrics,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
sync_dist=True,
)
return loss
def training_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="train")
def validation_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="valid")
def test_step(self, batch, batch_idx):
return self.common_step(batch, batch_idx, mode="test")
def configure_optimizers(self):
optimizer = torch.optim.AdamW(
self.network.parameters(),
lr=self.lr,
weight_decay=self.lr_weight_decay,
)
return optimizer
|