Repository navigation
whisper : optional ANEForge encoder backend (Apple Neural Engine) - #3905
Conversation
|
Quite interesting work.
Have you investigated how the number of tiles affects the performance? Is 3 tiles always the best option for all model sizes and hardware? |
The count isn't fixed at 3 @ggerganov, sharp question and some learning for both of us here. It's n_tiles = max(1, (S+256)//512), so it scales with the query length, and the encoder's S=1500 gets 3. I swept it on an M5 Pro across the model sizes (S=1500, head_dim=64, n_head 6 to 20), timing the attention core as one fused program: 3 is close, but not optimal: 5 is consistently 5-10% faster here. And the first-order effect is just tiling at all. At high head count, the untiled [H,1500,1500] score is about 3x slower (it stops pipelining on the engine), while for tiny and base, it fits in cache and tiling is roughly flat. The optimum is broad (3 to 8 tiles within 10%), and it's bounded by L2 residency and pipelining, so it moves with the chip, as you noticed. Rather than a constant, the tile count is now autotuned in ANEForge (I merged a PR for this): it measures the best count once per (chip, S, T, heads, head_dim), caches it, and falls back to the heuristic until a tuned value exists. On the M5 Pro, it picks 5; on the M1/M2, it may pick something else, which is fine. The autotune picks that up with no code change. |
|
Following up on the tile-count question. Short version: it is no longer a constant. ANEForge autotunes the count once per (chip, S, T, heads, head_dim) and caches it, so the 3 in the original patch is gone. Is there anything else you want addressed before this can be considered? I am happy to put it behind a build flag or split it into smaller PRs if that makes review easier. |
Sorry about the delay, I'm taking a closer look at this now. Could you rebase and address the conflicts? I've converted the model according to the instructions provided above and uploaded it to huggingface, in case other want to try this out. |
|
Thanks for the review @danbev. Pushed the formatting fixes: split all the compound if-bodies to one statement per line and aligned the dlsym assignment block. Ready for another look when you have a moment. |
Runs the Whisper encoder directly on the Apple Neural Engine via ANEForge, an
alternative to the CoreML encoder backend. About 2x faster than the CoreML encoder
and faster than the Metal GPU encoder on M-series, at ~5x lower energy, with the
same transcripts (cosine 0.999 vs the reference encoder).
Mirrors the existing CoreML/OpenVINO seam: fills embd_enc from the external aneforge
package via the same whisper_encode_external path, gated at runtime by the
ANEFORGE_ENCODER env var. With the variable unset the build behaves exactly like
stock whisper.cpp (the backend dlopens its dispatch dylib only when enabled, no new
link-time dependency). Encoder only; the decoder is untouched.
Adds src/aneforge/whisper-aneforge.{h,cpp}, one line to src/CMakeLists.txt, and ~30
lines to src/whisper.cpp (include, state field, encode branch, init, free).
2fb4164 to
c19d34e
Compare
|
Rebased onto master and resolved the conflicts. They were with the VitisAI encoder backend that landed in the meantime, which touches the same three spots ( |
…-Apple CI) whisper-aneforge.cpp uses <dlfcn.h> and __fp16, which are unavailable on Windows (MSVC) and non-ARM Linux, so the unconditional build broke those CI jobs. Wrap the real implementation in #if defined(__APPLE__) && defined(__aarch64__) and provide no-op stubs elsewhere; the encoder is Apple-Neural-Engine-only anyway, and the library now links on every platform.
|
Thanks for approving the runs - they caught a real portability bug. The Windows and vad (Linux) jobs failed because |
|
re-requesting review @danbev after some time waiting on this. Cheers. |
Sorry about the delay/forgetting about this. I'll try to take another look today or tomorrow 👍 |
This commit updates the android jobs to specify platform-tools as an explicit package. The motivation for this to try to fix the Setup Android SDK step which is also trying to install an obolete tools package. Refs: https://github.com/ggml-org/whisper.cpp/actions/runs/35215042978/job/105181619536?pr=3905
|
many thanks @danbev ... do need someone to merge |
…e fork docs (#275) * docs: the whisper.cpp encoder backend is upstream, not a fork ggml-org/whisper.cpp#3905 merged 2026-09-18, so the two "in a fork" notes in the encoder benchmark README are stale. Records how it is enabled (the ANEFORGE_ENCODER / ANEFORGE_DYLIB env vars) and adds the integration to the feature list, where it was missing entirely. * bench: export a usable Whisper encoder bundle (real weights, fast layout, any size) export_bundle.py produced a bundle that could not be used with the whisper.cpp ANEForge backend: make_encoder() gives randomly-initialised weights, and build(attn="mha") is the generic [seq,d] layout the README clocks at ~33 ms, not the channels-first query-tiled encoder the 5.7 ms and 2x-vs-CoreML numbers come from. It was also whisper-tiny only. Defaults now to the trained checkpoint via real_encoder() and build_cf, adds --model (dimensions read from the HF config through the new set_dims), --layout, --compress, and keeps the old behaviour behind an explicitly-labelled --random. The manifest records which model, layout and dims produced the bundle. Verified: tiny exports at cosine 0.999970 and the C++ runner loads it the way whisper.cpp does at 5.569 ms/call, matching the benchmarked 5.7 ms; base exports at cosine 0.999961 with dims picked up from the config (d=512, layers=6, heads=8).
* ggerganov/master: (81 commits) fix(yt-wsp): Resolve script path without GNU realpath (ggml-org#4072) cli : load backends after validating input files (ggml-org#4069) ci : update android-actions to v4.0.4 (ggml-org#4074) docs : clarify VAD mode timestamps and CWD model path errors (ggml-org#4019) readme : document the ANEForge encoder backend (ggml-org#4073) whisper : optional ANEForge encoder backend (Apple Neural Engine) (ggml-org#3905) whisper : fix int overflow in whisper_full_parallel chunk offsets (ggml-org#4044) sync : ggml ggml : bump version to 0.24.0 (ggml/1627) tests(s390x): add non-vxe build to tests (llama/28776) sycl: rfc: Use radix select for top_k (llama/28670) ggml-cpu : disable PCH and fix CACHE_LINE_SIZE ambiguity to fix heap corruption (llama/28882) sycl : fix oneDNN scratchpad breaking the pool free order (llama/28704) ggml-cuda: fallback to F32 on device without BF16 hardware acceleration (llama/28846) ggml-cpu(s390x): guard VXE-only repack helpers (llama/28775) sycl : Fix get mem error (llama/28227) vulkan: workaround NV queuesubmit driver bug (llama/28830) opencl: apply the noshuffle row-alignment rule to q4_K, q5_K and q8_0, not just q6_K (llama/28575) ggml-cuda: hip add specific config table for AMD GCN (llama/27841) syscl : Handle (fail gracefully) unsupported tq1_0 quants (llama/28681) ...
…ne pas Deux questions posées, deux réponses mesurées, et une hypothèse à moi qui était fausse. **Ce que vaut l'accélération, mesuré.** 60 s de parole française réelle, `large-v3-turbo-q5`, un coup de chauffe jeté puis la médiane de deux passages (`studies/asr_acceleration_rtf.md`) : whisper.cpp + Metal 1,99 s RTF 0,033 30× le temps réel mlx-whisper (MLX / GPU) 3,69 s RTF 0,061 16× whisper.cpp CPU seul 9,83 s RTF 0,164 6× faster-whisper (CT2 int8) 39,44 s RTF 0,657 1,5× Metal vaut **4,9×** sur le même moteur et le même modèle. whisper.cpp bat MLX de 1,85 % — pardon, de 1,85 **fois** — sur le propre terrain d'Apple, ce qui valide le défaut de ce dépôt. Et faster-whisper, annoncé « jusqu'à 4× plus rapide que whisper.cpp » par les comparatifs de 2026, est ici 20× plus lent : CTranslate2 n'a pas de chemin Metal. **L'accélération est désormais sondée, plus supposée.** `vocal_helper.accel` lit le matériel, inspecte les bibliothèques réellement compilées dans le whisper.cpp installé, et choisit le meilleur étage disponible (ANE > CoreML > Metal > CPU). Une roue construite sans Metal est indiscernable de l'extérieur et coûte un facteur cinq en silence : d'où une sonde plutôt qu'une hypothèse. Le plan retenu porte sa raison, parce qu'un RTF décevant sans explication est le pire genre de problème de performance. **Et les fils sont dimensionnés aux cœurs rapides.** Le défaut était 6, codé en dur : sur cette machine il laissait deux des huit cœurs de performance inoccupés, et sur un portable à quatre il débordait de moitié sur les cœurs d'efficience — ce qui *ralentit* l'étage, puisque chaque point de synchronisation attend alors le plus lent des participants. **Le RTF ne s'additionne pas, et mon étude le supposait.** Dans un schéma producteur/consommateur, deux étages sur des unités différentes se **recouvrent** (la chaîne coûte le plus lent), deux étages sur la même unité font la **queue** (là les coûts s'ajoutent). Donc : additionner par unité, prendre le maximum entre unités. `live_budget` calcule ça, et ça renverse une conclusion : déplacer la diarisation hors du GPU **n'aide pas** si l'alternative est chère — le goulot change de main pour le pire. On ne gagne pas en répartissant, on gagne en répartissant vers une unité à la fois libre et rapide. Le cas tendu est sans torch et sans GPU : tout s'empile sur le CPU, 1,3× de marge. C'est exactement ce que borne `source_policy="drop_oldest"`, et c'est là que l'ANE compte — pas par sa vitesse mais parce qu'il **libère le CPU**. **Pistes au-dessus de Metal, et leur coût.** Ni CoreML ni ANE ne sont compilés dans le binaire installé (vérifié à `otool` et `nm`). Le backend ANE est fusionné en amont depuis le 2026-09-18 (`ggml-org/whisper.cpp#3905`, confirmé par l'API GitHub) : ~2× l'encodeur CoreML, 1,0 à 1,3× Metal, et **~5× moins d'énergie**. À 30× le temps réel, le gain de vitesse ne change pas la vie d'un corpus ; l'énergie et le direct sur machine modeste, oui. **Modèle vérifié.** `large-v3-turbo-q5_0` partout — vocal-helper, la config du produit, le cœur Rust. Et c'est déjà le plus récent : la lignée Whisper s'arrête à `large-v3-turbo` (octobre 2024), il n'existe pas de `large-v4`, vérifié le 2026-11-01 sur la liste publiée par OpenAI. Un test épingle la famille sans épingler la quantification : la famille est une décision mesurée, la quantification un réglage. 390 tests verts, dont 13 nouveaux sur l'accélération et le placement.
…ne pas Deux questions posées, deux réponses mesurées, et une hypothèse à moi qui était fausse. **Ce que vaut l'accélération, mesuré.** 60 s de parole française réelle, `large-v3-turbo-q5`, un coup de chauffe jeté puis la médiane de deux passages (`studies/asr_acceleration_rtf.md`) : whisper.cpp + Metal 1,99 s RTF 0,033 30× le temps réel mlx-whisper (MLX / GPU) 3,69 s RTF 0,061 16× whisper.cpp CPU seul 9,83 s RTF 0,164 6× faster-whisper (CT2 int8) 39,44 s RTF 0,657 1,5× Metal vaut **4,9×** sur le même moteur et le même modèle. whisper.cpp bat MLX de 1,85 fois — pardon, de 1,85 **fois** — sur le propre terrain d'Apple, ce qui valide le défaut de ce dépôt. Et faster-whisper, annoncé « jusqu'à 4× plus rapide que whisper.cpp » par les comparatifs de 2026, est ici 20× plus lent : CTranslate2 n'a pas de chemin Metal. **L'accélération est désormais sondée, plus supposée.** `vocal_helper.accel` lit le matériel, inspecte les bibliothèques réellement compilées dans le whisper.cpp installé, et choisit le meilleur étage disponible (ANE > CoreML > Metal > CPU). Une roue construite sans Metal est indiscernable de l'extérieur et coûte un facteur cinq en silence : d'où une sonde plutôt qu'une hypothèse. Le plan retenu porte sa raison, parce qu'un RTF décevant sans explication est le pire genre de problème de performance. **Et les fils sont dimensionnés aux cœurs rapides.** Le défaut était 6, codé en dur : sur cette machine il laissait deux des huit cœurs de performance inoccupés, et sur un portable à quatre il débordait de moitié sur les cœurs d'efficience — ce qui *ralentit* l'étage, puisque chaque point de synchronisation attend alors le plus lent des participants. **Le RTF ne s'additionne pas, et mon étude le supposait.** Dans un schéma producteur/consommateur, deux étages sur des unités différentes se **recouvrent** (la chaîne coûte le plus lent), deux étages sur la même unité font la **queue** (là les coûts s'ajoutent). Donc : additionner par unité, prendre le maximum entre unités. `live_budget` calcule ça, et ça renverse une conclusion : déplacer la diarisation hors du GPU **n'aide pas** si l'alternative est chère — le goulot change de main pour le pire. On ne gagne pas en répartissant, on gagne en répartissant vers une unité à la fois libre et rapide. Le cas tendu est sans torch et sans GPU : tout s'empile sur le CPU, 1,3× de marge. C'est exactement ce que borne `source_policy="drop_oldest"`, et c'est là que l'ANE compte — pas par sa vitesse mais parce qu'il **libère le CPU**. **Pistes au-dessus de Metal, et leur coût.** Ni CoreML ni ANE ne sont compilés dans le binaire installé (vérifié à `otool` et `nm`). Le backend ANE est fusionné en amont depuis le 2026-09-18 (`ggml-org/whisper.cpp#3905`, confirmé par l'API GitHub) : ~2× l'encodeur CoreML, 1,0 à 1,3× Metal, et **~5× moins d'énergie**. À 30× le temps réel, le gain de vitesse ne change pas la vie d'un corpus ; l'énergie et le direct sur machine modeste, oui. **Modèle vérifié.** `large-v3-turbo-q5_0` partout — vocal-helper, la config du produit, le cœur Rust. Et c'est déjà le plus récent : la lignée Whisper s'arrête à `large-v3-turbo` (octobre 2024), il n'existe pas de `large-v4`, vérifié le 2026-11-01 sur la liste publiée par OpenAI. Un test épingle la famille sans épingler la quantification : la famille est une décision mesurée, la quantification un réglage. 390 tests verts, dont 13 nouveaux sur l'accélération et le placement.
As offered in #3903, this adds an optional encoder backend that runs the Whisper encoder directly on the Apple Neural Engine through ANEForge, as an alternative to the CoreML encoder. On M-series it is about 2x faster than the CoreML encoder and faster than the Metal GPU encoder, at ~5x lower energy, with the same transcripts.
Per-call encoder latency, trained checkpoints, measured with
whisper-bench(CoreML and Metal are the existing backends, fp16):Cosine 0.999 against the reference encoder; the transcript of
jfk.wavis unchanged across tiny/small/medium, and a 199 s real-speech clip matches the stock Metal encoder to within 3 words out of 370 (the expected variation between two fp16 encoders).How it hooks in
It follows the existing CoreML/OpenVINO seam exactly. The backend fills
embd_encthrough the samewhisper_encode_externalpath, gated at runtime by theANEFORGE_ENCODERenv var:src/aneforge/whisper-aneforge.{h,cpp}(the backend), one line insrc/CMakeLists.txt, and ~30 lines insrc/whisper.cpp(an include, a state field, the encode branch, init, and free).ANEFORGE_ENCODERunset the build behaves exactly like stock whisper.cpp. The backenddlopens the ANEForge dispatch dylib only when enabled, so there is no new link-time dependency and nothing changes for existing users.Notes / caveats
aneforgepackage (pip), which reaches the ANE through Apple private Espressoe5rtsymbols, the same stack CoreML uses internally. Undocumented, can change with macOS, so this is a research path, gated behind the env var.n_audio_ctx=1500, so it does not honor--audio-ctx.master(verifiedwhisper-cli).Export script, the full benchmark, and reproduction steps are in the companion repo: https://github.com/sbryngelson/whisper-aneforge
Happy to adjust the seam, naming, or gating to fit how you would prefer an optional backend to land.