Skip to content

whisper : optional ANEForge encoder backend (Apple Neural Engine) - #3905

Merged
danbev merged 5 commits into
ggml-org:masterfrom
sbryngelson:aneforge-encoder-backend
Sep 18, 2026
Merged

danbev merged 5 commits into
ggml-org:masterfrom
sbryngelson:aneforge-encoder-backend

Conversation

@sbryngelson

Copy link
Copy Markdown
Contributor

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):

model ANEForge (ANE) CoreML (ANE) Metal (GPU) vs CoreML vs Metal
tiny 5.7 ms 11.2 ms 7.3 ms 2.0x 1.3x
base 12.2 ms 23.0 ms 13.5 ms 1.9x 1.1x
small 40.3 ms 77.2 ms 40.9 ms 1.9x 1.0x
medium 117.6 ms 236.0 ms 120.0 ms 2.0x 1.0x

Cosine 0.999 against the reference encoder; the transcript of jfk.wav is 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_enc through the same whisper_encode_external path, gated at runtime by the ANEFORGE_ENCODER env var:

  • src/aneforge/whisper-aneforge.{h,cpp} (the backend), one line in src/CMakeLists.txt, and ~30 lines in src/whisper.cpp (an include, a state field, the encode branch, init, and free).
  • With ANEFORGE_ENCODER unset the build behaves exactly like stock whisper.cpp. The backend dlopens the ANEForge dispatch dylib only when enabled, so there is no new link-time dependency and nothing changes for existing users.
  • Encoder only; the autoregressive decoder is untouched.
ANEFORGE_DYLIB=... ANEFORGE_ENCODER=./whisper-small-ane \
  ./build/bin/whisper-cli -m models/ggml-small.bin -f samples/jfk.wav

Notes / caveats

  • Apple Silicon only. The ANE work lives in the external aneforge package (pip), which reaches the ANE through Apple private Espresso e5rt symbols, the same stack CoreML uses internally. Undocumented, can change with macOS, so this is a research path, gated behind the env var.
  • The exported encoder bundle is built on the target Mac at load (~0.6 s) since it is keyed to the OS build; it is fixed to n_audio_ctx=1500, so it does not honor --audio-ctx.
  • Builds clean on current master (verified whisper-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.

@ggerganov

Copy link
Copy Markdown
Member

Quite interesting work.

Query-tiled attention. The score matrix is never fully materialized. The query axis is split into tiles, so each head computes [S, S/3] score tiles rather than the full [S, S] (the flash-attention idea, written as einsum so there is no transpose). This roughly halves attention time, is exact (each tile attends to all keys), and is what puts the ANE ahead of the GPU rather than even with it.

Have you investigated how the number of tiles affects the performance? Is 3 tiles always the best option for all model sizes and hardware?

@sbryngelson

Copy link
Copy Markdown
Contributor Author

Quite interesting work.

Query-tiled attention. The score matrix is never fully materialized. The query axis is split into tiles, so each head computes [S, S/3] score tiles rather than the full [S, S] (the flash-attention idea, written as einsum so there is no transpose). This roughly halves attention time, is exact (each tile attends to all keys), and is what puts the ANE ahead of the GPU rather than even with it.

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:

size    H | t=1  t=2  t=3  t=4  t=5  t=6  t=8   (ms)
tiny    6 | 2.50 2.65 2.57 2.54 2.41 2.68 2.51
base    8 | 3.28 3.47 3.33 3.33 3.06 3.51 3.17
small  12 | 5.07 5.45 5.12 5.15 4.90 5.22 5.00
medium 16 |20.31 7.16 6.84 7.12 6.52 6.91 6.59
large  20 |26.83 8.99 8.77 8.60 8.03 8.59 8.20

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.

@sbryngelson

Copy link
Copy Markdown
Contributor Author

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.

Comment thread src/aneforge/whisper-aneforge.cpp Resolved
Comment thread src/aneforge/whisper-aneforge.cpp Resolved
Comment thread src/aneforge/whisper-aneforge.cpp Resolved
@danbev

danbev commented Aug 24, 2026

Copy link
Copy Markdown
Member

Is there anything else you want addressed before this can be considered?

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.

@sbryngelson

Copy link
Copy Markdown
Contributor Author

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.

sbryngelson and others added 2 commits August 24, 2026 10:58
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).
@sbryngelson
sbryngelson force-pushed the aneforge-encoder-backend branch from 2fb4164 to c19d34e Compare August 24, 2026 16:00
@sbryngelson

Copy link
Copy Markdown
Contributor Author

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 (whisper_encode_external, the external-encode dispatch, and state init) — I kept both, so VitisAI and ANEForge coexist: ANEForge is a runtime check (ANEFORGE_ENCODER), the compile-time CoreML/VitisAI/OpenVINO chain stays as the fallback. Verified the whisper target builds clean. And thanks for converting the model and posting it to HF.

…-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.
@sbryngelson

Copy link
Copy Markdown
Contributor Author

Thanks for approving the runs - they caught a real portability bug. The Windows and vad (Linux) jobs failed because whisper-aneforge.cpp used <dlfcn.h> and __fp16 unconditionally, which don't exist on Windows/MSVC and non-ARM Linux. Fixed in fbda7e6: the implementation is now guarded to __APPLE__ && __aarch64__ with no-op stubs elsewhere (the backend is Apple-Neural-Engine-only anyway), so the whisper library links on every platform. Verified both the real and stub paths compile. Needs another CI approval when you have a moment.

@sbryngelson
sbryngelson requested a review from danbev September 16, 2026 16:05
@sbryngelson

Copy link
Copy Markdown
Contributor Author

re-requesting review @danbev after some time waiting on this. Cheers.

@danbev

danbev commented Sep 17, 2026

Copy link
Copy Markdown
Member

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 👍

@sbryngelson

Copy link
Copy Markdown
Contributor Author

many thanks @danbev ... do need someone to merge

@danbev
danbev merged commit 4afa009 into ggml-org:master Sep 18, 2026
46 of 47 checks passed
sbryngelson added a commit to sbryngelson/ANEForge that referenced this pull request Sep 18, 2026
…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).
bygreencn added a commit to bygreencn/whisper.cpp that referenced this pull request Sep 23, 2026
* 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)
  ...
warith-harchaoui pushed a commit to warith-harchaoui/vocal-helper that referenced this pull request Nov 1, 2026
…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.
warith-harchaoui pushed a commit to warith-harchaoui/vocal-helper that referenced this pull request Nov 1, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants