File size: 12,324 Bytes
627dcfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""#212: build the Wobble Split pack (SCNet-Large, Core ML) and (with --go) upload it to monokern/wobble-split.

    python package_split.py          # convert, check against PyTorch, pack, write manifest + card (dry run)
    python package_split.py --go     # ... and upload

Same pack format as the Ears packs (ears/package.py in the Wobble repo): one Apple Archive (lzfse) per
pack in packs/<id>/<version>/, a manifest.json listing size + SHA-256, pack files never overwritten.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import shutil
import subprocess
import tempfile
from datetime import date
from pathlib import Path

os.environ.setdefault("HF_HUB_DISABLE_XET", "1")

import coremltools as ct
import numpy as np
import torch

from common import OUT, SR, SOURCES, load_model, sdr, separate, test_mix
from core import SCNetCore
from frontend import HOP, NFFT, frames_for, istft, pad_amount, stft

HERE = Path(__file__).resolve().parent
REPO = "monokern/wobble-split"
PACK_ID, VERSION = "split-large", 1
SEGMENT_S = 11
SEGMENT = SEGMENT_S * SR
FRONT_END = "scnet-stft-4096-v1"
# Only the weight-heavy ops run in fp16: with everything in fp16 the GPU gives NaN (overflow inside
# the norms / DFT matmuls). This keeps the file at fp16 size and the output within ~60 dB of fp32.
FP16_OPS = {"conv", "conv_transpose", "lstm", "linear"}
SCRIPTS = ["common.py", "core.py", "frontend.py", "package_split.py", "kits.py"]

LICENSE_SCNET = (HERE.parent / "src" / "SCNet" / "LICENSE").read_text()

NOTICE = """Wobble Split pack: SCNet-Large

SCNet-Large music source separation model by Weinan Tong et al. (github.com/starrytong/SCNet),
checkpoint "SCNet-large" from the official repository, MIT licence (see LICENSE-scnet).
Converted to Core ML (mlprogram; conv/LSTM/linear weights in fp16) by monokern for Wobble.
The model starts and ends at the spectrogram; the app computes the STFT and inverse STFT itself.

Credit: Tong, Zhu, Chen, Kang, Jiang, Li, Wu, Meng. "SCNet: Sparse Compression Network for Music
Source Separation." ICASSP 2024. arXiv:2401.13276.

The model was trained on MUSDB18-HQ, whose audio is licensed for research and education.
"""

CARD = """---
license: mit
tags: [music-source-separation, stems, scnet, coreml, wobble]
---
# Wobble Split model pack

Core ML build of **SCNet-Large** for the Wobble sample browser (macOS 14+): pulls a loop apart into
drums, bass, other and vocals, on the Mac. The app downloads it when Split is first used (or in
Settings); nothing here is needed to run Wobble, and the app works without it.

`manifest.json` lists the pack with its size, SHA-256 and settings. Pack files live in
`packs/<id>/<version>/` and are never changed after upload; a new build gets a new version.

| Pack | What it is | Size |
|---|---|---|
{rows}

## What the app does around the model (front end `{front_end}`)

The pack unpacks to `split.mlpackage`, `NOTICE` and `LICENSE-scnet`. `convert/frontend.py` is the exact
reference (numpy); `convert/common.py` `separate()` is the whole-file loop.

1. 44.1 kHz stereo. Normalise the whole loop by the mean and standard deviation (ddof 1) of its mono mix.
2. Cut into {seg_s} s segments ({seg} samples), 50 % overlap; the last ones centre-padded with zeros.
3. Each segment: pad {pad} zeros at the end ({padded} samples), STFT with **no window** (rectangular),
   n_fft {nfft}, hop {hop}, centre with reflect padding of {half}, one-sided ({bins} bins), × 1/√{nfft}.
4. Model input `spec` [1, 4, {bins}, {frames}]: channels L.re, L.im, R.re, R.im (float32).
5. Model output `stems` [1, 16, {bins}, {frames}]: channel (source × 2 + L/R) × 2 + (re | im); sources
   drums, bass, other, vocals.
6. Inverse: irfft each frame × √{nfft}, overlap-add at hop {hop}, divide by the number of frames covering
   each sample, drop the first {half} samples, keep {seg}.
7. Cross-fade the segments with a triangle window, undo step 1.

Runs on CPU + GPU (`computeUnits: cpuAndGPU`; the Neural Engine compiler stalls on this model).
On an Apple Silicon Mac a segment takes about {ms} ms; a 25 s loop about {loop_s:.0f} s.

## Quality

Output matches the original PyTorch model to {match:.0f} dB SDR (no audible difference). On 10 jazzy
construction kits rebuilt from their parts (so every stem has a known answer), mean SDR: drums
{kits[0]:.1f} dB, bass {kits[1]:.1f} dB, other {kits[2]:.1f} dB (`convert/kits.py`).

## Licences and credit

- Weights and model code: SCNet by Weinan Tong et al., MIT (https://github.com/starrytong/SCNet).
  Tong et al., "SCNet: Sparse Compression Network for Music Source Separation", ICASSP 2024.
  The author allows redistributing the original and converted checkpoints with credit.
- Training data: MUSDB18-HQ, licensed for research and education; it carries its own terms.
- Conversion scripts in `convert/`: MIT, monokern.
"""


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def dir_bytes(path: Path) -> int:
    return sum(p.stat().st_size for p in path.rglob("*") if p.is_file())


def convert() -> Path:
    frames = frames_for(SEGMENT)
    core = SCNetCore(load_model()).eval()
    with torch.no_grad():
        traced = torch.jit.trace(core, torch.randn(1, 4, NFFT // 2 + 1, frames), check_trace=False)
    ml = ct.convert(traced, inputs=[ct.TensorType(name="spec", shape=(1, 4, NFFT // 2 + 1, frames))],
                    outputs=[ct.TensorType(name="stems")], minimum_deployment_target=ct.target.macOS14,
                    compute_precision=ct.transform.FP16ComputePrecision(op_selector=lambda op: op.op_type in FP16_OPS),
                    skip_model_load=True)
    ml.author = "Weinan Tong et al. (SCNet, MIT); Core ML conversion by monokern for Wobble"
    ml.license = "MIT"
    ml.short_description = "SCNet-Large music source separation: drums, bass, other, vocals. Spectrogram in, spectrogram out."
    ml.version = str(VERSION)
    ml.input_description["spec"] = f"STFT of an {SEGMENT_S} s stereo segment ({FRONT_END}): L.re, L.im, R.re, R.im"
    ml.output_description["stems"] = "STFT of 4 sources x 2 channels x (re, im): drums, bass, other, vocals"
    ml.user_defined_metadata.update({"frontEnd": FRONT_END, "sources": ",".join(SOURCES), "sampleRate": str(SR),
                                     "segmentSamples": str(SEGMENT)})
    path = OUT / "split.mlpackage"
    shutil.rmtree(path, ignore_errors=True)
    ml.save(str(path))
    return path


def check(path: Path) -> dict:
    """Separate the kit-08 test mix with the Core ML model and the PyTorch original."""
    ml = ct.models.MLModel(str(path), compute_units=ct.ComputeUnit.CPU_AND_GPU)
    pad = pad_amount(SEGMENT)
    times = []

    def run(chunk):
        xp = np.pad(chunk, ((0, 0), (0, pad)))
        import time
        t = time.time()
        y = ml.predict({"spec": stft(xp)})["stems"]
        times.append(time.time() - t)
        return istft(y, xp.shape[1])[..., :SEGMENT]

    run(np.zeros((2, SEGMENT), np.float32)); times.clear()
    mix, truth = test_mix()
    import time
    t = time.time()
    est = separate(run, mix, SEGMENT)
    loop_s = time.time() - t
    ref = np.load(OUT / f"torch_{SEGMENT_S}s.npy")
    match = min(sdr(ref[i], est[i]) for i in range(3))
    print(f"  Core ML vs PyTorch: worst stem {match:.1f} dB; {np.mean(times)*1000:.0f} ms a segment, "
          f"{loop_s:.1f} s for {mix.shape[1]/SR:.1f} s")
    if match < 40 or not np.isfinite(est).all():
        raise SystemExit("Core ML output doesn't match the PyTorch model")
    return {"match": match, "ms": np.mean(times) * 1000, "loop_s": loop_s}


def build(kits: list[float]) -> tuple[dict, Path]:
    model = convert()
    stats = check(model)
    dest = OUT / "packs" / PACK_ID / str(VERSION)
    shutil.rmtree(dest, ignore_errors=True)
    dest.mkdir(parents=True)
    archive = dest / f"{PACK_ID}.aar"
    with tempfile.TemporaryDirectory() as tmp:
        st = Path(tmp)
        shutil.copytree(model, st / "split.mlpackage")
        (st / "NOTICE").write_text(NOTICE)
        (st / "LICENSE-scnet").write_text(LICENSE_SCNET)
        unpacked = dir_bytes(st)
        subprocess.run(["aa", "archive", "-d", str(st), "-o", str(archive), "-a", "lzfse"], check=True)
        with tempfile.TemporaryDirectory() as back:
            subprocess.run(["aa", "extract", "-i", str(archive), "-d", back], check=True)
            if dir_bytes(Path(back)) != unpacked:
                raise SystemExit("archive does not unpack to what went in")
    pack = {
        "id": PACK_ID,
        "kind": "split",
        "title": "Split",
        "summary": "Pull a loop apart into drums, bass, other and vocals.",
        "model": "scnet-large",
        "version": VERSION,
        "file": f"packs/{PACK_ID}/{VERSION}/{archive.name}",
        "bytes": archive.stat().st_size,
        "unpackedBytes": unpacked,
        "sha256": sha256(archive),
        "minAppVersion": "0.1.0",
        "features": ["split"],
        "requires": [],
        "default": True,
        "dimensions": 0,
        "licence": "MIT",
        "source": "starrytong/SCNet SCNet-large (official checkpoint)",
        "modelFile": "split.mlpackage",
        "frontEnd": FRONT_END,
        "computeUnits": "cpuAndGPU",
        "sampleRate": SR,
        "segmentSamples": SEGMENT,
        "overlap": 0.5,
        "frames": frames_for(SEGMENT),
        "sources": SOURCES,
    }
    print(f"  {PACK_ID} v{VERSION}  {pack['bytes'] / 1e6:.1f} MB  {pack['sha256'][:12]}")
    manifest = {"schema": 1, "updated": date.today().isoformat(), "repo": REPO, "packs": [pack]}
    (OUT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    rows = f"| `{PACK_ID}` | {pack['title']}: {pack['summary']} | {pack['bytes'] / 1e6:.0f} MB |"
    card = CARD.format(rows=rows, front_end=FRONT_END, seg_s=SEGMENT_S, seg=SEGMENT, pad=pad_amount(SEGMENT),
                       padded=SEGMENT + pad_amount(SEGMENT), nfft=NFFT, hop=HOP, half=NFFT // 2, bins=NFFT // 2 + 1,
                       frames=frames_for(SEGMENT), ms=round(stats["ms"], -1), loop_s=stats["loop_s"],
                       match=stats["match"], kits=kits)
    (OUT / "README.md").write_text(card)
    return manifest, archive


def upload(manifest: dict, archive: Path) -> None:
    from huggingface_hub import HfApi
    api = HfApi(token=True)
    api.create_repo(REPO, repo_type="model", private=True, exist_ok=True)
    existing = set(api.list_repo_files(REPO))
    p = manifest["packs"][0]
    if p["file"] in existing:
        remote = api.get_paths_info(REPO, [p["file"]], expand=True)[0]
        lfs = getattr(remote, "lfs", None)
        if lfs is None or lfs.sha256 != p["sha256"]:
            raise SystemExit(f"{p['file']} already exists with different content. Bump VERSION instead.")
        print(f"  {p['file']}: already there")
    else:
        print(f"  uploading {p['file']} ...")
        api.upload_file(path_or_fileobj=str(archive), path_in_repo=p["file"], repo_id=REPO,
                        commit_message=f"{p['id']} v{p['version']}")
    for name in SCRIPTS:
        api.upload_file(path_or_fileobj=str(HERE / name), path_in_repo=f"convert/{name}", repo_id=REPO,
                        commit_message="Conversion scripts")
    api.upload_file(path_or_fileobj=str(OUT / "README.md"), path_in_repo="README.md", repo_id=REPO,
                    commit_message="Model card")
    api.upload_file(path_or_fileobj=str(OUT / "manifest.json"), path_in_repo="manifest.json", repo_id=REPO,
                    commit_message=f"Manifest {manifest['updated']}")
    print(f"Uploaded to https://huggingface.co/{REPO}")


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--go", action="store_true", help=f"upload to {REPO} (private)")
    ap.add_argument("--kits", default="7.88,14.58,10.35", help="mean SDR drums,bass,other from kits.py (11 s)")
    args = ap.parse_args()
    manifest, archive = build([float(v) for v in args.kits.split(",")])
    if args.go:
        upload(manifest, archive)
    else:
        print("Dry run: add --go to upload.")


if __name__ == "__main__":
    main()