mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented demucs engine
This commit is contained in:
1 parent
e4e98eda3f
commit
f655bb4cf2
12 files changed
+693
-11
No files matched your search
@@ -0,0 +1,142 @@
|
||||
# The stem engine: a frozen torch + Demucs program, built per target and
|
||||
# published on its OWN release channel (`engine-v<version>`), separate from the
|
||||
# app's `v<version>-b<N>` releases. The app downloads the one it needs on first
|
||||
# use (see backend/konduktor/stems/engine_manager.py).
|
||||
#
|
||||
# * A tag `engine-v1.2.3` builds, tests and publishes — the tag must match
|
||||
# `konduktor_engine.VERSION`.
|
||||
# * A manual run builds and tests only (artifacts, no release).
|
||||
#
|
||||
# Releases are `prerelease: true` and `make_latest: false`: GitHub's "latest"
|
||||
# is what an app would take for itself, and the app's update check reads the
|
||||
# release list (UpdateDialog.tsx) — an engine release must never look like one.
|
||||
#
|
||||
# The weights are NOT in the engine (their licence is ambiguous): CI fetches the
|
||||
# pinned files from Hugging Face only to run the golden test.
|
||||
name: Engine
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["engine-v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: engine-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: macos-arm64
|
||||
os: macos-latest
|
||||
torch_index: ""
|
||||
- target: windows-x64-cpu
|
||||
os: windows-latest
|
||||
torch_index: "" # PyPI's Windows torch is the CPU build
|
||||
- target: windows-x64-cuda
|
||||
os: windows-latest
|
||||
# CUDA 13: Turing (RTX 20) through Blackwell (RTX 50); needs an
|
||||
# NVIDIA driver from r580. Older cards get the CPU engine — the
|
||||
# manager checks `engine info`'s arch list before offering this.
|
||||
torch_index: "https://download.pytorch.org/whl/cu130"
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: ${{ matrix.target }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
working-directory: engine
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Check the tag matches the engine version
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
run: |
|
||||
want="$(python -c 'import konduktor_engine as e; print(e.VERSION)')"
|
||||
[ "${GITHUB_REF_NAME#engine-v}" = "$want" ] || { echo "tag ${GITHUB_REF_NAME} != engine $want"; exit 1; }
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
python -m pip install --upgrade pip uv
|
||||
uv venv .venv --python 3.12
|
||||
PY=.venv/bin/python; [ -f .venv/Scripts/python.exe ] && PY=.venv/Scripts/python.exe
|
||||
echo "PY=$PY" >> "$GITHUB_ENV"
|
||||
if [ -n "${{ matrix.torch_index }}" ]; then
|
||||
uv pip install --python "$PY" "torch==2.14.0" --index-url "${{ matrix.torch_index }}"
|
||||
fi
|
||||
uv pip install --python "$PY" -r requirements.txt "pyinstaller==6.21.0"
|
||||
|
||||
- name: Weights (for the golden test only)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: engine/weights
|
||||
key: htdemucs-ft-d74ac89c3a1e874fc78f152555cf4d8533f06cd4
|
||||
- run: $PY fetch_weights.py weights
|
||||
|
||||
- name: Freeze
|
||||
run: $PY -m PyInstaller --noconfirm --clean konduktor-engine.spec
|
||||
|
||||
- name: Golden test (frozen vs unfrozen, CPU)
|
||||
run: |
|
||||
EXE=dist/konduktor-engine/konduktor-engine; [ -f "$EXE.exe" ] && EXE="$EXE.exe"
|
||||
$PY test_engine.py --weights weights --frozen "$EXE"
|
||||
|
||||
- name: Package
|
||||
run: $PY package.py ${{ matrix.target }} dist out
|
||||
|
||||
- name: Paths fit Windows' limit once installed
|
||||
run: |
|
||||
# Installed under e.g. %LOCALAPPDATA%\Konduktor\engine\<ver>\<target>\
|
||||
# (~70 characters on a typical user name): the tree must stay short.
|
||||
$PY -c "import json,sys; n=json.load(open('out/${{ matrix.target }}.json'))['longest_path']; print('longest', n); sys.exit(n > 180)"
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: engine-${{ matrix.target }}
|
||||
path: engine/out/*
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/engine-v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: Manifest
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import json, glob, os
|
||||
targets = {}
|
||||
for f in glob.glob("artifacts/*.json"):
|
||||
info = json.load(open(f))
|
||||
targets[info["target"]] = info
|
||||
version = os.environ["GITHUB_REF_NAME"].removeprefix("engine-v")
|
||||
weights = json.load(open("engine/weights.json"))
|
||||
json.dump({"version": version, "targets": targets, "weights": weights},
|
||||
open("artifacts/engine-manifest.json", "w"), indent=1)
|
||||
PY
|
||||
- uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: Konduktor stem engine ${{ github.ref_name }}
|
||||
prerelease: true
|
||||
make_latest: false
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
artifacts/*.tar.gz*
|
||||
artifacts/engine-manifest.json
|
||||
body: |
|
||||
The stem engine Konduktor downloads for **Convert to Stems** — not an app release.
|
||||
Konduktor fetches the right file for your computer itself; there is nothing to install by hand.
|
||||
@@ -47,3 +47,7 @@ backend/userprefs.json
|
||||
# build_sidecar.sh are source and ARE tracked.
|
||||
backend/build/
|
||||
backend/dist/
|
||||
|
||||
# ---- Stem engine (PyInstaller onedir build) ----
|
||||
engine/build/
|
||||
engine/dist/
|
||||
@@ -406,15 +406,37 @@ Two independent apps that talk over HTTP:
|
||||
offering a Rekordbox `master.db` to someone who just chose Traktor is an
|
||||
offer that cannot be taken.
|
||||
- **`engine/`** — the **stem engine**, a separate program (`konduktor_engine`,
|
||||
Python 3.12, torch + demucs 4.1 pinned in `engine/requirements.txt`) that
|
||||
imports nothing from `konduktor`. `core.py` loads htdemucs_ft from a LOCAL
|
||||
weights folder (never online — the weights' licence rules out shipping them,
|
||||
so the app downloads them) and separates, seeded (shifts=1 is random).
|
||||
Audio crosses as raw planar float32 files; protocol messages are JSON lines
|
||||
on a private copy of stdout, with `sys.stdout` pointed at stderr so torch's
|
||||
prints cannot corrupt one. For now a one-shot `separate` CLI; the persistent
|
||||
`serve` mode and the frozen per-OS build come next. `backend/dev_stems.py`
|
||||
(dev only) converts files with the real writer through an unfrozen engine.
|
||||
Python 3.12, torch 2.14 + demucs 4.1 pinned in `engine/requirements.txt`)
|
||||
that imports nothing from `konduktor`, built and released on its OWN channel.
|
||||
- `core.py` loads htdemucs_ft from a LOCAL weights folder — never online: the
|
||||
weights' licence rules out shipping them, so the app downloads them, pinned
|
||||
by revision + SHA-256 in `engine/weights.json` (`fetch_weights.py` for
|
||||
CI/dev). Seeded — and demucs draws its random shift from PYTHON's `random`,
|
||||
not torch's, so both are seeded or no two runs match.
|
||||
- `serve.py`: one process per batch, the model loaded once; JSON requests on
|
||||
stdin, JSON-line replies on a private copy of stdout (`sys.stdout` points
|
||||
at stderr, since torch prints), one lock for writes from two threads.
|
||||
A reader THREAD ends the process the moment stdin closes — the backend dies
|
||||
without killing children, and torch keeps the main thread busy. `cancel`
|
||||
raises from the progress callback and keeps the model loaded; CUDA OOM
|
||||
falls back to CPU for that track; the process lowers its own priority.
|
||||
`info` reports the CUDA card, capability and the build's arch list, which
|
||||
is how the app decides whether to offer the CUDA engine.
|
||||
- Frozen as a PyInstaller **onedir** (`konduktor-engine.spec`; onefile would
|
||||
re-extract ~500 MB per launch), `torch/include` and the HF client dropped:
|
||||
macOS arm64 = 164 MB download / 550 MB unpacked, runs after a tar round
|
||||
trip (ad-hoc signature intact). `test_engine.py` pins the protocol
|
||||
(reproducible seed, cancel, stdin-EOF exit) and, with `--frozen`, that the
|
||||
frozen build separates BIT-FOR-BIT like the unfrozen code (CPU).
|
||||
- `package.py` → tar.gz (zip loses exec bits on macOS), split under GitHub's
|
||||
2 GiB asset cap, per-part SHA-256; symlinks are archived as links and not
|
||||
double-counted. `.github/workflows/engine.yml` builds macos-arm64,
|
||||
windows-x64-cpu and windows-x64-cuda (torch cu130: Turing–Blackwell,
|
||||
driver r580+; older cards get the CPU engine), runs the golden test on CPU
|
||||
(runners have no GPU), checks Windows path length, and on an `engine-v*`
|
||||
tag publishes `prerelease` / NOT latest with an `engine-manifest.json`.
|
||||
- `backend/dev_stems.py` (dev only) converts files with the real writer
|
||||
through an unfrozen engine, and can swap them into a collection.
|
||||
- **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track
|
||||
explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx).
|
||||
- `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**:
|
||||
|
||||
@@ -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())
|
||||
@@ -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]))
|
||||
@@ -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)
|
||||
@@ -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,8 +33,15 @@ 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")
|
||||
# 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()
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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]))
|
||||
@@ -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())
|
||||
@@ -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"}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user