Implemented demucs engine

This commit is contained in:
patben8 committed 2026-09-30 19:26:00 +02:00
1 parent e4e98eda3f
commit f655bb4cf2
12 files changed
+694 -12

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
"""PyInstaller entry point for the frozen stem engine (`konduktor-engine`)."""
import sys
from konduktor_engine.__main__ import main
if __name__ == "__main__":
sys.exit(main())
+51
View File
@@ -0,0 +1,51 @@
"""Fetch and verify the pinned htdemucs_ft weights into a folder (CI, dev).
python fetch_weights.py DEST
Standard library only. Files already present with the right hash are kept.
Konduktor itself downloads through its engine manager, from the same manifest.
"""
from __future__ import annotations
import hashlib
import json
import sys
import urllib.request
from pathlib import Path
MANIFEST = json.loads((Path(__file__).resolve().parent / "weights.json").read_text())
def sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def main(dest: str) -> int:
folder = Path(dest)
folder.mkdir(parents=True, exist_ok=True)
for f in MANIFEST["files"]:
target = folder / f["name"]
if target.exists() and sha256(target) == f["sha256"]:
print(f"ok {f['name']}")
continue
url = MANIFEST["url"].format(repo=MANIFEST["repo"], revision=MANIFEST["revision"], name=f["name"])
partial = target.with_name(target.name + ".part")
with urllib.request.urlopen(url, timeout=60) as r, open(partial, "wb") as out:
while chunk := r.read(1 << 20):
out.write(chunk)
got = sha256(partial)
if got != f["sha256"]:
partial.unlink()
print(f"HASH MISMATCH {f['name']}: {got}")
return 1
partial.replace(target)
print(f"fetched {f['name']}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))
+37
View File
@@ -0,0 +1,37 @@
# PyInstaller spec for the frozen stem engine. ONEDIR, not onefile: a onefile
# build re-extracts ~500 MB of torch into a temp folder on EVERY launch; the
# folder is instead unpacked once, into app-data, by Konduktor's engine manager.
#
# .venv/bin/python -m PyInstaller --noconfirm --clean konduktor-engine.spec
from PyInstaller.utils.hooks import collect_submodules
hidden = collect_submodules("demucs")
a = Analysis(
["engine_main.py"],
pathex=["."],
hiddenimports=hidden,
excludes=[
# Never used for inference, and large.
"tkinter", "matplotlib", "IPython", "notebook", "tensorboard",
"torchvision", "torchaudio", "PIL",
# The engine never goes online: Konduktor downloads the weights.
"huggingface_hub", "hf_xet",
],
)
# torch ships C++ headers (tens of MB, thousands of files) that only matter for
# building extensions; they are also the deepest paths in the tree, which is
# what trips Windows' 260-character limit.
a.datas = [d for d in a.datas if "/include/" not in d[0].replace("\\", "/")
and not d[0].replace("\\", "/").startswith("torch/include")]
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="konduktor-engine",
console=True,
upx=False,
)
coll = COLLECT(exe, a.binaries, a.datas, name="konduktor-engine", upx=False)
+34 -3
View File
@@ -10,6 +10,7 @@ print) goes to stderr, so a stray print can never corrupt a message.
python -m konduktor_engine info
python -m konduktor_engine separate --input mix.f32 --samples N \\
--output-dir OUT --weights DIR [--device auto|cpu|gpu|mps|cuda] [--seed 0]
python -m konduktor_engine serve --weights DIR [--device auto] (see serve.py)
"""
from __future__ import annotations
@@ -17,6 +18,7 @@ import argparse
import json
import os
import sys
import threading
import time
from pathlib import Path
@@ -31,9 +33,16 @@ def _protocol():
return os.fdopen(fd, "w", buffering=1, encoding="utf-8")
_EMIT = threading.Lock()
def _emit(out, **msg) -> None:
out.write(json.dumps(msg) + "\n")
out.flush()
# Locked: `serve` writes from two threads, and two half-lines would be
# one unparseable message.
line = json.dumps(msg) + "\n"
with _EMIT:
out.write(line)
out.flush()
def main(argv: list[str] | None = None) -> int:
@@ -47,6 +56,9 @@ def main(argv: list[str] | None = None) -> int:
sep.add_argument("--weights", required=True)
sep.add_argument("--device", default="auto")
sep.add_argument("--seed", type=int, default=0)
srv = sub.add_parser("serve")
srv.add_argument("--weights", required=True)
srv.add_argument("--device", default="auto")
args = parser.parse_args(argv)
out = _protocol()
@@ -55,10 +67,29 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "info":
import torch
cuda = None
if torch.cuda.is_available():
# What the backend needs to decide whether to offer this engine: the
# card, its compute capability, and the capabilities torch was
# built for (a card outside that list fails at the first kernel).
cuda = {"name": torch.cuda.get_device_name(0),
"capability": ".".join(map(str, torch.cuda.get_device_capability(0))),
"arch_list": torch.cuda.get_arch_list(),
"memory": torch.cuda.get_device_properties(0).total_memory}
_emit(out, event="info", version=VERSION, torch=torch.__version__,
devices=core.available_devices(), model=core.MODEL)
devices=core.available_devices(), model=core.MODEL,
cuda_build=torch.version.cuda, cuda=cuda)
return 0
if args.command == "serve":
from . import serve
try:
return serve.run(out, lambda **m: _emit(out, **m), args.weights, args.device)
except Exception as ex: # noqa: BLE001 — e.g. weights missing: say so, then exit
_emit(out, event="error", message=f"{type(ex).__name__}: {ex}")
return 1
import numpy as np
try:
+6
View File
@@ -64,13 +64,19 @@ def separate(model, pcm: np.ndarray, device: str, *, seed: int = 0,
Seeded per call: `shifts=1` applies a RANDOM time shift, so without a seed
the same track separates slightly differently each time (measured: Vox 9.2
vs 9.6 dB SDR between runs) and a re-conversion would not be reproducible.
The shift is drawn from Python's `random` module (`demucs.apply`:
`random.randint`), NOT torch's generator — seeding torch alone left every
run different — so both are seeded.
"""
import random
import torch
from demucs.apply import apply_model
if pcm.ndim != 2 or pcm.shape[0] != 2:
raise ValueError("Expected a stereo mix shaped (2, n)")
n = pcm.shape[1]
random.seed(seed)
torch.manual_seed(seed)
def callback(d: dict) -> None:
+137
View File
@@ -0,0 +1,137 @@
"""`serve`: one engine process per batch, the model loaded once.
Requests are JSON lines on stdin, replies JSON lines on the protocol stream
(a private copy of stdout — see `__main__._protocol`):
-> {"id": "t1", "cmd": "separate", "input": "mix.f32", "samples": N,
"output_dir": "out/", "seed": 0}
<- {"id": "t1", "event": "progress", "fraction": 0.42}
<- {"id": "t1", "event": "done", "seconds": 61.2, "device": "mps"}
(or "error" with "message", or "cancelled")
-> {"cmd": "cancel", "id": "t1"} the running separation stops at its next
progress step; the model stays loaded
-> {"cmd": "ping"} <- {"event": "pong"}
**stdin closing means the parent is gone** — the backend exits without killing
its children — so a reader THREAD watches it and ends the process at once, even
mid-separation (the main thread is busy inside torch and could not notice).
"""
from __future__ import annotations
import json
import os
import queue
import sys
import threading
import time
from pathlib import Path
class Cancelled(Exception):
pass
def _lower_priority() -> None:
"""A batch may run for hours: stay out of the way of the DJ app itself."""
try:
if sys.platform == "win32":
import ctypes
BELOW_NORMAL = 0x00004000
ctypes.windll.kernel32.SetPriorityClass(ctypes.windll.kernel32.GetCurrentProcess(), BELOW_NORMAL)
else:
os.nice(10)
except Exception: # noqa: BLE001 — a hint, never a failure
pass
def run(out, emit, weights: str, device_request: str) -> int:
import numpy as np
import torch
from . import core
_lower_priority()
torch.set_num_threads(max(1, (os.cpu_count() or 2) - 1))
requests: "queue.Queue[dict]" = queue.Queue()
cancel: set[str] = set()
lock = threading.Lock()
def reader() -> None:
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
msg = json.loads(line)
except ValueError:
emit(event="error", message=f"not JSON: {line[:80]}")
continue
if msg.get("cmd") == "cancel":
with lock:
cancel.add(str(msg.get("id")))
else:
requests.put(msg)
os._exit(0) # the parent is gone: do not linger, whatever is running
threading.Thread(target=reader, name="stdin", daemon=True).start()
device = core.pick_device(device_request)
t0 = time.time()
model = core.load_model(weights)
emit(event="ready", device=device, seconds=round(time.time() - t0, 2))
while True:
msg = requests.get()
cmd = msg.get("cmd")
if cmd == "ping":
emit(event="pong")
continue
if cmd == "shutdown":
return 0
if cmd != "separate":
emit(event="error", message=f"unknown command {cmd!r}")
continue
rid = str(msg.get("id"))
started = time.time()
try:
n = int(msg["samples"])
pcm = np.fromfile(msg["input"], dtype=np.float32)
if pcm.size != 2 * n:
raise ValueError(f"expected {2 * n} floats, found {pcm.size}")
pcm = pcm.reshape(2, n)
def progress(f: float) -> None:
with lock:
if rid in cancel:
raise Cancelled()
emit(id=rid, event="progress", fraction=round(f, 4))
used = device
try:
stems = core.separate(model, pcm, device, seed=int(msg.get("seed", 0)), on_progress=progress)
except torch.OutOfMemoryError:
# A long track on a small GPU: finish it on the CPU rather than fail.
if device == "cpu":
raise
torch.cuda.empty_cache() if device == "cuda" else None
used = "cpu"
emit(id=rid, event="fallback", device="cpu")
stems = core.separate(model, pcm, "cpu", seed=int(msg.get("seed", 0)), on_progress=progress)
folder = Path(msg["output_dir"])
folder.mkdir(parents=True, exist_ok=True)
for name, x in stems.items():
x.tofile(folder / f"{name}.f32")
emit(id=rid, event="done", seconds=round(time.time() - started, 2), device=used)
except Cancelled:
emit(id=rid, event="cancelled")
except BaseException as ex: # noqa: BLE001 — reported, the process lives on
# demucs re-raises a callback's exception wrapped; unwrap a cancel.
if isinstance(ex.__cause__, Cancelled) or isinstance(ex.__context__, Cancelled):
emit(id=rid, event="cancelled")
else:
emit(id=rid, event="error", message=f"{type(ex).__name__}: {ex}")
finally:
with lock:
cancel.discard(rid)
+69
View File
@@ -0,0 +1,69 @@
"""Archive a frozen engine for release: tar.gz, split under GitHub's asset cap.
python package.py TARGET DIST_DIR OUT_DIR
Writes `konduktor-engine-<version>-<target>.tar.gz[.partNN]` and
`<target>.json` (the parts with sizes and SHA-256, plus the whole archive's
hash) for the release job to fold into `engine-manifest.json`.
tar.gz, not zip: `zipfile` drops the executable bit on macOS. Split because a
release asset is capped at 2 GiB and the CUDA engine is bigger than that.
"""
from __future__ import annotations
import hashlib
import json
import sys
import tarfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from konduktor_engine import VERSION # noqa: E402
PART = 1_900 * 1024 * 1024 # below the 2 GiB cap with room to spare
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def main(target: str, dist: str, out: str) -> int:
src = Path(dist) / "konduktor-engine"
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
# Symlinks are archived as links (the macOS build has several), so they
# must not be counted — following them counted torch's libraries twice.
files = [p for p in src.rglob("*") if p.is_file() and not p.is_symlink()]
unpacked = sum(p.lstat().st_size for p in files)
longest = max(len(p.relative_to(src.parent).as_posix()) for p in files)
base = f"konduktor-engine-{VERSION}-{target}.tar.gz"
archive = out_dir / base
with tarfile.open(archive, "w:gz", compresslevel=6) as tar:
tar.add(src, arcname="konduktor-engine")
whole = sha256_file(archive)
size = archive.stat().st_size
parts = []
if size <= PART:
parts.append({"name": base, "size": size, "sha256": whole})
else:
with open(archive, "rb") as f:
n = 0
while chunk := f.read(PART):
name = f"{base}.part{n:02d}"
(out_dir / name).write_bytes(chunk)
parts.append({"name": name, "size": len(chunk), "sha256": hashlib.sha256(chunk).hexdigest()})
n += 1
archive.unlink()
info = {"target": target, "version": VERSION, "archive": base, "size": size, "sha256": whole,
"unpacked_size": unpacked, "files": len(files), "longest_path": longest, "parts": parts}
(out_dir / f"{target}.json").write_text(json.dumps(info, indent=1))
print(json.dumps({k: v for k, v in info.items() if k != "parts"}), f"{len(parts)} part(s)")
return 0
if __name__ == "__main__":
sys.exit(main(*sys.argv[1:4]))
+163
View File
@@ -0,0 +1,163 @@
"""The stem engine's process protocol, and (with --frozen) the golden test.
.venv/bin/python test_engine.py --weights DIR [--frozen dist/konduktor-engine/konduktor-engine]
Needs the htdemucs_ft weights folder (`htdemucs_ft.yaml` + four
`.safetensors`); defaults to the Hugging Face cache snapshot when present.
Runs on CPU so results are comparable across machines (CI runners have no GPU).
Pins what would fail silently or hang the app:
* `serve` loads once, separates repeatedly, and the SAME seed gives the SAME
stems — a re-conversion is reproducible;
* a cancel stops the running separation and the process stays usable;
* closing stdin (the backend died) ends the process even mid-separation —
otherwise an orphaned engine keeps a CPU pinned for an hour;
* the frozen build separates bit-for-bit like the unfrozen code (golden).
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import tempfile
import time
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def default_weights() -> str | None:
snaps = sorted(Path.home().glob(".cache/huggingface/hub/models--adefossez--HTDemucs-ft/snapshots/*/"))
return str(snaps[-1]) if snaps else None
def clip(seconds: float, seed: int = 0) -> np.ndarray:
"""Something with drums, bass and a tone: enough for every model in the bag."""
sr = 44100
n = int(seconds * sr)
t = np.arange(n) / sr
rng = np.random.default_rng(seed)
x = 0.3 * np.sin(2 * np.pi * 55 * t) + 0.1 * np.sin(2 * np.pi * 440 * t)
for start in range(0, n, sr // 2):
k = min(2000, n - start)
x[start:start + k] += rng.uniform(-0.6, 0.6, k) * np.linspace(1, 0, k)
return np.stack([x, x * 0.9]).astype(np.float32)
class Engine:
def __init__(self, cmd: list[str], weights: str):
self.proc = subprocess.Popen(cmd + ["serve", "--weights", weights, "--device", "cpu"],
cwd=HERE, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, bufsize=1)
def send(self, **msg):
self.proc.stdin.write(json.dumps(msg) + "\n")
self.proc.stdin.flush()
def recv(self) -> dict:
line = self.proc.stdout.readline()
if not line:
raise EOFError("engine closed its output")
return json.loads(line)
def until(self, *events, rid=None):
seen = []
while True:
m = self.recv()
seen.append(m)
if m.get("event") in events and (rid is None or m.get("id") == rid):
return m, seen
def separate(self, rid, pcm, out: Path, seed=0):
src = out / f"{rid}.f32"
pcm.tofile(src)
self.send(cmd="separate", id=rid, input=str(src), samples=pcm.shape[1], output_dir=str(out / rid), seed=seed)
def read_stems(folder: Path):
return {n: np.fromfile(folder / f"{n}.f32", dtype=np.float32) for n in ("drums", "bass", "other", "vocals")}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--weights", default=default_weights())
ap.add_argument("--frozen")
args = ap.parse_args()
if not args.weights:
print("no weights folder: pass --weights")
return 2
unfrozen = [sys.executable, "-m", "konduktor_engine"]
tmp = Path(tempfile.mkdtemp(prefix="konduktor-engine-test-"))
print("== info ==")
info = json.loads(subprocess.run(unfrozen + ["info"], cwd=HERE, capture_output=True, text=True).stdout)
check("info reports the version, model and devices",
info.get("event") == "info" and info.get("model") == "htdemucs_ft" and "cpu" in info.get("devices", []), str(info))
print("== serve ==")
e = Engine(unfrozen, args.weights)
ready = e.recv()
check("serve loads the model once and says so", ready.get("event") == "ready", str(ready))
e.send(cmd="ping")
check("ping -> pong", e.recv().get("event") == "pong")
pcm = clip(8)
e.separate("a", pcm, tmp, seed=0)
done, seen = e.until("done", "error", rid="a")
check("a separation completes", done["event"] == "done", str(done))
check("…reporting progress on the way", any(m.get("event") == "progress" for m in seen))
a = read_stems(tmp / "a")
check("four stems, each the mix's size", all(x.size == pcm.size for x in a.values()))
e.separate("b", pcm, tmp, seed=0)
e.until("done", rid="b")
b = read_stems(tmp / "b")
check("the same seed gives the SAME stems (reproducible)", all(np.array_equal(a[k], b[k]) for k in a))
e.separate("c", clip(30, seed=1), tmp)
e.until("progress", rid="c")
e.send(cmd="cancel", id="c")
m, _ = e.until("cancelled", "done", "error", rid="c")
check("a cancel stops the running separation", m["event"] == "cancelled", str(m))
e.send(cmd="ping")
check("…and the engine is still usable", e.until("pong")[0]["event"] == "pong")
e.separate("d", clip(60, seed=2), tmp)
e.until("progress", rid="d")
t0 = time.time()
e.proc.stdin.close() # the backend died
try:
e.proc.wait(timeout=10)
check("closing stdin ends the engine even mid-separation", True)
except subprocess.TimeoutExpired:
e.proc.kill()
check("closing stdin ends the engine even mid-separation", False, "still running after 10 s")
print(f" (exited {time.time() - t0:.2f} s after stdin closed)")
if args.frozen:
print("== golden: frozen vs unfrozen ==")
fe = Engine([args.frozen], args.weights)
check("the frozen engine starts and loads the model", fe.recv().get("event") == "ready")
fe.separate("f", pcm, tmp, seed=0)
fdone, _ = fe.until("done", "error", rid="f")
check("the frozen engine separates", fdone["event"] == "done", str(fdone))
f = read_stems(tmp / "f")
worst = max(float(np.max(np.abs(f[k] - a[k]))) for k in a)
check("…bit-for-bit like the unfrozen code", worst == 0.0, f"max |diff| {worst:.3g}")
fe.proc.stdin.close()
fe.proc.wait(timeout=10)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+13
View File
@@ -0,0 +1,13 @@
{
"comment": "The htdemucs_ft weights, pinned. Fetched from the official Hugging Face repo on each machine and verified here; never re-hosted (their licence is ambiguous — see the stem-conversion discussion log). Konduktor's engine manager and CI both read this file.",
"repo": "adefossez/HTDemucs-ft",
"revision": "d74ac89c3a1e874fc78f152555cf4d8533f06cd4",
"url": "https://huggingface.co/{repo}/resolve/{revision}/{name}",
"files": [
{"name": "htdemucs_ft.yaml", "size": 149, "sha256": "69470b8c1bbd674437b51bc9fb491327a10ab0396b702c93389b9cf750016346"},
{"name": "f7e0c4bc.safetensors", "size": 84025440, "sha256": "2c85ab3c62dd6edd8e0b965e38b16fd1cdde357cc25de6b6bc9ce7c83f60925f"},
{"name": "d12395a8.safetensors", "size": 84025440, "sha256": "5b01a97567ae9a3178a6236fb520251045c03eb8834bc8c24a4eec11d6c8fb56"},
{"name": "92cfc3b6.safetensors", "size": 84025440, "sha256": "a241863551f30d01c42bd7b97da40839922ead3acb0f1fcab25682f55b4eeb59"},
{"name": "04573f0d.safetensors", "size": 84025440, "sha256": "68854b0d7c2b3274723b5761f6fd9f5aec5f1bcd3f0de7c1669546fdb7871b7c"}
]
}