Spaces:
Running on Zero
Running on Zero
LING commited on
Commit ·
3579235
1
Parent(s): f1315dd
Deploy SongFormer structure analysis
Browse files- .gitignore +4 -0
- README.md +22 -7
- SOURCES.md +8 -0
- app.py +308 -0
- model.json +22 -0
- packages.txt +2 -0
- requirements.txt +21 -0
- src/SongFormer/configs/SongFormer.yaml +186 -0
- src/SongFormer/dataset/custom_types.py +14 -0
- src/SongFormer/dataset/label2id.py +163 -0
- src/SongFormer/models/SongFormer.py +521 -0
- src/SongFormer/postprocessing/functional.py +71 -0
- src/SongFormer/postprocessing/helpers.py +101 -0
- src/third_party/musicfm/LICENSE +224 -0
- src/third_party/musicfm/model/__init__.py +2 -0
- src/third_party/musicfm/model/musicfm_25hz.py +252 -0
- src/third_party/musicfm/modules/__init__.py +2 -0
- src/third_party/musicfm/modules/conv.py +82 -0
- src/third_party/musicfm/modules/features.py +45 -0
- src/third_party/musicfm/modules/random_quantizer.py +83 -0
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.venv/
|
| 4 |
+
.DS_Store
|
README.md
CHANGED
|
@@ -1,15 +1,30 @@
|
|
| 1 |
---
|
| 2 |
-
title: SongFormer
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: cc-by-nc-4.0
|
| 12 |
short_description: Find section boundaries and labels in music
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: SongFormer Music Structure Analysis
|
| 3 |
+
emoji: 🎵
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.28.0
|
| 8 |
+
python_version: 3.10.13
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: cc-by-nc-4.0
|
| 12 |
short_description: Find section boundaries and labels in music
|
| 13 |
+
preload_from_hub:
|
| 14 |
+
- ASLP-lab/SongFormer SongFormer.safetensors
|
| 15 |
+
- minzwon/MusicFM msd_stats.json,pretrained_msd.pt
|
| 16 |
+
- OpenMuQ/MuQ-large-msd-iter config.json,model.safetensors
|
| 17 |
+
- facebook/wav2vec2-conformer-rope-large-960h-ft config.json
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# SongFormer Music Structure Analysis
|
| 21 |
+
|
| 22 |
+
Upload a music recording of at least five seconds to identify its sections. The Space returns a JSON file
|
| 23 |
+
with each section's start time, end time, and label. Times are in seconds.
|
| 24 |
+
|
| 25 |
+
SongFormer combines representations from MuQ and MusicFM for structure analysis.
|
| 26 |
+
The model runs on ZeroGPU and loads its checkpoints from Hugging Face.
|
| 27 |
+
|
| 28 |
+
The MuQ checkpoint is licensed under CC BY-NC 4.0.
|
| 29 |
+
|
| 30 |
+
The research code and model sources are listed in [SOURCES.md](SOURCES.md).
|
SOURCES.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sources
|
| 2 |
+
|
| 3 |
+
- SongFormer code: [ASLP-lab/SongFormer](https://github.com/ASLP-lab/SongFormer), CC BY 4.0.
|
| 4 |
+
- Original Space: [ASLP-lab/SongFormer](https://huggingface.co/spaces/ASLP-lab/SongFormer/tree/e566526662c92865ab677a684cec2e2c6cfe345e).
|
| 5 |
+
- SongFormer checkpoint: [ASLP-lab/SongFormer](https://huggingface.co/ASLP-lab/SongFormer).
|
| 6 |
+
- MusicFM checkpoint: [minzwon/MusicFM](https://huggingface.co/minzwon/MusicFM).
|
| 7 |
+
- MuQ checkpoint: [OpenMuQ/MuQ-large-msd-iter](https://huggingface.co/OpenMuQ/MuQ-large-msd-iter), CC BY-NC 4.0.
|
| 8 |
+
- MusicFM source included under `src/third_party/musicfm`, MIT license.
|
app.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import tempfile
|
| 6 |
+
import uuid
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import spaces
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parent
|
| 12 |
+
SONGFORMER = ROOT / "src" / "SongFormer"
|
| 13 |
+
os.chdir(SONGFORMER)
|
| 14 |
+
sys.path.insert(0, str(ROOT / "src" / "third_party"))
|
| 15 |
+
sys.path.insert(0, str(SONGFORMER))
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
import gradio as gr
|
| 20 |
+
import torch
|
| 21 |
+
import librosa
|
| 22 |
+
from omegaconf import OmegaConf
|
| 23 |
+
from ema_pytorch import EMA
|
| 24 |
+
from huggingface_hub import hf_hub_download
|
| 25 |
+
from muq import MuQ
|
| 26 |
+
from musicfm.model.musicfm_25hz import MusicFM25Hz
|
| 27 |
+
from postprocessing.functional import postprocess_functional_structure
|
| 28 |
+
from dataset.label2id import DATASET_ID_ALLOWED_LABEL_IDS, DATASET_LABEL_TO_DATASET_ID
|
| 29 |
+
from pyharp import ModelCard, build_endpoint
|
| 30 |
+
|
| 31 |
+
AFTER_DOWNSAMPLING_FRAME_RATES = 8.333
|
| 32 |
+
DATASET_LABEL = "SongForm-HX-8Class"
|
| 33 |
+
DATASET_IDS = [5]
|
| 34 |
+
TIME_DUR = 420
|
| 35 |
+
INPUT_SAMPLING_RATE = 24000
|
| 36 |
+
OUTPUT_ROOT = Path(tempfile.gettempdir()) / "songformer_outputs"
|
| 37 |
+
|
| 38 |
+
def initialize_models():
|
| 39 |
+
from models.SongFormer import Model
|
| 40 |
+
from safetensors.torch import load_file
|
| 41 |
+
|
| 42 |
+
device = torch.device("cuda")
|
| 43 |
+
hp = OmegaConf.load("configs/SongFormer.yaml")
|
| 44 |
+
muq_model = MuQ.from_pretrained("OpenMuQ/MuQ-large-msd-iter")
|
| 45 |
+
muq_model = muq_model.to(device).eval()
|
| 46 |
+
|
| 47 |
+
musicfm_model = MusicFM25Hz(
|
| 48 |
+
is_flash=False,
|
| 49 |
+
stat_path=hf_hub_download("minzwon/MusicFM", "msd_stats.json"),
|
| 50 |
+
model_path=hf_hub_download("minzwon/MusicFM", "pretrained_msd.pt"),
|
| 51 |
+
)
|
| 52 |
+
musicfm_model = musicfm_model.to(device).eval()
|
| 53 |
+
|
| 54 |
+
msa_model = Model(hp)
|
| 55 |
+
checkpoint = hf_hub_download("ASLP-lab/SongFormer", "SongFormer.safetensors")
|
| 56 |
+
model_ema = EMA(msa_model, include_online_model=False)
|
| 57 |
+
model_ema.load_state_dict(load_file(checkpoint, device="cpu"))
|
| 58 |
+
msa_model.load_state_dict(model_ema.ema_model.state_dict())
|
| 59 |
+
msa_model.to(device).eval()
|
| 60 |
+
return muq_model, musicfm_model, msa_model, hp, device
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def process_audio(audio_path, muq_model, musicfm_model, msa_model, hp, device, win_size=420, hop_size=420, num_classes=128):
|
| 64 |
+
wav, _ = librosa.load(audio_path, sr=INPUT_SAMPLING_RATE)
|
| 65 |
+
if len(wav) < 5 * INPUT_SAMPLING_RATE:
|
| 66 |
+
raise gr.Error("Audio must be at least 5 seconds long.")
|
| 67 |
+
audio = torch.tensor(wav).to(device)
|
| 68 |
+
|
| 69 |
+
# Prepare output
|
| 70 |
+
total_len = (
|
| 71 |
+
(audio.shape[0] // INPUT_SAMPLING_RATE) // TIME_DUR * TIME_DUR
|
| 72 |
+
) + TIME_DUR
|
| 73 |
+
total_frames = math.ceil(total_len * AFTER_DOWNSAMPLING_FRAME_RATES)
|
| 74 |
+
|
| 75 |
+
logits = {
|
| 76 |
+
"function_logits": np.zeros([total_frames, num_classes]),
|
| 77 |
+
"boundary_logits": np.zeros([total_frames]),
|
| 78 |
+
}
|
| 79 |
+
logits_num = {
|
| 80 |
+
"function_logits": np.zeros([total_frames, num_classes]),
|
| 81 |
+
"boundary_logits": np.zeros([total_frames]),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
# Prepare label masks
|
| 85 |
+
dataset_id2label_mask = {}
|
| 86 |
+
for key, allowed_ids in DATASET_ID_ALLOWED_LABEL_IDS.items():
|
| 87 |
+
dataset_id2label_mask[key] = np.ones(num_classes, dtype=bool)
|
| 88 |
+
dataset_id2label_mask[key][allowed_ids] = False
|
| 89 |
+
|
| 90 |
+
lens = 0
|
| 91 |
+
i = 0
|
| 92 |
+
|
| 93 |
+
with torch.no_grad():
|
| 94 |
+
while True:
|
| 95 |
+
start_idx = i * INPUT_SAMPLING_RATE
|
| 96 |
+
end_idx = min((i + win_size) * INPUT_SAMPLING_RATE, audio.shape[-1])
|
| 97 |
+
if start_idx >= audio.shape[-1]:
|
| 98 |
+
break
|
| 99 |
+
if end_idx - start_idx <= 1024:
|
| 100 |
+
break
|
| 101 |
+
|
| 102 |
+
audio_seg = audio[start_idx:end_idx]
|
| 103 |
+
|
| 104 |
+
# Get embeddings
|
| 105 |
+
muq_output = muq_model(audio_seg.unsqueeze(0), output_hidden_states=True)
|
| 106 |
+
muq_embd_420s = muq_output["hidden_states"][10]
|
| 107 |
+
del muq_output
|
| 108 |
+
torch.cuda.empty_cache()
|
| 109 |
+
|
| 110 |
+
_, musicfm_hidden_states = musicfm_model.get_predictions(
|
| 111 |
+
audio_seg.unsqueeze(0)
|
| 112 |
+
)
|
| 113 |
+
musicfm_embd_420s = musicfm_hidden_states[10]
|
| 114 |
+
del musicfm_hidden_states
|
| 115 |
+
torch.cuda.empty_cache()
|
| 116 |
+
|
| 117 |
+
# Process 30-second segments
|
| 118 |
+
wraped_muq_embd_30s = []
|
| 119 |
+
wraped_musicfm_embd_30s = []
|
| 120 |
+
|
| 121 |
+
for idx_30s in range(i, i + hop_size, 30):
|
| 122 |
+
start_idx_30s = idx_30s * INPUT_SAMPLING_RATE
|
| 123 |
+
end_idx_30s = min(
|
| 124 |
+
(idx_30s + 30) * INPUT_SAMPLING_RATE,
|
| 125 |
+
audio.shape[-1],
|
| 126 |
+
(i + hop_size) * INPUT_SAMPLING_RATE,
|
| 127 |
+
)
|
| 128 |
+
if start_idx_30s >= audio.shape[-1]:
|
| 129 |
+
break
|
| 130 |
+
if end_idx_30s - start_idx_30s <= 1024:
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
wraped_muq_embd_30s.append(
|
| 134 |
+
muq_model(
|
| 135 |
+
audio[start_idx_30s:end_idx_30s].unsqueeze(0),
|
| 136 |
+
output_hidden_states=True,
|
| 137 |
+
)["hidden_states"][10]
|
| 138 |
+
)
|
| 139 |
+
torch.cuda.empty_cache()
|
| 140 |
+
|
| 141 |
+
wraped_musicfm_embd_30s.append(
|
| 142 |
+
musicfm_model.get_predictions(
|
| 143 |
+
audio[start_idx_30s:end_idx_30s].unsqueeze(0)
|
| 144 |
+
)[1][10]
|
| 145 |
+
)
|
| 146 |
+
torch.cuda.empty_cache()
|
| 147 |
+
|
| 148 |
+
if wraped_muq_embd_30s:
|
| 149 |
+
wraped_muq_embd_30s = torch.concatenate(wraped_muq_embd_30s, dim=1)
|
| 150 |
+
wraped_musicfm_embd_30s = torch.concatenate(
|
| 151 |
+
wraped_musicfm_embd_30s, dim=1
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
all_embds = [
|
| 155 |
+
wraped_musicfm_embd_30s,
|
| 156 |
+
wraped_muq_embd_30s,
|
| 157 |
+
musicfm_embd_420s,
|
| 158 |
+
muq_embd_420s,
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
# Align embedding lengths
|
| 162 |
+
if len(all_embds) > 1:
|
| 163 |
+
embd_lens = [x.shape[1] for x in all_embds]
|
| 164 |
+
min_embd_len = min(embd_lens)
|
| 165 |
+
for idx in range(len(all_embds)):
|
| 166 |
+
all_embds[idx] = all_embds[idx][:, :min_embd_len, :]
|
| 167 |
+
|
| 168 |
+
embd = torch.concatenate(all_embds, axis=-1)
|
| 169 |
+
|
| 170 |
+
# Inference
|
| 171 |
+
dataset_ids = torch.Tensor(DATASET_IDS).to(device, dtype=torch.long)
|
| 172 |
+
msa_info, chunk_logits = msa_model.infer(
|
| 173 |
+
input_embeddings=embd,
|
| 174 |
+
dataset_ids=dataset_ids,
|
| 175 |
+
label_id_masks=torch.Tensor(
|
| 176 |
+
dataset_id2label_mask[
|
| 177 |
+
DATASET_LABEL_TO_DATASET_ID[DATASET_LABEL]
|
| 178 |
+
]
|
| 179 |
+
)
|
| 180 |
+
.to(device, dtype=bool)
|
| 181 |
+
.unsqueeze(0)
|
| 182 |
+
.unsqueeze(0),
|
| 183 |
+
with_logits=True,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Accumulate logits
|
| 187 |
+
start_frame = int(i * AFTER_DOWNSAMPLING_FRAME_RATES)
|
| 188 |
+
end_frame = start_frame + min(
|
| 189 |
+
math.ceil(hop_size * AFTER_DOWNSAMPLING_FRAME_RATES),
|
| 190 |
+
chunk_logits["boundary_logits"][0].shape[0],
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
logits["function_logits"][start_frame:end_frame, :] += (
|
| 194 |
+
chunk_logits["function_logits"][0].detach().cpu().numpy()
|
| 195 |
+
)
|
| 196 |
+
logits["boundary_logits"][start_frame:end_frame] = (
|
| 197 |
+
chunk_logits["boundary_logits"][0].detach().cpu().numpy()
|
| 198 |
+
)
|
| 199 |
+
logits_num["function_logits"][start_frame:end_frame, :] += 1
|
| 200 |
+
logits_num["boundary_logits"][start_frame:end_frame] += 1
|
| 201 |
+
lens += end_frame - start_frame
|
| 202 |
+
|
| 203 |
+
i += hop_size
|
| 204 |
+
|
| 205 |
+
# Average logits
|
| 206 |
+
logits["function_logits"] /= np.maximum(logits_num["function_logits"], 1)
|
| 207 |
+
logits["boundary_logits"] /= np.maximum(logits_num["boundary_logits"], 1)
|
| 208 |
+
|
| 209 |
+
logits["function_logits"] = torch.from_numpy(
|
| 210 |
+
logits["function_logits"][:lens]
|
| 211 |
+
).unsqueeze(0)
|
| 212 |
+
logits["boundary_logits"] = torch.from_numpy(
|
| 213 |
+
logits["boundary_logits"][:lens]
|
| 214 |
+
).unsqueeze(0)
|
| 215 |
+
|
| 216 |
+
# Post-process
|
| 217 |
+
msa_infer_output = postprocess_functional_structure(logits, hp)
|
| 218 |
+
|
| 219 |
+
return logits, msa_infer_output
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def rule_post_processing(msa_list):
|
| 223 |
+
if len(msa_list) <= 2:
|
| 224 |
+
return msa_list
|
| 225 |
+
|
| 226 |
+
result = msa_list.copy()
|
| 227 |
+
|
| 228 |
+
while len(result) > 2:
|
| 229 |
+
first_duration = result[1][0] - result[0][0]
|
| 230 |
+
if first_duration < 1.0 and len(result) > 2:
|
| 231 |
+
result[0] = (result[0][0], result[1][1])
|
| 232 |
+
result = [result[0]] + result[2:]
|
| 233 |
+
else:
|
| 234 |
+
break
|
| 235 |
+
|
| 236 |
+
while len(result) > 2:
|
| 237 |
+
last_label_duration = result[-1][0] - result[-2][0]
|
| 238 |
+
if last_label_duration < 1.0:
|
| 239 |
+
result = result[:-2] + [result[-1]]
|
| 240 |
+
else:
|
| 241 |
+
break
|
| 242 |
+
|
| 243 |
+
while len(result) > 2:
|
| 244 |
+
if result[0][1] == result[1][1] and result[1][0] <= 10.0:
|
| 245 |
+
result = [(result[0][0], result[0][1])] + result[2:]
|
| 246 |
+
else:
|
| 247 |
+
break
|
| 248 |
+
|
| 249 |
+
while len(result) > 2:
|
| 250 |
+
last_duration = result[-1][0] - result[-2][0]
|
| 251 |
+
if result[-2][1] == result[-3][1] and last_duration <= 10.0:
|
| 252 |
+
result = result[:-2] + [result[-1]]
|
| 253 |
+
else:
|
| 254 |
+
break
|
| 255 |
+
|
| 256 |
+
return result
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
model_card = ModelCard(
|
| 260 |
+
name="SongFormer",
|
| 261 |
+
description="Analyze the section boundaries and labels of a music recording.",
|
| 262 |
+
author="ASLP Lab",
|
| 263 |
+
tags=["music-structure-analysis", "music-information-retrieval"],
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@spaces.GPU(duration=300)
|
| 268 |
+
def process_fn(audio_path: str | None) -> str:
|
| 269 |
+
if not audio_path:
|
| 270 |
+
raise gr.Error("Upload a music recording.")
|
| 271 |
+
|
| 272 |
+
models = initialize_models()
|
| 273 |
+
_, msa_output = process_audio(audio_path, *models)
|
| 274 |
+
msa_output = rule_post_processing(msa_output)
|
| 275 |
+
segments = [
|
| 276 |
+
{
|
| 277 |
+
"start": round(float(msa_output[index][0]), 2),
|
| 278 |
+
"end": round(float(msa_output[index + 1][0]), 2),
|
| 279 |
+
"label": msa_output[index][1],
|
| 280 |
+
}
|
| 281 |
+
for index in range(len(msa_output) - 1)
|
| 282 |
+
]
|
| 283 |
+
|
| 284 |
+
output_dir = OUTPUT_ROOT / uuid.uuid4().hex
|
| 285 |
+
output_dir.mkdir(parents=True)
|
| 286 |
+
output_path = output_dir / "structure.json"
|
| 287 |
+
output_path.write_text(json.dumps({"segments": segments}, indent=2) + "\n")
|
| 288 |
+
return str(output_path)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
with gr.Blocks(title="SongFormer Music Structure Analysis") as demo:
|
| 292 |
+
build_endpoint(
|
| 293 |
+
model_card=model_card,
|
| 294 |
+
input_components=[
|
| 295 |
+
gr.Audio(type="filepath", label="Music Recording")
|
| 296 |
+
.harp_required(True)
|
| 297 |
+
.set_info("Upload a music recording for section analysis."),
|
| 298 |
+
],
|
| 299 |
+
output_components=[
|
| 300 |
+
gr.File(type="filepath", file_types=[".json"], label="Structure")
|
| 301 |
+
.set_info("Section start, end, and label in seconds."),
|
| 302 |
+
],
|
| 303 |
+
process_fn=process_fn,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
if __name__ == "__main__":
|
| 308 |
+
demo.queue(default_concurrency_limit=1).launch(show_error=True)
|
model.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "SongFormer",
|
| 3 |
+
"task": "Music structure analysis",
|
| 4 |
+
"source_repository": "ASLP-lab/SongFormer",
|
| 5 |
+
"source_license": "CC BY 4.0",
|
| 6 |
+
"checkpoints": {
|
| 7 |
+
"songformer": "ASLP-lab/SongFormer",
|
| 8 |
+
"musicfm": "minzwon/MusicFM",
|
| 9 |
+
"muq": "OpenMuQ/MuQ-large-msd-iter"
|
| 10 |
+
},
|
| 11 |
+
"checkpoint_license": "CC BY-NC 4.0 (MuQ)",
|
| 12 |
+
"input": {
|
| 13 |
+
"sample_rate": 24000,
|
| 14 |
+
"channels": 1,
|
| 15 |
+
"minimum_duration_seconds": 5
|
| 16 |
+
},
|
| 17 |
+
"output": {
|
| 18 |
+
"type": "JSON",
|
| 19 |
+
"fields": ["start", "end", "label"],
|
| 20 |
+
"time_unit": "seconds"
|
| 21 |
+
}
|
| 22 |
+
}
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
| 2 |
+
libsndfile1
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.8.0
|
| 2 |
+
torchaudio==2.8.0
|
| 3 |
+
transformers==4.51.1
|
| 4 |
+
accelerate==1.5.2
|
| 5 |
+
safetensors==0.5.3
|
| 6 |
+
numpy==1.25.0
|
| 7 |
+
scipy==1.15.2
|
| 8 |
+
librosa==0.11.0
|
| 9 |
+
soundfile==0.13.1
|
| 10 |
+
matplotlib==3.10.1
|
| 11 |
+
omegaconf==2.3.0
|
| 12 |
+
einops==0.8.1
|
| 13 |
+
einx==0.3.0
|
| 14 |
+
x-transformers==2.4.14
|
| 15 |
+
ema-pytorch==0.7.7
|
| 16 |
+
julius==0.2.7
|
| 17 |
+
muq==0.1.0
|
| 18 |
+
gradio==5.28.0
|
| 19 |
+
spaces>=0.51.1
|
| 20 |
+
huggingface-hub==0.33.5
|
| 21 |
+
git+https://github.com/TEAMuP-dev/pyharp.git@d65c4f7d0264dcdb3024a6c5466cddd7b2defdca
|
src/SongFormer/configs/SongFormer.yaml
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================
|
| 2 |
+
# Model Configuration
|
| 3 |
+
# ============================
|
| 4 |
+
|
| 5 |
+
input_dim_raw: 4096 # Downsampled Fused SSL Representation Dimension
|
| 6 |
+
input_dim: 2048 # Input Dimension after Linear Layer
|
| 7 |
+
|
| 8 |
+
# Downsampling Module
|
| 9 |
+
down_sample_conv_kernel_size: 3
|
| 10 |
+
down_sample_conv_stride: 3
|
| 11 |
+
down_sample_conv_dropout: 0.1
|
| 12 |
+
down_sample_conv_padding: 0
|
| 13 |
+
|
| 14 |
+
# Transformer Module
|
| 15 |
+
transformer_encoder_input_dim: 1024
|
| 16 |
+
transformer_input_dim: 512
|
| 17 |
+
num_transformer_layers: 4
|
| 18 |
+
transformer_nhead: 8
|
| 19 |
+
transformer_dropout: 0.1
|
| 20 |
+
|
| 21 |
+
# task-specific heads
|
| 22 |
+
boundary_head_hidden_dims: [128, 64, 8]
|
| 23 |
+
function_head_hidden_dims: []
|
| 24 |
+
|
| 25 |
+
num_classes: 128
|
| 26 |
+
num_dataset_classes: 64
|
| 27 |
+
|
| 28 |
+
# scheduler
|
| 29 |
+
warmup_steps: 300
|
| 30 |
+
total_steps: 12010
|
| 31 |
+
warmup_max_lr: 0.0001
|
| 32 |
+
|
| 33 |
+
# frame rates after downsampling
|
| 34 |
+
output_logits_frame_rates: 8.333
|
| 35 |
+
# it means output_logits_frame_rates = input_embd_frame_rates // downsample_rates, because the padding is 0.
|
| 36 |
+
downsample_rates: 3
|
| 37 |
+
# frame rates after downsampling, used by model and post process
|
| 38 |
+
frame_rates: 8.333
|
| 39 |
+
|
| 40 |
+
# ema config
|
| 41 |
+
ema_kwargs:
|
| 42 |
+
{update_after_step: 200}
|
| 43 |
+
|
| 44 |
+
# ============================
|
| 45 |
+
# Loss Functions configuration
|
| 46 |
+
# ============================
|
| 47 |
+
|
| 48 |
+
# Focal loss
|
| 49 |
+
label_focal_loss_weight: 0.2
|
| 50 |
+
|
| 51 |
+
label_focal_loss_alpha: 0.25
|
| 52 |
+
label_focal_loss_gamma: 2.0
|
| 53 |
+
|
| 54 |
+
# Boundary TV loss
|
| 55 |
+
boundary_tvloss_weight: 0.05
|
| 56 |
+
|
| 57 |
+
boundary_tv_loss_beta: 0.6
|
| 58 |
+
boundary_tv_loss_lambda: 0.4
|
| 59 |
+
boundary_tv_loss_boundary_threshold: 0.01
|
| 60 |
+
boundary_tv_loss_reduction_weight: 0.1
|
| 61 |
+
|
| 62 |
+
loss_weight_section: 0.2
|
| 63 |
+
loss_weight_function: 0.8
|
| 64 |
+
|
| 65 |
+
# ============================
|
| 66 |
+
# Training config
|
| 67 |
+
# ============================
|
| 68 |
+
|
| 69 |
+
# Number of neighbors used to augment boundaries in the dataset.
|
| 70 |
+
# Example: 1/25*3 * 10s = 1.2s (both sides total 4.2s)
|
| 71 |
+
num_neighbors: 10
|
| 72 |
+
learn_label: true
|
| 73 |
+
learn_segment: true
|
| 74 |
+
accumulation_steps: 2
|
| 75 |
+
slice_dur: 420
|
| 76 |
+
early_stopping_step: 3
|
| 77 |
+
local_maxima_filter_size: 3
|
| 78 |
+
|
| 79 |
+
# ============================
|
| 80 |
+
# Dataset config
|
| 81 |
+
# ============================
|
| 82 |
+
|
| 83 |
+
train_dataset:
|
| 84 |
+
_target_: dataset.SongFormerDataset.Dataset
|
| 85 |
+
dataset_abstracts:
|
| 86 |
+
[
|
| 87 |
+
{
|
| 88 |
+
"internal_tmp_id": "SongForm-HX-8Class",
|
| 89 |
+
"dataset_type": "SongForm-HX-8Class",
|
| 90 |
+
"input_embedding_dir": "your_data_dir/30s_420s/harmonix/musicfm_hop420/layer_10 your_data_dir/30s_420s/harmonix/muq_hop420/layer_10 your_data_dir/420s/harmonix/musicfm_hop420/layer_10 your_data_dir/420s/harmonix/muq_hop420/layer_10",
|
| 91 |
+
"label_path": "your_data_dir/labels/harmonixset_8class_rule_revision.jsonl",
|
| 92 |
+
"split_ids_path": "your_data_dir/separated_ids/harmonixset_separated_ids_with_val_set/train.txt",
|
| 93 |
+
"multiplier": 4,
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"internal_tmp_id": "SongForm-Private",
|
| 97 |
+
"dataset_type": "SongForm-Private",
|
| 98 |
+
"input_embedding_dir": "your_data_dir/30s_420s/Internal_data/musicfm_hop420/layer_10 your_data_dir/30s_420s/Internal_data/muq_hop420/layer_10 your_data_dir/420s/Internal_data/musicfm_hop420/layer_10 your_data_dir/420s/Internal_data/muq_hop420/layer_10",
|
| 99 |
+
"label_path": "your_data_dir/labels/0006_single_layer_transformer_musicfm_muq_along_time_00_5k_v1.jsonl",
|
| 100 |
+
"split_ids_path": "your_data_dir/separated_ids/internal_data_sofa_clean/train.txt",
|
| 101 |
+
"multiplier": 1,
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
adapter: HookTheoryAdapter,
|
| 105 |
+
internal_tmp_id: "SongForm-Hook",
|
| 106 |
+
structure_jsonl_paths: [
|
| 107 |
+
"your_data_dir/HookTheoryStructure.train.jsonl"
|
| 108 |
+
],
|
| 109 |
+
dataset_type: "SongForm-Hook",
|
| 110 |
+
input_embedding_dir: "your_data_dir/30s_420s/HookTheory/musicfm_hop420/layer_10 your_data_dir/30s_420s/HookTheory/muq_hop420/layer_10 your_data_dir/420s/HookTheory/musicfm_hop420/layer_10 your_data_dir/420s/HookTheory/muq_hop420/layer_10",
|
| 111 |
+
split_ids_path: "your_data_dir/separated_ids/hooktheory_separated_ids/train.txt",
|
| 112 |
+
multiplier: 1,
|
| 113 |
+
},
|
| 114 |
+
]
|
| 115 |
+
hparams:
|
| 116 |
+
output_logits_frame_rates: ${output_logits_frame_rates}
|
| 117 |
+
downsample_rates: ${downsample_rates}
|
| 118 |
+
num_neighbors: ${num_neighbors}
|
| 119 |
+
input_dim: ${input_dim_raw}
|
| 120 |
+
slice_dur: ${slice_dur}
|
| 121 |
+
num_classes: ${num_classes}
|
| 122 |
+
frame_rates: ${frame_rates}
|
| 123 |
+
|
| 124 |
+
eval_dataset:
|
| 125 |
+
_target_: dataset.SongFormerDataset.Dataset
|
| 126 |
+
dataset_abstracts:
|
| 127 |
+
[
|
| 128 |
+
{
|
| 129 |
+
"internal_tmp_id": "SongForm-HX-8Classs_val",
|
| 130 |
+
"dataset_type": "SongForm-HX-8Class",
|
| 131 |
+
"input_embedding_dir": "your_data_dir/30s_420s/harmonix/musicfm_hop420/layer_10 your_data_dir/30s_420s/harmonix/muq_hop420/layer_10 your_data_dir/420s/harmonix/musicfm_hop420/layer_10 your_data_dir/420s/harmonix/muq_hop420/layer_10",
|
| 132 |
+
"label_path": "your_data_dir/processed_data/labels/harmonixset_8class_rule_revision.jsonl",
|
| 133 |
+
"split_ids_path": "your_data_dir/separated_ids/harmonixset_separated_ids_with_val_set/val.txt",
|
| 134 |
+
"multiplier": 1,
|
| 135 |
+
},
|
| 136 |
+
]
|
| 137 |
+
hparams:
|
| 138 |
+
output_logits_frame_rates: ${output_logits_frame_rates}
|
| 139 |
+
downsample_rates: ${downsample_rates}
|
| 140 |
+
num_neighbors: ${num_neighbors}
|
| 141 |
+
input_dim: ${input_dim_raw}
|
| 142 |
+
slice_dur: ${slice_dur}
|
| 143 |
+
num_classes: ${num_classes}
|
| 144 |
+
frame_rates: ${frame_rates}
|
| 145 |
+
|
| 146 |
+
# ============================
|
| 147 |
+
# DataLoader configuration
|
| 148 |
+
# ============================
|
| 149 |
+
|
| 150 |
+
train_dataloader:
|
| 151 |
+
num_workers: 4
|
| 152 |
+
batch_size: 4
|
| 153 |
+
pin_memory: True
|
| 154 |
+
prefetch_factor: 4
|
| 155 |
+
drop_last: True
|
| 156 |
+
persistent_workers: True
|
| 157 |
+
shuffle: true
|
| 158 |
+
|
| 159 |
+
eval_dataloader:
|
| 160 |
+
num_workers: 0
|
| 161 |
+
batch_size: 1
|
| 162 |
+
shuffle: false
|
| 163 |
+
|
| 164 |
+
# ============================
|
| 165 |
+
# Optimizer configuration
|
| 166 |
+
# ============================
|
| 167 |
+
|
| 168 |
+
optimizer:
|
| 169 |
+
lr: ${warmup_max_lr}
|
| 170 |
+
betas: [0.8, 0.999]
|
| 171 |
+
eps: 1e-08
|
| 172 |
+
weight_decay: 3e-7
|
| 173 |
+
|
| 174 |
+
# ============================
|
| 175 |
+
# Training Run configuration
|
| 176 |
+
# ============================
|
| 177 |
+
|
| 178 |
+
args:
|
| 179 |
+
run_name: SongFormer
|
| 180 |
+
model_name: SongFormer
|
| 181 |
+
save_interval: 800
|
| 182 |
+
eval_interval: 800
|
| 183 |
+
checkpoint_dir: output/SongFormer
|
| 184 |
+
max_epochs: 1000
|
| 185 |
+
max_steps: 12010
|
| 186 |
+
tags: null
|
src/SongFormer/dataset/custom_types.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MsaInfo
|
| 3 |
+
A list of (timestamp, label) tuples used to represent music structure
|
| 4 |
+
analysis (MSA). The first element of the tuple is a float timestamp
|
| 5 |
+
(in seconds) and the second is a string label
|
| 6 |
+
|
| 7 |
+
Example
|
| 8 |
+
-------
|
| 9 |
+
>>> msa: MsaInfo = [(0.0, "intro"), (12.5, "verse"), (34.0, "chorus")]
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from typing import List, Tuple
|
| 13 |
+
|
| 14 |
+
MsaInfo = List[Tuple[float, str]]
|
src/SongFormer/dataset/label2id.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LABEL_TO_ID = {
|
| 2 |
+
"intro": 0,
|
| 3 |
+
"verse": 1,
|
| 4 |
+
"chorus": 2,
|
| 5 |
+
"bridge": 3,
|
| 6 |
+
"inst": 4,
|
| 7 |
+
"outro": 5,
|
| 8 |
+
"silence": 6,
|
| 9 |
+
"intchorus": 7,
|
| 10 |
+
"prechorus": 8,
|
| 11 |
+
"gtrbreak": 9,
|
| 12 |
+
"solo": 10,
|
| 13 |
+
"quietchorus": 11,
|
| 14 |
+
"bre": 12,
|
| 15 |
+
"break": 13,
|
| 16 |
+
"introverse": 14,
|
| 17 |
+
"mainriff": 15,
|
| 18 |
+
"chorushalf": 16,
|
| 19 |
+
"instintro": 17,
|
| 20 |
+
"gtr": 18,
|
| 21 |
+
"vocaloutro": 19,
|
| 22 |
+
"verse_slow": 20,
|
| 23 |
+
"fadein": 21,
|
| 24 |
+
"saxobeat": 22,
|
| 25 |
+
"transition": 23,
|
| 26 |
+
"verse1a": 24,
|
| 27 |
+
"build": 25,
|
| 28 |
+
"pre-chorus": 26,
|
| 29 |
+
"outroa": 27,
|
| 30 |
+
"bigoutro": 28,
|
| 31 |
+
"fast": 29,
|
| 32 |
+
"instrumentalverse": 30,
|
| 33 |
+
"section": 31,
|
| 34 |
+
"choruspart": 32,
|
| 35 |
+
"instbridge": 33,
|
| 36 |
+
"guitar": 34,
|
| 37 |
+
"instrumental": 35,
|
| 38 |
+
"breakdown": 36,
|
| 39 |
+
"rhythmlessintro": 37,
|
| 40 |
+
"intropt": 38,
|
| 41 |
+
"interlude": 39,
|
| 42 |
+
"postchorus": 40,
|
| 43 |
+
"postverse": 41,
|
| 44 |
+
"opening": 42,
|
| 45 |
+
"altchorus": 43,
|
| 46 |
+
"stutter": 44,
|
| 47 |
+
"oddriff": 45,
|
| 48 |
+
"synth": 46,
|
| 49 |
+
"preverse": 47,
|
| 50 |
+
"quiet": 48,
|
| 51 |
+
"raps": 49,
|
| 52 |
+
"verseinst": 50,
|
| 53 |
+
"instchorus": 51,
|
| 54 |
+
"chorus_instrumental": 52,
|
| 55 |
+
"slowverse": 53,
|
| 56 |
+
"slow": 54,
|
| 57 |
+
"worstthingever": 55,
|
| 58 |
+
"transition2a": 56,
|
| 59 |
+
"miniverse": 57,
|
| 60 |
+
"refrain": 58,
|
| 61 |
+
"introchorus": 59,
|
| 62 |
+
"drumroll": 60,
|
| 63 |
+
"guitarsolo": 61,
|
| 64 |
+
"versepart": 62,
|
| 65 |
+
"chorusinst": 63,
|
| 66 |
+
"ending": 64,
|
| 67 |
+
"no-vocal-intro": 65,
|
| 68 |
+
"no-vocal-interlude": 66,
|
| 69 |
+
"no-vocal-outro": 67,
|
| 70 |
+
"NO_LABEL": 68, # Only referring to cases without labels, this portion of labels will be ignored during the loss calculation process.
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
ID_TO_LABEL = {v: k for k, v in LABEL_TO_ID.items()}
|
| 74 |
+
|
| 75 |
+
# Reserve 64 embedding positions for dataset identifiers in the model.
|
| 76 |
+
DATASET_LABEL_TO_DATASET_ID = {
|
| 77 |
+
"SongForm-HX-7Class": 0, # Categories after rule mapping for HarmonixSet
|
| 78 |
+
"SongForm-HX-Widen": 1, # Original HarmonixSet
|
| 79 |
+
"SongForm-Private-Raw": 2,
|
| 80 |
+
"SongForm-Private": 3,
|
| 81 |
+
"SongForm-HX-Gemini-Relabeled": 4, # Rule-mapped HarmonixSet corrected by Gemini
|
| 82 |
+
"SongForm-HX-8Class": 5, # Rule-mapped (pre-chorus retained)
|
| 83 |
+
"SongForm-Hook": 6,
|
| 84 |
+
"SongForm-Gem": 7,
|
| 85 |
+
"SongForm-Gem-Only-Label": 8, # Use only segments with labels in SongForm-Gem
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
DATASET_ID_TO_DATASET_LABEL = {v: k for k, v in DATASET_LABEL_TO_DATASET_ID.items()}
|
| 89 |
+
|
| 90 |
+
DATASET_ID_ALLOWED_LABEL_IDS = {
|
| 91 |
+
0: [0, 1, 2, 3, 4, 5, 6],
|
| 92 |
+
1: [
|
| 93 |
+
0,
|
| 94 |
+
1,
|
| 95 |
+
2,
|
| 96 |
+
3,
|
| 97 |
+
4,
|
| 98 |
+
5,
|
| 99 |
+
6,
|
| 100 |
+
7,
|
| 101 |
+
8,
|
| 102 |
+
9,
|
| 103 |
+
10,
|
| 104 |
+
11,
|
| 105 |
+
12,
|
| 106 |
+
13,
|
| 107 |
+
14,
|
| 108 |
+
15,
|
| 109 |
+
16,
|
| 110 |
+
17,
|
| 111 |
+
18,
|
| 112 |
+
19,
|
| 113 |
+
20,
|
| 114 |
+
21,
|
| 115 |
+
22,
|
| 116 |
+
23,
|
| 117 |
+
24,
|
| 118 |
+
25,
|
| 119 |
+
27,
|
| 120 |
+
28,
|
| 121 |
+
29,
|
| 122 |
+
30,
|
| 123 |
+
31,
|
| 124 |
+
32,
|
| 125 |
+
33,
|
| 126 |
+
34,
|
| 127 |
+
35,
|
| 128 |
+
36,
|
| 129 |
+
37,
|
| 130 |
+
38,
|
| 131 |
+
40,
|
| 132 |
+
41,
|
| 133 |
+
42,
|
| 134 |
+
43,
|
| 135 |
+
44,
|
| 136 |
+
45,
|
| 137 |
+
46,
|
| 138 |
+
47,
|
| 139 |
+
48,
|
| 140 |
+
49,
|
| 141 |
+
50,
|
| 142 |
+
51,
|
| 143 |
+
52,
|
| 144 |
+
53,
|
| 145 |
+
54,
|
| 146 |
+
55,
|
| 147 |
+
56,
|
| 148 |
+
57,
|
| 149 |
+
58,
|
| 150 |
+
59,
|
| 151 |
+
60,
|
| 152 |
+
61,
|
| 153 |
+
62,
|
| 154 |
+
63,
|
| 155 |
+
],
|
| 156 |
+
2: [0, 1, 2, 3, 26, 39, 64, 65, 66, 67],
|
| 157 |
+
3: [0, 1, 2, 3, 4, 5, 6, 26, 39, 64, 65, 66, 67],
|
| 158 |
+
4: [0, 1, 2, 3, 4, 5, 6, 26],
|
| 159 |
+
5: [0, 1, 2, 3, 4, 5, 6, 26],
|
| 160 |
+
6: [0, 1, 2, 3, 4, 5, 6, 26],
|
| 161 |
+
7: [0, 1, 2, 3, 4, 5, 6, 26],
|
| 162 |
+
8: [0, 1, 2, 3, 4, 5, 6, 26],
|
| 163 |
+
}
|
src/SongFormer/models/SongFormer.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from dataset.custom_types import MsaInfo
|
| 6 |
+
from postprocessing.functional import postprocess_functional_structure
|
| 7 |
+
from x_transformers import Encoder
|
| 8 |
+
import bisect
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Head(nn.Module):
|
| 12 |
+
def __init__(self, input_dim, output_dim, hidden_dims=None, activation="silu"):
|
| 13 |
+
super().__init__()
|
| 14 |
+
hidden_dims = hidden_dims or []
|
| 15 |
+
act_layers = {"relu": nn.ReLU, "silu": nn.SiLU, "gelu": nn.GELU}
|
| 16 |
+
act_layer = act_layers.get(activation.lower())
|
| 17 |
+
if not act_layer:
|
| 18 |
+
raise ValueError(f"Unsupported activation: {activation}")
|
| 19 |
+
|
| 20 |
+
dims = [input_dim] + hidden_dims + [output_dim]
|
| 21 |
+
layers = []
|
| 22 |
+
for i in range(len(dims) - 1):
|
| 23 |
+
layers.append(nn.Linear(dims[i], dims[i + 1]))
|
| 24 |
+
if i < len(dims) - 2:
|
| 25 |
+
layers.append(act_layer())
|
| 26 |
+
self.net = nn.Sequential(*layers)
|
| 27 |
+
|
| 28 |
+
def reset_parameters(self, confidence):
|
| 29 |
+
bias_value = -torch.log(torch.tensor((1 - confidence) / confidence))
|
| 30 |
+
self.net[-1].bias.data.fill_(bias_value.item())
|
| 31 |
+
|
| 32 |
+
def forward(self, x):
|
| 33 |
+
batch, T, C = x.shape
|
| 34 |
+
x = x.reshape(-1, C)
|
| 35 |
+
x = self.net(x)
|
| 36 |
+
return x.reshape(batch, T, -1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class WrapedTransformerEncoder(nn.Module):
|
| 40 |
+
def __init__(
|
| 41 |
+
self, input_dim, transformer_input_dim, num_layers=1, nhead=8, dropout=0.1
|
| 42 |
+
):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.input_dim = input_dim
|
| 45 |
+
self.transformer_input_dim = transformer_input_dim
|
| 46 |
+
|
| 47 |
+
if input_dim != transformer_input_dim:
|
| 48 |
+
self.input_proj = nn.Sequential(
|
| 49 |
+
nn.Linear(input_dim, transformer_input_dim),
|
| 50 |
+
nn.LayerNorm(transformer_input_dim),
|
| 51 |
+
nn.GELU(),
|
| 52 |
+
nn.Dropout(dropout * 0.5),
|
| 53 |
+
nn.Linear(transformer_input_dim, transformer_input_dim),
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
self.input_proj = nn.Identity()
|
| 57 |
+
|
| 58 |
+
self.transformer = Encoder(
|
| 59 |
+
dim=transformer_input_dim,
|
| 60 |
+
depth=num_layers,
|
| 61 |
+
heads=nhead,
|
| 62 |
+
layer_dropout=dropout,
|
| 63 |
+
attn_dropout=dropout,
|
| 64 |
+
ff_dropout=dropout,
|
| 65 |
+
attn_flash=True,
|
| 66 |
+
rotary_pos_emb=True,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def forward(self, x, src_key_padding_mask=None):
|
| 70 |
+
"""
|
| 71 |
+
The input src_key_padding_mask is a B x T boolean mask, where True indicates masked positions.
|
| 72 |
+
However, in x-transformers, False indicates masked positions.
|
| 73 |
+
Therefore, it needs to be converted so that False represents masked positions.
|
| 74 |
+
"""
|
| 75 |
+
x = self.input_proj(x)
|
| 76 |
+
mask = (
|
| 77 |
+
~torch.tensor(src_key_padding_mask, dtype=torch.bool, device=x.device)
|
| 78 |
+
if src_key_padding_mask is not None
|
| 79 |
+
else None
|
| 80 |
+
)
|
| 81 |
+
return self.transformer(x, mask=mask)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def prefix_dict(d, prefix: str):
|
| 85 |
+
if prefix:
|
| 86 |
+
return d
|
| 87 |
+
return {prefix + key: value for key, value in d.items()}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class TimeDownsample(nn.Module):
|
| 91 |
+
def __init__(
|
| 92 |
+
self, dim_in, dim_out=None, kernel_size=5, stride=5, padding=0, dropout=0.1
|
| 93 |
+
):
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.dim_out = dim_out or dim_in
|
| 96 |
+
assert self.dim_out % 2 == 0
|
| 97 |
+
|
| 98 |
+
self.depthwise_conv = nn.Conv1d(
|
| 99 |
+
in_channels=dim_in,
|
| 100 |
+
out_channels=dim_in,
|
| 101 |
+
kernel_size=kernel_size,
|
| 102 |
+
stride=stride,
|
| 103 |
+
padding=padding,
|
| 104 |
+
groups=dim_in,
|
| 105 |
+
bias=False,
|
| 106 |
+
)
|
| 107 |
+
self.pointwise_conv = nn.Conv1d(
|
| 108 |
+
in_channels=dim_in,
|
| 109 |
+
out_channels=self.dim_out,
|
| 110 |
+
kernel_size=1,
|
| 111 |
+
bias=False,
|
| 112 |
+
)
|
| 113 |
+
self.pool = nn.AvgPool1d(kernel_size, stride, padding=padding)
|
| 114 |
+
self.norm1 = nn.LayerNorm(self.dim_out)
|
| 115 |
+
self.act1 = nn.GELU()
|
| 116 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 117 |
+
|
| 118 |
+
if dim_in != self.dim_out:
|
| 119 |
+
self.residual_conv = nn.Conv1d(
|
| 120 |
+
dim_in, self.dim_out, kernel_size=1, bias=False
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
self.residual_conv = None
|
| 124 |
+
|
| 125 |
+
def forward(self, x):
|
| 126 |
+
residual = x # [B, T, D_in]
|
| 127 |
+
# Convolutional module
|
| 128 |
+
x_c = x.transpose(1, 2) # [B, D_in, T]
|
| 129 |
+
x_c = self.depthwise_conv(x_c) # [B, D_in, T_down]
|
| 130 |
+
x_c = self.pointwise_conv(x_c) # [B, D_out, T_down]
|
| 131 |
+
|
| 132 |
+
# Residual module
|
| 133 |
+
res = self.pool(residual.transpose(1, 2)) # [B, D_in, T]
|
| 134 |
+
if self.residual_conv:
|
| 135 |
+
res = self.residual_conv(res) # [B, D_out, T_down]
|
| 136 |
+
x_c = x_c + res # [B, D_out, T_down]
|
| 137 |
+
x_c = x_c.transpose(1, 2) # [B, T_down, D_out]
|
| 138 |
+
x_c = self.norm1(x_c)
|
| 139 |
+
x_c = self.act1(x_c)
|
| 140 |
+
x_c = self.dropout1(x_c)
|
| 141 |
+
return x_c
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class AddFuse(nn.Module):
|
| 145 |
+
def __init__(self):
|
| 146 |
+
super(AddFuse, self).__init__()
|
| 147 |
+
|
| 148 |
+
def forward(self, x, cond):
|
| 149 |
+
return x + cond
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class TVLoss1D(nn.Module):
|
| 153 |
+
def __init__(
|
| 154 |
+
self, beta=1.0, lambda_tv=0.4, boundary_threshold=0.01, reduction_weight=0.1
|
| 155 |
+
):
|
| 156 |
+
"""
|
| 157 |
+
Args:
|
| 158 |
+
beta: Exponential parameter for TV loss (recommended 0.5~1.0)
|
| 159 |
+
lambda_tv: Overall weight for TV loss
|
| 160 |
+
boundary_threshold: Label threshold to determine if a region is a "boundary area" (e.g., 0.01)
|
| 161 |
+
reduction_weight: Scaling factor for TV penalty within boundary regions (e.g., 0.1, meaning only 10% penalty)
|
| 162 |
+
"""
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.beta = beta
|
| 165 |
+
self.lambda_tv = lambda_tv
|
| 166 |
+
self.boundary_threshold = boundary_threshold
|
| 167 |
+
self.reduction_weight = reduction_weight
|
| 168 |
+
|
| 169 |
+
def forward(self, pred, target=None):
|
| 170 |
+
"""
|
| 171 |
+
Args:
|
| 172 |
+
pred: (B, T) or (B, T, 1), float boundary scores output by the model
|
| 173 |
+
target: (B, T) or (B, T, 1), ground truth labels (optional, used for spatial weighting if provided)
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
scalar: weighted TV loss
|
| 177 |
+
"""
|
| 178 |
+
if pred.dim() == 3:
|
| 179 |
+
pred = pred.squeeze(-1)
|
| 180 |
+
if target is not None and target.dim() == 3:
|
| 181 |
+
target = target.squeeze(-1)
|
| 182 |
+
|
| 183 |
+
diff = pred[:, 1:] - pred[:, :-1]
|
| 184 |
+
tv_base = torch.pow(torch.abs(diff) + 1e-8, self.beta)
|
| 185 |
+
|
| 186 |
+
if target is None:
|
| 187 |
+
return self.lambda_tv * tv_base.mean()
|
| 188 |
+
|
| 189 |
+
left_in_boundary = target[:, :-1] > self.boundary_threshold
|
| 190 |
+
right_in_boundary = target[:, 1:] > self.boundary_threshold
|
| 191 |
+
near_boundary = left_in_boundary | right_in_boundary
|
| 192 |
+
weight_mask = torch.where(
|
| 193 |
+
near_boundary,
|
| 194 |
+
self.reduction_weight * torch.ones_like(tv_base),
|
| 195 |
+
torch.ones_like(tv_base),
|
| 196 |
+
)
|
| 197 |
+
tv_weighted = (tv_base * weight_mask).mean()
|
| 198 |
+
return self.lambda_tv * tv_weighted
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class SoftmaxFocalLoss(nn.Module):
|
| 202 |
+
"""
|
| 203 |
+
Softmax Focal Loss for single-label multi-class classification.
|
| 204 |
+
Suitable for mutually exclusive classes.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def __init__(self, alpha: float = 0.25, gamma: float = 2.0):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.alpha = alpha
|
| 210 |
+
self.gamma = gamma
|
| 211 |
+
|
| 212 |
+
def forward(self, pred: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
|
| 213 |
+
"""
|
| 214 |
+
Args:
|
| 215 |
+
pred: [B, T, C], raw logits
|
| 216 |
+
targets: [B, T, C] (soft) or [B, T] (hard, dtype=long)
|
| 217 |
+
Returns:
|
| 218 |
+
loss: scalar or [B, T] depending on reduction
|
| 219 |
+
"""
|
| 220 |
+
log_probs = F.log_softmax(pred, dim=-1)
|
| 221 |
+
probs = torch.exp(log_probs)
|
| 222 |
+
|
| 223 |
+
if targets.dtype == torch.long:
|
| 224 |
+
targets_onehot = F.one_hot(targets, num_classes=pred.size(-1)).float()
|
| 225 |
+
else:
|
| 226 |
+
targets_onehot = targets
|
| 227 |
+
|
| 228 |
+
p_t = (probs * targets_onehot).sum(dim=-1)
|
| 229 |
+
p_t = p_t.clamp(min=1e-8, max=1.0 - 1e-8)
|
| 230 |
+
|
| 231 |
+
if self.alpha > 0:
|
| 232 |
+
alpha_t = self.alpha * targets_onehot + (1 - self.alpha) * (
|
| 233 |
+
1 - targets_onehot
|
| 234 |
+
)
|
| 235 |
+
alpha_weight = (alpha_t * targets_onehot).sum(dim=-1)
|
| 236 |
+
else:
|
| 237 |
+
alpha_weight = 1.0
|
| 238 |
+
|
| 239 |
+
focal_weight = (1 - p_t) ** self.gamma
|
| 240 |
+
ce_loss = -log_probs * targets_onehot
|
| 241 |
+
ce_loss = ce_loss.sum(dim=-1)
|
| 242 |
+
|
| 243 |
+
loss = alpha_weight * focal_weight * ce_loss
|
| 244 |
+
return loss
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class Model(nn.Module):
|
| 248 |
+
def __init__(self, config):
|
| 249 |
+
super().__init__()
|
| 250 |
+
self.config = config
|
| 251 |
+
|
| 252 |
+
self.input_norm = nn.LayerNorm(config.input_dim)
|
| 253 |
+
self.mixed_win_downsample = nn.Linear(config.input_dim_raw, config.input_dim)
|
| 254 |
+
self.dataset_class_prefix = nn.Embedding(
|
| 255 |
+
num_embeddings=config.num_dataset_classes,
|
| 256 |
+
embedding_dim=config.transformer_encoder_input_dim,
|
| 257 |
+
)
|
| 258 |
+
self.down_sample_conv = TimeDownsample(
|
| 259 |
+
dim_in=config.input_dim,
|
| 260 |
+
dim_out=config.transformer_encoder_input_dim,
|
| 261 |
+
kernel_size=config.down_sample_conv_kernel_size,
|
| 262 |
+
stride=config.down_sample_conv_stride,
|
| 263 |
+
dropout=config.down_sample_conv_dropout,
|
| 264 |
+
padding=config.down_sample_conv_padding,
|
| 265 |
+
)
|
| 266 |
+
self.AddFuse = AddFuse()
|
| 267 |
+
self.transformer = WrapedTransformerEncoder(
|
| 268 |
+
input_dim=config.transformer_encoder_input_dim,
|
| 269 |
+
transformer_input_dim=config.transformer_input_dim,
|
| 270 |
+
num_layers=config.num_transformer_layers,
|
| 271 |
+
nhead=config.transformer_nhead,
|
| 272 |
+
dropout=config.transformer_dropout,
|
| 273 |
+
)
|
| 274 |
+
self.boundary_TVLoss1D = TVLoss1D(
|
| 275 |
+
beta=config.boundary_tv_loss_beta,
|
| 276 |
+
lambda_tv=config.boundary_tv_loss_lambda,
|
| 277 |
+
boundary_threshold=config.boundary_tv_loss_boundary_threshold,
|
| 278 |
+
reduction_weight=config.boundary_tv_loss_reduction_weight,
|
| 279 |
+
)
|
| 280 |
+
self.label_focal_loss = SoftmaxFocalLoss(
|
| 281 |
+
alpha=config.label_focal_loss_alpha, gamma=config.label_focal_loss_gamma
|
| 282 |
+
)
|
| 283 |
+
self.boundary_head = Head(config.transformer_input_dim, 1)
|
| 284 |
+
self.function_head = Head(config.transformer_input_dim, config.num_classes)
|
| 285 |
+
|
| 286 |
+
def cal_metrics(self, gt_info: MsaInfo, msa_info: MsaInfo):
|
| 287 |
+
from msaf.eval import compute_results
|
| 288 |
+
assert gt_info[-1][1] == "end" and msa_info[-1][1] == "end", (
|
| 289 |
+
"gt_info and msa_info should end with 'end'"
|
| 290 |
+
)
|
| 291 |
+
gt_info_labels = [label for time_, label in gt_info][:-1]
|
| 292 |
+
gt_info_inters = [time_ for time_, label in gt_info]
|
| 293 |
+
gt_info_inters = np.column_stack(
|
| 294 |
+
[np.array(gt_info_inters[:-1]), np.array(gt_info_inters[1:])]
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
msa_info_labels = [label for time_, label in msa_info][:-1]
|
| 298 |
+
msa_info_inters = [time_ for time_, label in msa_info]
|
| 299 |
+
msa_info_inters = np.column_stack(
|
| 300 |
+
[np.array(msa_info_inters[:-1]), np.array(msa_info_inters[1:])]
|
| 301 |
+
)
|
| 302 |
+
result = compute_results(
|
| 303 |
+
ann_inter=gt_info_inters,
|
| 304 |
+
est_inter=msa_info_inters,
|
| 305 |
+
ann_labels=gt_info_labels,
|
| 306 |
+
est_labels=msa_info_labels,
|
| 307 |
+
bins=11,
|
| 308 |
+
est_file="test.txt",
|
| 309 |
+
weight=0.58,
|
| 310 |
+
)
|
| 311 |
+
return result
|
| 312 |
+
|
| 313 |
+
def cal_acc(
|
| 314 |
+
self, ann_info: MsaInfo | str, est_info: MsaInfo | str, post_digit: int = 3
|
| 315 |
+
):
|
| 316 |
+
ann_info_time = [
|
| 317 |
+
int(round(time_, post_digit) * (10**post_digit))
|
| 318 |
+
for time_, label in ann_info
|
| 319 |
+
]
|
| 320 |
+
est_info_time = [
|
| 321 |
+
int(round(time_, post_digit) * (10**post_digit))
|
| 322 |
+
for time_, label in est_info
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
common_start_time = max(ann_info_time[0], est_info_time[0])
|
| 326 |
+
common_end_time = min(ann_info_time[-1], est_info_time[-1])
|
| 327 |
+
|
| 328 |
+
time_points = {common_start_time, common_end_time}
|
| 329 |
+
time_points.update(
|
| 330 |
+
{
|
| 331 |
+
time_
|
| 332 |
+
for time_ in ann_info_time
|
| 333 |
+
if common_start_time <= time_ <= common_end_time
|
| 334 |
+
}
|
| 335 |
+
)
|
| 336 |
+
time_points.update(
|
| 337 |
+
{
|
| 338 |
+
time_
|
| 339 |
+
for time_ in est_info_time
|
| 340 |
+
if common_start_time <= time_ <= common_end_time
|
| 341 |
+
}
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
time_points = sorted(time_points)
|
| 345 |
+
total_duration, total_score = 0, 0
|
| 346 |
+
|
| 347 |
+
for idx in range(len(time_points) - 1):
|
| 348 |
+
duration = time_points[idx + 1] - time_points[idx]
|
| 349 |
+
ann_label = ann_info[
|
| 350 |
+
bisect.bisect_right(ann_info_time, time_points[idx]) - 1
|
| 351 |
+
][1]
|
| 352 |
+
est_label = est_info[
|
| 353 |
+
bisect.bisect_right(est_info_time, time_points[idx]) - 1
|
| 354 |
+
][1]
|
| 355 |
+
total_duration += duration
|
| 356 |
+
if ann_label == est_label:
|
| 357 |
+
total_score += duration
|
| 358 |
+
return total_score / total_duration
|
| 359 |
+
|
| 360 |
+
def infer_with_metrics(self, batch, prefix: str = None):
|
| 361 |
+
with torch.no_grad():
|
| 362 |
+
logits = self.forward_func(batch)
|
| 363 |
+
|
| 364 |
+
losses = self.compute_losses(logits, batch, prefix=None)
|
| 365 |
+
|
| 366 |
+
expanded_mask = batch["label_id_masks"].expand(
|
| 367 |
+
-1, logits["function_logits"].size(1), -1
|
| 368 |
+
)
|
| 369 |
+
logits["function_logits"] = logits["function_logits"].masked_fill(
|
| 370 |
+
expanded_mask, -float("inf")
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
msa_info = postprocess_functional_structure(
|
| 374 |
+
logits=logits, config=self.config
|
| 375 |
+
)
|
| 376 |
+
gt_info = batch["msa_infos"][0]
|
| 377 |
+
results = self.cal_metrics(gt_info=gt_info, msa_info=msa_info)
|
| 378 |
+
|
| 379 |
+
ret_results = {
|
| 380 |
+
"loss": losses["loss"].item(),
|
| 381 |
+
"HitRate_3P": results["HitRate_3P"],
|
| 382 |
+
"HitRate_3R": results["HitRate_3R"],
|
| 383 |
+
"HitRate_3F": results["HitRate_3F"],
|
| 384 |
+
"HitRate_0.5P": results["HitRate_0.5P"],
|
| 385 |
+
"HitRate_0.5R": results["HitRate_0.5R"],
|
| 386 |
+
"HitRate_0.5F": results["HitRate_0.5F"],
|
| 387 |
+
"PWF": results["PWF"],
|
| 388 |
+
"PWP": results["PWP"],
|
| 389 |
+
"PWR": results["PWR"],
|
| 390 |
+
"Sf": results["Sf"],
|
| 391 |
+
"So": results["So"],
|
| 392 |
+
"Su": results["Su"],
|
| 393 |
+
"acc": self.cal_acc(ann_info=gt_info, est_info=msa_info),
|
| 394 |
+
}
|
| 395 |
+
if prefix:
|
| 396 |
+
ret_results = prefix_dict(ret_results, prefix)
|
| 397 |
+
|
| 398 |
+
return ret_results
|
| 399 |
+
|
| 400 |
+
def infer(
|
| 401 |
+
self,
|
| 402 |
+
input_embeddings,
|
| 403 |
+
dataset_ids,
|
| 404 |
+
label_id_masks,
|
| 405 |
+
prefix: str = None,
|
| 406 |
+
with_logits=False,
|
| 407 |
+
):
|
| 408 |
+
with torch.no_grad():
|
| 409 |
+
input_embeddings = self.mixed_win_downsample(input_embeddings)
|
| 410 |
+
input_embeddings = self.input_norm(input_embeddings)
|
| 411 |
+
logits = self.down_sample_conv(input_embeddings)
|
| 412 |
+
|
| 413 |
+
dataset_prefix = self.dataset_class_prefix(dataset_ids)
|
| 414 |
+
dataset_prefix_expand = dataset_prefix.unsqueeze(1).expand(
|
| 415 |
+
logits.size(0), 1, -1
|
| 416 |
+
)
|
| 417 |
+
logits = self.AddFuse(x=logits, cond=dataset_prefix_expand)
|
| 418 |
+
logits = self.transformer(x=logits, src_key_padding_mask=None)
|
| 419 |
+
|
| 420 |
+
function_logits = self.function_head(logits)
|
| 421 |
+
boundary_logits = self.boundary_head(logits).squeeze(-1)
|
| 422 |
+
|
| 423 |
+
logits = {
|
| 424 |
+
"function_logits": function_logits,
|
| 425 |
+
"boundary_logits": boundary_logits,
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
expanded_mask = label_id_masks.expand(
|
| 429 |
+
-1, logits["function_logits"].size(1), -1
|
| 430 |
+
)
|
| 431 |
+
logits["function_logits"] = logits["function_logits"].masked_fill(
|
| 432 |
+
expanded_mask, -float("inf")
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
msa_info = postprocess_functional_structure(
|
| 436 |
+
logits=logits, config=self.config
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
return (msa_info, logits) if with_logits else msa_info
|
| 440 |
+
|
| 441 |
+
def compute_losses(self, outputs, batch, prefix: str = None):
|
| 442 |
+
loss = 0.0
|
| 443 |
+
losses = {}
|
| 444 |
+
|
| 445 |
+
loss_section = F.binary_cross_entropy_with_logits(
|
| 446 |
+
outputs["boundary_logits"],
|
| 447 |
+
batch["widen_true_boundaries"],
|
| 448 |
+
reduction="none",
|
| 449 |
+
)
|
| 450 |
+
loss_section += self.config.boundary_tvloss_weight * self.boundary_TVLoss1D(
|
| 451 |
+
pred=outputs["boundary_logits"],
|
| 452 |
+
target=batch["widen_true_boundaries"],
|
| 453 |
+
)
|
| 454 |
+
loss_function = F.cross_entropy(
|
| 455 |
+
outputs["function_logits"].transpose(1, 2),
|
| 456 |
+
batch["true_functions"].transpose(1, 2),
|
| 457 |
+
reduction="none",
|
| 458 |
+
)
|
| 459 |
+
# input is [B, T, C]
|
| 460 |
+
ttt = self.config.label_focal_loss_weight * self.label_focal_loss(
|
| 461 |
+
pred=outputs["function_logits"], targets=batch["true_functions"]
|
| 462 |
+
)
|
| 463 |
+
loss_function += ttt
|
| 464 |
+
|
| 465 |
+
float_masks = (~batch["masks"]).float()
|
| 466 |
+
boundary_mask = batch.get("boundary_mask", None)
|
| 467 |
+
function_mask = batch.get("function_mask", None)
|
| 468 |
+
if boundary_mask is not None:
|
| 469 |
+
boundary_mask = (~boundary_mask).float()
|
| 470 |
+
else:
|
| 471 |
+
boundary_mask = 1
|
| 472 |
+
|
| 473 |
+
if function_mask is not None:
|
| 474 |
+
function_mask = (~function_mask).float()
|
| 475 |
+
else:
|
| 476 |
+
function_mask = 1
|
| 477 |
+
|
| 478 |
+
loss_section = torch.mean(boundary_mask * float_masks * loss_section)
|
| 479 |
+
loss_function = torch.mean(function_mask * float_masks * loss_function)
|
| 480 |
+
|
| 481 |
+
loss_section *= self.config.loss_weight_section
|
| 482 |
+
loss_function *= self.config.loss_weight_function
|
| 483 |
+
|
| 484 |
+
if self.config.learn_label:
|
| 485 |
+
loss += loss_function
|
| 486 |
+
if self.config.learn_segment:
|
| 487 |
+
loss += loss_section
|
| 488 |
+
|
| 489 |
+
losses.update(
|
| 490 |
+
loss=loss,
|
| 491 |
+
loss_section=loss_section,
|
| 492 |
+
loss_function=loss_function,
|
| 493 |
+
)
|
| 494 |
+
if prefix:
|
| 495 |
+
losses = prefix_dict(losses, prefix)
|
| 496 |
+
return losses
|
| 497 |
+
|
| 498 |
+
def forward_func(self, batch):
|
| 499 |
+
input_embeddings = batch["input_embeddings"]
|
| 500 |
+
input_embeddings = self.mixed_win_downsample(input_embeddings)
|
| 501 |
+
input_embeddings = self.input_norm(input_embeddings)
|
| 502 |
+
logits = self.down_sample_conv(input_embeddings)
|
| 503 |
+
|
| 504 |
+
dataset_prefix = self.dataset_class_prefix(batch["dataset_ids"])
|
| 505 |
+
logits = self.AddFuse(x=logits, cond=dataset_prefix.unsqueeze(1))
|
| 506 |
+
src_key_padding_mask = batch["masks"]
|
| 507 |
+
logits = self.transformer(x=logits, src_key_padding_mask=src_key_padding_mask)
|
| 508 |
+
|
| 509 |
+
function_logits = self.function_head(logits)
|
| 510 |
+
boundary_logits = self.boundary_head(logits).squeeze(-1)
|
| 511 |
+
|
| 512 |
+
logits = {
|
| 513 |
+
"function_logits": function_logits,
|
| 514 |
+
"boundary_logits": boundary_logits,
|
| 515 |
+
}
|
| 516 |
+
return logits
|
| 517 |
+
|
| 518 |
+
def forward(self, batch):
|
| 519 |
+
logits = self.forward_func(batch)
|
| 520 |
+
losses = self.compute_losses(logits, batch, prefix=None)
|
| 521 |
+
return logits, losses["loss"], losses
|
src/SongFormer/postprocessing/functional.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains code adapted from the following sources:
|
| 2 |
+
# [MIT license] https://github.com/mir-aidj/all-in-one/blob/main/src/allin1/postprocessing/functional.py
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from .helpers import (
|
| 7 |
+
local_maxima,
|
| 8 |
+
peak_picking,
|
| 9 |
+
# event_frames_to_time,
|
| 10 |
+
)
|
| 11 |
+
from dataset.label2id import LABEL_TO_ID, ID_TO_LABEL
|
| 12 |
+
from dataset.custom_types import MsaInfo
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def event_frames_to_time(frame_rates, boundary: np.array):
|
| 16 |
+
boundary = np.array(boundary)
|
| 17 |
+
boundary_times = boundary / frame_rates
|
| 18 |
+
return boundary_times
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def postprocess_functional_structure(
|
| 22 |
+
logits,
|
| 23 |
+
config,
|
| 24 |
+
):
|
| 25 |
+
# pdb.set_trace()
|
| 26 |
+
boundary_logits = logits["boundary_logits"]
|
| 27 |
+
function_logits = logits["function_logits"]
|
| 28 |
+
|
| 29 |
+
assert boundary_logits.shape[0] == 1 and function_logits.shape[0] == 1, (
|
| 30 |
+
"Only batch size 1 is supported"
|
| 31 |
+
)
|
| 32 |
+
raw_prob_sections = torch.sigmoid(boundary_logits[0])
|
| 33 |
+
raw_prob_functions = torch.softmax(function_logits[0].transpose(0, 1), dim=0)
|
| 34 |
+
|
| 35 |
+
# filter_size=4 * cfg.min_hops_per_beat + 1
|
| 36 |
+
prob_sections, _ = local_maxima(
|
| 37 |
+
raw_prob_sections, filter_size=config.local_maxima_filter_size
|
| 38 |
+
)
|
| 39 |
+
prob_sections = prob_sections.cpu().numpy()
|
| 40 |
+
|
| 41 |
+
prob_functions = raw_prob_functions.cpu().numpy()
|
| 42 |
+
|
| 43 |
+
boundary_candidates = peak_picking(
|
| 44 |
+
boundary_activation=prob_sections,
|
| 45 |
+
window_past=int(12 * config.frame_rates), # 原来是fps
|
| 46 |
+
window_future=int(12 * config.frame_rates),
|
| 47 |
+
)
|
| 48 |
+
boundary = boundary_candidates > 0.0
|
| 49 |
+
|
| 50 |
+
duration = len(prob_sections) / config.frame_rates
|
| 51 |
+
pred_boundary_times = event_frames_to_time(
|
| 52 |
+
frame_rates=config.frame_rates, boundary=np.flatnonzero(boundary)
|
| 53 |
+
)
|
| 54 |
+
if pred_boundary_times[0] != 0:
|
| 55 |
+
pred_boundary_times = np.insert(pred_boundary_times, 0, 0)
|
| 56 |
+
if pred_boundary_times[-1] != duration:
|
| 57 |
+
pred_boundary_times = np.append(pred_boundary_times, duration)
|
| 58 |
+
pred_boundaries = np.stack([pred_boundary_times[:-1], pred_boundary_times[1:]]).T
|
| 59 |
+
|
| 60 |
+
pred_boundary_indices = np.flatnonzero(boundary)
|
| 61 |
+
pred_boundary_indices = pred_boundary_indices[pred_boundary_indices > 0]
|
| 62 |
+
prob_segment_function = np.split(prob_functions, pred_boundary_indices, axis=1)
|
| 63 |
+
pred_labels = [p.mean(axis=1).argmax().item() for p in prob_segment_function]
|
| 64 |
+
|
| 65 |
+
segments: MsaInfo = []
|
| 66 |
+
for (start, end), label in zip(pred_boundaries, pred_labels):
|
| 67 |
+
segment = (float(start), str(ID_TO_LABEL[label]))
|
| 68 |
+
segments.append(segment)
|
| 69 |
+
|
| 70 |
+
segments.append((float(pred_boundary_times[-1]), "end"))
|
| 71 |
+
return segments
|
src/SongFormer/postprocessing/helpers.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains code adapted from the following sources:
|
| 2 |
+
# [MIT license] https://github.com/mir-aidj/all-in-one/blob/main/src/allin1/postprocessing/helpers.py
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
import torch
|
| 7 |
+
import librosa
|
| 8 |
+
from typing import Union
|
| 9 |
+
from scipy.signal import argrelextrema
|
| 10 |
+
from scipy.interpolate import interp1d
|
| 11 |
+
from numpy.lib.stride_tricks import sliding_window_view
|
| 12 |
+
from numpy.typing import NDArray
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def local_maxima(tensor, filter_size=41):
|
| 16 |
+
assert len(tensor.shape) in (1, 2), "Input tensor should have 1 or 2 dimensions"
|
| 17 |
+
assert filter_size % 2 == 1, "Filter size should be an odd number"
|
| 18 |
+
|
| 19 |
+
original_shape = tensor.shape
|
| 20 |
+
if len(original_shape) == 1:
|
| 21 |
+
tensor = tensor.unsqueeze(0)
|
| 22 |
+
|
| 23 |
+
# Pad the input array with the minimum value
|
| 24 |
+
padding = filter_size // 2
|
| 25 |
+
padded_arr = F.pad(tensor, (padding, padding), mode="constant", value=-torch.inf)
|
| 26 |
+
|
| 27 |
+
# Create a rolling window view of the padded array
|
| 28 |
+
rolling_view = padded_arr.unfold(1, filter_size, 1)
|
| 29 |
+
|
| 30 |
+
# Find the indices of the local maxima
|
| 31 |
+
center = filter_size // 2
|
| 32 |
+
local_maxima_mask = torch.eq(
|
| 33 |
+
rolling_view[:, :, center], torch.max(rolling_view, dim=-1).values
|
| 34 |
+
)
|
| 35 |
+
local_maxima_indices = local_maxima_mask.nonzero()
|
| 36 |
+
|
| 37 |
+
# Initialize a new PyTorch tensor with zeros and the same shape as the input tensor
|
| 38 |
+
output_arr = torch.zeros_like(tensor)
|
| 39 |
+
|
| 40 |
+
# Set the local maxima values in the output tensor
|
| 41 |
+
output_arr[local_maxima_mask] = tensor[local_maxima_mask]
|
| 42 |
+
|
| 43 |
+
output_arr = output_arr.reshape(original_shape)
|
| 44 |
+
|
| 45 |
+
return output_arr, local_maxima_indices
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def local_maxima_numpy(arr, order=20):
|
| 49 |
+
is_batch = len(arr.shape) == 2
|
| 50 |
+
if is_batch:
|
| 51 |
+
return np.stack([local_maxima_numpy(x, order) for x in arr])
|
| 52 |
+
|
| 53 |
+
# Define a comparison function for argrelextrema to find local maxima
|
| 54 |
+
compare_func = np.greater
|
| 55 |
+
|
| 56 |
+
# Find the indices of the local maxima
|
| 57 |
+
local_maxima_indices = argrelextrema(arr, compare_func, order=order)
|
| 58 |
+
|
| 59 |
+
# Initialize a new numpy array with zeros and the same shape as the input array
|
| 60 |
+
output_arr = np.zeros_like(arr)
|
| 61 |
+
|
| 62 |
+
# Set the local maxima values in the output array
|
| 63 |
+
output_arr[local_maxima_indices] = arr[local_maxima_indices]
|
| 64 |
+
|
| 65 |
+
return output_arr
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def peak_picking(boundary_activation, window_past=12, window_future=6):
|
| 69 |
+
# Find local maxima using a sliding window
|
| 70 |
+
window_size = window_past + window_future
|
| 71 |
+
assert window_size % 2 == 0, "window_past + window_future must be even"
|
| 72 |
+
window_size += 1
|
| 73 |
+
|
| 74 |
+
# Pad boundary_activation
|
| 75 |
+
boundary_activation_padded = np.pad(
|
| 76 |
+
boundary_activation, (window_past, window_future), mode="constant"
|
| 77 |
+
)
|
| 78 |
+
max_filter = sliding_window_view(boundary_activation_padded, window_size)
|
| 79 |
+
local_maxima = (boundary_activation == np.max(max_filter, axis=-1)) & (
|
| 80 |
+
boundary_activation > 0
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Compute strength values by subtracting the mean of the past and future windows
|
| 84 |
+
past_window_filter = sliding_window_view(
|
| 85 |
+
boundary_activation_padded[: -(window_future + 1)], window_past
|
| 86 |
+
)
|
| 87 |
+
future_window_filter = sliding_window_view(
|
| 88 |
+
boundary_activation_padded[window_past + 1 :], window_future
|
| 89 |
+
)
|
| 90 |
+
past_mean = np.mean(past_window_filter, axis=-1)
|
| 91 |
+
future_mean = np.mean(future_window_filter, axis=-1)
|
| 92 |
+
strength_values = boundary_activation - ((past_mean + future_mean) / 2)
|
| 93 |
+
|
| 94 |
+
# Get boundary candidates and their corresponding strength values
|
| 95 |
+
boundary_candidates = np.flatnonzero(local_maxima)
|
| 96 |
+
strength_values = strength_values[boundary_candidates]
|
| 97 |
+
|
| 98 |
+
strength_activations = np.zeros_like(boundary_activation)
|
| 99 |
+
strength_activations[boundary_candidates] = strength_values
|
| 100 |
+
|
| 101 |
+
return strength_activations
|
src/third_party/musicfm/LICENSE
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Dual Licensing Information
|
| 2 |
+
-------------------------
|
| 3 |
+
|
| 4 |
+
This software is dual-licensed under both the MIT License and the Apache License, Version 2.0.
|
| 5 |
+
|
| 6 |
+
- The file `modules/flash_conformer.py` is distributed under the terms of the Apache License, Version 2.0.
|
| 7 |
+
- All other files and modules in this software are distributed under the terms of the MIT License.
|
| 8 |
+
|
| 9 |
+
### MIT License
|
| 10 |
+
|
| 11 |
+
Copyright 2023 ByteDance Inc.
|
| 12 |
+
|
| 13 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 14 |
+
|
| 15 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
### Apache License, Version 2.0
|
| 21 |
+
|
| 22 |
+
Copyright 2018- The Hugging Face team. All rights reserved.
|
| 23 |
+
|
| 24 |
+
Apache License
|
| 25 |
+
Version 2.0, January 2004
|
| 26 |
+
http://www.apache.org/licenses/
|
| 27 |
+
|
| 28 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 29 |
+
|
| 30 |
+
1. Definitions.
|
| 31 |
+
|
| 32 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 33 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 34 |
+
|
| 35 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 36 |
+
the copyright owner that is granting the License.
|
| 37 |
+
|
| 38 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 39 |
+
other entities that control, are controlled by, or are under common
|
| 40 |
+
control with that entity. For the purposes of this definition,
|
| 41 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 42 |
+
direction or management of such entity, whether by contract or
|
| 43 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 44 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 45 |
+
|
| 46 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 47 |
+
exercising permissions granted by this License.
|
| 48 |
+
|
| 49 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 50 |
+
including but not limited to software source code, documentation
|
| 51 |
+
source, and configuration files.
|
| 52 |
+
|
| 53 |
+
"Object" form shall mean any form resulting from mechanical
|
| 54 |
+
transformation or translation of a Source form, including but
|
| 55 |
+
not limited to compiled object code, generated documentation,
|
| 56 |
+
and conversions to other media types.
|
| 57 |
+
|
| 58 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 59 |
+
Object form, made available under the License, as indicated by a
|
| 60 |
+
copyright notice that is included in or attached to the work
|
| 61 |
+
(an example is provided in the Appendix below).
|
| 62 |
+
|
| 63 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 64 |
+
form, that is based on (or derived from) the Work and for which the
|
| 65 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 66 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 67 |
+
of this License, Derivative Works shall not include works that remain
|
| 68 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 69 |
+
the Work and Derivative Works thereof.
|
| 70 |
+
|
| 71 |
+
"Contribution" shall mean any work of authorship, including
|
| 72 |
+
the original version of the Work and any modifications or additions
|
| 73 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 74 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 75 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 76 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 77 |
+
means any form of electronic, verbal, or written communication sent
|
| 78 |
+
to the Licensor or its representatives, including but not limited to
|
| 79 |
+
communication on electronic mailing lists, source code control systems,
|
| 80 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 81 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 82 |
+
excluding communication that is conspicuously marked or otherwise
|
| 83 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 84 |
+
|
| 85 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 86 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 87 |
+
subsequently incorporated within the Work.
|
| 88 |
+
|
| 89 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 90 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 91 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 92 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 93 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 94 |
+
Work and such Derivative Works in Source or Object form.
|
| 95 |
+
|
| 96 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 97 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 98 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 99 |
+
(except as stated in this section) patent license to make, have made,
|
| 100 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 101 |
+
where such license applies only to those patent claims licensable
|
| 102 |
+
by such Contributor that are necessarily infringed by their
|
| 103 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 104 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 105 |
+
institute patent litigation against any entity (including a
|
| 106 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 107 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 108 |
+
or contributory patent infringement, then any patent licenses
|
| 109 |
+
granted to You under this License for that Work shall terminate
|
| 110 |
+
as of the date such litigation is filed.
|
| 111 |
+
|
| 112 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 113 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 114 |
+
modifications, and in Source or Object form, provided that You
|
| 115 |
+
meet the following conditions:
|
| 116 |
+
|
| 117 |
+
(a) You must give any other recipients of the Work or
|
| 118 |
+
Derivative Works a copy of this License; and
|
| 119 |
+
|
| 120 |
+
(b) You must cause any modified files to carry prominent notices
|
| 121 |
+
stating that You changed the files; and
|
| 122 |
+
|
| 123 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 124 |
+
that You distribute, all copyright, patent, trademark, and
|
| 125 |
+
attribution notices from the Source form of the Work,
|
| 126 |
+
excluding those notices that do not pertain to any part of
|
| 127 |
+
the Derivative Works; and
|
| 128 |
+
|
| 129 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 130 |
+
distribution, then any Derivative Works that You distribute must
|
| 131 |
+
include a readable copy of the attribution notices contained
|
| 132 |
+
within such NOTICE file, excluding those notices that do not
|
| 133 |
+
pertain to any part of the Derivative Works, in at least one
|
| 134 |
+
of the following places: within a NOTICE text file distributed
|
| 135 |
+
as part of the Derivative Works; within the Source form or
|
| 136 |
+
documentation, if provided along with the Derivative Works; or,
|
| 137 |
+
within a display generated by the Derivative Works, if and
|
| 138 |
+
wherever such third-party notices normally appear. The contents
|
| 139 |
+
of the NOTICE file are for informational purposes only and
|
| 140 |
+
do not modify the License. You may add Your own attribution
|
| 141 |
+
notices within Derivative Works that You distribute, alongside
|
| 142 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 143 |
+
that such additional attribution notices cannot be construed
|
| 144 |
+
as modifying the License.
|
| 145 |
+
|
| 146 |
+
You may add Your own copyright statement to Your modifications and
|
| 147 |
+
may provide additional or different license terms and conditions
|
| 148 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 149 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 150 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 151 |
+
the conditions stated in this License.
|
| 152 |
+
|
| 153 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 154 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 155 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 156 |
+
this License, without any additional terms or conditions.
|
| 157 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 158 |
+
the terms of any separate license agreement you may have executed
|
| 159 |
+
with Licensor regarding such Contributions.
|
| 160 |
+
|
| 161 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 162 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 163 |
+
except as required for reasonable and customary use in describing the
|
| 164 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 165 |
+
|
| 166 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 167 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 168 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 169 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 170 |
+
implied, including, without limitation, any warranties or conditions
|
| 171 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 172 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 173 |
+
appropriateness of using or redistributing the Work and assume any
|
| 174 |
+
risks associated with Your exercise of permissions under this License.
|
| 175 |
+
|
| 176 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 177 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 178 |
+
unless required by applicable law (such as deliberate and grossly
|
| 179 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 180 |
+
liable to You for damages, including any direct, indirect, special,
|
| 181 |
+
incidental, or consequential damages of any character arising as a
|
| 182 |
+
result of this License or out of the use or inability to use the
|
| 183 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 184 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 185 |
+
other commercial damages or losses), even if such Contributor
|
| 186 |
+
has been advised of the possibility of such damages.
|
| 187 |
+
|
| 188 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 189 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 190 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 191 |
+
or other liability obligations and/or rights consistent with this
|
| 192 |
+
License. However, in accepting such obligations, You may act only
|
| 193 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 194 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 195 |
+
defend, and hold each Contributor harmless for any liability
|
| 196 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 197 |
+
of your accepting any such warranty or additional liability.
|
| 198 |
+
|
| 199 |
+
END OF TERMS AND CONDITIONS
|
| 200 |
+
|
| 201 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 202 |
+
|
| 203 |
+
To apply the Apache License to your work, attach the following
|
| 204 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 205 |
+
replaced with your own identifying information. (Don't include
|
| 206 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 207 |
+
comment syntax for the file format. We also recommend that a
|
| 208 |
+
file or class name and description of purpose be included on the
|
| 209 |
+
same "printed page" as the copyright notice for easier
|
| 210 |
+
identification within third-party archives.
|
| 211 |
+
|
| 212 |
+
Copyright [yyyy] [name of copyright owner]
|
| 213 |
+
|
| 214 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 215 |
+
you may not use this file except in compliance with the License.
|
| 216 |
+
You may obtain a copy of the License at
|
| 217 |
+
|
| 218 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 219 |
+
|
| 220 |
+
Unless required by applicable law or agreed to in writing, software
|
| 221 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 222 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 223 |
+
See the License for the specific language governing permissions and
|
| 224 |
+
limitations under the License.
|
src/third_party/musicfm/model/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
src/third_party/musicfm/model/musicfm_25hz.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2023 ByteDance Inc.
|
| 4 |
+
#
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
|
| 6 |
+
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 7 |
+
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 8 |
+
#
|
| 9 |
+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 10 |
+
#
|
| 11 |
+
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 12 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 13 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 14 |
+
# IN THE SOFTWARE.
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import random
|
| 18 |
+
import torch
|
| 19 |
+
from torch import nn
|
| 20 |
+
from einops import rearrange
|
| 21 |
+
|
| 22 |
+
from musicfm.modules.random_quantizer import RandomProjectionQuantizer
|
| 23 |
+
from musicfm.modules.features import MelSTFT
|
| 24 |
+
from musicfm.modules.conv import Conv2dSubsampling
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MusicFM25Hz(nn.Module):
|
| 28 |
+
"""
|
| 29 |
+
MusicFM
|
| 30 |
+
|
| 31 |
+
Input: 128-band mel spectrogram
|
| 32 |
+
Frontend: 2-layer Residual convolution
|
| 33 |
+
Backend: 12-layer Conformer
|
| 34 |
+
Quantizer: a codebook for mel spectrogram
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
num_codebooks=1,
|
| 40 |
+
codebook_dim=16,
|
| 41 |
+
codebook_size=4096,
|
| 42 |
+
features=["melspec_2048"],
|
| 43 |
+
hop_length=240,
|
| 44 |
+
n_mels=128,
|
| 45 |
+
conv_dim=512,
|
| 46 |
+
encoder_dim=1024,
|
| 47 |
+
encoder_depth=12,
|
| 48 |
+
mask_hop=0.4,
|
| 49 |
+
mask_prob=0.6,
|
| 50 |
+
is_flash=False,
|
| 51 |
+
stat_path="./data/fma_stats.json",
|
| 52 |
+
model_path="./data/pretrained_fma.pt",
|
| 53 |
+
):
|
| 54 |
+
super(MusicFM25Hz, self).__init__()
|
| 55 |
+
|
| 56 |
+
# global variables
|
| 57 |
+
self.hop_length = hop_length
|
| 58 |
+
self.mask_hop = mask_hop
|
| 59 |
+
self.mask_prob = mask_prob
|
| 60 |
+
self.num_codebooks = num_codebooks
|
| 61 |
+
self.codebook_size = codebook_size
|
| 62 |
+
self.features = features
|
| 63 |
+
|
| 64 |
+
# load feature mean / std stats
|
| 65 |
+
with open(stat_path, "r") as f:
|
| 66 |
+
self.stat = json.load(f)
|
| 67 |
+
|
| 68 |
+
# feature extractor
|
| 69 |
+
self.preprocessor_melspec_2048 = MelSTFT(
|
| 70 |
+
n_fft=2048, hop_length=hop_length, is_db=True
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# random quantizer
|
| 74 |
+
seed = 142
|
| 75 |
+
for feature in self.features:
|
| 76 |
+
for i in range(num_codebooks):
|
| 77 |
+
setattr(
|
| 78 |
+
self,
|
| 79 |
+
f"quantizer_{feature}_{i}",
|
| 80 |
+
RandomProjectionQuantizer(
|
| 81 |
+
n_mels * 4, codebook_dim, codebook_size, seed=seed + i
|
| 82 |
+
),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# two residual convolution layers + one projection layer
|
| 86 |
+
self.conv = Conv2dSubsampling(
|
| 87 |
+
1, conv_dim, encoder_dim, strides=[2, 2], n_bands=n_mels
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Conformer
|
| 91 |
+
if is_flash:
|
| 92 |
+
from modules.flash_conformer import (
|
| 93 |
+
Wav2Vec2ConformerEncoder,
|
| 94 |
+
Wav2Vec2ConformerConfig,
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer import (
|
| 98 |
+
Wav2Vec2ConformerEncoder,
|
| 99 |
+
Wav2Vec2ConformerConfig,
|
| 100 |
+
)
|
| 101 |
+
config = Wav2Vec2ConformerConfig.from_pretrained(
|
| 102 |
+
"facebook/wav2vec2-conformer-rope-large-960h-ft"
|
| 103 |
+
)
|
| 104 |
+
config.num_hidden_layers = encoder_depth
|
| 105 |
+
config.hidden_size = encoder_dim
|
| 106 |
+
|
| 107 |
+
self.conformer = Wav2Vec2ConformerEncoder(config)
|
| 108 |
+
|
| 109 |
+
# projection
|
| 110 |
+
self.linear = nn.Linear(encoder_dim, codebook_size)
|
| 111 |
+
|
| 112 |
+
# loss function
|
| 113 |
+
self.loss = nn.CrossEntropyLoss()
|
| 114 |
+
|
| 115 |
+
# cls token (used for sequence classification)
|
| 116 |
+
random.seed(seed)
|
| 117 |
+
self.cls_token = nn.Parameter(torch.randn(encoder_dim))
|
| 118 |
+
|
| 119 |
+
# load model
|
| 120 |
+
if model_path:
|
| 121 |
+
S = torch.load(model_path, map_location="cpu", weights_only=False)["state_dict"]
|
| 122 |
+
SS = {k[6:]: v for k, v in S.items()}
|
| 123 |
+
self.load_state_dict(SS, strict=True)
|
| 124 |
+
|
| 125 |
+
def masking(self, x):
|
| 126 |
+
"""random masking of 400ms with given probability"""
|
| 127 |
+
mx = x.clone()
|
| 128 |
+
b, t = mx.shape
|
| 129 |
+
len_masking_raw = int(24000 * self.mask_hop)
|
| 130 |
+
len_masking_token = int(24000 / self.hop_length / 2 / 2 * self.mask_hop)
|
| 131 |
+
|
| 132 |
+
# get random mask indices
|
| 133 |
+
start_indices = torch.rand(b, t // len_masking_raw) < self.mask_prob
|
| 134 |
+
time_domain_masked_indices = torch.nonzero(
|
| 135 |
+
start_indices.repeat_interleave(len_masking_raw, dim=1)
|
| 136 |
+
)
|
| 137 |
+
token_domain_masked_indices = torch.nonzero(
|
| 138 |
+
start_indices.repeat_interleave(len_masking_token, dim=1)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# mask with random values
|
| 142 |
+
masking_noise = (
|
| 143 |
+
torch.randn(time_domain_masked_indices.shape[0], dtype=x.dtype) * 0.1
|
| 144 |
+
) # 0 mean 0.1 std
|
| 145 |
+
mx[tuple(time_domain_masked_indices.t())] = masking_noise.to(x.device)
|
| 146 |
+
|
| 147 |
+
return mx, token_domain_masked_indices
|
| 148 |
+
|
| 149 |
+
@torch.no_grad()
|
| 150 |
+
def preprocessing(self, x, features):
|
| 151 |
+
"""extract classic audio features"""
|
| 152 |
+
# check precision
|
| 153 |
+
if x.dtype == torch.float16:
|
| 154 |
+
precision = 16
|
| 155 |
+
else:
|
| 156 |
+
precision = 32
|
| 157 |
+
|
| 158 |
+
out = {}
|
| 159 |
+
for key in features:
|
| 160 |
+
layer = getattr(self, "preprocessor_%s" % key)
|
| 161 |
+
out[key] = layer.float()(x.float())[..., :-1]
|
| 162 |
+
if precision == 16:
|
| 163 |
+
out[key] = out[key].half()
|
| 164 |
+
return out
|
| 165 |
+
|
| 166 |
+
def encoder(self, x):
|
| 167 |
+
"""2-layer conv + w2v-conformer"""
|
| 168 |
+
x = self.conv(x)
|
| 169 |
+
out = self.conformer(x, output_hidden_states=True)
|
| 170 |
+
hidden_emb = out["hidden_states"]
|
| 171 |
+
last_emb = out["last_hidden_state"]
|
| 172 |
+
logits = self.linear(last_emb)
|
| 173 |
+
logits = {
|
| 174 |
+
key: logits[:, :, i * self.codebook_size : (i + 1) * self.codebook_size]
|
| 175 |
+
for i, key in enumerate(self.features)
|
| 176 |
+
}
|
| 177 |
+
return logits, hidden_emb
|
| 178 |
+
|
| 179 |
+
@torch.no_grad()
|
| 180 |
+
def normalize(self, x):
|
| 181 |
+
"""normalize the input audio to have zero mean unit variance"""
|
| 182 |
+
for key in x.keys():
|
| 183 |
+
x[key] = (x[key] - self.stat["%s_mean" % key]) / self.stat["%s_std" % key]
|
| 184 |
+
return x
|
| 185 |
+
|
| 186 |
+
@torch.no_grad()
|
| 187 |
+
def rearrange(self, x):
|
| 188 |
+
"""rearrange the batch to flatten every 4 steps"""
|
| 189 |
+
for key in x.keys():
|
| 190 |
+
if key == "chromagram":
|
| 191 |
+
x[key] = rearrange(x[key], "b f t -> b t f")
|
| 192 |
+
else:
|
| 193 |
+
x[key] = rearrange(x[key], "b f (t s) -> b t (s f)", s=4)
|
| 194 |
+
return x
|
| 195 |
+
|
| 196 |
+
@torch.no_grad()
|
| 197 |
+
def tokenize(self, x):
|
| 198 |
+
out = {}
|
| 199 |
+
for key in x.keys():
|
| 200 |
+
layer = getattr(self, "quantizer_%s" % key)
|
| 201 |
+
out[key] = layer(x[key])
|
| 202 |
+
return out
|
| 203 |
+
|
| 204 |
+
def get_targets(self, x):
|
| 205 |
+
x = self.preprocessing(x, features=self.features)
|
| 206 |
+
x = self.normalize(x)
|
| 207 |
+
x = self.rearrange(x)
|
| 208 |
+
target_tokens = self.tokenize(x)
|
| 209 |
+
return target_tokens
|
| 210 |
+
|
| 211 |
+
def get_predictions(self, x):
|
| 212 |
+
# preprocessing
|
| 213 |
+
x = self.preprocessing(x, features=["melspec_2048"])
|
| 214 |
+
x = self.normalize(x)
|
| 215 |
+
|
| 216 |
+
# encoding
|
| 217 |
+
logits, hidden_emb = self.encoder(x["melspec_2048"])
|
| 218 |
+
|
| 219 |
+
return logits, hidden_emb
|
| 220 |
+
|
| 221 |
+
def get_latent(self, x, layer_ix=12):
|
| 222 |
+
_, hidden_states = self.get_predictions(x)
|
| 223 |
+
emb = hidden_states[layer_ix]
|
| 224 |
+
return emb
|
| 225 |
+
|
| 226 |
+
def get_loss(self, logits, target_tokens, masked_indices):
|
| 227 |
+
losses = {}
|
| 228 |
+
accuracies = {}
|
| 229 |
+
for key in logits.keys():
|
| 230 |
+
masked_logits = logits[key][tuple(masked_indices.t())]
|
| 231 |
+
masked_tokens = target_tokens[key][tuple(masked_indices.t())]
|
| 232 |
+
losses[key] = self.loss(masked_logits, masked_tokens)
|
| 233 |
+
accuracies[key] = (
|
| 234 |
+
torch.sum(masked_logits.argmax(-1) == masked_tokens)
|
| 235 |
+
/ masked_tokens.numel()
|
| 236 |
+
)
|
| 237 |
+
return losses, accuracies
|
| 238 |
+
|
| 239 |
+
def forward(self, x):
|
| 240 |
+
# get target feature tokens
|
| 241 |
+
target_tokens = self.get_targets(x)
|
| 242 |
+
|
| 243 |
+
# masking
|
| 244 |
+
x, masked_indices = self.masking(x)
|
| 245 |
+
|
| 246 |
+
# forward
|
| 247 |
+
logits, hidden_emb = self.get_predictions(x)
|
| 248 |
+
|
| 249 |
+
# get loss
|
| 250 |
+
losses, accuracies = self.get_loss(logits, target_tokens, masked_indices)
|
| 251 |
+
|
| 252 |
+
return logits, hidden_emb, losses, accuracies
|
src/third_party/musicfm/modules/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
src/third_party/musicfm/modules/conv.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2023 ByteDance Inc.
|
| 4 |
+
#
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
|
| 6 |
+
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 7 |
+
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 8 |
+
#
|
| 9 |
+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 10 |
+
#
|
| 11 |
+
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 12 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 13 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 14 |
+
# IN THE SOFTWARE.
|
| 15 |
+
|
| 16 |
+
from torch import nn
|
| 17 |
+
from einops import rearrange
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Res2dModule(nn.Module):
|
| 21 |
+
def __init__(self, idim, odim, stride=(2, 2)):
|
| 22 |
+
super(Res2dModule, self).__init__()
|
| 23 |
+
self.conv1 = nn.Conv2d(idim, odim, 3, padding=1, stride=stride)
|
| 24 |
+
self.bn1 = nn.BatchNorm2d(odim)
|
| 25 |
+
self.conv2 = nn.Conv2d(odim, odim, 3, padding=1)
|
| 26 |
+
self.bn2 = nn.BatchNorm2d(odim)
|
| 27 |
+
self.relu = nn.ReLU()
|
| 28 |
+
|
| 29 |
+
# residual
|
| 30 |
+
self.diff = False
|
| 31 |
+
if (idim != odim) or (stride[0] > 1):
|
| 32 |
+
self.conv3 = nn.Conv2d(idim, odim, 3, padding=1, stride=stride)
|
| 33 |
+
self.bn3 = nn.BatchNorm2d(odim)
|
| 34 |
+
self.diff = True
|
| 35 |
+
|
| 36 |
+
def forward(self, x):
|
| 37 |
+
out = self.bn2(self.conv2(self.relu(self.bn1(self.conv1(x)))))
|
| 38 |
+
if self.diff:
|
| 39 |
+
x = self.bn3(self.conv3(x))
|
| 40 |
+
out = x + out
|
| 41 |
+
out = self.relu(out)
|
| 42 |
+
return out
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Conv2dSubsampling(nn.Module):
|
| 46 |
+
"""Convolutional 2D subsampling (to 1/4 length).
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
idim (int): Input dimension.
|
| 50 |
+
hdim (int): Hidden dimension.
|
| 51 |
+
odim (int): Output dimension.
|
| 52 |
+
strides (list): Sizes of strides.
|
| 53 |
+
n_bands (int): Number of frequency bands.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(self, idim, hdim, odim, strides=[2, 2], n_bands=64):
|
| 57 |
+
"""Construct an Conv2dSubsampling object."""
|
| 58 |
+
super(Conv2dSubsampling, self).__init__()
|
| 59 |
+
|
| 60 |
+
self.conv = nn.Sequential(
|
| 61 |
+
Res2dModule(idim, hdim, (2, strides[0])),
|
| 62 |
+
Res2dModule(hdim, hdim, (2, strides[1])),
|
| 63 |
+
)
|
| 64 |
+
self.linear = nn.Linear(hdim * n_bands // 2 // 2, odim)
|
| 65 |
+
|
| 66 |
+
def forward(self, x):
|
| 67 |
+
"""Subsample x.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
x (torch.Tensor): Input tensor (#batch, idim, time).
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
torch.Tensor: Subsampled tensor (#batch, time', odim),
|
| 74 |
+
where time' = time // 4.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
if x.dim() == 3:
|
| 78 |
+
x = x.unsqueeze(1) # (b, c, f, t)
|
| 79 |
+
x = self.conv(x)
|
| 80 |
+
x = rearrange(x, "b c f t -> b t (c f)")
|
| 81 |
+
x = self.linear(x)
|
| 82 |
+
return x
|
src/third_party/musicfm/modules/features.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2023 ByteDance Inc.
|
| 4 |
+
#
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
|
| 6 |
+
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 7 |
+
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 8 |
+
#
|
| 9 |
+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 10 |
+
#
|
| 11 |
+
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 12 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 13 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 14 |
+
# IN THE SOFTWARE.
|
| 15 |
+
|
| 16 |
+
import torchaudio
|
| 17 |
+
from torch import nn
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MelSTFT(nn.Module):
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
sample_rate=24000,
|
| 24 |
+
n_fft=2048,
|
| 25 |
+
hop_length=240,
|
| 26 |
+
n_mels=128,
|
| 27 |
+
is_db=False,
|
| 28 |
+
):
|
| 29 |
+
super(MelSTFT, self).__init__()
|
| 30 |
+
|
| 31 |
+
# spectrogram
|
| 32 |
+
self.mel_stft = torchaudio.transforms.MelSpectrogram(
|
| 33 |
+
sample_rate=sample_rate, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# amplitude to decibel
|
| 37 |
+
self.is_db = is_db
|
| 38 |
+
if is_db:
|
| 39 |
+
self.amplitude_to_db = torchaudio.transforms.AmplitudeToDB()
|
| 40 |
+
|
| 41 |
+
def forward(self, waveform):
|
| 42 |
+
if self.is_db:
|
| 43 |
+
return self.amplitude_to_db(self.mel_stft(waveform))
|
| 44 |
+
else:
|
| 45 |
+
return self.mel_stft(waveform)
|
src/third_party/musicfm/modules/random_quantizer.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
#
|
| 3 |
+
# Copyright 2023 ByteDance Inc.
|
| 4 |
+
#
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”),
|
| 6 |
+
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 7 |
+
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 8 |
+
#
|
| 9 |
+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 10 |
+
#
|
| 11 |
+
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 12 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 13 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 14 |
+
# IN THE SOFTWARE.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn, einsum
|
| 18 |
+
from einops import rearrange
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RandomProjectionQuantizer(nn.Module):
|
| 22 |
+
"""
|
| 23 |
+
Random projection and codebook lookup module
|
| 24 |
+
|
| 25 |
+
Some code is borrowed from:
|
| 26 |
+
https://github.com/lucidrains/vector-quantize-pytorch/blob/master/vector_quantize_pytorch/random_projection_quantizer.py
|
| 27 |
+
But I did normalization using pre-computed global mean & variance instead of using layer norm.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
input_dim,
|
| 33 |
+
codebook_dim,
|
| 34 |
+
codebook_size,
|
| 35 |
+
seed=142,
|
| 36 |
+
):
|
| 37 |
+
super().__init__()
|
| 38 |
+
|
| 39 |
+
# random seed
|
| 40 |
+
torch.manual_seed(seed)
|
| 41 |
+
|
| 42 |
+
# randomly initialized projection
|
| 43 |
+
random_projection = torch.empty(input_dim, codebook_dim)
|
| 44 |
+
nn.init.xavier_normal_(random_projection)
|
| 45 |
+
self.register_buffer("random_projection", random_projection)
|
| 46 |
+
|
| 47 |
+
# randomly initialized codebook
|
| 48 |
+
codebook = torch.empty(codebook_size, codebook_dim)
|
| 49 |
+
nn.init.normal_(codebook)
|
| 50 |
+
self.register_buffer("codebook", codebook)
|
| 51 |
+
|
| 52 |
+
def codebook_lookup(self, x):
|
| 53 |
+
# reshape
|
| 54 |
+
b = x.shape[0]
|
| 55 |
+
x = rearrange(x, "b n e -> (b n) e")
|
| 56 |
+
|
| 57 |
+
# L2 normalization
|
| 58 |
+
normalized_x = nn.functional.normalize(x, dim=1, p=2)
|
| 59 |
+
normalized_codebook = nn.functional.normalize(self.codebook, dim=1, p=2)
|
| 60 |
+
|
| 61 |
+
# compute distances
|
| 62 |
+
distances = torch.cdist(normalized_codebook, normalized_x)
|
| 63 |
+
|
| 64 |
+
# get nearest
|
| 65 |
+
nearest_indices = torch.argmin(distances, dim=0)
|
| 66 |
+
|
| 67 |
+
# reshape
|
| 68 |
+
xq = rearrange(nearest_indices, "(b n) -> b n", b=b)
|
| 69 |
+
|
| 70 |
+
return xq
|
| 71 |
+
|
| 72 |
+
@torch.no_grad()
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
# always eval
|
| 75 |
+
self.eval()
|
| 76 |
+
|
| 77 |
+
# random projection [batch, length, input_dim] -> [batch, length, codebook_dim]
|
| 78 |
+
x = einsum("b n d, d e -> b n e", x, self.random_projection)
|
| 79 |
+
|
| 80 |
+
# codebook lookup
|
| 81 |
+
xq = self.codebook_lookup(x)
|
| 82 |
+
|
| 83 |
+
return xq
|