Skip to content

About

C++/ggml port of the BeatNet+ music beat & downbeat tracker (CPU + Metal GPU, no Python runtime)

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

beatnetplus.cpp

Self-contained C++ port of the BeatNet+ music beat / downbeat tracker, built on ggml. One small binary, no Python, PyTorch, madmom, librosa or NumPy at runtime:

./beatnetplus-cli --weights models/generic-f32.gguf song.mp3
# 0.440 1
# 1.120 2
# 1.440 1        <time_seconds> <1 = downbeat, 2 = beat>
# ...

BeatNet+ (Heydari, Cwitkowitz, Duan — TISMIR 2024) is an enhanced version of BeatNet with a deeper CRNN and a dual-branch training strategy. This repository ports its online inference mode (causal cascade particle filter) to C++ with verified numerical parity against the Python reference.


Table of contents


Pipeline

Three stages; only the middle one is a neural network:

mp3/wav/npy ─► audio.cpp     decode (dr_mp3 / dr_wav / CoreAudio / ffmpeg) + Kaiser-
                             windowed-sinc resample to 22050 Hz mono
            ─► features.cpp  madmom-parity LOG_SPECT features:
                             Hann window 1764 (80 ms), hop 441 (20 ms),
                             PocketFFT of size 1764, 882x144 logarithmic
                             triangular filterbank, log10(x+1), positive
                             1-frame spectral difference
                             → one 288-dim vector per 20 ms frame (50 fps)
            ─► model.cpp     CRNN (767k params, fp32):
                             conv1d(1→2, k=10) → ReLU → maxpool(2)
                             → linear 278→150 → 4-layer LSTM(150)
                             → linear 150→3 → softmax
                             → per frame [P(beat), P(downbeat)]
            ─► particle_filter.cpp
                             cascade particle filter (causal): 1500 beat
                             particles over a 1449-state bar-pointer tempo
                             space (55–215 BPM) + 250 downbeat particles
                             over 2/3/4-beat meters
                             → list of (time_seconds, beat_type)

The full porting spec lives in the BeatNet-Plus repository as PORTING_TO_CPP_GGML.md, including several corrections to madmom behaviour discovered during this port (diff_frames = 1, frame count ceil(len/441), the exact tempo-transition formula).

Building

Requires CMake ≥ 3.14 and a C++17 compiler. ggml is used from a sibling checkout at ../ggml if present, otherwise fetched automatically:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j8

GPU backends are ggml's: add -DGGML_METAL=ON on macOS, -DGGML_VULKAN=ON or -DGGML_CUDA=ON on Linux/Windows — the code selects whatever GPU device ggml exposes at runtime and falls back to CPU. mp3/wav/npy decoding is built in; other containers (m4a/aac/…) use CoreAudio on macOS and fall back to the ffmpeg CLI on Linux/Windows (runtime dependency only).

Note for the curious: src is a quote-only include directory (-iquote) — with a plain -I, src/features.h would shadow glibc's <features.h> on Linux and break every libc header.

Cross-compiling for Windows (from Linux)

Same recipe as edmformer.cpp: MinGW-w64 (POSIX threads), Vulkan backend, fully static exe (only system DLLs + vulkan-1.dll). With the one-time win-deps/ setup from that README (Vulkan-Headers checkout, libvulkan-1.a import lib, spirv-include/):

cmake -B build-win -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw64.cmake \
    -DCMAKE_BUILD_TYPE=Release -DGGML_VULKAN=ON \
    -DGGML_NATIVE=OFF -DGGML_SSE42=ON -DGGML_AVX=ON -DGGML_AVX2=ON \
    -DGGML_FMA=ON -DGGML_F16C=ON -DGGML_BMI2=ON \
    -DGGML_OPENMP=OFF -DBUILD_SHARED_LIBS=OFF \
    -DCMAKE_CXX_FLAGS="-isystem $PWD/../win-deps/spirv-include" \
    -DVulkan_INCLUDE_DIR=$PWD/../win-deps/Vulkan-Headers/include \
    -DVulkan_LIBRARY=$PWD/../win-deps/libvulkan-1.a \
    -DVulkan_GLSLC_EXECUTABLE=/usr/bin/glslc \
    -DSPIRV-Headers_DIR=/usr/share/cmake/SPIRV-Headers
cmake --build build-win -j$(nproc)

Verified under WINE on an RTX 5090 (winevulkan needs the patches/ggml-vulkan-winevulkan-queue-lookup.patch from edmformer.cpp applied to the ggml checkout): GPU run matches the documented parity numbers, --stream - stdin input works (_setmode(_O_BINARY) guards the raw f32 pipe), and --device cpu reproduces the Linux beat list exactly.

Produces:

Binary Purpose
beatnetplus-cli beat/downbeat tracking CLI
beatnetplus-test parity tests against Python-dumped fixtures
beatnetplus-debug-graph stage-by-stage ggml graph debugging tool

CLI usage

beatnetplus-cli --weights model.gguf [options] audio.{mp3,wav,npy}

  --weights PATH   model gguf (see conversion section below)
  --device DEV     gpu (default; Metal/Vulkan/CUDA, CPU fallback) or cpu
  --json           emit a JSON document instead of text lines
  -o PATH          write the output to PATH instead of stdout
  --stream         incremental (chunked) processing; beats print as they are
                   detected. With audio '-', reads raw f32le mono 22050 Hz
                   PCM from stdin; with a file, simulates a live stream in
                   100 ms chunks (see Streaming / live input)
  --dump-feats P   save features to P (npy, T x 288)
  --dump-acts P    save NN activations to P (npy, T x 2)
  --quiet          suppress progress on stderr

Input formats: .mp3, .wav (any sample rate / channel count; resampled internally), .npy (fp32 mono, assumed already at 22050 Hz), and anything else via CoreAudio on macOS or the ffmpeg CLI on Linux/Windows (m4a/aac/…). Text output is one line per beat: <time_seconds> <type> with type 1 = downbeat, 2 = beat.

JSON output

--json replaces the text lines with a single document:

{
  "audio": "song.mp3",
  "sample_rate": 22050,
  "duration_seconds": 170.650,
  "fps": 50,
  "bpm": 130.4,
  "num_beats": 362,
  "num_downbeats": 91,
  "beats": [
    {"time": 0.440, "type": "downbeat"},
    {"time": 1.120, "type": "beat"}
  ]
}

bpm is 60 / median(inter-beat interval), null when fewer than two beats were found.

Using it as a library

beatnetplus_core is a static library; link it and include the headers of the stages you need (audio.h, features.h, model.h, particle_filter.h, and stream.h for chunked input). The whole batch pipeline is:

#include "audio.h"
#include "features.h"
#include "model.h"
#include "particle_filter.h"

int main() {
    // 1. load the model (weights + baked filterbank/window from the gguf)
    beatnet_model model;
    if (!model.load("models/generic-f32.gguf")) return 1;
    model.init_compute(/*n_threads=*/4, /*use_gpu=*/true);  // optional: enables
                                                            // the ggml graph path

    // 2. decode + resample to 22050 Hz mono
    std::vector<float> audio = load_audio("song.mp3", model.sample_rate);

    // 3. features: (T, 288) at 50 fps
    int64_t T = 0;
    std::vector<float> feats = compute_features(audio.data(), audio.size(), model, T);

    // 4. neural network: (T, 2) = [P(beat), P(downbeat)] per frame
    std::vector<float> acts = model.infer(feats.data(), T);

    // 5. causal decoder
    particle_filter_cascade pf(/*fps=*/50, /*seed=*/1);
    for (const beat_event & e : pf.process(acts.data(), T)) {
        if (e.type != 0)  // skip the initial sentinel
            printf("%.3f %s\n", e.time, e.type == 1 ? "downbeat" : "beat");
    }
}

Notes:

  • model.infer() uses ggml graphs (GPU when available) once init_compute() was called, otherwise the scalar CPU path. Both are also callable explicitly: infer_graph() / infer_cpu().
  • particle_filter_cascade::process() is stateful and causal — you may call it repeatedly with any number of frames (including one at a time); it returns the accumulated beat list. Construct a fresh instance per audio stream.
  • compute_features and infer are stateless whole-buffer calls. For chunked/live input use beatnet_stream (or the underlying feature_stream + infer_stream primitives) — see Streaming / live input.
  • Everything is plain fp32 on the host; no ggml types appear in the public API except the opaque weight tensors inside beatnet_model.

CMake integration:

add_subdirectory(beatnetplus.cpp)
target_link_libraries(your_target PRIVATE beatnetplus_core)

The weights: where they come from and how they were converted

Provenance

The weights are not trained by this project. They are the official pre-trained checkpoints of BeatNet-Plus (BeatNet+), by Mojtaba Heydari, Frank Cwitkowitz and Zhiyao Duan (University of Rochester), published alongside:

BeatNet+: Advancing Music Beat and Downbeat Tracking for Non-Percussive Music and Singing Voices, Transactions of the International Society for Music Information Retrieval (TISMIR), 2024.

The BeatNet-Plus repository ships three PyTorch state_dict files in src/BeatNetPlus/models/:

Upstream file Model Best for
generic_weights.pt generic (auxiliary branch) general-purpose music (default)
generic_main_weights.pt generic (main branch) percussive-heavy music
af_non_percussive_weights.pt AF-adapted student non-percussive / classical / ambient

models/generic-f32.gguf in this repository is a converted copy of generic_weights.pt. The upstream weights are distributed free for non-commercial use — the converted GGUF inherits that license (see Dependencies and licenses).

What the conversion does

scripts/convert_pt_to_gguf.py performs a one-off, lossless (fp32 → fp32) repackaging of the PyTorch checkpoint into GGUF, ggml's tensor container format:

  1. Loads the state_dict with torch.load and writes all 22 tensors unchanged (no transposition needed: a PyTorch (out, in) row-major matrix maps directly onto a ggml tensor with ne = {in, out}):

    conv1.weight (2,1,10)   conv1.bias (2,)
    linear0.weight (150,278)  linear0.bias (150,)
    lstm.weight_ih_l{0..3} (600,150)  lstm.bias_ih_l{0..3} (600,)
    lstm.weight_hh_l{0..3} (600,150)  lstm.bias_hh_l{0..3} (600,)
    output_linear.weight (3,150)  output_linear.bias (3,)
    

    PyTorch's LSTM gate order [i | f | g | o] inside the 600-row matrices is preserved as-is; the C++ cell update replicates it exactly.

  2. Bakes the DSP constants in as extra tensors, so the C++ side never has to re-derive madmom's filter design:

    • feats.filterbank (882, 144) — the madmom LogarithmicFilterbank (24 bands/octave, 30 Hz–17 kHz, normalized triangular filters), extracted by instantiating madmom's FilteredSpectrogram with the exact BeatNet+ configuration and dumping its .filterbank matrix;
    • feats.window (1764,) — the Hann analysis window np.hanning(1764).

    Embedding these removes an entire class of feature-parity bugs.

  3. Records hyperparameters as GGUF metadata: dim_in=288, num_cells=150, num_layers=4, sample_rate=22050, win_length=1764, hop_size=441, num_bands=144.

No quantization is applied — the model is only ~3 MB in fp32, and quantizing an LSTM this small would risk accuracy for no meaningful size or speed benefit.

Converting the weights yourself

The conversion needs the BeatNet-Plus repository and its Python environment (PyTorch + madmom + the gguf package). With the PDM setup from that repo:

cd BeatNet-Plus
pdm run python /path/to/beatnetplus.cpp/scripts/convert_pt_to_gguf.py \
    --weights src/BeatNetPlus/models/generic_weights.pt \
    --out     /path/to/beatnetplus.cpp/models/generic-f32.gguf

The same command converts generic_main_weights.pt or af_non_percussive_weights.pt — all three share the architecture, so the resulting GGUFs are drop-in interchangeable via --weights.

GPU (Metal / Vulkan) support

--device gpu is the default. Every time-batchable NN stage — the conv front-end (as explicit f32 ggml_im2col + matmul), linear0, the four LSTM input projections W_ih·x over all T frames, and the output head + softmax — runs as ggml graphs on whatever GPU backend ggml was built with (Metal on macOS, Vulkan/CUDA on Linux and Windows). Only the irreducible sequential LSTM cell update (W_hh·h + gate nonlinearities) runs on the CPU. Ops a backend doesn't support fall back transparently via ggml_backend_sched. BEATNETPLUS_CPU=1 forces the graph path onto the CPU backend; --device cpu selects the hand-written scalar path.

Honest caveat: at 767k parameters the network is far too small for the GPU to pay off — measured end-to-end times are within a few percent of the CPU path. The GPU path exists correctness-verified for scaling to bigger models. GPU matmul accumulation order differs from the CPU, so GPU activations match Python to ~1e-3 (amplified through the recurrence) instead of ~1e-6; decoded beat lists are equivalent (same counts, same tempo, F ≥ 0.99).

Porting gotcha worth knowing: ggml_conv_1d silently scrambles batched (N > 1) inputs — its final reshape assumes N = 1 — and forces an f16 im2col. This port uses explicit ggml_im2col(..., GGML_TYPE_F32) + ggml_mul_mat + ggml_permute instead.

Validation and parity tests

Reference fixtures are dumped from the Python implementation and compared by the test binary:

cd BeatNet-Plus
pdm run python /path/to/beatnetplus.cpp/scripts/dump_fixtures.py \
    --weights src/BeatNetPlus/models/generic_weights.pt \
    --out /path/to/beatnetplus.cpp/fixtures \
    kick=test/test_data/808kick120bpm.mp3 edm=/path/to/some_song.mp3

cd /path/to/beatnetplus.cpp
./build/beatnetplus-test models/generic-f32.gguf fixtures kick edm

Measured parity against the Python reference (generic_weights.pt):

Check kick (808 @ 120 BPM) full EDM track (170 s)
features max abs diff 2.4e-7 4.8e-7
NN activations max abs diff (CPU) 8.3e-7 9.8e-7
NN activations max abs diff (Metal) 3.5e-4 9.8e-4
beat F-measure (70 ms tolerance) 1.000 0.993
downbeat F-measure n/a (3 refs, RNG-ambiguous meter) 0.978
tempo 120.0 BPM (exact) 130.4 BPM (exact)

The particle filter uses std::mt19937(1). Output is deterministic across runs, but not bit-identical to NumPy's RNG stream, so beat lists are compared by F-measure rather than exactly (this is inherent — verified by re-running the Python reference with different seeds, which moves its downbeat choices on ambiguous material). Rebuilding with a modified Metal graph can shift GPU activations by ~1e-4, which the stochastic decoder may amplify into a ~1% beat-count difference on ambiguous sections; use --device cpu when exact reproducibility across builds matters.

Performance

Single-threaded on an Apple M1 Max, 170 s EDM track end-to-end (decode → resample → features → NN → particle filter): ~6.5 s ≈ 26x realtime. Roughly half of that is mp3 decode + sinc resampling; features + NN + decoder are ~3.2 s. The Python reference takes ~22 s for the same file.

On Linux (Core Ultra 9 285K, Vulkan graph path on an RTX 5090) the same track takes ~6.9 s ≈ 25x realtime — as the GPU-support section notes, the model is too small for the GPU to matter; decode + features dominate.

Streaming / live input

The library processes incoming audio chunk by chunk — from a microphone, a network source, or a file — via three stateful pieces plus a convenience wrapper (stream.h):

  • feature_stream — ring-buffer feature extractor. Frames are centered, so emitting frame t needs 882 samples (40 ms) of lookahead — an inherent property of the BeatNet+ design; push() emits every frame whose future context has arrived, flush() emits the zero-padded tail at end-of-stream.
  • beatnet_lstm_state + beatnet_model::infer_stream() — the LSTM hidden/cell state (4×150 each) is held by the caller and preserved between chunks.
  • particle_filter_cascade::process() — already causal/stateful.
  • beatnet_stream — combines all three: samples in, beats out.
#include "stream.h"

beatnet_stream bs(model);                  // model must outlive the stream
while (have_audio) {
    // any chunk size, 22050 Hz mono
    for (const beat_event & e : bs.push(chunk, n)) {
        printf("%.3f %s\n", e.time, e.type == 1 ? "DOWNBEAT" : "beat");
    }
}
bs.flush();                                // end-of-stream tail

Guarantee (tested): for a finite input, chunked push() + flush() produces beat lists bit-identical to the batch pipeline, for any chunk sizes — the batch compute_features is itself implemented on top of feature_stream, and infer_cpu on top of infer_stream.

The CLI exposes this as --stream. With - it reads raw f32le mono 22050 Hz PCM from stdin and prints beats as they are detected:

# live microphone (macOS/Linux, via sox)
sox -d -t raw -e float -b 32 -c 1 -r 22050 - 2>/dev/null | \
    ./build/beatnetplus-cli --weights models/generic-f32.gguf --stream -

# any file/URL through ffmpeg
ffmpeg -i song.mp3 -f f32le -ac 1 -ar 22050 - 2>/dev/null | \
    ./build/beatnetplus-cli --weights models/generic-f32.gguf --stream -

# simulate a live stream from a file (100 ms chunks)
./build/beatnetplus-cli --weights models/generic-f32.gguf --stream song.mp3

Latency ≈ 40 ms feature lookahead + the particle filter's beat-confirmation delay (one to a few frames). Per-frame cost is one 1764-point FFT + ~1.4 MFLOP of LSTM — microseconds per 20 ms hop, so real-time is trivial on any CPU (the streaming NN intentionally uses the scalar CPU path; per-chunk GPU graph launches would be pure overhead at this model size).

Dependencies and licenses

Component What for License
C++ port (this repo, src/, tests/, scripts/) — MIT
ggml GGUF container + Metal/CPU backends MIT
PocketFFT (third_party/pocketfft_hdronly.h) FFT of size 1764 (radix 2·3·7) BSD-3-Clause
dr_mp3 / dr_wav (third_party/) mp3/wav decoding public domain / MIT-0
BeatNet+ pre-trained weights (models/*.gguf) the model itself free for non-commercial use (© the BeatNet+ authors)

The code of this port is MIT-licensed, but the converted weights inherit the upstream BeatNet+ terms: non-commercial use only. For commercial use, contact the BeatNet+ authors.

Citation

If you use this in research, cite the original BeatNet+ paper:

@article{heydari2024beatnetplus,
  title={BeatNet+: Advancing Music Beat and Downbeat Tracking for
         Non-Percussive Music and Singing Voices},
  author={Heydari, Mojtaba and Cwitkowitz, Frank and Duan, Zhiyao},
  journal={Transactions of the International Society for Music Information
           Retrieval},
  year={2024}
}

and for the original BeatNet architecture and particle-filtering decoder:

@inproceedings{heydari2021beatnet,
  title={BeatNet: CRNN and Particle Filtering for Online Joint Beat,
         Downbeat and Meter Tracking},
  author={Heydari, Mojtaba and Cwitkowitz, Frank and Duan, Zhiyao},
  booktitle={22nd International Society for Music Information Retrieval
             Conference (ISMIR)},
  year={2021}
}

About

C++/ggml port of the BeatNet+ music beat & downbeat tracker (CPU + Metal GPU, no Python runtime)

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages