diff --git a/.gitattributes b/.gitattributes index 3e04daa51efa077f863599f52a64a32b47055ec5..d6436ca845eb12ca764597c0e49a770ce0962566 100644 --- a/.gitattributes +++ b/.gitattributes @@ -37,3 +37,41 @@ model/embeddinggemma-2-text.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -te model/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text model/embeddinggemma-2-text-mm.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text model/embeddinggemma-2-vision.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text +model/embeddinggemma-2-audio.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text +tests/audio/edge_tone_10khz_96k.wav filter=lfs diff=lfs merge=lfs -text +tests/audio/long_melody_35s_16k.mp3 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/edge_tone_10khz_96k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/edge_tone_10khz_96k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/long_melody_35s_16k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/long_melody_35s_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_birds_rain_16k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_chirp_siren_48k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_chirp_siren_48k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_chord_piano_44k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_clicks_noise_22k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/sound_clicks_noise_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_de_garten_48k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_en_parcel_8k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_en_parcel_8k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_en_train_16k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_en_train_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_es_tienda_16k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_es_tienda_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_fr_pont_44k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_fr_pont_44k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_it_mercato_22k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_it_mercato_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_pt_barco_44k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_pt_barco_44k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_sv_buss_22k.features.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/ref/speech_sv_buss_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -text +tests/audio/sound_chirp_siren_48k.flac filter=lfs diff=lfs merge=lfs -text +tests/audio/sound_chord_piano_44k_stereo.wav filter=lfs diff=lfs merge=lfs -text +tests/audio/sound_clicks_noise_22k.wav filter=lfs diff=lfs merge=lfs -text +tests/audio/speech_de_garten_48k_stereo.wav filter=lfs diff=lfs merge=lfs -text +tests/audio/speech_en_train_16k.wav filter=lfs diff=lfs merge=lfs -text +tests/audio/speech_it_mercato_22k.aiff filter=lfs diff=lfs merge=lfs -text +tests/audio/speech_pt_barco_44k.caf filter=lfs diff=lfs merge=lfs -text diff --git a/CHANGELOG.md b/CHANGELOG.md index 38ff967b083fce1e77cbb19f9c0363a6512431dd..5cd95800bdb0a3ec34c0485d95103f10fe95802e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,91 @@ # Changelog +## 1.2 — 2026-10-12 + +Audio. The audio encoder of google/embeddinggemma-2 is added, so text queries, images and audio clips share one +768-d space (a text query finds a spoken sentence or a sound; a clip finds its caption). + +- Model: new `model/embeddinggemma-2-audio.aimodel` (functions `audio_192`, `audio_384`, `audio_1024`, + `audio_1536`, `audio_3000`: log-mel frames of 10 ms → soft tokens, one function per frame bucket; up to 30 s = + 2999 frames → 750 soft tokens). Every function is one Neural Engine region, or runs entirely on the GPU. The + text asset `model/embeddinggemma-2-text-mm.aimodel` and the image asset are **unchanged** (byte-identical to + 1.1), so text and image vectors indexed with 1.1 stay valid; the audio sequence ` <|audio> [n soft tokens] + ` goes through the same `mm_` functions. +- Two compute routes for audio, chosen independently of text and images: Neural Engine (default) or GPU. Swift + `audioCompute:`, CLI `--audio-compute`, Python `audio_compute=`; default = same as `compute`. Measured on the + validation machine (M5, Swift `eg2-cli latency`), audio encoder only: 3 s clip 11 ms (Neural Engine) / 14 ms + (GPU), 10 s 24 / 19–21 ms, 30 s 86 / 50 ms; plus 7–70 ms for the clip's pass through the text encoder (`mm_128` … + `mm_1024`). +- Audio parity vs fp32 sentence-transformers on 214 generated clips (112 spoken sentences in 11 languages from + 50+ macOS `say` voices, used for local validation only and not shipped, 42 synthesized sounds, 30 edge cases, 17 + format copies, 11 long clips, 3 mixtures; features computed by the upstream extractor): embedding cosine median + 0.99996 on the Neural Engine (min 0.9981, a synthesized chord; speech ≥ 0.9983 across both validation sets) and + 0.99998 on the GPU (min 0.9994). Cross-modal retrieval (154 captions ↔ + clips, both directions): R@1 identical to fp32 on both routes (text → audio 0.545, audio → text 0.597), MRR + within 0.0005. The re-authored graph in fp32 matches the reference soft tokens to cosine ≥ 0.99999998 (213 clips). +- Exact front end: the upstream log-mel feature extractor re-implemented in numpy (`python/eg2_audio_frontend.py`, + bit-identical on 214/214 clips) and Swift (`AudioFrontend`, Accelerate FFT, within 0.006 of numpy on lossless + files). Decoding with Apple's AudioToolbox in Swift (sample-identical to libsndfile for PCM/FLAC/ALAC, AAC within 3e-7; MP3 + trimmed with the LAME tag, then within 3e-5) and with `soundfile` or `afconvert` in Python. Resampling to 16 kHz + with a Kaiser-windowed sinc shared by numpy and Swift (bit-identical to each other; the upstream libsoxr "HQ" + differs by cosine ≤ 0.007 on synthesized noise-like sounds, ≤ 0.00012 on speech, see README "Audio: decoding and + resampling"). +- Long audio: `.truncate` (the first 30 s, upstream's behaviour, default) or `.chunkMean` (mean of the 30 s + windows' embeddings): Swift `longAudio:`, CLI `--long`, Python `long_audio=`. +- Swift: `EmbeddingGemma2(bundle:compute:loadVision:imageCompute:loadAudio:audioCompute:)`, `audioCompute`, + `hasAudio`, `embedAudio(url:)`, `embedAudio(samples:sampleRate:)`, `embedAudio(samples16k:)`, + `audioSoftTokens`, `audioSequence`, `AudioDecoder`, `AudioResampler`, `AudioFrontend`, `AudioInputs`, + `LongAudioPolicy`. New CLI commands `embed-audio`, `audiocheck`, `dump-audio`; `smoke` takes the audio reference; + `latency` / `prewarm` load the audio asset unless `--text-only`; every model command takes `--audio-compute`. + The 1.0 / 1.1 API is unchanged and without `loadAudio: true` the audio asset is not loaded. +- Python: `embed_audio`, `embed_audio_16k`, `embed_audio_inputs`, `audio_soft_tokens`, `audio_sequence`, + `load_audio=` / `audio_compute=` / `--audio-compute`, the `embed-audio` command, audio in `smoke` and `latency`; + `smoke_test.py` runs the audio reference too (`--no-audio` skips it). `soundfile` is a new requirement + (`requirements.txt` installs it; without it the runner falls back to macOS `afconvert`). +- Tests: 16 generated clips (`tests/audio/`: 8 invented sentences in 7 languages (English ×2, Italian, French, + German, Portuguese, Spanish, Swedish) spoken by the eSpeak NG formant synthesizer, synthesized sounds, edge cases, + 8–96 kHz, mono/stereo, WAV/AIFF/FLAC/ALAC/AAC/MP3, a 35 s clip), `audio-smoke-reference.json` (fp32 vectors of 15 + clips and 26 caption texts), `audio-preprocess-cases.json` + `tests/audio/ref/` (the Python + front end's waveforms and features for `eg2-cli audiocheck`) and the generators. +- Exporter: `export/export.py` builds the third asset (`eg2_audio.py`, `--part audio`, `--audio-buckets`). +- Audio frame buckets are limited to the sizes validated on the Neural Engine (192, 384, 1024, 1536, 3000); other + sizes are excluded for compatibility. +- Independent validation pass (a second generated set of 287 clips, both runners, every route; README "Audio + accuracy"): Neural Engine median 0.99996 / min 0.9972, GPU min 0.9994; text and image vectors bit-identical to + 1.1 (Swift and Python, Neural Engine and GPU). Fixes from that pass: + - MP3 via Apple's decoder: some files come out with the delay trimmed but one or two whole frames too many at the + end; Swift `AudioDecoder` and the Python `afconvert` fallback now bring every tagged MP3 to the tag's gapless + length (55/55 tagged MP3s match libsndfile within 3e-5; before, 2 of the new set were one frame long). + - Python `embed_audio(array, sample_rate)` rejects a channel-first `[channels, n]` array (it was silently + embedded as an empty clip), arrays of more than 2 dimensions and a missing, zero or fractional rate. + - Swift `embedAudio(samples:sampleRate:)` rejects frame-major arrays (silently wrong before), channels of + different lengths and a non-positive rate (both crashed before). + - The CPU route is refused for audio (not supported), with a clear message, before any asset is loaded. + - README corrections: speech minimum on the Neural Engine 0.9983 (not 0.9987), MP3 sensitivity to digital + silence (0.990–0.9999, not 0.99998 for all speech), tag-less MP3 (529 samples, 0.92–0.993) and Ogg Vorbis (128 + samples) offsets of Apple's decoder, Swift log-mel within 0.006 of numpy, the audio asset leaves no MPSGraph + temp folder, measured GPU time per clip and first-load times. + +- Review fixes before release (licence/privacy review and a clean-room test of the package): + - The spoken test clips are now synthesized with eSpeak NG (rule-based formant synthesis, no voice recordings) + instead of macOS system voices, whose output may not be redistributed; Portuguese replaces Japanese (eSpeak NG's + Japanese was not recognisable enough for the model). `audio-smoke-reference.json`, `audio-preprocess-cases.json` + and `tests/audio/ref/` were regenerated; the synthesized sounds and edge cases are unchanged. + - `audioCompute: .cpu` / `audio_compute="cpu"` / `--audio-compute cpu` is refused before any asset is loaded (it + used to be checked after loading the text and image assets; in Python the error then skipped `--cleanup-temp` + and left ~358 MB of temp files). The Python CLI and `smoke_test.py` print a one-line error instead of a + traceback, and `--cleanup-temp` now also runs after an error. + - README: how to get Python 3.12 (Homebrew or uv), the full SwiftPM dependency lines (the package identity is + `swift`), `soundfile` installed by default, corrected disk and memory figures, the first-load time with all + three assets (~5 min), timings measured on AC power (1.4–1.6× slower on battery with Low Power Mode), stale 1.1 + paths, the tested-language claim, long-audio GPU figures; NOTICE: copyright holders of transformers' + `feature_extraction_gemma4.py` (Google LLC) and `audio_utils.py`, the mel-filter formula credit, tools used to + make the test audio; code comments (`Package.swift`, `Embedder.swift`, `AudioFrontend.swift`, `eg2_audio.py`). + +Upgrading from 1.1: nothing changes for text and images (same assets, same functions, same API). Load the audio +asset with `loadAudio: true` / `load_audio=True` when you need it; the first load of the new asset pays the +one-time specialization (about 90 s for the Neural Engine route on the validation machine). + ## 1.1 — 2026-10-12 Images. The vision encoder of google/embeddinggemma-2 is added, so text queries and images share one 768-d space diff --git a/CHECKSUMS.sha256 b/CHECKSUMS.sha256 index da506d9aaa1e7351f08f45b901db0439e8853f9f..126e52f0853df17c9366fa9fd17224de7df78a20 100644 --- a/CHECKSUMS.sha256 +++ b/CHECKSUMS.sha256 @@ -1,13 +1,17 @@ -eba43e8b37c1451b6d52dde5e2d0fec9adf9f8532e25c371cc905b8a7ff74b3c CHANGELOG.md +5a51bbf6a3e88dd68bdff18b0f9af0a64c51f60c745ac407be526d7743d0a178 CHANGELOG.md cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE -452793453512cf94b6bc7ebc472ee3a465088b9a9be6f7e1eee0996ce5b134bc NOTICE -6c59634a45192f864cf35e85a298b5c5ca736f046c299a8b71401b1b9873fe53 README.md +b9ac552f2eb418f79dc23cc325a7b8c38ae05c1fcc8c1880014bae281a0963a6 NOTICE +35e441a4c6176f40e460371fe0bd3ee85f5e6715f2de9d80d5cc91e191462609 README.md +af31323d3ac2646a6c520741f36c7816f393c54dfe7ef5ccd0d207e7fe49c2aa export/eg2_audio.py bb778eee49dab44fb997f67c875a615d754d54477e257d02771e94f250b4cd38 export/eg2_text.py 75b6ef5a3836fa24ecd5601ea2ca999fd222fe68986c0fd1bf47a00392cf04c2 export/eg2_text_mm.py 84effb9443f0e3183a71436796998e1d588bfa69d86a2496fb94d4c8c0b42bb6 export/eg2_vision.py -46ebe20f907d3b974cd6f82af57487781935c5acb7ded23c45c6f4daf754099d export/export.py -3c4b8ff2f44680507323c83e5d1765835edada530765550e6f916fb47d0ae7f2 model/MODEL-ATTRIBUTION.json -0e22b6bd07af788f61e0ffa0dd5492e33108250495ce5b2297ce4d83d68efbf5 model/config.json +5b1076b875845ee0289c7c68f1209419b50b494d7bda082165c58dcd2690572e export/export.py +7951556c4559c8609cf67715acc53e58d8c70f7f62242494d7858406b1bbe2f7 model/MODEL-ATTRIBUTION.json +0204c8d4532f6930709c3c8eb7f7b25b54e4be42aa7b8c6c397fc17e872fb7bf model/config.json +e8e6db4dcacc0a21bbc0b981420753b44ab561c516a673fe5e9db986c7266b78 model/embeddinggemma-2-audio.aimodel/main.hash +9ca590b09b327f7a8cae94ccace30d151621ae57a4a3f2a8b654145bc1df95f8 model/embeddinggemma-2-audio.aimodel/main.mlirb +dc64e3f52ce6778c0c9e5f58157f328a9f081b21deb5eca74e333fcd4b8f15f6 model/embeddinggemma-2-audio.aimodel/metadata.json ea089710e57b22972d6ab4d4b960b385394b81f333ba2f75b4fb4aac1d238e6f model/embeddinggemma-2-text-mm.aimodel/main.hash 0b51638f2d17794825de21def6ab485d968fdf412853ea209617623a51f1bbde model/embeddinggemma-2-text-mm.aimodel/main.mlirb 8984123cfdb32ba8cf526a1f3a41571205475aff40b3f1d65494f476f115f8a6 model/embeddinggemma-2-text-mm.aimodel/metadata.json @@ -16,19 +20,74 @@ ce93c518c185454be41b493738f9ab3d5b662dd0306d1007cd4e12ad4c0baaa5 model/embeddin 45bb764a8df5e1b2a6ef4260d4dd006a57dc7af4f408f07ed2976022cd39390c model/embeddinggemma-2-vision.aimodel/metadata.json 4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 model/tokenizer/tokenizer.json 17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 model/tokenizer/tokenizer_config.json +7fda3a163630254dd777c854b591fa3b290eecf43fc87874dab7a44c34c08343 python/eg2_audio_frontend.py 5879dd6a20d7fc66fff212d5c74503ddaa628eef5b8e05e8b974bb5c8659e2f2 python/eg2_image.py -3c076b19910efdc741cafadf5565c4205a36aae847102ceba5e5f6176fc9d699 python/embeddinggemma2_coreai.py -fe37b2abfaa762f68e80ecd5ca9ad62968c170b87943d5c27d3fc209cd18245e python/requirements.lock -53a450a96e6185a9ea05f9834c7a8e6b227124b90c78ccb9c9f21d9402573042 python/requirements.txt -1ee2fe2d6effd6f347d4e5164a8d00e806a280379101cb7c573636bcb70afcda python/smoke_test.py -02ed112242f7fad88429c645cddb20bd6fa7797ba8c02fa17a5cacaf80102b55 swift/Package.swift -10e088ec01cbba052e8214d3ae87ecea6606227fa5a9fefcb35793a6635f7d7c swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift -7b99edfefc47a343d07df32a3b06a8da2f94a49ae0a8e299e733c1a44c09e38f swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift +56d528a06f0e3023d8014f085202a7669ddfe18151dc663dd02b570e76a10e76 python/embeddinggemma2_coreai.py +4810309e44023efe0879465f631a63863d68eb7719ffddcb0df626c58f7c0de2 python/requirements.lock +445a1161b6ade113db251b71798b765e751f8aade67405755dbbeaf19bcb62d3 python/requirements.txt +3265d3ab97f53a765ca2c56bc62fc89dfd4e2fca5b404d4be34e0f65cbfa0aef python/smoke_test.py +ef0b32f69dd40ae0741106429f8fa4fe6851521227ba364334e5d32c03d31782 swift/Package.swift +deac17f843673a60141c98df5382ca998f5da3d4c71f3bbe7388b0abbbf255a9 swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swift +0ff2b33d299e4382ce8f83e89ec8b82e104d417721829f50a450451c09fd474d swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swift +b7c43cc7f0b753a65effd7ad909f7f61b7c62e2b544f4052b58e4f5fee097993 swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swift +c2e94d3a82d2d0829e0182cf258a4eaec1cbece2e26f4d45d8f6c0411d82096a swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift +5d73797991ed17635d4aedfbd6c59df19024cf2e8f3c2c7293e6457c23c430b4 swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift 4f5ef8a454a84937e503ba99c9f05e237347178933a442f2352a2c5db0ad87eb swift/Sources/EmbeddingGemma2CoreAI/GemmaTokenizer.swift ce2f6a31d65894386ad90087db4b7eb8e0e0e77f3ad2402d8cba64e94f80d38c swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swift 970be86b313ba24206ce7034f2082d71b672dda8e1b7d4da05912b587208d062 swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swift af5dd321e1a9f0e7c146f37b21a4b2963cf4c69fe01555568e8b10397003ae26 swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swift -b01a994c45db681fa007709a5311d04befdbfbc0d374cdb1fa91c83cba6c7c0c swift/Sources/eg2-cli/main.swift +0415062c5277e66a7a363ce974a9405c25be6718578a9fe168be9105d64e003e swift/Sources/eg2-cli/main.swift +643f8a8dc8bd9c19225afffad2becfec5426180b3749cb208abdf1a6c8354efc tests/audio/edge_silence_1s_16k.wav +10e19f462aa13cbed8333dac47eaafd349f6d7850118060fbddc777e6b3f9bd3 tests/audio/edge_tiny_100smp_16k.wav +381583606c2987aff0e9ae56fc6d2af8d247e125b7ae59d0673c158a9d5fd431 tests/audio/edge_tone_10khz_96k.wav +9c9dc64b6d46a70f3a680f3d0e957436f31174fc84618c23fb1abe19920b3b39 tests/audio/long_melody_35s_16k.mp3 +007cda760aa83100c95dfcc8bb34557cb20a7cca8ea98a87a21f3a94952f3c3b tests/audio/manifest.json +686d8f234eec98a082e45c5f291db725fb966aaba896d1e7e7edfe82c27a42ba tests/audio/ref/edge_silence_1s_16k.features.f32 +4f7988030a00d082fe445e00a2ac5dab502300ff1b80e8592dd569867b60ef74 tests/audio/ref/edge_silence_1s_16k.wave16k.f32 +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tests/audio/ref/edge_tiny_100smp_16k.features.f32 +42d99bd225d1e32ad26fe623cfbbe01f0df0aaba3e7966f5055a270d9bea9548 tests/audio/ref/edge_tiny_100smp_16k.wave16k.f32 +19b6e0b19a4dc3aac04d0e979910d85c83ebb7815c837fb4045a3cebdaf7ee84 tests/audio/ref/edge_tone_10khz_96k.features.f32 +2567b77a52392e8f0dc40bade829a63374eb026bedf494e15ed28c1f0e56c4ba tests/audio/ref/edge_tone_10khz_96k.wave16k.f32 +6f4638c771e3a3b5180a4509e1a55bbc713e3616634ec468cf3812284bfd7d98 tests/audio/ref/long_melody_35s_16k.features.f32 +d4a6b9daa6f1e4385cf1310f05431fa785da244ca2b0932133016651384c846c tests/audio/ref/long_melody_35s_16k.wave16k.f32 +53b924a3b71bb2478852a8d1ca493e91308b3359d85ace339e15a2590da946ca tests/audio/ref/sound_birds_rain_16k_stereo.features.f32 +e425c153bdc58bd84e73dbde653146597cf3ed1606a9fa569ffa59fe007f6934 tests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f32 +2ad38e26bb8bf5c209d1a20468ecdbf1fede29373e9a5d85ae3fcab59a99816b tests/audio/ref/sound_chirp_siren_48k.features.f32 +bb52eff27889c682d46cbcdc984f7e1b41f59b36fd1671c0d8903a4ce88666e0 tests/audio/ref/sound_chirp_siren_48k.wave16k.f32 +466751ffa6f1909515eb5693e7375c240ae2ef9130d7e9c8abf54162a8545386 tests/audio/ref/sound_chord_piano_44k_stereo.features.f32 +e45747d1b1c14a21050f2614c58684be77cb3d85c343e6e697ae996458ff8252 tests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f32 +2e115ff7e33f3f116fd1336f8142d80ced4610b5f9543c5af0932865d883cce9 tests/audio/ref/sound_clicks_noise_22k.features.f32 +33fd0381a39409fee2e421e90dd353885120268644e7b8ae676e5d550cef26a9 tests/audio/ref/sound_clicks_noise_22k.wave16k.f32 +8bec6c3cafd40c2cfd464fb864da306f32b0eb3a6f8abb6d440251126f555ba4 tests/audio/ref/speech_de_garten_48k_stereo.features.f32 +c20659bd84f7bfd6fe9e695238cb4917fd981cde5f075e3c81fad3dd1dfa00a3 tests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32 +790833ec67d07977f1d685f89a8b64897e618dc7d08924c4edd0e94b869db258 tests/audio/ref/speech_en_parcel_8k.features.f32 +513961580f843da853465b58dd96f1c55f5aeea5e1550b8c0ec9cae7e43a0f3d tests/audio/ref/speech_en_parcel_8k.wave16k.f32 +1b2dc5139da71d6e674078bdb46b29a38b646b539ee496c99928730e16988916 tests/audio/ref/speech_en_train_16k.features.f32 +8e1da811c75c5865f0ceaf6ca163a908acc6adab7d4431e90f2f0cdad8fe586a tests/audio/ref/speech_en_train_16k.wave16k.f32 +27db536530247de6a9c2129ff539e73ae1cf78529623004414fbd2b744f16bdf tests/audio/ref/speech_es_tienda_16k.features.f32 +75744fbf5dd270d45ebdd00530e01b614f04682b81f7cefb1c408dcb76973f5f tests/audio/ref/speech_es_tienda_16k.wave16k.f32 +032bc989d3a63bb10cdd04aa79dd2eb484503e3cc30f94f885a19da1070c27da tests/audio/ref/speech_fr_pont_44k.features.f32 +c28ab5b7458eceb6aebc3eab40a5dddbf842988401d4ac9fc06858187a1c2a82 tests/audio/ref/speech_fr_pont_44k.wave16k.f32 +c82d988458dd9c4b1b5654f31865573836dbfe458c53f8679100cbc77416ee9a tests/audio/ref/speech_it_mercato_22k.features.f32 +0cd3fd6073a9613f12eaa2ecd339fb01264b31ef0847a354858e373efc6ccd5f tests/audio/ref/speech_it_mercato_22k.wave16k.f32 +c02cf5d84f82ec039f7079842ab5881be8d40663da262f8e6044b00bee97f3a5 tests/audio/ref/speech_pt_barco_44k.features.f32 +8a515f30e332f31c86c7f076b9d9a9b9e157bb75b91cc7556fca62637b946506 tests/audio/ref/speech_pt_barco_44k.wave16k.f32 +0e24839f583281e4580159b30b6436fb725d4ad40feb5aec3314ddc0958d4a60 tests/audio/ref/speech_sv_buss_22k.features.f32 +ac3f69f92163a571ff4e0a067e3b42a12a394376593bf7ea57a8c3edfcc412ee tests/audio/ref/speech_sv_buss_22k.wave16k.f32 +bb710fc775183d51613c20eda273cef3d934ef8f56033afa1a672d83386beccb tests/audio/sound_birds_rain_16k_stereo.m4a +7cfefb8e87712771eab7ec4a077e31cf215933ec57f1006d07155ab153b161fb tests/audio/sound_chirp_siren_48k.flac +007af1d5cfe64d8de9773b95ed787360fd3e8e2a12198f8d21a5bb694fdf4a13 tests/audio/sound_chord_piano_44k_stereo.wav +4963f45f47e82a95d3fe5dd0b5fc43ae3ffcfb1dee483c7122e3416de85dda58 tests/audio/sound_clicks_noise_22k.wav +5dfb55fe58589119faf8af3059480c8dfd50b8f74036c625e96be9afe9bb28fd tests/audio/speech_de_garten_48k_stereo.wav +3427d488a828f85ff7e08ea76719f0aa992b81632f0366403ed44973e50001ca tests/audio/speech_en_parcel_8k.wav +e858470982ce2d7d9b59bf4381a17375234da9007c71f9a17737c7bfc1950949 tests/audio/speech_en_train_16k.wav +e9186c1f6982efa2f6154e4283cc082b090546708de1b0bd7d9de44278d2f7c8 tests/audio/speech_es_tienda_16k.flac +9ddd4783a6a96b5ad47fd07db884089f7c53b8b46960a1e373d9432f3d4e744c tests/audio/speech_fr_pont_44k.m4a +e099fec89f94386a59c73b88f71c1d26566ba37d9b0b39ee7fe9e0eb1f801cac tests/audio/speech_it_mercato_22k.aiff +90b1561f496f9de9a75229f8424405ac9706e8a716f927f0f4053bd6f1eacf0e tests/audio/speech_pt_barco_44k.caf +c763fade16da3626a93580442b5f7a635adbf17299e7e8f13e98ed18e1bc8410 tests/audio/speech_sv_buss_22k.mp3 +e4a2e6915106767933b58537367ffe8e5ee1ea761f72d048bb9209ceb7608e7e tests/audio-preprocess-cases.json +363a092fe6132a6774535a4bfbb851f0cba2c4c5ef812226b273fd4adc4cc99b tests/audio-smoke-reference.json 11f9e4ccd9e8ea626351f7f4b049ced15a74f53f14fe362bf856a15c184631e2 tests/check_preprocess.py 15c72e722e5743d9fc21337b3ec9ce92dc4c485c58cedb7385f92281567f1002 tests/image-smoke-reference.json 47f27fcdfac105cf72c250c85583ca862137d511840a67e40d547e3b49796af3 tests/images/chart_bar.png @@ -44,9 +103,12 @@ d0b2bd592499a3244a337c47bd8ce91c6d77542f0eb4b463c499016e1e3bddce tests/images/i 363dd39880ce42d00f459466680bd30bee9ab164be4fbddb2411b42937f2aeb6 tests/images/shape_red_circle.png 0c394a7842a1cf2068ca87cf16341677d8d0008893b73b69cf9281dbf0d515cd tests/images/slide_launch.png ba808ff8c33ef4232aaf13a9736c7c02b57c5881a8456a1344b3d3ac04001828 tests/images/ui_login.png +deaa4467cc00c918973913d294f5ec2c2488708db2684a5dccff83841cbcdc4f tests/make_audio_preprocess_cases.py +373918597ab9e095dbf930e03b1b90ddc395f82009fb571ff96eca9ef74cec64 tests/make_audio_smoke_reference.py 36f3a7c12829aacc5360a0f918c6dccd5584a8805b9ca43f99e0e7b5f6467a3c tests/make_image_smoke_reference.py a0e4c0d5559148d26eb1949316d31bb806a17fca4ed0a7e2f481b075103418bf tests/make_preprocess_cases.py 1df8f74c85f4a02be0caaf4b99ee0bb8f4cfc1759ad091fdf65a98fdea917df8 tests/make_smoke_reference.py +1a60f0b6369cc7d063d3c24fdf4498785361f5a8a800d6ac68c95cddac1bdb84 tests/make_test_audio.py e78e8cab57918747717bbcce74509f183a2def72a7450cf2a363b1d5f504ac50 tests/make_test_images.py 07daa7415beb15e9049a307aa17bf048ba2edaa0613301293e6250a66ed552b8 tests/make_tokenizer_cases.py b580d5bc45d7fb4039e79e88008d7e40e530afb4f9c504abb0befaf6f46fbaaa tests/preprocess-cases.json diff --git a/NOTICE b/NOTICE index 83933b791ef4d9493b6deed3a6e8e0cdd6b9a7b3..1b1c47ea6650ccbcb6ad4ec96e866b002226ef44 100644 --- a/NOTICE +++ b/NOTICE @@ -1,4 +1,4 @@ -EmbeddingGemma-2-CoreAI v1.1 +EmbeddingGemma-2-CoreAI v1.2 ============================ This package contains a derivative of the EmbeddingGemma 2 model. @@ -23,13 +23,13 @@ google/embeddinggemma-2 and are covered by the same license and attribution. MODIFICATIONS (Apache License, Section 4(b)) -------------------------------------------- -Changes made to google/embeddinggemma-2, 11-12 October 2026, to produce model/embeddinggemma-2-text-mm.aimodel -and model/embeddinggemma-2-vision.aimodel. +Changes made to google/embeddinggemma-2, 11-12 October 2026, to produce model/embeddinggemma-2-text-mm.aimodel, +model/embeddinggemma-2-vision.aimodel and model/embeddinggemma-2-audio.aimodel. -Text encoder (v1.0, unchanged in v1.1 except where noted): +Text encoder (v1.0, unchanged in v1.1 and v1.2 except where noted): 2026-10-11 The audio encoder of the multimodal checkpoint was dropped (v1.0 also dropped the vision - encoder; v1.1 adds it back, see below). + encoder; v1.1 adds the vision encoder back and v1.2 the audio encoder, see below). 2026-10-11 The encoder architecture (24 bidirectional Gemma 4 layers, per-layer embeddings, RMSNorm with max-abs rescaling, RoPE, GQA/MQA attention, GELU-tanh MLP, final RMSNorm, 512->768 projection, masked mean pooling, L2 normalization) was re-authored in plain PyTorch for the Core AI @@ -85,6 +85,39 @@ Added in v1.1: kernel used by torchvision) re-implemented in numpy and in Swift so that the pixels fed to the model are identical to the reference pipeline. +Added in v1.2: + + 2026-10-12 Audio encoder (Gemma 4 audio model: two stride-2 subsampling convolutions with channel LayerNorm, + a 1024->1024 projection, 12 conformer layers of half-step feed-forward, local causal attention with + relative-position bias, light depthwise convolution, half-step feed-forward and RMSNorm, the + 1024->1536 output projection) and the audio embedder (RMSNorm without scale + 1536->512 projection) + re-authored in plain PyTorch for the Core AI converter. The weights are the original ones rounded + from bfloat16 to float16, with the scale folds listed below. + 2026-10-12 Audio attention written in its banded form: the upstream chunked local attention (chunks of 12, + 13 of left context, pad / unfold / rel-shift) lets every token see itself and the 11 previous + tokens; the port computes exactly those 12 logits per token, logit[t, d] = q_t . (k_{t-d} + + relk_d), where relk_d = relative_k_proj(sinusoid(d)) is precomputed per layer as a constant. The + query scale (128^-0.5 / ln 2 times softplus(per_dim_scale)) and the key scale (ln(1 + e) / ln 2) + are folded into q_proj / k_proj and their output clip bounds. The masked_fill(-1e9) of padded keys + is an additive -10000; the gradient-clipping clamps (+-1e10, no-ops in inference) are dropped; the + 120 clipped linears keep their clip bounds. Mathematically identical to the reference (fp32 + soft-token cosine >= 0.99999998 on 213 clips, max abs diff 8e-4). + 2026-10-12 Audio fp16 handling for the Neural Engine: every RMSNorm (including the scale-free one of the + audio embedder) divides the row by its max-abs value before squaring (the residual stream reaches + ~412), divisions are expressed as rsqrt(x)*rsqrt(x), the logit softcap is tanh(x/50)*50. + 2026-10-12 Audio: fixed frame buckets 192, 384, 1024, 1536 and 3000 frames of 10 ms (functions audio_); + inputs longer than 30 s are truncated by the host, as upstream does by default. The three masks + (frames, after the first convolution, tokens) are host inputs. The bucket set is limited to the + sizes validated on the Neural Engine. + 2026-10-12 Audio preprocessing (host side, not part of the model): the upstream feature extractor's log-mel + computation (30 s truncation, 160-sample left pad, 320-sample periodic Hann frames every 160 + samples, 512-point magnitude FFT, 128 HTK mel bands 0-8000 Hz without normalization, ln(mel + + 0.001), frame validity rule) re-implemented in numpy and in Swift; the mono mix (mean of the + channels) as librosa does it; resampling to 16 kHz with a Kaiser-windowed sinc low-pass of our own + (pass band 0.913 and stop band 1.0 of the lower Nyquist, 125 dB) instead of the libsoxr "HQ" + resampler that librosa.load uses upstream (the only intended deviation from upstream in the audio + pipeline; README gives the measured difference). + 2026-10-11/12 Converted with coreai-torch 0.4.3 / coreai-core 1.0.0b3 on torch 2.9.0 to the Core AI .aimodel format (macOS 27). @@ -94,14 +127,26 @@ The exporter in export/ reproduces these changes from the original checkpoint. THIRD-PARTY ATTRIBUTIONS ------------------------ -HF transformers (Apache-2.0, Copyright 2026 The HuggingFace Team). export/eg2_text.py re-authors the -architecture described by modeling_embedding_gemma2.py / configuration_embedding_gemma2.py, and -export/eg2_vision.py the vision model and vision embedder described by modeling_gemma4.py / -modeling_embedding_gemma2.py, from transformers 5.19. The host-side image preprocessing (python/eg2_image.py, -swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swift) ports the logic of image_processing_gemma4.py, -including its aspect-preserving size rule (`get_aspect_ratio_preserving_size`). No transformers source files -are included in this package; the re-authored and ported modules carry their own Apache-2.0 header and credit -transformers. +HF transformers (Apache-2.0; Copyright 2026 The HuggingFace Team for the modeling, configuration and image-processing +files named below, Copyright 2026 Google LLC for feature_extraction_gemma4.py, Copyright 2023 The HuggingFace Inc. +team and the librosa & torchaudio authors for audio_utils.py). export/eg2_text.py re-authors the +architecture described by modeling_embedding_gemma2.py / configuration_embedding_gemma2.py, export/eg2_vision.py +the vision model and vision embedder, and export/eg2_audio.py the audio model (Gemma4AudioModel) and audio +embedder, all described by modeling_gemma4.py / modeling_embedding_gemma2.py, from transformers 5.19. The +host-side image preprocessing (python/eg2_image.py, swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swift) +ports the logic of image_processing_gemma4.py, including its aspect-preserving size rule +(`get_aspect_ratio_preserving_size`); the host-side audio front end (python/eg2_audio_frontend.py, +swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swift) re-implements the log-mel feature extraction described by +feature_extraction_gemma4.py with the defaults sentence-transformers uses for this model, and the HTK mel filter +bank formula (as in librosa / torchaudio) of transformers' audio_utils.py (HTK scale, no normalization). No +transformers source files are included in this package; the re-authored and ported modules carry their own +Apache-2.0 header and credit transformers. + +librosa (ISC) and libsoxr (LGPL-2.1+) are what upstream uses to load and resample audio files; neither is included, +and no librosa or libsoxr code is ported; the HTK mel filter formula above is the one librosa and torchaudio also +implement (credited through transformers' audio_utils.py). The resampler in this package is our own design (a +Kaiser-windowed sinc, see MODIFICATIONS); the decode-mono-resample order and the output-length rule follow what +librosa.load does, re-implemented from its documented behaviour. PyTorch / ATen (BSD-3-Clause, notice below). The integer antialiased bicubic resize in python/eg2_image.py and swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swift is ported from the logic of ATen's uint8 @@ -119,9 +164,14 @@ FluidInference Core ML port of EmbeddingGemma 2 (Apache-2.0, https://huggingface dividing each RMSNorm row by its max-abs value to keep fp16 in range was taken from the README of that port and re-derived independently; no code was copied from it. Nothing else in this package derives from it. -Apple Core AI (coreai-torch, coreai-core, the CoreAI framework), ImageIO and Core Graphics: used as tools and -runtime, not redistributed. Hugging Face tokenizers (Apache-2.0): used by the Python runner and to generate the -test fixtures; not redistributed. +Apple Core AI (coreai-torch, coreai-core, the CoreAI framework), ImageIO, Core Graphics, AVFoundation / AudioToolbox +(audio decoding) and Accelerate (vDSP FFT and dot products): used as tools and runtime, not redistributed. Hugging +Face tokenizers (Apache-2.0): used by the Python runner and to generate the test fixtures; not redistributed. +python-soundfile / libsndfile (BSD-3-Clause / LGPL-2.1+): audio decoder of the Python runner (installed by +python/requirements.txt, not redistributed) and the decoder of the audio reference fixtures; not redistributed. +eSpeak NG (GPL-3.0-or-later): used as a tool to synthesize the spoken test clips (tests/make_test_audio.py); no part +of it is included. FFmpeg with libmp3lame (LGPL / GPL): used as a tool to encode the MP3 test clips and to decode +AAC for the reference fixtures; not included. TRADEMARKS @@ -135,8 +185,8 @@ OUR OWN CODE ------------ Everything in this package that is not the model weights or the tokenizer files, i.e. the exporter -(export/), the Python runner (python/), the Swift library and command-line tool (swift/), the tests and test -images (tests/) and the documentation, is +(export/), the Python runner (python/), the Swift library and command-line tool (swift/), the tests, test +images and test audio clips (tests/) and the documentation, is Copyright 2026 Everpaper Licensed under the Apache License, Version 2.0 (LICENSE). @@ -145,10 +195,12 @@ The parts ported from transformers, PyTorch and Pillow (see THIRD-PARTY ATTRIBUT those projects' licenses: Apache-2.0 for transformers (LICENSE), and the PyTorch and Pillow notices reproduced below. -The test texts and test images are written or rendered from code (tests/make_*.py). The people, companies, -products, numbers and events in them are invented; a few real place names and common words that are also -brand names (for example in the chart and invoice test images) appear only as fictional content, with no -reference to any real business. +The test texts, test images and test audio clips are written, rendered or synthesized from code (tests/make_*.py). +The people, companies, products, numbers and events in them are invented; a few real place names and common +words that are also brand names (for example in the chart and invoice test images) appear only as fictional +content, with no reference to any real business. The spoken clips are invented sentences synthesized with the +eSpeak NG formant synthesizer, which generates speech from rules and formant parameters rather than from voice +recordings; no recording of a person is included or was used. THIRD-PARTY LICENSE NOTICES diff --git a/README.md b/README.md index da266ec3547347170dff0d11626e43fac7a850dc..871d610307348afe041e93cb0d095c6b50a7ce8e 100644 --- a/README.md +++ b/README.md @@ -13,18 +13,22 @@ tags: - sentence-similarity - image-embeddings - image-feature-extraction + - audio-embeddings + - audio-feature-extraction - multimodal - text-to-image-retrieval + - text-to-audio-retrieval - gemma - macos --- -# EmbeddingGemma 2 for Apple Core AI (text + images) +# EmbeddingGemma 2 for Apple Core AI (text + images + audio) [google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) (Gemma 4 family, 768-d Matryoshka -embeddings) converted to Apple's **Core AI** runtime for **macOS 27 on Apple silicon**: the text encoder and, -since 1.1, the image encoder, in one shared 768-d space. A screenshot, a chart, a slide or a photo becomes one -vector, and the vector of the query "bar chart of lamp units sold per city" lands next to it. +embeddings) converted to Apple's **Core AI** runtime for **macOS 27 on Apple silicon**: the text encoder, since +1.1 the image encoder and since 1.2 the audio encoder, in one shared 768-d space. A screenshot, a chart, a slide, +a photo, a voice memo or a sound becomes one vector, and the vector of the query "bar chart of lamp units sold per +city" (or "the night train to the coast") lands next to it. - **Text** — everything `SentenceTransformer("google/embeddinggemma-2").encode()` does for text runs in one graph: token embedding, 24 bidirectional encoder layers, final norm, 512→768 projection, masked mean pooling and L2 @@ -35,6 +39,11 @@ vector, and the vector of the query "bar chart of lamp units sold per city" land Swift and numpy. Two compute routes for images, both shipped and validated: the **Neural Engine** (default, ~0.37 s per image, ~2 ms of CPU, almost no GPU) or the **GPU** (~0.13 s per image, about 3× faster, more power), chosen independently of the text route (see "Images: Neural Engine or GPU"). +- **Audio** — the 12-layer conformer audio encoder turns up to 30 s of audio into 25 soft tokens per second that go + through the same text encoder, exactly as upstream does, plus the exact host-side front end (decode, mono, + 16 kHz, log-mel) in Swift and numpy. Neural Engine (default, 18 ms end to end for a 3 s clip, 0.16 s for 30 s, + ~1–2 ms of CPU) or GPU (22 ms / 0.12 s), chosen independently of text and images (see "Audio: Neural Engine or + GPU"). Speech (18 languages tested), music, sounds: a text query finds the clip and a clip finds its caption. Ported by Everpaper — everpaper.app. Weights are the original ones (bf16 rounded to fp16), with a few constant scales folded in and unused position rows cut (listed in NOTICE). Apache-2.0, see @@ -43,70 +52,102 @@ scales folded in and unused position rows cut (listed in NOTICE). Apache-2.0, se ## Download ```bash -hf download iannedev/embeddinggemma-2-coreai --local-dir EmbeddingGemma-2-CoreAI-v1.1 -cd EmbeddingGemma-2-CoreAI-v1.1 +hf download EverPaper/embeddinggemma-2-coreai --local-dir EmbeddingGemma-2-CoreAI-v1.2 +cd EmbeddingGemma-2-CoreAI-v1.2 ``` (`hf` comes with `pip install -U huggingface_hub`.) Then run one of the quick starts below; both begin with a -smoke test that checks the model on your machine. Text only? Add `--exclude "model/embeddinggemma-2-vision.aimodel/*"` -to skip the 293 MiB image encoder. - -## What's new in 1.1 - -- **Images**: `model/embeddinggemma-2-vision.aimodel`, `embedImage` / `embed_image` in both runners, exact image - preprocessing, image smoke tests. Video and audio are not included (see "Limits"). -- **Two image routes**: the image encoder runs on the Neural Engine (default) or on the GPU, set independently of - the text route (`imageCompute:` / `image_compute=` / `--image-compute`). -- **Text is unchanged**: the text asset is now `embeddinggemma-2-text-mm.aimodel` (functions `mm_`, the v1.0 - encoder plus an input for image soft tokens). With no image in the sequence its outputs are **bit-identical to - v1.0** (466 texts, every bucket, including texts that moved from the 256 or 512 bucket to the new 288 - bucket), so vectors indexed with 1.0 stay valid. The 256 bucket became 288. -- **Same API**: the Swift library `EmbeddingGemma2CoreAI`, the `eg2-cli` tool and the Python - `EmbeddingGemma2CoreAI` class keep their 1.0 names and calls; without `loadVision: true` / `load_vision=True` - they load the text asset only, as before. Code that calls the `.aimodel` functions directly: see CHANGELOG.md - ("Upgrading from 1.0"). Version 1.0 remains available as the repository's earlier revision. +smoke test that checks the model on your machine. Text only? Add `--exclude "model/embeddinggemma-2-vision.aimodel/*" +--exclude "model/embeddinggemma-2-audio.aimodel/*"` to skip the 293 MiB image encoder and the 562 MiB audio +encoder (or only one of them). + +## What's new in 1.2 + +- **Audio**: `model/embeddinggemma-2-audio.aimodel` (functions `audio_192` … `audio_3000`, one per frame bucket), + `embedAudio` / `embed_audio` in both runners, the exact audio front end (decode, mono, 16 kHz, log-mel) in Swift + and numpy, audio smoke tests and 16 generated test clips. Up to 30 s per clip (the model's window, as upstream); + longer audio is truncated or, on request, embedded as the mean of its 30 s windows. +- **Two audio routes**: the audio encoder runs on the Neural Engine (default) or on the GPU, set independently of + text and images (`audioCompute:` / `audio_compute=` / `--audio-compute`). +- **Text and images are unchanged**: the text and image assets are byte-identical to 1.1, so vectors indexed with + 1.1 (and text vectors indexed with 1.0) stay valid. The audio sequence goes through the same `mm_` functions. +- **Same API**: without `loadAudio: true` / `load_audio=True` nothing changes; the audio asset is not even loaded. + +What was new in 1.1: images (`model/embeddinggemma-2-vision.aimodel`, `embedImage` / `embed_image`, exact image +preprocessing, two image routes); the text asset became `embeddinggemma-2-text-mm.aimodel` (functions `mm_`, +bit-identical to the 1.0 text encoder with no image in the sequence; the 256 bucket became 288). Versions 1.0 and +1.1 remain available as the repository's earlier revisions; see CHANGELOG.md. ## What is in the package ``` -EmbeddingGemma-2-CoreAI-v1.1/ +EmbeddingGemma-2-CoreAI-v1.2/ README.md, LICENSE, NOTICE, CHANGELOG.md, CHECKSUMS.sha256 model/ embeddinggemma-2-text-mm.aimodel/ text encoder, functions mm_32 … mm_2048 (fp16, 632.2 MB = 602.9 MiB) embeddinggemma-2-vision.aimodel/ image encoder, function vision_2520 (fp16, 307.0 MB = 292.8 MiB) + embeddinggemma-2-audio.aimodel/ audio encoder, functions audio_192 … audio_3000 (fp16, 589.3 MB = 562.0 MiB) config.json assets, buckets, shapes, special ids, prompts, Matryoshka dims tokenizer/ tokenizer.json + tokenizer_config.json, unchanged from google/embeddinggemma-2 MODEL-ATTRIBUTION.json base model, checkpoint sha256, exporter versions, modification list swift/ SwiftPM package: library `EmbeddingGemma2CoreAI` + tool `eg2-cli` (no third-party dependencies) - python/ embeddinggemma2_coreai.py (library + CLI), eg2_image.py (exact image preprocessing), smoke_test.py, - requirements(.lock) + python/ embeddinggemma2_coreai.py (library + CLI), eg2_image.py (exact image preprocessing), + eg2_audio_frontend.py (exact audio front end), smoke_test.py, requirements(.lock) tests/ smoke-reference.json + tokenizer-cases.json (text), images/ (12 generated test images), - image-smoke-reference.json, preprocess-cases.json, check_preprocess.py, and the generators - export/ eg2_text.py, eg2_text_mm.py, eg2_vision.py, export.py: reproduce both assets from the checkpoint + image-smoke-reference.json, preprocess-cases.json, check_preprocess.py, audio/ (16 generated clips + + ref/ front-end references), audio-smoke-reference.json, audio-preprocess-cases.json, and the generators + export/ eg2_text.py, eg2_text_mm.py, eg2_vision.py, eg2_audio.py, export.py: reproduce the assets from the checkpoint ``` ## Requirements -- macOS 27.0 or later on Apple silicon (validated on an M5 with 24 GB; macOS 27.0 build 26A5406e, Xcode 27 beta). -- Swift: Xcode 27 / Swift 6 toolchain; the `CoreAI`, `ImageIO` and `CoreGraphics` frameworks of the macOS 27 SDK. -- Python (runtime): Python 3.12 (the validated version; 3.14 with numpy 2.5 also passed the smoke tests), Apple's - `coreai-core` Python runtime (provides `coreai.runtime`), `numpy`, `tokenizers`, and `pillow` for images (`python/requirements.txt`; the exact validated versions are in - `python/requirements.lock`). Only the exporter (`export/`, optional) needs torch 2.9.0. -- Disk: 971 MB for `model/` (926 MiB). The system keeps a per-app specialization cache under - `~/Library/Caches/coreai-cache/` (about 1.4 GB for the text asset, more with the image asset). +- macOS 27 or later on Apple silicon (validated on an M5 with 24 GB). +- Swift: Xcode 27 / Swift 6 toolchain; the `CoreAI`, `ImageIO`, `CoreGraphics`, `AVFoundation` (audio decoding) + and `Accelerate` (audio FFT) frameworks of the macOS 27 SDK. +- Python (runtime): Python 3.12 (the validated version; 3.14 with numpy 2.5 also passed the text smoke tests). macOS + does not ship 3.12: install it with `brew install python@3.12` or `uv python install 3.12` (see "Quick start — + Python"). `python/requirements.txt` installs Apple's `coreai-core` Python runtime (provides `coreai.runtime`), + `numpy`, `tokenizers`, `pillow` (images) and `soundfile` (audio decoding with libsndfile, the decoder upstream + uses; if it is missing, the runner falls back to macOS `afconvert`). The exact validated versions are in + `python/requirements.lock`. Only the exporter (`export/`, optional) needs torch 2.9.0. +- Disk: 1.56 GB for `model/` (1488 MiB): text asset 0.63 GB, image asset 0.31 GB, audio asset 0.59 GB, tokenizer + 0.03 GB (text + image assets 0.94 GB, 0.97 GB with the tokenizer). The system keeps a per-app specialization + cache under `~/Library/Caches/coreai-cache/` (about 1.4 GB for the text asset, 5.5 GB with the image and audio + assets). +- Memory with all three assets loaded on the Neural Engine: Python ~415 MB process footprint plus ~2.1 GB on the + Neural Engine (the audio asset accounts for ~1.4 GB of it: five functions); the Swift CLI reported ~300 MB plus + ~0.77 GB. 16 GB Macs: fine; 8 GB Macs were not tested. ## Quick start — Swift +Add the package to your app's `Package.swift`. SwiftPM names a local package after its folder, so the package +identity is `swift`: + +```swift +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "MyApp", + platforms: [.macOS("27.0")], + dependencies: [.package(path: "…/EmbeddingGemma-2-CoreAI-v1.2/swift")], + targets: [ + .executableTarget(name: "MyApp", dependencies: [.product(name: "EmbeddingGemma2CoreAI", package: "swift")]), + ] +) +``` + ```swift -// Package.swift: .package(path: "…/EmbeddingGemma-2-CoreAI-v1.1/swift"), product "EmbeddingGemma2CoreAI" import Foundation import EmbeddingGemma2CoreAI -let pkg = URL(fileURLWithPath: "…/EmbeddingGemma-2-CoreAI-v1.1") // the downloaded package folder +let pkg = URL(fileURLWithPath: "…/EmbeddingGemma-2-CoreAI-v1.2") // the downloaded package folder let modelURL = pkg.appendingPathComponent("model") -let model = try await EmbeddingGemma2(bundle: modelURL, compute: .neuralEngine, loadVision: true) +let model = try await EmbeddingGemma2(bundle: modelURL, compute: .neuralEngine, loadVision: true, loadAudio: true) // images on the GPU instead (≈3× faster, more power), text stays on the Neural Engine: // let model = try await EmbeddingGemma2(bundle: modelURL, compute: .neuralEngine, loadVision: true, imageCompute: .gpu) +// audio on the GPU instead (faster for long clips, ~16 ms of CPU per clip), text stays on the Neural Engine: +// let model = try await EmbeddingGemma2(bundle: modelURL, compute: .neuralEngine, loadAudio: true, audioCompute: .gpu) try await model.prewarm() // optional, ~1 s warm // text (unchanged from 1.0) @@ -128,38 +169,64 @@ let inputs = try ImagePreprocessor.prepare(url: imageURL) // decode + exact r let soft = try await model.softTokens(inputs) // [n * 512] Float16 (vision_2520) let rawImage = try await model.embed(sequence: model.imageSequence(softTokens: soft)) // runs mm_288 +// audio, same space (two of the package's test clips) +let clipURL = pkg.appendingPathComponent("tests/audio/speech_en_train_16k.wav") +let a = try await model.embedAudio(url: clipURL) // first 30 s, as upstream +let longURL = pkg.appendingPathComponent("tests/audio/long_melody_35s_16k.mp3") +let long = try await model.embedAudio(url: longURL, longAudio: .chunkMean) // mean of the 30 s windows +// let live = try await model.embedAudio(samples: [leftChannel, rightChannel], sampleRate: 48000) // PCM from AVAudioEngine etc. +let spoken = try await model.embed("the night train to the coast", kind: "search_query") +let hit = cosineSimilarity(spoken, a) +// lower level: decode -> mono -> 16 kHz -> log-mel frames -> audio_ -> sequence <|audio> [n] -> mm_ +let wav = try AudioFrontend.loadMono16k(url: clipURL) // [Float] at 16 kHz (AudioDecoder + AudioResampler) +let audioInputs = try AudioFrontend.prepare(wav16k: wav) // log-mel features + masks for one frame bucket +let audioSoft = try await model.audioSoftTokens(audioInputs) // [n * 512] Float16 (audio_) +let rawAudio = try await model.embed(sequence: model.audioSequence(softTokens: audioSoft)) + // when the model is released (or at exit) you may delete the temp files this process created, see "Temp files" EmbeddingGemma2.removeOwnMPSGraphTempFiles() ``` -`EmbeddingGemma2(bundle:compute:)` without `loadVision: true` loads only the text asset (300 MB less memory, no -image first-load cost); image calls then throw. `compute` places the text asset; `imageCompute` (default: the same -as `compute`) places the image encoder, see "Images: Neural Engine or GPU". `GemmaTokenizer` is public too (`encode`, `encodeWithSpecials`, +`EmbeddingGemma2(bundle:compute:)` without `loadVision: true` / `loadAudio: true` loads only the text asset (no +extra memory, no extra first-load cost); image and audio calls then throw. `compute` places the text asset; +`imageCompute` and `audioCompute` (default: the same as `compute`) place the image and audio encoders, see +"Images: Neural Engine or GPU" and "Audio: Neural Engine or GPU". `GemmaTokenizer` is public too (`encode`, `encodeWithSpecials`, `decode`): an exact re-implementation of the Hugging Face `tokenizers` pipeline for this `tokenizer.json`. Command line (`cd swift && swift build -c release`; the binary is `.build/release/eg2-cli` or `.build/out/Products/Release/eg2-cli` depending on the toolchain): ``` -eg2-cli smoke ../model ../tests/smoke-reference.json ../tests/image-smoke-reference.json --compute ane --cleanup-temp -eg2-cli embed ../model --kind search_query "bar chart of lamp units sold per city" (text only, no vision asset) +eg2-cli smoke ../model ../tests/smoke-reference.json ../tests/image-smoke-reference.json ../tests/audio-smoke-reference.json --compute ane --cleanup-temp +eg2-cli embed ../model --kind search_query "bar chart of lamp units sold per city" (text only, no vision/audio asset) eg2-cli embed-image ../model ../tests/images/chart_bar.png ../tests/images/scene_sunset.jpg [--image-compute gpu] [--exif] [--dim 768] (one JSON line per image) +eg2-cli embed-audio ../model ../tests/audio/speech_en_train_16k.wav ../tests/audio/long_melody_35s_16k.mp3 [--audio-compute gpu] + [--long truncate|chunk_mean] [--dim 768] (one JSON line per clip) eg2-cli tokcheck ../model ../tests/tokenizer-cases.json eg2-cli pixcheck ../tests/preprocess-cases.json (decode + resize vs the Python reference, no model) -eg2-cli latency ../model --compute ane [--image-compute gpu] --trials 50 [--text-only] -eg2-cli prewarm ../model [--image-compute gpu] [--text-only] +eg2-cli audiocheck ../tests/audio-preprocess-cases.json (decode + resample + log-mel vs the Python reference, no model) +eg2-cli latency ../model --compute ane [--image-compute gpu] [--audio-compute gpu] --trials 50 [--text-only] +eg2-cli prewarm ../model [--image-compute gpu] [--audio-compute gpu] [--text-only] ``` -`--compute ane|gpu|cpu` places the text asset (and the image encoder, unless `--image-compute` is given); -`--image-compute ane|gpu|cpu` places only the image encoder. +`--compute ane|gpu|cpu` places the text asset (and the image and audio encoders, unless `--image-compute` / +`--audio-compute` are given); `--image-compute` / `--audio-compute ane|gpu` place only that encoder. ## Quick start — Python -From the package folder: +From the package folder. macOS has no Python 3.12 of its own (its `python3` is 3.9 and Homebrew's default is +newer), so install one first, with Homebrew or with uv: + +``` +brew install python@3.12 # then: +python3.12 -m venv .venv && .venv/bin/pip install -r python/requirements.txt + +# or, with uv instead of Homebrew: +uv python install 3.12 && uv venv --python 3.12 .venv && uv pip install --python .venv -r python/requirements.txt +``` ``` -python3.12 -m venv .venv && .venv/bin/pip install -r python/requirements.txt # 3.12 validated; 3.14 also works source .venv/bin/activate cd python && python3 smoke_test.py --compute ane --cleanup-temp # first run: a few minutes to specialize, see below ``` @@ -167,21 +234,25 @@ cd python && python3 smoke_test.py --compute ane --cleanup-temp # first run ```python from embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_files -m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True) # ane | gpu | cpu | default +m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True, load_audio=True) # ane | gpu | cpu | default # images on the GPU (≈3× faster, more power), text on the Neural Engine: # m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True, image_compute="gpu") +# audio on the GPU, text on the Neural Engine: ..., load_audio=True, audio_compute="gpu" m.prewarm() q = m.embed("bar chart of lamp units sold per city", kind="search_query") # numpy float32 [768] v = m.embed_image("../tests/images/chart_bar.png") # path or PIL image; apply_exif_orientation=True for photos +a = m.embed_audio("../tests/audio/speech_en_train_16k.wav") # path, or (samples array, sample_rate=...); first 30 s +long = m.embed_audio("../tests/audio/long_melody_35s_16k.mp3", long_audio="chunk_mean") # mean of the 30 s windows d = m.embed("The lease runs until the last day of March.", kind="document", dim=256) score = float(q @ v) del m remove_own_mpsgraph_temp_files() # the Python runtime leaks ~650 MB per load, see below ``` -`python3 embeddinggemma2_coreai.py embed|embed-image|smoke|tokcheck|latency|prewarm …` mirrors the Swift tool, -including `--compute` and `--image-compute` (run it with the venv's Python). `smoke_test.py --text-only` checks the -text path without loading the image encoder; `smoke_test.py --image-compute gpu` checks the GPU image route. +`python3 embeddinggemma2_coreai.py embed|embed-image|embed-audio|smoke|tokcheck|latency|prewarm …` mirrors the +Swift tool, including `--compute`, `--image-compute` and `--audio-compute` (run it with the venv's Python). +`smoke_test.py --text-only` checks the text path without loading the image and audio encoders; `--no-audio` skips +the audio reference; `smoke_test.py --image-compute gpu --audio-compute gpu` checks the GPU routes. ## Text @@ -190,7 +261,7 @@ text path without loading the image encoder; `smoke_test.py --image-compute gpu` | Functions | `mm_32`, `mm_64`, `mm_128`, `mm_288`, `mm_512`, `mm_1024`, `mm_2048` (one per sequence bucket S) in `embeddinggemma-2-text-mm.aimodel` | | `input_ids` | `[1, S]` int32: ``=2, prompt-prefix tokens, text tokens, ``=1, right-padded with ``=0 | | `attention_mask` | `[1, S]` float16: 1 for real tokens, 0 for padding | -| `mm_embeds`, `mm_mask` | `[1, S, 512]` / `[1, S]` float16: **zeros for text** (see "Images" for what goes there) | +| `mm_embeds`, `mm_mask` | `[1, S, 512]` / `[1, S]` float16: **zeros for text** (see "Images" and "Audio" for what goes there) | | `embedding` | `[1, 768]` float16, already L2-normalized | | Max length | 2048 tokens including ``/`` and the prefix. Longer input is **truncated** by the runners (the original model accepts 8192; chunk long documents at ≤ 512 tokens for retrieval, the embedding is a mean over tokens anyway). | | Bucket choice | the smallest S ≥ token count. Padding does not change the result (padded and unpadded runs are bit-identical). | @@ -220,7 +291,7 @@ is not what you want. The image encoder (`vision_2520`, ~0.92 TFLOP per image) runs on either the Neural Engine or the GPU. Both routes use the same asset, both are validated, and you choose the route **for images independently of text**. Text always runs where `compute` says (default: Neural Engine), and so does the image's final pass through the text encoder -(`mm_288`, ~15 ms). Measured on an M5 (24 GB, macOS 27.0) for one typical image (273 soft tokens): +(`mm_288`, ~15 ms). Measured on an M5 (24 GB, macOS 27) for one typical image (273 soft tokens): | | **Neural Engine** (default) | **GPU** | |---|---|---| @@ -326,18 +397,198 @@ vector differs from the as-stored one by cosine ~0.97 and matches the same pictu from cameras and phones an app almost certainly wants `true`; for screenshots, renders and documents it makes no difference. The default is `false` for parity with the reference. Pick one and index consistently. -### Video and audio +### Video Not included. Upstream embeds a video as **one** sequence of frames sampled at 1 fps (up to 32 frames, 140 soft tokens per frame, `<|video|>` placeholders), which needs a 140-token vision shape and longer text buckets than this package exports. Embedding sampled frames one by one as images works with this package and is a common -approximation, but it is not what upstream does and was not compared with upstream video vectors. The audio -encoder is not ported. +approximation, but it is not what upstream does and was not compared with upstream video vectors. + +## Audio + +### Neural Engine or GPU + +The audio encoder (`audio_`, ~0.6 GFLOP per soft token, ~450 GFLOP for 30 s) runs on either the Neural Engine +or the GPU; the clip's final pass through the text encoder (`mm_`, S = tokens + 4) runs where `compute` says. +Measured on an M5 (24 GB, macOS 27), Swift `eg2-cli latency`, text on the Neural Engine: + +| clip | bucket / tokens | `audio_` Neural Engine | `audio_` GPU | `mm_` (Neural Engine) | end to end NE / GPU | CPU per clip NE / GPU | +|---|---|---|---|---|---|---| +| 3 s | 384 / 75 | 10.9 ms | 14.4 ms | 7 ms (`mm_128`) | **18 ms** / 22 ms | **1.1 ms** / 16 ms | +| 10 s | 1024 / 250 | 23.6 ms | 19–21 ms | 15 ms (`mm_288`) | 38 ms / **33–44 ms** | 1.2 ms / 14–22 ms | +| 30 s | 3000 / 750 | 86 ms | **50 ms** | 70 ms (`mm_1024`) | 156 ms / **119 ms** | 1.8 ms / 20 ms | + +Front end (Swift, one core): decode + mono + resample of a 30 s stereo 48 kHz clip 39 ms (Accelerate dot products; +16 kHz input needs no resampling), log-mel + inputs 3 ms. The numpy front end takes ~0.6 s for the same resample. +Accuracy of the two routes is the same (table below). **Default: the Neural Engine** — a few milliseconds slower on +long clips, ~10–20× less CPU, almost no GPU (0.3–0.5 ms of GPU time per clip, against 10–47 ms per clip on the +GPU route). **Choose the GPU** for bulk indexing of long recordings when wall-clock time matters. +`audioCompute: .cpu` / `audio_compute="cpu"` / `--audio-compute cpu` is refused with an error before any asset is +loaded: the CPU route is not supported for audio. + +```swift +let model = try await EmbeddingGemma2(bundle: url, compute: .neuralEngine, loadAudio: true, audioCompute: .gpu) +model.audioCompute // .gpu (if `audioCompute:` is omitted, it equals `compute`) +``` + +``` +eg2-cli embed-audio ../model --audio-compute gpu ../tests/audio/speech_en_train_16k.wav +python3 embeddinggemma2_coreai.py embed-audio ../model --audio-compute gpu ../tests/audio/speech_en_train_16k.wav +``` + +### How an audio clip becomes a vector + +1. **Decode** at the file's own sample rate, every channel, float32. Swift: AVAudioFile (AudioToolbox: WAV, AIFF, + CAF, FLAC, ALAC, AAC/M4A, MP3, …). Python: `soundfile` (libsndfile, what upstream's `librosa.load` uses; + installed by `requirements.txt`), and macOS `afconvert` for what libsndfile cannot read (AAC/M4A) or when + `soundfile` is not installed. +2. **Mono**: the mean of the channels (as librosa does). +3. **Resample to 16 kHz** with the package's Kaiser-windowed sinc (identical in Swift and numpy, see "Audio: + decoding and resampling"). Clips already at 16 kHz are untouched. +4. **Window**: the first 30 s (480 000 samples). Longer audio: see "Long audio". +5. **Log-mel frames** exactly as the upstream feature extractor: 160 zeros in front, frames of 320 samples every + 160 (periodic Hann), |FFT 512|, 128 triangular HTK mel bands 0–8 kHz, ln(mel + 0.001). A frame counts only if + its whole window lies in real audio: n frames = ⌊(samples − 161) / 160⌋ + 1 (2999 for 30 s; fewer than 161 + samples give 0 frames and 0 tokens). +6. **Bucket**: the smallest of 192, 384, 1024, 1536, 3000 frames ≥ n; features zero-padded, three masks (frames, + half frames, tokens) → `audio_` → `[Tb/4, 512]` soft tokens, of which the first ⌈⌈n/2⌉/2⌉ are valid (25 per + second; 750 for 30 s). +7. **Sequence** ``=2, `<|audio>`=256000, n × `<|audio|>`=258881, ``=258883, ``=1 (n + 4 ≤ 754 + tokens → up to bucket 1024), the soft tokens placed in the placeholder slots → `mm_` → `[768]`, L2-normalized. + +Audio takes **no prompt** (as the model card prescribes). Text queries use `search_query`; captions as documents +use `document`. Image, audio and text vectors share the space, so one index can hold all three. Padding is exact: +the encoder is causal, so a clip's tokens do not depend on the bucket (verified: the same clip through its own +bucket and through `audio_3000` gives bit-identical soft tokens on the Neural Engine and tokens within float16 +noise, cosine ≥ 0.99999, on the GPU). + +### `audio_` (asset `embeddinggemma-2-audio.aimodel`) + +| | | +|---|---| +| Functions | `audio_192`, `audio_384`, `audio_1024`, `audio_1536`, `audio_3000` (frames of 10 ms; 1.92 s, 3.84 s, 10.24 s, 15.36 s, 30 s) | +| `features` | `[1, Tb, 128]` float16 log-mel frames, the first n rows real, zero after (values −6.9 … +7) | +| `frame_mask` | `[1, Tb]` float16: 1 for the first n rows | +| `half_mask` | `[1, Tb/2]` float16: 1 for the first ⌈n/2⌉ rows (after the first stride-2 convolution) | +| `token_mask` | `[1, Tb/4]` float16: 1 for the first ⌈⌈n/2⌉/2⌉ rows (= the soft-token count) | +| `soft_tokens` | `[1, Tb/4, 512]` float16; rows at index ≥ tokens are padding and must be ignored | + +Why these buckets: they are the frame counts validated on the Neural Engine (placement and correctness); other +sizes are excluded for compatibility. Clips of 3.9–10 s therefore use the 1024 bucket (24 ms instead of ~15). +`export.py --audio-buckets` builds other sets; **verify every bucket you add on the Neural Engine**: correctness +with `eg2-cli smoke` and placement with the Neural Engine footprint that `eg2-cli latency` prints, not only that it +loads. + +### Audio: decoding and resampling + +The reference (`sentence-transformers` → `librosa.load(sr=16000)`) decodes with **libsndfile**, mixes to mono and +resamples with **libsoxr "HQ"**. The package reproduces the first two exactly and replaces the third: + +- **Decoders.** Apple's AudioToolbox decoder (Swift; also the Python `afconvert` fallback) is sample-identical to + libsndfile for WAV/AIFF/AIFC/CAF (any PCM depth, 8-bit to 64-bit float), FLAC and ALAC, and within 3e-7 for AAC + (same decoder family). For **MP3** AudioToolbox does not always honour the LAME/Xing/Info tag: most files come out + gapless, some as whole frames (encoder delay and padding still in place), and some with the delay removed but one + or two whole frames too many at the end (`afinfo` then counts one packet more than the tag). The Swift decoder and + the Python fallback read the tag and bring every case to its gapless length, after which the samples match + libsndfile/mpg123 within 3e-5 (all 55 tagged MP3s tested: 16–48 kHz, mono/stereo, CBR/VBR). The residue sits + where Apple's decoder outputs exact zeros and mpg123 values around 1e-5: inaudible, but the log-mel floor (0.001) + makes the model sensitive to it in **digitally silent** passages. Clips with long digital silence (synthesized + speech with pauses, synthesized sounds with silent decays) scored 0.990–0.9999 against the libsndfile-decoded + reference (fp32, the same model on both waveforms; ≥ 0.99998 when the same files are decoded with libsndfile); + MP3s without digital silence ≥ 0.99998. The Python runner decodes MP3 with `soundfile` (installed by + `requirements.txt`) and is libsndfile-exact; only its `afconvert` fallback has this difference. In + Swift, decode MP3 with another decoder and pass the samples to `embedAudio(samples:sampleRate:)`. **MP3 files + without a LAME/Xing tag** cannot be trimmed: Apple's decoder removes the 529-sample decoder delay and libsndfile + does not, so the two are 529 samples apart (cosine 0.92–0.993 on speech). **Ogg Vorbis**: libsndfile (Python with + `soundfile`) is exact; Apple's decoder (Swift, `afconvert`) is 128 samples off libsndfile (cosine 0.990–0.9985 on + speech). +- **Resampler.** libsoxr is LGPL and its "HQ" / "VHQ" settings already differ from each other by cosine up to + 0.004, so the package ships its own Kaiser-windowed sinc (polyphase, pass band 0.913 and stop band 1.0 of the + lower Nyquist, 125 dB attenuation, unity DC gain, output length ⌈n·16000/rate⌉ like librosa), computed in double + precision by the same formulas in Swift and numpy: the two give **bit-identical** 16 kHz waveforms on all 147 + resampled validation clips. Against libsoxr HQ, measured through the fp32 model on those 147 clips (8–96 kHz): + median cosine 0.999999, 140 of 147 ≥ 0.9999, minimum 0.9953 (96 kHz synthesized wind noise; the 7 clips below + 0.9999 are all synthesized noise-like sounds), waveform SNR median 81 dB. Speech is unaffected (≥ 0.9999). + An independent set (171 resampled lossless/AAC clips, 7.35–192 kHz) gave median 0.999999, 163 of 171 ≥ 0.9999, + speech ≥ 0.99988, minimum 0.9939 (a synthesized 22.05 kHz engine hum whose upper mel bands sit at the log-mel + floor); Swift and numpy were bit-identical on 191 of its 201 resampled clips and within 4e-15 on the rest (the AAC + ones within the 3e-7 decoder difference). 16 kHz input bypasses the resampler entirely. Apple's own + `AudioConverter` (even at maximum quality) would cost down to 0.93. +- **Features.** The numpy log-mel is bit-identical to the upstream extractor (214/214 clips, and 279/279 of the + independent set). The Swift log-mel (Accelerate single-precision FFT) differs from numpy's by at most 0.006 per + value (same waveform), which costs ≤ 0.0005 of cosine on the Neural Engine route (Swift vs Python vectors on 287 + clips: median 0.999996, min 0.99954). + +### Long audio + +The model's window is 30 s (`processor` default, 480 000 samples): upstream silently drops the rest. The runners +offer two policies: **`truncate`** (default; the first 30 s, exactly upstream) and **`chunk_mean`** (the mean of +the L2-normalized embeddings of consecutive 30 s windows, re-normalized; a trailing window too short for one +frame is dropped). Measured against the fp32 model on clips of 45–130 s (Neural Engine route): `chunk_mean` +matches the same policy in fp32 to ≥ 0.99996, and the mean is closer to an (unsupported) whole-clip embedding than the truncated one is (0.95 +vs 0.94 at 130 s). Neither is what upstream returns for long audio, which is the truncated vector. For retrieval +over long recordings consider indexing each 30 s window as its own document. + +### Audio accuracy + +Parity with fp32 sentence-transformers on 214 generated clips (112 spoken sentences in 11 languages from 50+ +macOS `say` voices and rates, used for local validation only and not shipped, 42 synthesized sounds, 30 edge cases, 17 copies of one sentence in different formats and +rates, 11 long clips, 3 mixtures; features from the upstream extractor so that the table measures the model): + +| route (audio / text) | median | min | speech min | sounds min | edge / format / long min | +|---|---|---|---|---|---| +| Neural Engine / Neural Engine (default) | 0.99996 | 0.9981 (a synthesized chord) | 0.9987 | 0.9981 | 0.9991 / 0.99994 / 0.9997 | +| GPU / Neural Engine | 0.99998 | 0.9994 (phase-inverted stereo noise) | 0.99978 | 0.99943 | 0.9994 / 0.99997 / 0.99977 | + +Cross-modal retrieval, 154 captions ↔ 154 clips (captions as `search_query` / `document`): + +| | text → audio R@1 / R@5 / MRR | audio → text R@1 / R@5 / MRR | +|---|---|---| +| fp32 reference, 768 dims | 0.545 / 0.701 / 0.629 | 0.597 / 0.682 / 0.642 | +| Neural Engine route, 768 dims | 0.545 / 0.727 / 0.629 | 0.597 / 0.688 / 0.643 | +| GPU route, 768 dims | 0.545 / 0.714 / 0.628 | 0.597 / 0.682 / 0.642 | +| fp32 reference, 128 dims | 0.532 / 0.643 / 0.603 | 0.500 / 0.643 / 0.573 | +| Neural Engine route, 128 dims | 0.532 / 0.649 / 0.603 | 0.500 / 0.630 / 0.573 | + +(Spoken sentences alone retrieve at MRR 0.79; the 42 synthesized sounds are a parity check, not a retrieval +benchmark: fp32 itself ranks only a third of them first.) The re-authored graph run in fp32 reproduces the +reference soft tokens to cosine ≥ 0.99999998 (213 clips). + +On the Neural Engine the least precise inputs are digital silence (0.9993 on a 1 s silent clip, 0.9991 on 30 s) +and dense synthesized chords (0.998): float16 arithmetic on near-constant spectra. Speech from every voice and +language tested stayed ≥ 0.9983 (median 0.99997) across both validation sets. + +**Independent validation set** (generated separately from the set above: 287 clips — 100 spoken sentences in 18 +languages from 84 macOS `say` voices and rates (local only, not shipped), 46 synthesized sounds, 74 copies of two sentences in 17 containers/codecs +at 7.35–192 kHz, 54 edge cases (1 sample to 40 s, every bucket boundary, silence, clipping, DC offset, a 30 kHz +tone at 96 kHz, 2/4/6 channels, phase-inverted stereo), 8 long clips of 29.9–150 s, 5 speech-over-sound mixtures; +reference: fp32 sentence-transformers on the runner's own 16 kHz waveform, so the table measures features + model; +282 clips, upstream fails below 129 samples). Cosine at 768 dims, both runners: + +| route (audio / text) | median | min | speech min (any format) | sounds min | edge min | Swift vs Python | +|---|---|---|---|---|---|---| +| Neural Engine / Neural Engine | 0.99996 | 0.9972 (30 kHz tone at 96 kHz: near-silence after resampling) | 0.9983 | 0.9984 | 0.9972 | median 0.999996, min 0.99954 | +| GPU / Neural Engine | 0.99998 | 0.9994 (speech at −90 dBFS) | 0.99996 | 0.9997 | 0.9994 | min 0.9999 | +| GPU / GPU | 1.00000 | 0.9995 (the same clip) | 0.99997 | 0.99985 | 0.9995 | min 0.99993 | + +512 / 256 / 128 dims are the same or better (Neural Engine minimum 0.9973 / 0.9979 / 0.9987); the runners' +`dim:` output equals the truncated, re-normalized 768-d vector. Long clips: `truncate` ≥ 0.9999 and `chunk_mean` ≥ +0.99978 (Neural Engine), ≥ 0.99985 (audio on the GPU, text on the Neural Engine) and ≥ 0.99996 (everything on the +GPU) against the same policy in fp32. Retrieval with the 146 captions (100 +sentences, 46 sounds) as `search_query` / `document`: fp32 text → audio R@1 / R@5 / MRR 0.548 / 0.699 / 0.625, +audio → text 0.568 / 0.664 / 0.625; at 768 dims every route is within one query (0.007) of fp32 on every metric +(R@1 identical); at every size R@1 stays within one query and MRR within 0.007, and R@5 within one query except +text → audio R@5 at 256 dims (2 of 146 queries lower on the Neural Engine and GPU-audio routes) and at 128 dims +(2 of 146, Python GPU-audio route): synthesized-sound captions whose own clip tied the 5th result within 0.002 in +fp32. +End to end against upstream's own file path (libsndfile + libsoxr), the decoder and resampler effects described +above come on top: median 0.99995, minimum 0.990 for MP3/Ogg via Apple's decoder, 0.92 for an MP3 without a tag. ## Accuracy (measured) Reference: sentence-transformers 6.1 / transformers 5.19 / torch 2.14.1 / torchvision 0.29.1, fp32, CPU, original -checkpoint; images passed as paths with no prompt. All test texts and images are fictional and generated from code +checkpoint; images passed as paths with no prompt; audio as 16 kHz arrays (libsndfile/ffmpeg + libsoxr HQ) with +no prompt (audio figures: "Audio accuracy" above). All test texts, images and audio clips are fictional and generated from code (charts, UI-like screens, slides, documents, diagrams, drawn scenes, shapes, plus size, aspect-ratio, colour-mode, JPEG-quality and EXIF stress cases); 19 files made from 14 public-domain camera photos (16 JPEGs plus 3 lossless PNG re-saves) were used for local validation only and are not shipped. @@ -422,16 +673,39 @@ must rank its own image first). This package on the validation machine, all SMOK | GPU / GPU (`--compute gpu`) | 0.99974 (the JPEG; PNGs ≥ 0.99998) / 0.99999 | 0.99999 | 10 / 10 | | CPU only (Swift) | 0.99965 | 0.99996 | 10 / 10 | -Text-only smoke (vision asset not loaded) passes with the same text cosines as 1.0 (0.999948 / 0.999979 / +Text-only smoke (vision and audio assets not loaded) passes with the same text cosines as 1.0 (0.999948 / 0.999979 / 0.999976; Matryoshka 512 / 256 / 128: 0.999979 / 0.999981 / 0.999989). `eg2-cli tokcheck` 3758 / 3758, `eg2-cli pixcheck` 11 / 12 bit-identical plus the JPEG (decoder difference, expected), `tests/check_preprocess.py` identical to torchvision and the upstream processor on all 12 test images. -Caveats: one machine, one OS build (M5, macOS 27.0 26A5406e). Core AI specializes per machine and OS build; re-run +**Audio smoke** (`tests/audio-smoke-reference.json`: 15 generated clips — 8 invented sentences in 7 languages +spoken by the eSpeak NG formant synthesizer, 4 synthesized sounds, silence, a tone and a 35 s MP3 melody — with +their 13 captions as queries and documents; per-clip thresholds 0.9995 for 16 kHz lossless clips, 0.995 for +resampled and MP3 clips, two measured exceptions carried in the file: digital silence 0.998 and the MP3 melody +0.985; a query must rank its own clip first wherever fp32 does, which is 11 of 13 — fp32 itself misses two +synthesized sounds). All SMOKE PASS: + +| route (audio / text) | 12 speech + sound clips, min (Swift / Python) | silence | MP3 melody (Swift / Python with `soundfile` / Python `afconvert` fallback) | text → audio | +|---|---|---|---|---| +| Neural Engine / Neural Engine (default) | 0.9983 / 0.9991 (the piano chord; speech ≥ 0.99995) | 0.99926 | 0.9908 / 0.9994 / 0.9909 | 11 / 11 | +| GPU / Neural Engine (`--audio-compute gpu`) | 0.99989 / 0.99986 (speech ≥ 0.99997) | 0.99986 | 0.9902 / 0.9997 / 0.9903 | 11 / 11 | +| GPU / GPU (`--compute gpu`, Swift) | 0.99993 | 0.99996 | 0.9904 | 11 / 11 | + +The MP3 melody is the one clip where the decoder matters: Apple's decoder (Swift, the Python `afconvert` fallback) +against libsndfile on a clip with silent decays (see "Audio: decoding and resampling"). `eg2-cli audiocheck` 16 / +16 within tolerance of the Python front end (11–13 waveforms bit-identical: every PCM, FLAC and ALAC file except +the 96 kHz tone, which is within 4e-17, and the two AAC files in some runs: Apple's AAC decoder varies by about one +float32 step between runs, ≤ 2e-7; MP3 within 3e-5; features within 0.0022 except MP3). + +Caveats: one machine (M5, macOS 27). Core AI specializes per machine and OS build; re-run `smoke` on your targets. ## Performance (measured, M5, Swift `eg2-cli latency`) +All timings in this README were measured on AC power. On battery with Low Power Mode on, the same machine took +1.4–1.6× as long for every figure (e.g. a 30 s clip 218 ms end to end on the Neural Engine, text `mm_1024` 107 ms +instead of 69 ms). + Images: see "Images: Neural Engine or GPU" for the side-by-side comparison (time, CPU, GPU, power, energy, memory). Per function: @@ -441,14 +715,22 @@ memory). Per function: | `mm_288` (the image's sequence) | 15 ms | 17 ms (14 ms when text stays on the Neural Engine) | | image end to end (excl. decode + resize) | 369 ms | 125 ms | | CPU time per image (excl. decode + resize) | 2.0 ms | 21 ms (text on the Neural Engine) / 34 ms (all on the GPU) | +| `audio_384` / `audio_1024` / `audio_3000` (3 s / 10 s / 30 s clips) | 10.9 / 23.6 / 86 ms | 14.4 / 19–21 / 50 ms | +| `mm_128` / `mm_288` / `mm_1024` (those clips' sequences, Neural Engine) | 7 / 15 / 70 ms | — | +| audio end to end, 3 s / 10 s / 30 s (excl. decode + front end) | 18 / 38 / 156 ms | 22 / 33–44 / 119 ms (text on the Neural Engine) | +| CPU time per clip (excl. decode + front end) | 0.7–1.9 ms | 14–22 ms | | text buckets 32 / 64 / 128 / 288 / 512 / 1024 / 2048, p50 | 4.9 / 5.3 / 6.8 / 14.4 / 28 / 69 / 196 ms | 8.1 / 8.4 / 10.3 / 16 / 22 / 50 / 143 ms | | text CPU per call | 0.3–0.7 ms | 10–31 ms | -| process footprint + Neural Engine footprint | 260–275 MB + 608–1061 MB | 435–440 MB + 608–766 MB (images on the GPU, text on the Neural Engine); 0.9–1.1 GB, no Neural Engine (all on the GPU) | +| process footprint + Neural Engine footprint (text + images) | 260–275 MB + 608–1061 MB | 435–440 MB + 608–766 MB (images on the GPU, text on the Neural Engine); 0.9–1.1 GB, no Neural Engine (all on the GPU) | +| process footprint + Neural Engine footprint (all three assets) | 300–475 MB + 1.6–2.5 GB (Python; the Swift CLI reported 0.77 GB) | 650–850 MB + 766 MB (audio and images on the GPU) | -Text-only use (`loadVision` off): ~225 MB footprint plus ~770 MB on the Neural Engine. Decode + exact resize + +Text-only use (`loadVision` and `loadAudio` off): ~225 MB footprint plus ~770 MB on the Neural Engine. Decode + exact resize + patches on the CPU (Swift, multi-threaded resampler): 10 ms median, 43 ms at the 90th percentile, 125 ms for a -6000×4000 JPEG (numpy: 45 ms median). The CPU-only route takes ~520 ms per image. The Python runner gives the same -model latencies within a few percent (8.5 ms CPU per image on the Neural Engine, 27 ms on the GPU). +6000×4000 JPEG (numpy: 45 ms median). Audio front end (Swift, one core): 14 ms median per clip over the 215 +validation clips, 39 ms for the resample of a 30 s 48 kHz stereo clip, 3 ms for the log-mel of 30 s (numpy: ~0.6 s +for that resample, 6 ms log-mel). The CPU-only route takes ~520 ms per image and does not work for audio. The +Python runner gives the same model latencies within a few percent (8.5 ms CPU per image on the Neural Engine, +27 ms on the GPU; 1.3–4.7 ms CPU and 0.3–0.5 ms GPU time per audio clip on the Neural Engine, 15–25 ms CPU and 10–47 ms GPU time with audio on the GPU). On the Neural Engine the 12 × 2520 × 2520 attention is the cost of the vision graph. Each function is batch-1; the Neural Engine serializes concurrent calls. Nothing stops an app from running two routes at once (e.g. one instance @@ -460,7 +742,8 @@ of a second instance. | situation | time | |---|---| | warm (this executable has loaded these assets before) | 0.5–1.8 s, plus ~0.7 s for `prewarm()` | -| first load by an executable that has not loaded them before (a new app, a new binary name, the Python interpreter) | **about 3–4 minutes** for both assets on the Neural Engine route (about 200 s observed for a Python interpreter that had never loaded them; the text asset alone took ~140 s in 1.0); about 30 s was observed for a renamed `eg2-cli` when another executable on the same machine had already compiled the same assets — do not rely on it | +| first load by an executable that has not loaded them before (a new app, a new binary name, the Python interpreter) | **about 5 minutes for all three assets** on the Neural Engine route (5 min 01 s measured for a new executable in a clean-room test); **about 3–4 minutes** for text + images (about 200 s observed for a Python interpreter that had never loaded them; the text asset alone took ~140 s in 1.0); about 30 s was observed for a renamed `eg2-cli` when another executable on the same machine had already compiled the same assets — do not rely on it | +| audio encoder, first load | 90–200 s on the Neural Engine when the assets were new to the machine; 19.5 s (Neural Engine) and 16 s (GPU) for a renamed `eg2-cli` after another executable had compiled them (text asset 28.5 s in the same situation) | | image encoder on the GPU, first load | 2–25 s | Load and `prewarm()` in the background at app start (or in a first-run step) and show progress; never on the main @@ -470,24 +753,27 @@ thread and never lazily in front of the first query. The cache lives in e.g. Homebrew's). It survives reboots but not OS updates, a renamed executable or a re-exported asset (including the 1.0 → 1.1 upgrade). -## Why two assets (and why `mm_` also serves text) +## Why three assets (and why `mm_` also serves text) -- The image encoder is a separate asset so that text-only users neither download nor load 300 MB they do not - need (`--exclude` at download, `loadVision` off at runtime). The two graphs share nothing. -- The text asset carries the soft-token inputs so that one 600 MB text encoder serves both texts and images. With +- The image and audio encoders are separate assets so that users neither download nor load what they do not + need (`--exclude` at download, `loadVision` / `loadAudio` off at runtime). The three graphs share nothing. +- The text asset carries the soft-token inputs so that one 600 MB text encoder serves texts, images and audio. With zero soft tokens it is the 1.0 encoder, bit for bit, so there is no reason to ship both. -- The buckets are 32, 64, 128, **288**, 512, 1024, 2048: 288 holds one image sequence (≤ 284 tokens) and replaces - 256 so that an image does not pay for the 512 bucket. +- The text buckets are 32, 64, 128, **288**, 512, 1024, 2048: 288 holds one image sequence (≤ 284 tokens) and + replaces 256 so that an image does not pay for the 512 bucket; a 30 s clip (754 tokens) uses 1024. +- The audio buckets (192, 384, 1024, 1536, 3000 frames) are the sizes validated on the Neural Engine, see "Audio: + `audio_`". ## Temp files (please read) Each Neural Engine load writes compiled-graph copies to `$TMPDIR/com.apple.MetalPerformanceShadersGraph/ -mpsgraph---/` (~360 MB for the text asset, ~300 MB for the image asset). Measured on macOS 27.0: +mpsgraph---/` (~360 MB for the text asset, ~300 MB for the image asset; the audio asset added +nothing on either route in our measurements, only an empty folder on the GPU route). Measured on macOS 27: - Swift (`CoreAI` framework): the runtime deletes the folder when the model is released; our CLI leaves nothing behind. If your app exits or is killed while the model is loaded, the folder may remain. - Python (`coreai.runtime`): the folder is **never** deleted, not even after `del model` and a clean interpreter - exit (~650 MB per load with both assets). Over a day of development this fills a disk. + exit (~650 MB per load with all three assets). Over a day of development this fills a disk. Both runners ship a cleanup that removes only the folders belonging to the **current process** (its pid, created after the process started): `EmbeddingGemma2.removeOwnMPSGraphTempFiles()`, `remove_own_mpsgraph_temp_files()`, @@ -519,13 +805,39 @@ processes are never touched; a leftover from a crashed run has to be removed by to a colour-managed Core Graphics draw over black. - **2048-token cap** for text (longer input is truncated); buckets of 4096/8192 can be exported but were not validated and would run on the GPU. +- **Audio: 30 s window.** Like upstream, one call embeds at most 30 s; longer audio is truncated by default or + averaged over 30 s windows (`chunk_mean`, our extension, not an upstream vector). Fewer than 161 samples (10 ms) + give zero audio tokens and the embedding of an empty audio sequence (upstream crashes below 129 samples). +- **Audio: MP3 and Ogg decoding** with Apple's decoder (Swift and the Python `afconvert` fallback): tagged MP3s + match the reference decoder within ~3e-5 per sample after the gapless trim; inaudible, but digitally silent + passages amplify it in the log-mel floor: clips with long digital silence (synthesized speech with pauses, + synthesized sounds with silent decays) score 0.990–0.9999 against the reference, other MP3s ≥ 0.99998. MP3 files + without a LAME/Xing tag are 529 samples off the reference (cosine 0.92–0.993); Ogg Vorbis 128 samples (0.990– + 0.9985). The Python runner with `soundfile` (the default install) is exact; in Swift, decode these formats + yourself when that matters. +- **Audio: resampling** uses the package's sinc instead of libsoxr: ≤ 0.00012 of cosine on speech, up to 0.006 on + synthesized sounds whose upper bands sit at the log-mel floor. 16 kHz input is exact. +- **Audio on the Neural Engine**: near-silence (digital silence, a 30 kHz tone resampled to nothing, speech at + −90 dBFS) and dense synthesized chords are the least precise inputs (0.997–0.9993); speech ≥ 0.9983. The GPU + route is ≥ 0.9994 on everything. Only the shipped frame buckets are supported (see "Audio: `audio_`"), and + the CPU route is not supported for audio, so the runners refuse it. +- **Audio sample arrays**: Python `embed_audio(array, sample_rate)` takes `[n]` or `[n, channels]` and rejects a + channel-first `[channels, n]` array (librosa / torchaudio layout: pass `array.T`); Swift + `embedAudio(samples:sampleRate:)` takes channel-major `samples[channel][frame]` and rejects frame-major arrays, + channels of different lengths and a non-positive rate (before 1.2's validation pass, these were silently embedded + as near-empty audio or crashed). +- **Audio asset memory**: ~1.4 GB on the Neural Engine for the five functions (the runtime does not share the + weights between them on the Neural Engine); on the GPU route ~300 MB of process memory instead. +- **An interrupted first load** (the process is killed while the runtime specializes an asset) can leave the + per-app cache entry unusable, so later loads of that asset fail in `loadFunction`. Delete + `~/Library/Caches/coreai-cache////` and reload (one more first-load specialization). - **Batch 1.** Concurrency did not increase throughput (the Neural Engine serializes). Short texts are not faster - than ~4.8 ms (per-call floor of this Core AI build). + than ~4.8 ms (per-call floor in our measurements). - **Latency is not shape-stable across bucket sets**: Core AI specializes the whole function set together; measure the exact set you ship. - **Specialization cache is per app** (executable name or bundle identifier); **temp files** as described above; **fp16 output** (relative precision ~5e-4; convert to float32 before accumulating dot products, as the runners do). -- Validated on one machine and one OS build (macOS 27.0 26A5406e). Core AI is new in macOS 27 and its runtime +- Validated on one machine (macOS 27). Core AI is new in macOS 27 and its runtime behaviour (first-load time, placement, temp files) may change between OS releases. ## Reproducing the export @@ -538,12 +850,13 @@ pip install coreai-core==1.0.0b3 torch==2.9.0 coreai-torch==0.4.3 coreai-opt==0. hf download google/embeddinggemma-2 --local-dir ./embeddinggemma-2 cd export python3 -W ignore export.py --model-dir ../embeddinggemma-2 --out ../model-rebuilt \ - --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --date 2026-10-12 + --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --audio-buckets 192,384,1024,1536,3000 --date 2026-10-12 ``` -About 25 s on an M5. `eg2_text.py` is the re-authored text encoder (byte-identical to 1.0), `eg2_text_mm.py` adds -the soft-token mix, `eg2_vision.py` is the re-authored image encoder; `export.py` does one `torch.export` per asset, -converts with `coreai_torch.TorchConverter`, clones the text entry point per bucket with `set_static_shape_config` +About 40 s on an M5 (`--part text|vision|audio` rebuilds one asset). `eg2_text.py` is the re-authored text encoder +(byte-identical to 1.0), `eg2_text_mm.py` adds the soft-token mix, `eg2_vision.py` is the re-authored image +encoder, `eg2_audio.py` the re-authored audio encoder; `export.py` does one `torch.export` per asset, converts with +`coreai_torch.TorchConverter`, clones the text and audio entry points per bucket with `set_static_shape_config` and writes the bundle. torchao must be 0.17.0 with torch 2.9 (0.18 breaks `import coreai_opt`). A rebuilt bundle is **functionally identical, not byte-identical**: the converter names internal graph resources at @@ -552,19 +865,23 @@ time. `config.json`, `MODEL-ATTRIBUTION.json` and the tokenizer files come out b with `smoke`, not with checksums; a rebuilt asset has a new content hash, so its first load takes the full time. Neural Engine eligibility without running: `xcrun coreai-build compile model/.aimodel --output ./compiled ---preferred-compute neural-engine --architecture h17g 2>&1 | grep -c ane_validation_message` prints 0 for both -assets (no op rejected; delete `./compiled` afterwards). The specialized graphs have one Neural Engine region and -one GPU region (the token / position-table gather) per function. +--preferred-compute neural-engine --architecture h17g 2>&1 | grep -c ane_validation_message` prints 0 for the +text and image assets (no op rejected; delete `./compiled` afterwards). The specialized text and image graphs have +one Neural Engine region and one GPU region (the token / position-table gather) per function; each audio function +is a single Neural Engine region. For the audio asset this offline check is not sufficient: verify placement with +the process's Neural Engine footprint (`eg2-cli latency` prints it) and correctness with `smoke`. ## Credits and license - Model: EmbeddingGemma 2 by the Gemma Team, Google DeepMind — Apache-2.0. Deployments must adhere to the [Gemma Prohibited Use Policy](https://ai.google.dev/gemma/prohibited_use_policy). -- Architecture and image-processor reference: Hugging Face transformers (Apache-2.0). Resize arithmetic: ported - from the logic of ATen's uint8 antialiased bicubic kernel (PyTorch, BSD-3-Clause), itself modelled on Pillow's - resampling; CMYK conversion ported from Pillow's formula (MIT-CMU). Their license notices are in NOTICE. +- Architecture, image-processor and audio-feature-extractor reference: Hugging Face transformers (Apache-2.0). + Resize arithmetic: ported from the logic of ATen's uint8 antialiased bicubic kernel (PyTorch, BSD-3-Clause), + itself modelled on Pillow's resampling; CMYK conversion ported from Pillow's formula (MIT-CMU). Their license + notices are in NOTICE. The audio resampler is the package's own design (upstream uses libsoxr, not included). - The max-abs RMSNorm rescaling idea comes from the FluidInference Core ML port of this model (Apache-2.0); no code was copied. -- Port, exporter, runners, Swift tokenizer implementation, preprocessing, tests and test images: Copyright 2026 Everpaper, Apache-2.0. +- Port, exporter, runners, Swift tokenizer implementation, preprocessing and audio front end, tests, test images + and test audio: Copyright 2026 Everpaper, Apache-2.0. - Gemma and EmbeddingGemma are trademarks of Google LLC; Apple, Core AI, Apple silicon and Neural Engine are trademarks of Apple Inc. This port is not affiliated with, sponsored by or endorsed by Google or Apple. diff --git a/export/eg2_audio.py b/export/eg2_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..1b23897d61d5219a2aa1614b5d8eec498cc0595a --- /dev/null +++ b/export/eg2_audio.py @@ -0,0 +1,372 @@ +# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). +# +# Re-authoring of the Gemma 4 audio encoder (Gemma4AudioModel: a USM-style conformer) and the EmbeddingGemma 2 +# audio embedder as described by modeling_gemma4.py / modeling_embedding_gemma2.py in Hugging Face transformers +# 5.19 (Copyright 2026 The HuggingFace Team, Apache-2.0). Model weights: Google DeepMind (Gemma Team), +# Apache-2.0, https://huggingface.co/google/embeddinggemma-2 — see ../NOTICE for the attribution and +# modification list. +"""EmbeddingGemma 2 audio encoder re-authored for Core AI export: log-mel frames -> soft tokens in the text space. + +Inputs (one function per frame bucket Tb, functions `audio_`): + features [1, Tb, 128] fp16 log-mel frames of the upstream feature extractor (host side: python/eg2_audio_frontend.py, + swift AudioFrontend), the first n_frames rows real, the rest zero + frame_mask [1, Tb] fp16 1 for the first n_frames rows, 0 after + half_mask [1, Tb/2] fp16 1 for the first ceil(n_frames/2) rows (mask after the first stride-2 conv) + token_mask [1, Tb/4] fp16 1 for the first ceil(ceil(n_frames/2)/2) rows (= the soft-token count) +Output: + soft_tokens [1, Tb/4, 512] fp16; rows at index >= n_tokens are padding and must be ignored. + +The graph: features * frame_mask -> Conv2d 1->128 (3x3, stride 2) + LayerNorm over channels + ReLU -> * half_mask +-> Conv2d 128->32 (3x3, stride 2) + LayerNorm + ReLU -> [T, F=32, C=32] flattened to 1024 -> Linear 1024->1024 +-> 12 conformer layers (half-step FFN, local causal attention with relative position bias, light depthwise +convolution, half-step FFN, RMSNorm) -> Linear 1024->1536 (+bias) -> RMSNorm without scale -> Linear 1536->512. + +Differences from the upstream graph (all mathematically identical in exact arithmetic): + - the chunked local attention (pad / unfold / rel_shift view trick / 5-D blocks) is written in its banded form: + every query attends to itself and the 11 previous tokens (the mask of the upstream chunked attention lets each + position see exactly these 12 keys), logit[t, d] = q_t . (k_{t-d} + relk_d) for d = 0..11, where + relk_d = relative_k_proj(sinusoid(d)) is a per-layer constant; keys and values at offset d are the tensor + shifted by d with pad + slice. No gather, no rank-5 tensors. + - masked_fill(-1e9) on padded keys becomes an additive bias (-10000 in fp16, finite) added after the softcap; + rows whose 12 keys are all padding (only possible beyond the valid tokens) stay finite. + - the q scale (128^-0.5 / ln 2 * softplus(per_dim_scale), per head dimension) and the k scale (ln(1+e) / ln 2) + are folded into q_proj / k_proj and their output clip bounds: clamp(Wx, lo, hi) * s == clamp(sWx, s*lo, s*hi) + for s > 0. The clip bounds of all 120 clipped linears stay as min/max ops. + - the gradient-clipping clamps (+-1e10) are no-ops in inference and are dropped. + - the SubSampleConvProjection LayerNorms (over the channel axis of the NCHW tensor) are written as mean/variance + over dim 1; GLU as slice * sigmoid; the causal depthwise Conv1d as a grouped conv with 4 samples of left pad. + - fp16 "ane" precision mode as in eg2_text.py: every RMSNorm divides the row by its max-abs value before squaring + (the residual stream reaches ~412, whose square overflows fp16), every division is rsqrt(x)*rsqrt(x). +""" +from __future__ import annotations + +import json +import math +from pathlib import Path + +import torch +import torch.nn as nn +import torch.nn.functional as F + +PRECISION_MODE = "ane" # "ane" (all fp16, Neural Engine) | "fp32" (correctness gate of the re-authoring) +MASK_VALUE = -10000.0 +NORM_FLOOR = 1e-3 +CTX = 12 # keys per query: self + 11 past +N_MELS = 128 +FRAME_BUCKETS = [192, 384, 1024, 1536, 3000] # frames (10 ms); tokens = frames / 4; 3000 frames = 30 s (2999 valid frames) + + +class Cfg: + def __init__(self, model_dir: str): + c = json.loads((Path(model_dir) / "config.json").read_text())["audio_config"] + t = json.loads((Path(model_dir) / "config.json").read_text())["text_config"] + self.hidden = c["hidden_size"] # 1024 + self.n_layers = c["num_hidden_layers"] # 12 + self.n_heads = c["num_attention_heads"] # 8 + self.head_dim = self.hidden // self.n_heads # 128 + self.eps = c["rms_norm_eps"] # 1e-6 + self.conv_channels = c["subsampling_conv_channels"] # [128, 32] + self.conv_kernel = c["conv_kernel_size"] # 5 + self.softcap = c["attention_logit_cap"] # 50 + self.residual_weight = c["residual_weight"] # 0.5 + self.out_dims = c["output_proj_dims"] # 1536 + self.text_hidden = t["hidden_size"] # 512 + assert c["attention_chunk_size"] + c["attention_context_left"] - 1 + c["attention_context_right"] == 2 * CTX + assert c["attention_context_right"] == 0 and c["hidden_act"] == "silu" and c["use_clipped_linears"] + + +def _f16(x: float) -> torch.Tensor: + return torch.tensor(x, dtype=torch.float16) + + +def _recip(m: torch.Tensor) -> torch.Tensor: + r = torch.rsqrt(m) + return r * r + + +class RMSNorm(nn.Module): + """Gemma RMSNorm (weight used as-is), with the max-abs rescaling in "ane" mode.""" + + def __init__(self, dim: int, eps: float, with_scale: bool = True): + super().__init__() + self.with_scale = with_scale + if with_scale: + self.weight = nn.Parameter(torch.ones(dim), requires_grad=False) + self.eps = eps + self.register_buffer("sqrt_eps16", _f16(math.sqrt(eps)), persistent=False) + self.register_buffer("floor16", _f16(NORM_FLOOR), persistent=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if PRECISION_MODE == "ane": + inv_m = _recip(torch.maximum(x.abs().amax(-1, keepdim=True), self.floor16)) + u = x * inv_m + r = self.sqrt_eps16 * inv_m + y = u * torch.rsqrt((u * u).mean(-1, keepdim=True) + r * r) + return y * self.weight if self.with_scale else y + xf = x.float() + y = xf * torch.pow(xf.pow(2).mean(-1, keepdim=True) + self.eps, -0.5) + if self.with_scale: + y = y * self.weight.float() + return y.to(x.dtype) + + +class ClippedLinear(nn.Module): + """Linear whose input and output are clamped to bounds stored in the checkpoint (Gemma4ClippableLinear). + The output bounds are per output feature so that a per-feature scale can be folded in (see load_model).""" + + def __init__(self, din: int, dout: int): + super().__init__() + self.linear = nn.Linear(din, dout, bias=False) + self.register_buffer("input_min", torch.zeros(())) + self.register_buffer("input_max", torch.zeros(())) + self.register_buffer("output_min", torch.zeros(dout)) + self.register_buffer("output_max", torch.zeros(dout)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = torch.minimum(torch.maximum(x, self.input_min), self.input_max) + y = self.linear(x) + return torch.minimum(torch.maximum(y, self.output_min), self.output_max) + + +class FeedForward(nn.Module): + def __init__(self, cfg: Cfg): + super().__init__() + self.pre_layer_norm = RMSNorm(cfg.hidden, cfg.eps) + self.ffw_layer_1 = ClippedLinear(cfg.hidden, 4 * cfg.hidden) + self.ffw_layer_2 = ClippedLinear(4 * cfg.hidden, cfg.hidden) + self.post_layer_norm = RMSNorm(cfg.hidden, cfg.eps) + self.register_buffer("res_w16", _f16(cfg.residual_weight), persistent=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.ffw_layer_2(F.silu(self.ffw_layer_1(self.pre_layer_norm(x)))) + return self.post_layer_norm(h) * self.res_w16 + x + + +class Attention(nn.Module): + """Local causal attention in banded form: 12 keys per query (self + 11 past) with the relative-position + constant relk_d added to the key at offset d. q/k scales are folded into the projections.""" + + def __init__(self, cfg: Cfg): + super().__init__() + self.H, self.D = cfg.n_heads, cfg.head_dim + self.q_proj = ClippedLinear(cfg.hidden, cfg.hidden) + self.k_proj = ClippedLinear(cfg.hidden, cfg.hidden) + self.v_proj = ClippedLinear(cfg.hidden, cfg.hidden) + self.post = ClippedLinear(cfg.hidden, cfg.hidden) + self.register_buffer("relk", torch.zeros(CTX, cfg.n_heads, cfg.head_dim)) # relative_k_proj(sinusoid(d)) + self.register_buffer("inv_softcap16", _f16(1.0 / cfg.softcap), persistent=False) + self.register_buffer("softcap16", _f16(cfg.softcap), persistent=False) + self.register_buffer("mask_value", _f16(MASK_VALUE), persistent=False) + self.register_buffer("one", _f16(1.0), persistent=False) + self.softcap = cfg.softcap + + def forward(self, x: torch.Tensor, token_mask: torch.Tensor) -> torch.Tensor: + B, T, _ = x.shape + q = self.q_proj(x).view(B, T, self.H, self.D) + k = self.k_proj(x).view(B, T, self.H, self.D) + v = self.v_proj(x).view(B, T, self.H, self.D) + logits, vs, valid = [], [], [] + for d in range(CTX): + kd = k if d == 0 else F.pad(k, (0, 0, 0, 0, d, 0))[:, :T] + vd = v if d == 0 else F.pad(v, (0, 0, 0, 0, d, 0))[:, :T] + md = token_mask if d == 0 else F.pad(token_mask, (d, 0))[:, :T] + logits.append((q * (kd + self.relk[d])).sum(-1)) # [B, T, H] + vs.append(vd) + valid.append(md) + lg = torch.stack(logits, -1) # [B, T, H, CTX] + if PRECISION_MODE == "ane": + lg = torch.tanh(lg * self.inv_softcap16) * self.softcap16 + bias = ((self.one - torch.stack(valid, -1)) * self.mask_value)[:, :, None, :] # [B, T, 1, CTX] + w = torch.softmax(lg + bias, -1) + else: + lg = torch.tanh(lg.float() / self.softcap) * self.softcap + bias = (1.0 - torch.stack(valid, -1).float())[:, :, None, :] * -1e9 + w = torch.softmax(lg + bias, -1).to(x.dtype) + o = w[..., 0:1] * vs[0] + for d in range(1, CTX): + o = o + w[..., d:d + 1] * vs[d] + return self.post(o.reshape(B, T, self.H * self.D)) + + +class LightConv(nn.Module): + def __init__(self, cfg: Cfg): + super().__init__() + self.pre_layer_norm = RMSNorm(cfg.hidden, cfg.eps) + self.linear_start = ClippedLinear(cfg.hidden, 2 * cfg.hidden) + self.depthwise_conv1d = nn.Conv1d(cfg.hidden, cfg.hidden, cfg.conv_kernel, groups=cfg.hidden, bias=False) + self.conv_norm = RMSNorm(cfg.hidden, cfg.eps) + self.linear_end = ClippedLinear(cfg.hidden, cfg.hidden) + self.hidden = cfg.hidden + self.left_pad = cfg.conv_kernel - 1 + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.linear_start(self.pre_layer_norm(x)) + h = h[..., : self.hidden] * torch.sigmoid(h[..., self.hidden:]) + h = self.depthwise_conv1d(F.pad(h.transpose(1, 2), (self.left_pad, 0))).transpose(1, 2) + return self.linear_end(F.silu(self.conv_norm(h))) + x + + +class Layer(nn.Module): + def __init__(self, cfg: Cfg): + super().__init__() + self.feed_forward1 = FeedForward(cfg) + self.norm_pre_attn = RMSNorm(cfg.hidden, cfg.eps) + self.self_attn = Attention(cfg) + self.norm_post_attn = RMSNorm(cfg.hidden, cfg.eps) + self.lconv1d = LightConv(cfg) + self.feed_forward2 = FeedForward(cfg) + self.norm_out = RMSNorm(cfg.hidden, cfg.eps) + + def forward(self, x: torch.Tensor, token_mask: torch.Tensor) -> torch.Tensor: + x = self.feed_forward1(x) + x = self.norm_post_attn(self.self_attn(self.norm_pre_attn(x), token_mask)) + x + x = self.lconv1d(x) + x = self.feed_forward2(x) + return self.norm_out(x) + + +class SubsampleLayer(nn.Module): + """Conv2d 3x3 stride 2 (no bias) + LayerNorm over the channel axis (no bias) + ReLU, on NCHW [B, C, T, F].""" + + def __init__(self, cin: int, cout: int, eps: float): + super().__init__() + self.conv = nn.Conv2d(cin, cout, 3, stride=2, padding=1, bias=False) + self.norm_weight = nn.Parameter(torch.ones(cout), requires_grad=False) + self.eps = eps + self.register_buffer("eps16", _f16(eps), persistent=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + y = self.conv(x) + if PRECISION_MODE == "ane": + mu = y.mean(1, keepdim=True) + c = y - mu + var = (c * c).mean(1, keepdim=True) + y = c * torch.rsqrt(var + self.eps16) * self.norm_weight[None, :, None, None] + else: + yf = y.float() + mu = yf.mean(1, keepdim=True) + var = (yf - mu).pow(2).mean(1, keepdim=True) + y = ((yf - mu) * torch.rsqrt(var + self.eps) * self.norm_weight.float()[None, :, None, None]).to(y.dtype) + return F.relu(y) + + +class EmbeddingGemma2Audio(nn.Module): + def __init__(self, cfg: Cfg): + super().__init__() + self.cfg = cfg + c0, c1 = cfg.conv_channels + self.layer0 = SubsampleLayer(1, c0, cfg.eps) + self.layer1 = SubsampleLayer(c0, c1, cfg.eps) + self.input_proj_linear = nn.Linear((N_MELS // 4) * c1, cfg.hidden, bias=False) + self.layers = nn.ModuleList([Layer(cfg) for _ in range(cfg.n_layers)]) + self.output_proj = nn.Linear(cfg.hidden, cfg.out_dims, bias=True) + self.pre_projection_norm = RMSNorm(cfg.out_dims, cfg.eps, with_scale=False) + self.embedding_projection = nn.Linear(cfg.out_dims, cfg.text_hidden, bias=False) + + def forward(self, features, frame_mask, half_mask, token_mask): + B, T, Fm = features.shape + x = (features * frame_mask[:, :, None])[:, None] # [B, 1, T, 128] + x = self.layer0(x) * half_mask[:, None, :, None] # [B, 128, T/2, 64] + x = self.layer1(x) # [B, 32, T/4, 32] + C, T4, Fq = x.shape[1], x.shape[2], x.shape[3] + x = self.input_proj_linear(x.permute(0, 2, 3, 1).reshape(B, T4, Fq * C)) # index f*32 + c + for layer in self.layers: + x = layer(x, token_mask) + x = self.output_proj(x) + return self.embedding_projection(self.pre_projection_norm(x)) # [B, T/4, 512] + + +def masks_for(n_frames: int, bucket: int, dtype=torch.float16) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """(frame_mask [1,Tb], half_mask [1,Tb/2], token_mask [1,Tb/4]) for n_frames valid frames in a bucket.""" + fm = torch.zeros(1, bucket, dtype=dtype) + hm = torch.zeros(1, bucket // 2, dtype=dtype) + tm = torch.zeros(1, bucket // 4, dtype=dtype) + fm[0, :n_frames] = 1 + hm[0, : (n_frames + 1) // 2] = 1 + tm[0, : ((n_frames + 1) // 2 + 1) // 2] = 1 + return fm, hm, tm + + +def n_tokens(n_frames: int) -> int: + return ((n_frames + 1) // 2 + 1) // 2 + + +def bucket_for(n_frames: int, buckets=FRAME_BUCKETS) -> int: + for b in buckets: + if b >= n_frames: + return b + raise ValueError(f"{n_frames} frames exceed the largest bucket {buckets[-1]}") + + +def relative_keys(cfg: Cfg, rel_w: torch.Tensor) -> torch.Tensor: + """relk[d] = relative_k_proj(pos_d), pos_d = [sin(d*inv), cos(d*inv)], inv_i = exp(-i ln(1e4)/(512-1)) (fp32).""" + n = cfg.hidden // 2 + inv = torch.exp(torch.arange(n, dtype=torch.float32) * -(math.log(10000.0) / max(n - 1, 1))) + d = torch.arange(CTX, dtype=torch.float32)[:, None] + scaled = d * inv[None, :] + pos = torch.cat([torch.sin(scaled), torch.cos(scaled)], -1) # [CTX, 1024] + return (pos @ rel_w.float().T).view(CTX, cfg.n_heads, cfg.head_dim) + + +def load_model(model_dir: str, dtype: torch.dtype) -> EmbeddingGemma2Audio: + from safetensors import safe_open + + cfg = Cfg(model_dir) + m = EmbeddingGemma2Audio(cfg) + sd: dict[str, torch.Tensor] = {} + with safe_open(str(Path(model_dir) / "model.safetensors"), "pt") as f: + raw = {k: f.get_tensor(k).float() for k in f.keys() if k.startswith("audio_tower.") or k.startswith("embed_audio.")} + q_scale = (cfg.head_dim ** -0.5) / math.log(2) + k_scale = math.log(1 + math.e) / math.log(2) + + def clipped(dst: str, src: str, scale: torch.Tensor | float | None = None): + w = raw[f"{src}.linear.weight"] + omin = raw[f"{src}.output_min"].expand(w.shape[0]).clone() + omax = raw[f"{src}.output_max"].expand(w.shape[0]).clone() + if scale is not None: + s = torch.as_tensor(scale, dtype=torch.float32) + assert bool((s > 0).all()) + w = w * s[:, None] if s.ndim else w * s + omin, omax = omin * s, omax * s + sd[f"{dst}.linear.weight"] = w + sd[f"{dst}.input_min"] = raw[f"{src}.input_min"] + sd[f"{dst}.input_max"] = raw[f"{src}.input_max"] + sd[f"{dst}.output_min"] = omin + sd[f"{dst}.output_max"] = omax + + sd["layer0.conv.weight"] = raw["audio_tower.subsample_conv_projection.layer0.conv.weight"] + sd["layer0.norm_weight"] = raw["audio_tower.subsample_conv_projection.layer0.norm.weight"] + sd["layer1.conv.weight"] = raw["audio_tower.subsample_conv_projection.layer1.conv.weight"] + sd["layer1.norm_weight"] = raw["audio_tower.subsample_conv_projection.layer1.norm.weight"] + sd["input_proj_linear.weight"] = raw["audio_tower.subsample_conv_projection.input_proj_linear.weight"] + for i in range(cfg.n_layers): + p = f"audio_tower.layers.{i}" + for ff in ("feed_forward1", "feed_forward2"): + clipped(f"layers.{i}.{ff}.ffw_layer_1", f"{p}.{ff}.ffw_layer_1") + clipped(f"layers.{i}.{ff}.ffw_layer_2", f"{p}.{ff}.ffw_layer_2") + sd[f"layers.{i}.{ff}.pre_layer_norm.weight"] = raw[f"{p}.{ff}.pre_layer_norm.weight"] + sd[f"layers.{i}.{ff}.post_layer_norm.weight"] = raw[f"{p}.{ff}.post_layer_norm.weight"] + for nm in ("norm_pre_attn", "norm_post_attn", "norm_out"): + sd[f"layers.{i}.{nm}.weight"] = raw[f"{p}.{nm}.weight"] + a = f"{p}.self_attn" + per_dim = F.softplus(raw[f"{a}.per_dim_scale"]) * q_scale # [128], applied per head dim, shared by heads + clipped(f"layers.{i}.self_attn.q_proj", f"{a}.q_proj", per_dim.repeat(cfg.n_heads)) + clipped(f"layers.{i}.self_attn.k_proj", f"{a}.k_proj", k_scale) + clipped(f"layers.{i}.self_attn.v_proj", f"{a}.v_proj") + clipped(f"layers.{i}.self_attn.post", f"{a}.post") + sd[f"layers.{i}.self_attn.relk"] = relative_keys(cfg, raw[f"{a}.relative_k_proj.weight"]) + c = f"{p}.lconv1d" + sd[f"layers.{i}.lconv1d.pre_layer_norm.weight"] = raw[f"{c}.pre_layer_norm.weight"] + clipped(f"layers.{i}.lconv1d.linear_start", f"{c}.linear_start") + sd[f"layers.{i}.lconv1d.depthwise_conv1d.weight"] = raw[f"{c}.depthwise_conv1d.weight"] + sd[f"layers.{i}.lconv1d.conv_norm.weight"] = raw[f"{c}.conv_norm.weight"] + clipped(f"layers.{i}.lconv1d.linear_end", f"{c}.linear_end") + sd["output_proj.weight"] = raw["audio_tower.output_proj.weight"] + sd["output_proj.bias"] = raw["audio_tower.output_proj.bias"] + sd["embedding_projection.weight"] = raw["embed_audio.embedding_projection.weight"] + sd = {k: v.to(dtype) for k, v in sd.items()} + missing, unexpected = m.load_state_dict(sd, strict=False) + missing = [k for k in missing if not any(s in k for s in ("sqrt_eps16", "floor16", "eps16", "res_w16", "inv_softcap16", + "softcap16", "mask_value", "one"))] + assert not missing and not unexpected, (missing, unexpected) + return m.to(dtype).eval() diff --git a/export/export.py b/export/export.py index 3a4ecaf6aebef8d9fbbe97cd710fbb3be1f46bd0..454d478d6f544ad148b88b035617e7c7e48d2fdf 100644 --- a/export/export.py +++ b/export/export.py @@ -1,11 +1,15 @@ # Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). -"""Export EmbeddingGemma 2 (text + images) to the two Core AI `.aimodel` assets of this package. +"""Export EmbeddingGemma 2 (text + images + audio) to the three Core AI `.aimodel` assets of this package. # 1. download the original checkpoint: hf download google/embeddinggemma-2 --local-dir ./embeddinggemma-2 # 2. python3 -W ignore export.py --model-dir ./embeddinggemma-2 --out \ - # --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --date 2026-10-12 (the released bundle, ~2 min) + # --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --audio-buckets 192,384,1024,1536,3000 --date 2026-10-12 + # (the released bundle, ~3 min) -Written to (see README "Why two assets"): +Written to (see README "Why three assets"): + embeddinggemma-2-audio.aimodel functions audio_: features [1,Tb,128] fp16 (log-mel frames), frame_mask [1,Tb], + half_mask [1,Tb/2], token_mask [1,Tb/4] fp16 -> soft_tokens [1,Tb/4,512] fp16 + (eg2_audio.py; Tb in 192, 384, 1024, 1536, 3000 frames of 10 ms) embeddinggemma-2-text-mm.aimodel functions mm_: input_ids [1,S] int32, attention_mask [1,S] fp16, mm_embeds [1,S,512] fp16, mm_mask [1,S] fp16 -> embedding [1,768] fp16. The text encoder (eg2_text.py, unchanged from v1.0) with a soft-token mix at the @@ -16,7 +20,8 @@ Written to (see README "Why two assets"): tokenizer/ unchanged Gemma tokenizer (text queries and the image sequence ids) config.json, MODEL-ATTRIBUTION.json -`--part text` / `--part vision` re-exports one asset and keeps the other one's entry of an existing config.json. +`--part text` / `--part vision` / `--part audio` re-exports one asset and keeps the others' entries of an existing +config.json. The result is functionally identical to the released bundle, not byte-identical: the converter names internal graph resources at random (main.mlirb / main.hash differ) and the runtime writes metadata.json with the export time. @@ -40,6 +45,7 @@ import torch LAB = Path(__file__).resolve().parent sys.path.insert(0, str(LAB)) +import eg2_audio # noqa: E402 import eg2_text # noqa: E402 import eg2_text_mm # noqa: E402 import eg2_vision # noqa: E402 @@ -55,7 +61,8 @@ PROMPTS = { "clustering": "task: clustering | query: ", "sentence_similarity": "task: sentence similarity | query: ", } -SPECIAL = {"bos": 2, "eos": 1, "pad": 0, "boi": 255999, "image": 258880, "eoi": 258882, "video": 258884} +SPECIAL = {"bos": 2, "eos": 1, "pad": 0, "boi": 255999, "image": 258880, "eoi": 258882, "video": 258884, + "boa": 256000, "audio": 258881, "eoa": 258883} def log(msg: str) -> None: @@ -119,6 +126,42 @@ def export_vision(args, out: Path) -> dict: return {"asset": asset.name, "function": fn, "max_patches": N, "max_soft_tokens": eg2_vision.MAX_SOFT, "qchunks": args.qchunks} +def export_audio(args, out: Path, buckets: list[int]) -> dict: + """One dynamic-T torch.export (T = 4t) of eg2_audio, specialized to the frame buckets as functions audio_.""" + import coreai_torch + from torch.export import Dim + + eg2_audio.PRECISION_MODE = "ane" + model = eg2_audio.load_model(args.model_dir, torch.float16) + if args.num_layers: + model.layers = model.layers[: args.num_layers] + log(f"audio model loaded: {sum(p.numel() for p in model.parameters()) / 1e6:.1f} M params; frame buckets {buckets}") + assert all(b % 4 == 0 for b in buckets) and len(buckets) >= 2 + names = ["features", "frame_mask", "half_mask", "token_mask"] + b0 = buckets[1] + ex = {"features": torch.randn(1, b0, 128, dtype=torch.float16), "frame_mask": torch.ones(1, b0, dtype=torch.float16), + "half_mask": torch.ones(1, b0 // 2, dtype=torch.float16), "token_mask": torch.ones(1, b0 // 4, dtype=torch.float16)} + t = Dim("t", min=buckets[0] // 4, max=buckets[-1] // 4) + dyn = {"features": {1: 4 * t}, "frame_mask": {1: 4 * t}, "half_mask": {1: 2 * t}, "token_mask": {1: t}} + with torch.no_grad(): + ep = torch.export.export(model, args=(), kwargs=ex, dynamic_shapes=dyn) + log("torch.export (audio) done") + ep = ep.run_decompositions(coreai_torch.get_decomp_table()) + conv = coreai_torch.TorchConverter(mode=coreai_torch.TorchConverter.Mode.DEBUG if args.debug_info else coreai_torch.TorchConverter.Mode.RELEASE) + conv.add_exported_program(ep, input_names=names, output_names=["soft_tokens"], entrypoint_name="audio") + prog = conv.to_coreai() + log("converted audio to AIProgram") + cfg = {f'"{b}"': {"features": (1, b, 128), "frame_mask": (1, b), "half_mask": (1, b // 2), "token_mask": (1, b // 4)} for b in buckets} + prog.set_static_shape_config("audio", cfg) + functions = [f"audio_{b}" for b in buckets] + log(f"static shape specializations: {functions}") + asset = out / "embeddinggemma-2-audio.aimodel" + save_asset(prog, asset, f"EmbeddingGemma 2 audio encoder ({args.hf_id}): log-mel frames -> soft tokens in the text space; " + f"fp16, banded local attention, max-abs RMSNorm; frame buckets {buckets}.") + return {"asset": asset.name, "functions": functions, "frame_buckets": buckets, "max_frames": buckets[-1], + "max_soft_tokens": buckets[-1] // 4} + + def export_text_mm(args, out: Path, buckets: list[int]) -> dict: import coreai_torch from torch.export import Dim @@ -160,10 +203,13 @@ def main() -> None: ap.add_argument("--model-dir", required=True, help="folder with the original google/embeddinggemma-2 checkpoint") ap.add_argument("--hf-id", default="google/embeddinggemma-2") ap.add_argument("--out", required=True) - ap.add_argument("--part", default="all", choices=["all", "text", "vision"]) + ap.add_argument("--part", default="all", choices=["all", "text", "vision", "audio"]) ap.add_argument("--buckets", default="32,64,128,288,512,1024,2048") ap.add_argument("--qchunks", type=int, default=12, help="split the vision attention's queries into N blocks (released: 12; 1 = one 2520x2520 matmul per layer)") + ap.add_argument("--audio-buckets", default="192,384,1024,1536,3000", + help="frame buckets of the audio encoder (multiples of 4; only the default set is validated on the Neural " + "Engine, see README)") ap.add_argument("--num-layers", type=int, default=None, help="smoke export with the first N layers") ap.add_argument("--debug-info", action="store_true") ap.add_argument("--date", default=None, help="port date written to MODEL-ATTRIBUTION.json (default: today)") @@ -176,12 +222,17 @@ def main() -> None: vision = ({k: existing["vision"][k] for k in ("asset", "function", "max_patches", "max_soft_tokens", "qchunks")} if "vision" in existing else None) text = {k: existing[k] for k in ("asset", "functions", "buckets", "max_tokens")} if "asset" in existing else None + audio = ({k: existing["audio"][k] for k in ("asset", "functions", "frame_buckets", "max_frames", "max_soft_tokens")} + if "audio" in existing else None) + audio_buckets = sorted(int(b) for b in args.audio_buckets.split(",")) if args.part in ("all", "text"): text = export_text_mm(args, out, buckets) if args.part in ("all", "vision"): vision = export_vision(args, out) - if text is None or vision is None: - raise SystemExit("--part text|vision needs an existing config.json in --out with the other asset's entry") + if args.part in ("all", "audio"): + audio = export_audio(args, out, audio_buckets) + if text is None or vision is None or audio is None: + raise SystemExit("--part text|vision|audio needs an existing config.json in --out with the other assets' entries") tok_dir = out / "tokenizer" tok_dir.mkdir(exist_ok=True) @@ -206,10 +257,22 @@ def main() -> None: "resize": "aspect-preserving to multiples of 48 px within 2520 patches; antialiased bicubic on uint8 (torchvision-exact)", "image_prompt": None, "exif_orientation": "not applied (upstream parity); optional in the runners"}, "image_sequence": " <|image> <|image|> x n_soft (n_soft + 4 tokens, at most 284 -> bucket 288)", + "audio": {**audio, "inputs": { + "features": "[1, Tb, 128] float16 log-mel frames (10 ms hop, 128 HTK mel bands, ln(mel + 1e-3)), the first n_frames rows real, zero after", + "frame_mask": "[1, Tb] float16 (1 for the first n_frames rows)", + "half_mask": "[1, Tb/2] float16 (1 for the first ceil(n_frames/2) rows)", + "token_mask": "[1, Tb/4] float16 (1 for the first ceil(ceil(n_frames/2)/2) rows = the soft-token count)"}, + "output": {"soft_tokens": "[1, Tb/4, 512] float16; rows >= n_tokens are padding"}, + "sample_rate": 16000, "max_seconds": 30.0, "max_samples": 480000, "frame_ms": 20, "hop_ms": 10, "fft": 512, "n_mels": 128, + "frames_per_token": 4, "front_end": "python/eg2_audio_frontend.py, swift AudioFrontend (upstream Gemma4AudioFeatureExtractor defaults)", + "resampler": "Kaiser-windowed sinc, pass band 0.913 / stop band 1.0 of the lower Nyquist, 125 dB (upstream: libsoxr HQ)", + "audio_prompt": None, "long_audio": "the first 30 s (upstream); the runners also offer the mean of 30 s windows"}, + "audio_sequence": " <|audio> <|audio|> x n_tokens (n_tokens + 4 tokens, at most 754 -> bucket 1024)", "hidden_size": 512, "embedding_dim": 768, "matryoshka_dims": [768, 512, 256, 128], "bos_token_id": SPECIAL["bos"], "eos_token_id": SPECIAL["eos"], "pad_token_id": SPECIAL["pad"], "boi_token_id": SPECIAL["boi"], "image_token_id": SPECIAL["image"], "eoi_token_id": SPECIAL["eoi"], - "video_token_id": SPECIAL["video"], "prompts": PROMPTS, + "video_token_id": SPECIAL["video"], "boa_token_id": SPECIAL["boa"], "audio_token_id": SPECIAL["audio"], + "eoa_token_id": SPECIAL["eoa"], "prompts": PROMPTS, "tokenizer": "tokenizer/tokenizer.json (unchanged Gemma tokenizer; the runner adds and )", } (out / "config.json").write_text(json.dumps(cfg_json, indent=2) + "\n") @@ -219,7 +282,7 @@ def main() -> None: tb = text["buckets"] attribution = { "name": "EmbeddingGemma-2-CoreAI", - "version": "1.1", + "version": "1.2", "base_model": args.hf_id, "base_model_author": "Gemma Team, Google DeepMind", "base_model_source": f"https://huggingface.co/{args.hf_id}", @@ -233,14 +296,25 @@ def main() -> None: "format": "Apple Core AI .aimodel (macOS 27), fp16, static shapes", "exporter": { "coreai_torch": ct.__version__, "coreai_core": pkg_version("coreai-core"), "torch": torch.__version__.split("+")[0], - "recipe": f"export/export.py --buckets {','.join(map(str, tb))} --qchunks {vision['qchunks']}", + "recipe": f"export/export.py --buckets {','.join(map(str, tb))} --qchunks {vision['qchunks']} " + f"--audio-buckets {','.join(map(str, audio['frame_buckets']))}", "global_attention": eg2_text.GLOBAL_ATTN_MODE, "gqa": eg2_text.GQA_MODE, }, }, "modifications": [ - "Text and image encoders only: the audio encoder of the multimodal checkpoint is not included.", + "All three encoders of the multimodal checkpoint (text, vision, audio) are included, as separate assets.", "Architecture re-authored in plain PyTorch for Core AI export; weights are the original ones (bf16 rounded " "to fp16), with the scale folds and table cuts listed below.", + "Audio: encoder (Gemma4AudioModel: subsampling convolutions, 12 conformer layers) and audio embedder re-authored " + "in plain PyTorch; the chunked local attention is written in its banded form (each token attends to itself and " + "the 11 previous tokens; the relative-position term is a per-layer constant), the q/k scales are folded into " + "q_proj/k_proj and their clip bounds, the gradient-clipping clamps are dropped, the padded-key mask is an " + "additive -10000, every RMSNorm uses the max-abs rescaling (fp16). Mathematically identical to the reference " + "(fp32 soft-token cosine >= 0.99999998 on 213 clips).", + f"Audio: fixed frame buckets {', '.join(map(str, audio['frame_buckets']))} (10 ms frames) as functions audio_; " + "inputs longer than 30 s are truncated by the host (the upstream default). The three masks are host inputs.", + "Audio preprocessing (host): the upstream log-mel feature extractor re-implemented in numpy and Swift (bit-exact " + "in numpy); resampling to 16 kHz with a Kaiser-windowed sinc instead of upstream's libsoxr (see README).", "Text: the sqrt(512) token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into the tables.", "Text: the four global (full-attention, single-kv-head) layers compute attention as a plain 4-D matmul with k/v " "broadcast over the heads; the sliding-window layers use a 5-D grouped matmul. Mathematically identical to " diff --git a/model/MODEL-ATTRIBUTION.json b/model/MODEL-ATTRIBUTION.json index 865e4426f37715279bfc7f7d894960d506e3fb95..18af0bcfd88037378417bec4bbb9b6031b7313d1 100644 --- a/model/MODEL-ATTRIBUTION.json +++ b/model/MODEL-ATTRIBUTION.json @@ -1,6 +1,6 @@ { "name": "EmbeddingGemma-2-CoreAI", - "version": "1.1", + "version": "1.2", "base_model": "google/embeddinggemma-2", "base_model_author": "Gemma Team, Google DeepMind", "base_model_source": "https://huggingface.co/google/embeddinggemma-2", @@ -18,14 +18,17 @@ "coreai_torch": "0.4.3", "coreai_core": "1.0.0b3", "torch": "2.9.0", - "recipe": "export/export.py --buckets 32,64,128,288,512,1024,2048 --qchunks 12", + "recipe": "export/export.py --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --audio-buckets 192,384,1024,1536,3000", "global_attention": "mqa4d", "gqa": "grouped5d" } }, "modifications": [ - "Text and image encoders only: the audio encoder of the multimodal checkpoint is not included.", + "All three encoders of the multimodal checkpoint (text, vision, audio) are included, as separate assets.", "Architecture re-authored in plain PyTorch for Core AI export; weights are the original ones (bf16 rounded to fp16), with the scale folds and table cuts listed below.", + "Audio: encoder (Gemma4AudioModel: subsampling convolutions, 12 conformer layers) and audio embedder re-authored in plain PyTorch; the chunked local attention is written in its banded form (each token attends to itself and the 11 previous tokens; the relative-position term is a per-layer constant), the q/k scales are folded into q_proj/k_proj and their clip bounds, the gradient-clipping clamps are dropped, the padded-key mask is an additive -10000, every RMSNorm uses the max-abs rescaling (fp16). Mathematically identical to the reference (fp32 soft-token cosine >= 0.99999998 on 213 clips).", + "Audio: fixed frame buckets 192, 384, 1024, 1536, 3000 (10 ms frames) as functions audio_; inputs longer than 30 s are truncated by the host (the upstream default). The three masks are host inputs.", + "Audio preprocessing (host): the upstream log-mel feature extractor re-implemented in numpy and Swift (bit-exact in numpy); resampling to 16 kHz with a Kaiser-windowed sinc instead of upstream's libsoxr (see README).", "Text: the sqrt(512) token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into the tables.", "Text: the four global (full-attention, single-kv-head) layers compute attention as a plain 4-D matmul with k/v broadcast over the heads; the sliding-window layers use a 5-D grouped matmul. Mathematically identical to the reference (fp32 max abs diff 3e-7).", "fp16 everywhere (Neural Engine): every RMSNorm and the final L2 normalization divide the row by its max-abs value before squaring (text activations reach ~2000, the vision residual ~1400); in the model code every division is expressed as rsqrt(x)*rsqrt(x) (the Neural Engine compiler rejects divide).", diff --git a/model/config.json b/model/config.json index a39f819c784299b3748586d8d3e3351404b5b37d..02d76e41bb05d0a41a226a58f0f39d2fa6361352 100644 --- a/model/config.json +++ b/model/config.json @@ -59,6 +59,47 @@ "exif_orientation": "not applied (upstream parity); optional in the runners" }, "image_sequence": " <|image> <|image|> x n_soft (n_soft + 4 tokens, at most 284 -> bucket 288)", + "audio": { + "asset": "embeddinggemma-2-audio.aimodel", + "functions": [ + "audio_192", + "audio_384", + "audio_1024", + "audio_1536", + "audio_3000" + ], + "frame_buckets": [ + 192, + 384, + 1024, + 1536, + 3000 + ], + "max_frames": 3000, + "max_soft_tokens": 750, + "inputs": { + "features": "[1, Tb, 128] float16 log-mel frames (10 ms hop, 128 HTK mel bands, ln(mel + 1e-3)), the first n_frames rows real, zero after", + "frame_mask": "[1, Tb] float16 (1 for the first n_frames rows)", + "half_mask": "[1, Tb/2] float16 (1 for the first ceil(n_frames/2) rows)", + "token_mask": "[1, Tb/4] float16 (1 for the first ceil(ceil(n_frames/2)/2) rows = the soft-token count)" + }, + "output": { + "soft_tokens": "[1, Tb/4, 512] float16; rows >= n_tokens are padding" + }, + "sample_rate": 16000, + "max_seconds": 30.0, + "max_samples": 480000, + "frame_ms": 20, + "hop_ms": 10, + "fft": 512, + "n_mels": 128, + "frames_per_token": 4, + "front_end": "python/eg2_audio_frontend.py, swift AudioFrontend (upstream Gemma4AudioFeatureExtractor defaults)", + "resampler": "Kaiser-windowed sinc, pass band 0.913 / stop band 1.0 of the lower Nyquist, 125 dB (upstream: libsoxr HQ)", + "audio_prompt": null, + "long_audio": "the first 30 s (upstream); the runners also offer the mean of 30 s windows" + }, + "audio_sequence": " <|audio> <|audio|> x n_tokens (n_tokens + 4 tokens, at most 754 -> bucket 1024)", "hidden_size": 512, "embedding_dim": 768, "matryoshka_dims": [ @@ -74,6 +115,9 @@ "image_token_id": 258880, "eoi_token_id": 258882, "video_token_id": 258884, + "boa_token_id": 256000, + "audio_token_id": 258881, + "eoa_token_id": 258883, "prompts": { "document": "title: none | text: ", "search_query": "task: search result | query: ", diff --git a/model/embeddinggemma-2-audio.aimodel/main.hash b/model/embeddinggemma-2-audio.aimodel/main.hash new file mode 100644 index 0000000000000000000000000000000000000000..52479a368d85b1fb4dc0036ec67605a97b0731c3 --- /dev/null +++ b/model/embeddinggemma-2-audio.aimodel/main.hash @@ -0,0 +1 @@ +œ¥�°›2zŒ®”̬ã !®W¤£ò¨¶T[Áß•ø \ No newline at end of file diff --git a/model/embeddinggemma-2-audio.aimodel/main.mlirb b/model/embeddinggemma-2-audio.aimodel/main.mlirb new file mode 100644 index 0000000000000000000000000000000000000000..a8786beadad2c0e77385b30a3c8b4e9ac7b28572 --- /dev/null +++ b/model/embeddinggemma-2-audio.aimodel/main.mlirb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ca590b09b327f7a8cae94ccace30d151621ae57a4a3f2a8b654145bc1df95f8 +size 589332135 diff --git a/model/embeddinggemma-2-audio.aimodel/metadata.json b/model/embeddinggemma-2-audio.aimodel/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..34d5909e9028d114f4f2133dbaba8ab996055e8b --- /dev/null +++ b/model/embeddinggemma-2-audio.aimodel/metadata.json @@ -0,0 +1,8 @@ +{ + "assetVersion" : "2.0", + "description" : "EmbeddingGemma 2 audio encoder (google\/embeddinggemma-2): log-mel frames -> soft tokens in the text space; fp16, banded local attention, max-abs RMSNorm; frame buckets [192, 384, 1024, 1536, 3000].", + "creationDate" : "20261012T145159Z", + "author" : "Gemma Team (Google); Core AI port", + "license" : "Apache-2.0", + "producer" : "coreai-core 1.0.0b3" +} \ No newline at end of file diff --git a/python/eg2_audio_frontend.py b/python/eg2_audio_frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..82d96af6ac83d2cb9562a17cc5cd56590bc36379 --- /dev/null +++ b/python/eg2_audio_frontend.py @@ -0,0 +1,373 @@ +# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). +# +# The log-mel feature extraction re-implements the defaults of Gemma4AudioFeatureExtractor +# (feature_extraction_gemma4.py in Hugging Face transformers 5.19, Copyright 2026 Google LLC, Apache-2.0) as used by +# sentence-transformers for google/embeddinggemma-2, and the HTK mel filter-bank formula of transformers' +# audio_utils.py (Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio authors, Apache-2.0; the +# formula as in librosa / torchaudio). No transformers code is included. +"""Audio front end for EmbeddingGemma 2 on Core AI: file -> 16 kHz mono -> log-mel frames -> model inputs (numpy only). + +Reference pipeline (what upstream does with a file path: librosa.load(sr=16000) then the feature extractor): + 1. decode to float32 at the file's own rate; 2. mix to mono (mean of the channels, float32); + 3. resample to 16 kHz; 4. keep the first 30 s (480 000 samples); 5. log-mel frames every 10 ms. +This module keeps 1, 2, 4 and 5 identical to upstream. For 3, upstream uses libsoxr "HQ"; this package uses its own +Kaiser-windowed sinc (polyphase, 125 dB stop band, pass band 0.913 of 8 kHz), implemented identically here and in +Swift (`AudioResampler`), see README "Audio: decoding and resampling" for the measured difference (16 kHz input, +the model's native rate, is never resampled and is exact). + + import eg2_audio_frontend + wav = eg2_audio_frontend.load_mono_16k("clip.wav") # float32 [n] at 16 kHz + inputs = eg2_audio_frontend.prepare_audio_inputs(wav) # AudioInputs for the audio_ function + ids = eg2_audio_frontend.audio_sequence(inputs.n_tokens, ...) # [n] + +Decoders: `soundfile` (libsndfile, the decoder upstream's librosa uses: WAV, AIFF, FLAC, OGG, CAF/ALAC, MP3 with +gapless trimming) when it is installed, otherwise, and for AAC/M4A always, macOS `afconvert` (Apple's AudioToolbox +decoder; MP3 files are trimmed with the LAME/Info tag here so that they match libsndfile; see README). +""" +from __future__ import annotations + +import math +import os +import shutil +import struct +import subprocess +import tempfile +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +SAMPLE_RATE = 16000 +FRAME_LENGTH = 320 # 20 ms +HOP_LENGTH = 160 # 10 ms +FFT_LENGTH = 512 +N_MELS = 128 +F_MIN, F_MAX = 0.0, 8000.0 +MEL_FLOOR = 1e-3 +MAX_SAMPLES = 480_000 # 30 s: the upstream default (truncation=True) +PAD_MULTIPLE = 128 # samples +FRAME_BUCKETS = [192, 384, 1024, 1536, 3000] +MAX_FRAMES = 2999 # valid frames of 30 s + +# resampler design (shared with Swift AudioResampler; do not change one without the other) +RESAMPLE_PASSBAND = 0.913 # of the lower Nyquist (8 kHz when downsampling) +RESAMPLE_STOPBAND = 1.0 +RESAMPLE_ATTEN_DB = 125.0 + + +# ------------------------------------------------------------------------------------------------ decoding +@dataclass +class DecodedAudio: + samples: np.ndarray # float32 [frames, channels] + sample_rate: int + decoder: str + + +SOUNDFILE_EXT = {".wav", ".wave", ".aif", ".aiff", ".aifc", ".flac", ".ogg", ".oga", ".mp3", ".caf", ".w64", ".rf64"} + + +def decode(path: str | os.PathLike) -> DecodedAudio: + """float32 [frames, channels] at the file's own rate. libsndfile (soundfile) where available, Apple's decoder + (afconvert) otherwise; MP3 encoder delay/padding trimmed in both cases (libsndfile does it itself).""" + path = Path(path) + if path.suffix.lower() in SOUNDFILE_EXT: + try: + import soundfile as sf + except ImportError: + sf = None + if sf is not None: + try: + x, sr = sf.read(str(path), dtype="float32", always_2d=True) + return DecodedAudio(np.ascontiguousarray(x, dtype=np.float32), int(sr), "libsndfile") + except Exception: # noqa: BLE001 - fall back to Apple's decoder + pass + return _decode_afconvert(path) + + +def _decode_afconvert(path: Path) -> DecodedAudio: + afconvert = shutil.which("afconvert") + if not afconvert: + raise RuntimeError(f"cannot decode {path.name}: install soundfile (pip install soundfile) or run on macOS") + with tempfile.TemporaryDirectory() as td: + out = Path(td) / "decoded.wav" + subprocess.run([afconvert, "-f", "WAVE", "-d", "LEF32", str(path), str(out)], check=True, capture_output=True) + x, sr = _read_wav_f32(out) + if path.suffix.lower() == ".mp3": + x = _mp3_trim(x, mp3_gapless_info(path)) + return DecodedAudio(x, sr, "afconvert") + + +def _mp3_trim(x: np.ndarray, info: tuple[int, int, int, int] | None) -> np.ndarray: + """Brings Apple's MP3 output to libsndfile's gapless length. AudioToolbox applies the LAME tag itself for most + files, returns whole frames for some, and for others trims the delay but keeps one or two whole frames too many + at the end (it counts the Xing/Info frame as audio: `afinfo` shows one packet more than the tag's frame count). + Same rule in Swift (AudioDecoder).""" + if info is None: + return x + frames, spf, delay, padding = info + full = frames * spf + gapless = full - delay - padding + if len(x) == full: # untrimmed: cut delay and padding + return x[delay: len(x) - padding] if padding else x[delay:] + if gapless > 0 and len(x) > gapless and (len(x) - gapless) % spf == 0 and len(x) - gapless <= 2 * spf: + return x[:gapless] # delay trimmed, whole extra frames at the end + return x + + +def _read_wav_f32(path: Path) -> tuple[np.ndarray, int]: + b = path.read_bytes() + assert b[:4] == b"RIFF" and b[8:12] == b"WAVE", "afconvert did not write a WAVE file" + p, fmt, data = 12, None, None + while p + 8 <= len(b): + cid, size = b[p:p + 4], struct.unpack(" tuple[int, int, int, int] | None: + """(frames, samples per frame, encoder delay, padding) from the Xing/Info + LAME tag of the first MPEG frame, + None if absent. Apple's decoder compensates the 529-sample decoder delay itself; libsndfile (mpg123) trims + the delay and the padding too (gapless), which is the reference behaviour.""" + with open(path, "rb") as f: + b = f.read(1 << 20) + i = 0 + if b[:3] == b"ID3": + i = 10 + (((b[6] & 0x7F) << 21) | ((b[7] & 0x7F) << 14) | ((b[8] & 0x7F) << 7) | (b[9] & 0x7F)) + while i < len(b) - 4 and not (b[i] == 0xFF and (b[i + 1] & 0xE0) == 0xE0): + i += 1 + if i >= len(b) - 4: + return None + mpeg1 = ((b[i + 1] >> 3) & 3) == 3 + mono = ((b[i + 3] >> 6) & 3) == 3 + side = (17 if mono else 32) if mpeg1 else (9 if mono else 17) + p = i + 4 + side + if b[p:p + 4] not in (b"Xing", b"Info"): + return None + flags = struct.unpack(">I", b[p + 4:p + 8])[0] + p += 8 + if not flags & 1: + return None + frames = struct.unpack(">I", b[p:p + 4])[0] + p += 4 + (4 if flags & 2 else 0) + (100 if flags & 4 else 0) + (4 if flags & 8 else 0) + d = b[p + 21:p + 24] + if len(d) < 3 or not b[p:p + 4].isalpha(): + return None + return frames, 1152 if mpeg1 else 576, (d[0] << 4) | (d[1] >> 4), ((d[1] & 0x0F) << 8) | d[2] + + +def to_mono(x: np.ndarray) -> np.ndarray: + """Mean over channels in float32 (librosa.to_mono), [frames, channels] -> [frames].""" + x = np.asarray(x, dtype=np.float32) + if x.ndim == 1: + return x + if x.shape[1] == 1: + return np.ascontiguousarray(x[:, 0]) + acc = x[:, 0].copy() + for c in range(1, x.shape[1]): # sequential float32 sum, then one divide (same order as Swift) + acc = acc + x[:, c] + return (acc / np.float32(x.shape[1])).astype(np.float32) + + +# ------------------------------------------------------------------------------------------------ resampling +def _bessel_i0(x: float) -> float: + """Modified Bessel function of order 0 by its power series (same code in Swift).""" + s, t, k = 1.0, 1.0, 1 + h = x / 2.0 + while True: + t *= (h / k) ** 2 + s += t + if t < s * 1e-17: + return s + k += 1 + + +def sinc_filter(up: int, down: int, in_rate: int) -> tuple[np.ndarray, int]: + """Kaiser-windowed sinc low-pass for the polyphase resampler in_rate -> in_rate*up/down (float64 taps, odd length, + unity DC gain). Returns (taps, delay = (len-1)/2). Pass band 0.913 and stop band 1.0 of the lower Nyquist.""" + nyq_low = min(in_rate, in_rate * up // down) / 2.0 + nyq_hi = in_rate * up / 2.0 + fc = 0.5 * (RESAMPLE_PASSBAND + RESAMPLE_STOPBAND) * nyq_low / nyq_hi # normalized cutoff (1 = nyq_hi) + tw = (RESAMPLE_STOPBAND - RESAMPLE_PASSBAND) * nyq_low / nyq_hi + beta = 0.1102 * (RESAMPLE_ATTEN_DB - 8.7) + n = int(math.ceil((RESAMPLE_ATTEN_DB - 7.95) / (2.285 * math.pi * tw))) + n |= 1 + c = (n - 1) // 2 + i0b = _bessel_i0(beta) + h = np.empty(n, dtype=np.float64) + for k in range(n): + m = k - c + sinc = fc if m == 0 else math.sin(math.pi * fc * m) / (math.pi * m) + r = 2.0 * k / (n - 1) - 1.0 + w = _bessel_i0(beta * math.sqrt(max(0.0, 1.0 - r * r))) / i0b + h[k] = sinc * w + h /= h.sum() + return h, c + + +_FILTERS: dict[tuple[int, int, int], tuple[np.ndarray, int]] = {} + + +def resample_16k(x: np.ndarray, sr: int) -> np.ndarray: + """float32 [n] at sr -> float32 [ceil(n*16000/sr)] at 16 kHz (output length as librosa's fix=True). + Polyphase windowed sinc computed in float64: y[j] = up * sum_m x[m] h[c + j*down - m*up].""" + x = np.asarray(x, dtype=np.float32) + if sr == SAMPLE_RATE: + return x + n_out = int(math.ceil(len(x) * SAMPLE_RATE / sr)) + g = math.gcd(SAMPLE_RATE, sr) + up, down = SAMPLE_RATE // g, sr // g + key = (up, down, sr) + if key not in _FILTERS: + _FILTERS[key] = sinc_filter(up, down, sr) + h, c = _FILTERS[key] + xd = x.astype(np.float64) + y = np.zeros(n_out, dtype=np.float64) + nh = len(h) + # polyphase branches: outputs j with the same phase p = (j*down) % up share the taps h[c + p + r*up] + for p in range(up): + # outputs j with (j*down) % up == p + j0 = next((j for j in range(up) if (j * down) % up == p), None) + if j0 is None: + continue + js = np.arange(j0, n_out, up) + if len(js) == 0: + continue + # for these outputs, c + j*down - m*up = c + p + q*up - m*up with q = (j*down - p)//up -> taps at offsets + # k = c + p + (q - m)*up ; let r = q - m, k in [0, nh): r from ceil((-c-p)/up) to floor((nh-1-c-p)/up) + r_min = -((c + p) // up) + r_max = (nh - 1 - c - p) // up + q = (js * down - p) // up + acc = np.zeros(len(js), dtype=np.float64) + for r in range(r_min, r_max + 1): + k = c + p + r * up + m = q - r + ok = (m >= 0) & (m < len(xd)) + if not ok.any(): + continue + acc[ok] += h[k] * xd[m[ok]] + y[js] = acc * up + return y.astype(np.float32) + + +def load_mono_16k(path: str | os.PathLike) -> np.ndarray: + """decode -> mono -> 16 kHz (the librosa.load(sr=16000, mono=True) order), float32 [n].""" + d = decode(path) + return resample_16k(to_mono(d.samples), d.sample_rate) + + +# ------------------------------------------------------------------------------------------------ features +def _hz_to_mel_htk(f): + return 2595.0 * np.log10(1.0 + np.asarray(f, dtype=np.float64) / 700.0) + + +def _mel_to_hz_htk(m): + return 700.0 * (10.0 ** (np.asarray(m, dtype=np.float64) / 2595.0) - 1.0) + + +def mel_filters() -> np.ndarray: + """[257, 128] float64 triangular HTK filters, unnormalized (transformers mel_filter_bank(norm=None, mel_scale='htk')).""" + n_bins = FFT_LENGTH // 2 + 1 + mels = np.linspace(_hz_to_mel_htk(F_MIN), _hz_to_mel_htk(F_MAX), N_MELS + 2) + filter_freqs = _mel_to_hz_htk(mels) + fft_freqs = np.linspace(0, SAMPLE_RATE // 2, n_bins) + diff = np.diff(filter_freqs) + slopes = filter_freqs[None, :] - fft_freqs[:, None] + down = -slopes[:, :-2] / diff[:-1] + up = slopes[:, 2:] / diff[1:] + return np.maximum(0.0, np.minimum(down, up)) + + +def hann_periodic(n: int = FRAME_LENGTH) -> np.ndarray: + return (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)).astype(np.float32) + + +_MEL = None +_WIN = None + + +def num_valid_frames(n_samples: int) -> int: + """Frames whose whole 321-sample analysis window (incl. the 160-sample left pad) lies in real audio (max 2999).""" + n = min(n_samples, MAX_SAMPLES) + return max(0, (n + FRAME_LENGTH // 2 - (FRAME_LENGTH + 1)) // HOP_LENGTH + 1) + + +def n_audio_tokens(n_valid_frames: int) -> int: + return ((n_valid_frames + 1) // 2 + 1) // 2 + + +def log_mel(wav16k: np.ndarray, max_samples: int | None = MAX_SAMPLES) -> np.ndarray: + """[n_valid_frames, 128] float32 log-mel features, bit-for-bit the upstream feature extractor (invalid frames, + which upstream zeroes and masks, are not returned).""" + global _MEL, _WIN + if _MEL is None: + _MEL, _WIN = mel_filters(), hann_periodic() + x = np.asarray(wav16k, dtype=np.float32) + if max_samples is not None: + x = x[:max_samples] + n = len(x) + T = num_valid_frames(n) + if T <= 0: + return np.zeros((0, N_MELS), np.float32) + n_pad = int(math.ceil(n / PAD_MULTIPLE) * PAD_MULTIPLE) + xp = np.zeros(FRAME_LENGTH // 2 + n_pad, dtype=np.float32) + xp[FRAME_LENGTH // 2: FRAME_LENGTH // 2 + n] = x + idx = np.arange(T)[:, None] * HOP_LENGTH + np.arange(FRAME_LENGTH)[None, :] + frames = xp[idx] * _WIN # float32 + mag = np.abs(np.fft.rfft(frames, n=FFT_LENGTH, axis=-1)) # complex64 -> float32 (numpy >= 2) + mel = mag @ _MEL # float64 + return np.log(mel + MEL_FLOOR).astype(np.float32) + + +# ------------------------------------------------------------------------------------------------ model inputs +@dataclass +class AudioInputs: + features: np.ndarray # [1, Tb, 128] float16, zero beyond n_frames + frame_mask: np.ndarray # [1, Tb] float16 + half_mask: np.ndarray # [1, Tb/2] float16 + token_mask: np.ndarray # [1, Tb/4] float16 + n_frames: int + n_tokens: int + bucket: int + + +def bucket_for(n_frames: int, buckets=FRAME_BUCKETS) -> int: + for b in buckets: + if b >= n_frames: + return b + raise ValueError(f"{n_frames} frames exceed the largest bucket {buckets[-1]}") + + +def prepare_audio_inputs(wav16k: np.ndarray, buckets=FRAME_BUCKETS, max_samples: int | None = MAX_SAMPLES) -> AudioInputs: + """16 kHz mono float32 -> inputs of audio_. Shorter than 161 samples (0 valid frames) gives 0 tokens + (upstream crashes below 129 samples; here any length is accepted).""" + f = log_mel(wav16k, max_samples) + nv = f.shape[0] + Tb = bucket_for(max(nv, 1), buckets) + x = np.zeros((1, Tb, N_MELS), np.float16) + x[0, :nv] = f + fm = np.zeros((1, Tb), np.float16); fm[0, :nv] = 1 + hm = np.zeros((1, Tb // 2), np.float16); hm[0, :(nv + 1) // 2] = 1 + nt = n_audio_tokens(nv) + tm = np.zeros((1, Tb // 4), np.float16); tm[0, :nt] = 1 + return AudioInputs(x, fm, hm, tm, nv, nt, Tb) + + +def audio_sequence(n_tokens: int, bos: int, boa: int, audio: int, eoa: int, eos: int) -> list[int]: + """The upstream single-clip sequence (no prompt): <|audio> <|audio|> x n .""" + return [bos, boa] + [audio] * n_tokens + [eoa, eos] + + +def chunks_30s(wav16k: np.ndarray, chunk_samples: int = MAX_SAMPLES) -> list[np.ndarray]: + """Consecutive 30 s windows (the last one shorter) for the optional chunk-mean embedding of long audio. A trailing + window too short for one frame (< 161 samples, 0 tokens) is dropped unless it is the only one.""" + x = np.asarray(wav16k, dtype=np.float32) + parts = [x[i:i + chunk_samples] for i in range(0, max(len(x), 1), chunk_samples)] + return [p for i, p in enumerate(parts) if i == 0 or len(p) > FRAME_LENGTH // 2] diff --git a/python/embeddinggemma2_coreai.py b/python/embeddinggemma2_coreai.py index 3f82348411acaeb6c29ee49f15151be86d4de305..a18f3a6eb8f9a42f7aec026c6ecf215786d11d6e 100644 --- a/python/embeddinggemma2_coreai.py +++ b/python/embeddinggemma2_coreai.py @@ -1,38 +1,44 @@ #!/usr/bin/env python3 # Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). -"""EmbeddingGemma 2 (text + images) on Apple Core AI, macOS 27 — Python runner (library + CLI). +"""EmbeddingGemma 2 (text + images + audio) on Apple Core AI, macOS 27 — Python runner (library + CLI). Library: from embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_files - m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True) # ane | gpu | cpu | default + m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True, load_audio=True) # ane | gpu | cpu | default # images on the GPU (about 3x faster, more power), text on the Neural Engine: # m = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True, image_compute="gpu") - m.prewarm() # optional: one call per bucket (+ the vision function) + # audio on the GPU, independently: ..., load_audio=True, audio_compute="gpu" + m.prewarm() # optional: one call per bucket (+ the vision/audio functions) q = m.embed("bar chart of lamp units sold per city", kind="search_query") # 768-d, L2-normalized v = m.embed_image("chart.png") # path or PIL image, same 768-d space + a = m.embed_audio("clip.wav") # path (wav/aiff/flac/m4a/mp3/caf...) or (samples, rate) d = m.embed("The credits expire on the last day of March.", kind="document", dim=256) score = float(q @ v) del m remove_own_mpsgraph_temp_files() # see "Temp files" in the README -`EmbeddingGemma2CoreAI(bundle, compute)` without `load_vision=True` loads the text asset only (as in v1.0). -`compute` places the text asset; `image_compute` places the image encoder (default: the same as `compute`). +`EmbeddingGemma2CoreAI(bundle, compute)` without `load_vision=True` / `load_audio=True` loads the text asset only +(as in v1.0). `compute` places the text asset; `image_compute` / `audio_compute` place the image and audio encoders +(default: the same as `compute`). CLI: python3 embeddinggemma2_coreai.py embed ../model [--compute ane] [--kind document] [--dim 768] "text" ... python3 embeddinggemma2_coreai.py embed-image ../model [--compute ane] [--image-compute gpu] [--exif] [--dim 768] image ... - python3 embeddinggemma2_coreai.py smoke ../model ../tests/smoke-reference.json ../tests/image-smoke-reference.json [--image-compute gpu] [--cleanup-temp] + python3 embeddinggemma2_coreai.py embed-audio ../model [--compute ane] [--audio-compute gpu] [--long truncate|chunk_mean] [--dim 768] clip ... + python3 embeddinggemma2_coreai.py smoke ../model ../tests/smoke-reference.json ../tests/image-smoke-reference.json ../tests/audio-smoke-reference.json [--image-compute gpu] [--audio-compute gpu] [--cleanup-temp] python3 embeddinggemma2_coreai.py tokcheck ../model ../tests/tokenizer-cases.json - python3 embeddinggemma2_coreai.py latency ../model [--compute ane] [--image-compute gpu] [--trials 50] [--text-only] - python3 embeddinggemma2_coreai.py prewarm ../model [--compute ane] [--image-compute gpu] [--text-only] + python3 embeddinggemma2_coreai.py latency ../model [--compute ane] [--image-compute gpu] [--audio-compute gpu] [--trials 50] [--text-only] + python3 embeddinggemma2_coreai.py prewarm ../model [--compute ane] [--image-compute gpu] [--audio-compute gpu] [--text-only] Text goes through `mm_` with zero soft-token inputs (identical to the v1.0 text graph). Images are decoded with Pillow (`convert("RGB")`: alpha dropped, EXIF orientation not applied unless --exif), resized with the torchvision-exact bicubic in eg2_image.py and fed to `vision_2520`; the soft tokens then go through `mm_288` inside -the sequence <|image> [n slots] . Tokenization uses the Hugging Face `tokenizers` library on the -bundle's tokenizer.json (the reference tokenizer). +the sequence <|image> [n slots] . Audio is decoded, mixed to mono, resampled to 16 kHz and turned +into log-mel frames by eg2_audio_frontend.py (numpy; soundfile or macOS afconvert for decoding), fed to +`audio_` and then through `mm_` inside <|audio> [n slots] . Tokenization uses the Hugging +Face `tokenizers` library on the bundle's tokenizer.json (the reference tokenizer). """ from __future__ import annotations @@ -49,20 +55,22 @@ import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) +import eg2_audio_frontend # noqa: E402 import eg2_image # noqa: E402 _PROCESS_START = time.time() class EmbeddingGemma2CoreAI: - """Loads the bundle folder (config.json, tokenizer/, the text asset and optionally the vision asset) and embeds - texts and images into the same 768-d space.""" + """Loads the bundle folder (config.json, tokenizer/, the text asset and optionally the vision and audio assets) + and embeds texts, images and audio clips into the same 768-d space.""" def __init__(self, bundle: str | os.PathLike, compute: str = "ane", quiet: bool = True, load_vision: bool = False, - image_compute: str | None = None): - """compute: where the text asset runs (ane | gpu | cpu | default). image_compute: where the image encoder - runs, independently (None = same as compute). "ane" uses the least CPU, GPU and power; "gpu" is about 3x - faster per image (README, "Images: Neural Engine or GPU").""" + image_compute: str | None = None, load_audio: bool = False, audio_compute: str | None = None): + """compute: where the text asset runs (ane | gpu | cpu | default). image_compute / audio_compute: where the + image and audio encoders run, independently (None = same as compute). "ane" uses the least CPU, GPU and + power; "gpu" is about 3x faster per image (README, "Images: Neural Engine or GPU") and about 2x faster per + 30 s of audio (README, "Audio: Neural Engine or GPU").""" import coreai.runtime as rt from tokenizers import Tokenizer @@ -75,8 +83,15 @@ class EmbeddingGemma2CoreAI: self.tokenizer_load_s = time.perf_counter() - t self.compute = compute self.image_compute = image_compute or compute + self.audio_compute = audio_compute or compute + # refuse an unsupported audio request before loading anything (no specialization, no temp files) + if load_audio and self.config.get("audio") is None: + raise ValueError("this bundle has no audio asset (config.json 'audio')") + if load_audio and self.audio_compute == "cpu": + raise ValueError("audio_compute='cpu' is not supported for audio; use 'ane' or 'gpu'") opts = _specialization_options(rt, compute) image_opts = _specialization_options(rt, self.image_compute) + audio_opts = _specialization_options(rt, self.audio_compute) t = time.perf_counter() self.model = asyncio.run(rt.AIModel.load(self.bundle / self.config["asset"], opts)) self.functions: dict[int, object] = {} @@ -88,15 +103,28 @@ class EmbeddingGemma2CoreAI: vc = self.config["vision"] self.vision_model = asyncio.run(rt.AIModel.load(self.bundle / vc["asset"], image_opts)) self.vision_function = self.vision_model.load_function(vc["function"]) + self.audio_model = None + self.audio_functions: dict[int, object] = {} + if load_audio: + ac = self.config["audio"] + self.audio_model = asyncio.run(rt.AIModel.load(self.bundle / ac["asset"], audio_opts)) + for name in ac["functions"]: + self.audio_functions[int(name.rsplit("_", 1)[1])] = self.audio_model.load_function(name) + self.audio_buckets = sorted(self.audio_functions) self.load_s = time.perf_counter() - t if not quiet: print(f"loaded {self.bundle.name} compute={compute} image_compute={self.image_compute if load_vision else '-'} " - f"buckets={self.buckets} vision={load_vision} in {self.load_s:.1f}s", flush=True) + f"audio_compute={self.audio_compute if load_audio else '-'} buckets={self.buckets} vision={load_vision} " + f"audio={load_audio} in {self.load_s:.1f}s", flush=True) @property def has_vision(self) -> bool: return self.vision_function is not None + @property + def has_audio(self) -> bool: + return bool(self.audio_functions) + # ---- tokenization ------------------------------------------------------------------------------------- def tokenize(self, text: str, kind: str | None = "document") -> list[int]: """ + prompt prefix + text + , truncated to the largest bucket (longer input is cut).""" @@ -148,6 +176,63 @@ class EmbeddingGemma2CoreAI: ids = eg2_image.image_sequence(n, c["bos_token_id"], c["boi_token_id"], c["image_token_id"], c["eoi_token_id"], c["eos_token_id"]) return ids, soft, list(range(2, 2 + n)) + # ---- audio -------------------------------------------------------------------------------------------- + def embed_audio(self, audio, sample_rate: int | None = None, dim: int = 768, long_audio: str = "truncate") -> np.ndarray: + """Path (anything soundfile or macOS afconvert decodes) or a numpy array of samples ([n] or [n, channels], + with sample_rate) -> L2-normalized 768-d embedding (or a Matryoshka prefix). The clip is mixed to mono, + resampled to 16 kHz and, with long_audio="truncate" (upstream behaviour), its first 30 s are embedded; + "chunk_mean" averages the embeddings of consecutive 30 s windows instead. A channel-first array + ([channels, n], the librosa/torchaudio layout) is rejected: pass audio.T.""" + if isinstance(audio, (str, os.PathLike)): + wav = eg2_audio_frontend.load_mono_16k(audio) + else: + if sample_rate is None or int(sample_rate) != sample_rate or sample_rate <= 0: + raise ValueError(f"a positive integer sample_rate is required for sample arrays (got {sample_rate!r})") + x = np.asarray(audio, dtype=np.float32) + if x.ndim not in (1, 2): + raise ValueError(f"expected samples of shape [n] or [n, channels], got {x.shape}") + if x.ndim == 2 and x.shape[1] > max(x.shape[0], 1): + raise ValueError(f"samples of shape {x.shape} look channel-first ([channels, n], the librosa/torchaudio " + "layout): pass [n, channels], e.g. audio.T") + wav = eg2_audio_frontend.resample_16k(eg2_audio_frontend.to_mono(x), int(sample_rate)) + return self.embed_audio_16k(wav, dim, long_audio) + + def embed_audio_16k(self, wav16k: np.ndarray, dim: int = 768, long_audio: str = "truncate") -> np.ndarray: + """16 kHz mono float32 samples -> embedding.""" + if long_audio == "truncate": + return self._finish(self.embed_audio_inputs(eg2_audio_frontend.prepare_audio_inputs(wav16k, self.audio_buckets)), dim) + if long_audio != "chunk_mean": + raise ValueError("long_audio must be truncate or chunk_mean") + acc = np.zeros(self.config["embedding_dim"], np.float64) + for chunk in eg2_audio_frontend.chunks_30s(wav16k): + acc += self.embed_audio_inputs(eg2_audio_frontend.prepare_audio_inputs(chunk, self.audio_buckets)) + return self._finish(acc.astype(np.float32), dim) + + def embed_audio_inputs(self, inputs: eg2_audio_frontend.AudioInputs) -> np.ndarray: + """Prepared inputs -> raw 768-d output of mm_ (already L2-normalized by the graph).""" + soft = self.audio_soft_tokens(inputs) + ids, soft, slots = self.audio_sequence(soft) + return self.embed_sequence(ids, soft if slots else None, slots or None) + + def audio_soft_tokens(self, inputs: eg2_audio_frontend.AudioInputs) -> np.ndarray: + """[n_tokens, 512] float32 soft tokens of prepared audio (audio_).""" + fn = self.audio_functions.get(inputs.bucket) + if fn is None: + raise RuntimeError("audio asset not loaded: create the model with load_audio=True" if not self.audio_functions + else f"no audio function for bucket {inputs.bucket}") + rt = self._rt + out = asyncio.run(fn(inputs={"features": rt.NDArray(inputs.features), "frame_mask": rt.NDArray(inputs.frame_mask), + "half_mask": rt.NDArray(inputs.half_mask), "token_mask": rt.NDArray(inputs.token_mask)})) + return np.array(out["soft_tokens"].numpy(), dtype=np.float32)[0, : inputs.n_tokens] + + def audio_sequence(self, soft: np.ndarray) -> tuple[list[int], np.ndarray, list[int]]: + """(ids, soft tokens, slots) of the upstream single-clip sequence <|audio> [n] (no prompt).""" + c = self.config + n = soft.shape[0] + ids = eg2_audio_frontend.audio_sequence(n, c["bos_token_id"], c.get("boa_token_id", 256000), c.get("audio_token_id", 258881), + c.get("eoa_token_id", 258883), c["eos_token_id"]) + return ids, soft, list(range(2, 2 + n)) + # ---- any sequence ------------------------------------------------------------------------------------- def embed_sequence(self, ids: list[int], soft: np.ndarray | None = None, slots: list[int] | None = None, bucket: int | None = None) -> np.ndarray: @@ -185,11 +270,14 @@ class EmbeddingGemma2CoreAI: self.embed_ids([self.config["bos_token_id"], self.config["eos_token_id"]], S) if self.vision_function is not None: self.soft_tokens(eg2_image.patchify_cell_major(np.full((48, 48, 3), 128, np.uint8))) + for tb in self.audio_buckets: + self.audio_soft_tokens(eg2_audio_frontend.prepare_audio_inputs(np.zeros(min(tb, 3072) * 160, np.float32), [tb])) return time.perf_counter() - t def close(self) -> None: self.functions.clear() - self.model = self.vision_model = self.vision_function = None + self.audio_functions.clear() + self.model = self.vision_model = self.vision_function = self.audio_model = None def _specialization_options(rt, compute: str): @@ -214,7 +302,7 @@ def mpsgraph_temp_root() -> Path: def remove_own_mpsgraph_temp_files(pid: int | None = None, since: float | None = None) -> tuple[int, int]: """Each Neural Engine load makes MPSGraph write compiled-graph copies into $TMPDIR/com.apple.MetalPerformance ShadersGraph/mpsgraph---/ (~360 MB for the text asset, ~300 MB for the vision asset), and the - Python runtime (coreai.runtime, macOS 27.0) does NOT delete them when the model is released or the interpreter + Python runtime (coreai.runtime, macOS 27) does NOT delete them when the model is released or the interpreter exits. This removes the folders of the CURRENT process only (its pid, created after it started). Call it after the model object has been released, or at exit. Returns (folders, bytes).""" import shutil @@ -264,16 +352,18 @@ def cosine(a, b) -> float: # ---- smoke test (used by the CLI and smoke_test.py) ------------------------------------------------------- -def run_smoke(bundle, ref_paths: list, compute: str = "ane", image_compute: str | None = None) -> bool: - """Runs every reference file: text files (v1.0 format, "cases") and image files ("images" + "texts"). - Returns True when every cosine is above its threshold, all values are finite and every query ranks its own - image first.""" +def run_smoke(bundle, ref_paths: list, compute: str = "ane", image_compute: str | None = None, audio_compute: str | None = None) -> bool: + """Runs every reference file: text files (v1.0 format, "cases"), image files ("images" + "texts") and audio + files ("audio" + "texts"). Returns True when every cosine is above its threshold, all values are finite and + every query ranks its own image / clip first.""" refs = [(Path(p), json.loads(Path(p).read_text(encoding="utf-8"))) for p in ref_paths] need_vision = any(r.get("images") for _, r in refs) - m = EmbeddingGemma2CoreAI(bundle, compute, load_vision=need_vision, image_compute=image_compute) + need_audio = any(r.get("audio") for _, r in refs) + m = EmbeddingGemma2CoreAI(bundle, compute, load_vision=need_vision, image_compute=image_compute, load_audio=need_audio, + audio_compute=audio_compute) print(f"loaded in {m.load_s:.1f} s (tokenizer {m.tokenizer_load_s:.2f} s), compute={compute}, " - f"image_compute={m.image_compute if need_vision else '-'}, buckets={m.buckets}, " - f"vision {'loaded' if m.has_vision else 'not loaded'}") + f"image_compute={m.image_compute if need_vision else '-'}, audio_compute={m.audio_compute if need_audio else '-'}, " + f"buckets={m.buckets}, vision {'loaded' if m.has_vision else 'not loaded'}, audio {'loaded' if m.has_audio else 'not loaded'}") ok = True for path, ref in refs: print(f"-- {path.name}") @@ -301,6 +391,17 @@ def run_smoke(bundle, ref_paths: list, compute: str = "ane", image_compute: str ok = ok and passed img_vecs.append(v) print(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {thr_img}) image {c['file']} {int((time.perf_counter() - t0) * 1000)} ms") + audio = ref.get("audio", []) + aud_vecs = [] + for c in audio: + t0 = time.perf_counter() + v = m.embed_audio(path.parent / c["file"]) + cos = cosine(v, c["embedding"]) + thr_a = c.get("threshold_cosine", ref.get("threshold_cosine_audio", thr)) + passed = cos >= thr_a and bool(np.all(np.isfinite(v))) + ok = ok and passed + aud_vecs.append(v) + print(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {thr_a}) audio {c['file']} {int((time.perf_counter() - t0) * 1000)} ms") queries = [] for c in ref.get("texts", []): v = m.embed(c["text"], c["kind"]) @@ -320,6 +421,23 @@ def run_smoke(bundle, ref_paths: list, compute: str = "ane", image_compute: str print(f"{'PASS' if best == want else 'FAIL'} query \"{q}\" -> {images[best]['file']} ({scores[best]:.3f})") ok = ok and hits == len(queries) print(f"text -> image: {hits}/{len(queries)} queries rank their own image first") + if audio: + with_q = [i for i, c in enumerate(audio) if c.get("query")] + hits = total = 0 + for q, qv in queries: + want = next((i for i, c in enumerate(audio) if c.get("query") == q), -1) + if want < 0: + continue + scores = [cosine(qv, aud_vecs[i]) for i in with_q] + best = with_q[int(np.argmax(scores))] + if audio[want].get("fp32_rank1") is False: # checked only where fp32 itself ranks the clip first + print(f"SKIP query \"{q}\" -> {audio[best]['file']} ({max(scores):.3f}) (fp32 does not rank this clip first either)") + continue + total += 1 + hits += best == want + print(f"{'PASS' if best == want else 'FAIL'} query \"{q}\" -> {audio[best]['file']} ({max(scores):.3f})") + ok = ok and hits == total + print(f"text -> audio: {hits}/{total} queries rank their own clip first (as fp32 does)") fp, nf = footprints_mb() print(f"peak footprint {fp:.0f} MB, neural footprint {nf:.0f} MB ({'Neural Engine in use' if nf > 0 else 'Neural Engine not used'})") print("SMOKE PASS" if ok else "SMOKE FAIL") @@ -353,10 +471,29 @@ def cmd_embed_image(a) -> int: return 0 +def cmd_embed_audio(a) -> int: + m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_audio=True, audio_compute=a.audio_compute) + for p in a.args: + t0 = time.perf_counter() + d = eg2_audio_frontend.decode(p) + wav = eg2_audio_frontend.resample_16k(eg2_audio_frontend.to_mono(d.samples), d.sample_rate) + t1 = time.perf_counter() + v = m.embed_audio_16k(wav, a.dim, a.long) + frames = eg2_audio_frontend.num_valid_frames(len(wav)) + print(json.dumps({"audio": p, "dim": a.dim, "sample_rate": d.sample_rate, "channels": int(d.samples.shape[1]), + "decoder": d.decoder, "seconds": round(len(wav) / 16000, 3), "n_frames": frames, + "n_soft": eg2_audio_frontend.n_audio_tokens(frames), + "truncated_to_30s": bool(len(wav) > eg2_audio_frontend.MAX_SAMPLES and a.long == "truncate"), + "long_audio": a.long, "decode_ms": int((t1 - t0) * 1000), "model_ms": int((time.perf_counter() - t1) * 1000), + "embedding": [round(float(x), 6) for x in v]})) + m.close() + return 0 + + def cmd_smoke(a) -> int: if not a.args: raise SystemExit("smoke needs at least one reference file") - return 0 if run_smoke(a.bundle, a.args, a.compute, a.image_compute) else 1 + return 0 if run_smoke(a.bundle, a.args, a.compute, a.image_compute, a.audio_compute) else 1 def cmd_tokcheck(a) -> int: @@ -374,10 +511,48 @@ def cmd_tokcheck(a) -> int: return 0 if same == len(cases) else 1 +def _has_audio_asset(bundle) -> bool: + return "audio" in json.loads((Path(bundle) / "config.json").read_text(encoding="utf-8")) + + def cmd_latency(a) -> int: - m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=not a.text_only, image_compute=a.image_compute) + m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=not a.text_only, image_compute=a.image_compute, + load_audio=not a.text_only and _has_audio_asset(a.bundle), audio_compute=a.audio_compute) print(f"loaded in {m.load_s:.1f} s, compute={a.compute}, image_compute={m.image_compute if m.has_vision else '-'}, " - f"vision {'loaded' if m.has_vision else 'not loaded'}; prewarm {m.prewarm():.2f} s") + f"audio_compute={m.audio_compute if m.has_audio else '-'}, vision {'loaded' if m.has_vision else 'not loaded'}, " + f"audio {'loaded' if m.has_audio else 'not loaded'}; prewarm {m.prewarm():.2f} s") + if m.has_audio: + n_a = max(5, a.trials // 2) + print("audio seconds bucket tokens audio_ p50 ms mm_ p50 ms end-to-end p50 ms CPU ms/clip front end ms") + for seconds in (3.0, 10.0, 30.0): + t = np.arange(int(seconds * 16000)) / 16000.0 + wav = (0.3 * np.sin(2 * np.pi * 220 * t) + 0.2 * np.sin(2 * np.pi * 1375 * t + 0.5 * np.sin(2 * np.pi * 3 * t)) + + 0.05 * ((np.arange(len(t)) * 7919) % 1000) / 1000 - 0.025).astype(np.float32) + tf0 = time.perf_counter() + inputs = eg2_audio_frontend.prepare_audio_inputs(wav, m.audio_buckets) + front_ms = (time.perf_counter() - tf0) * 1000 + for _ in range(3): + m.embed_audio_inputs(inputs) + ta, tt, te = [], [], [] + c0 = time.process_time() + for _ in range(n_a): + t0 = time.perf_counter() + soft = m.audio_soft_tokens(inputs) + t1 = time.perf_counter() + ids, soft, slots = m.audio_sequence(soft) + m.embed_sequence(ids, soft, slots) + t2 = time.perf_counter() + ta.append((t1 - t0) * 1000); tt.append((t2 - t1) * 1000); te.append((t2 - t0) * 1000) + cpu = (time.process_time() - c0) / n_a * 1000 + print(f" {seconds:7.1f} {inputs.bucket:6d} {inputs.n_tokens:6d} {np.median(ta):17.1f} {np.median(tt):14.1f} " + f"{np.median(te):18.1f} {cpu:12.1f} {front_ms:12.1f}") + n48 = 30 * 48000 + st = np.stack([np.sin(np.arange(n48) * 0.01), np.sin(np.arange(n48) * 0.013)], 1).astype(np.float32) + tp0 = time.perf_counter() + w16 = eg2_audio_frontend.resample_16k(eg2_audio_frontend.to_mono(st), 48000) + tp1 = time.perf_counter() + eg2_audio_frontend.prepare_audio_inputs(w16, m.audio_buckets) + print(f"audio front end, 30 s stereo 48 kHz (numpy): mono + resample {(tp1 - tp0) * 1000:.0f} ms, log-mel + inputs {(time.perf_counter() - tp1) * 1000:.0f} ms") if m.has_vision: rng = np.random.RandomState(0) px = rng.randint(0, 256, (624, 1008, 3)).astype(np.uint8) @@ -423,36 +598,46 @@ def cmd_latency(a) -> int: def cmd_prewarm(a) -> int: t0 = time.perf_counter() - m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=not a.text_only, image_compute=a.image_compute) + m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=not a.text_only, image_compute=a.image_compute, + load_audio=not a.text_only and _has_audio_asset(a.bundle), audio_compute=a.audio_compute) w = m.prewarm() - print(f"load {m.load_s:.1f} s + prewarm {w:.2f} s = ready in {time.perf_counter() - t0:.1f} s (vision {'loaded' if m.has_vision else 'not loaded'})") + print(f"load {m.load_s:.1f} s + prewarm {w:.2f} s = ready in {time.perf_counter() - t0:.1f} s " + f"(vision {'loaded' if m.has_vision else 'not loaded'}, audio {'loaded' if m.has_audio else 'not loaded'})") m.close() return 0 def main() -> None: - ap = argparse.ArgumentParser(description="EmbeddingGemma 2 (text + images) on Apple Core AI") - ap.add_argument("cmd", choices=["embed", "embed-image", "smoke", "tokcheck", "latency", "prewarm"]) + ap = argparse.ArgumentParser(description="EmbeddingGemma 2 (text + images + audio) on Apple Core AI") + ap.add_argument("cmd", choices=["embed", "embed-image", "embed-audio", "smoke", "tokcheck", "latency", "prewarm"]) ap.add_argument("bundle", help="the model folder (config.json, tokenizer/, *.aimodel)") - ap.add_argument("args", nargs="*", help="texts (embed), image files (embed-image) or json files (smoke, tokcheck)") - ap.add_argument("--compute", default="ane", choices=["ane", "gpu", "cpu", "default"], help="text asset (and images, unless --image-compute)") + ap.add_argument("args", nargs="*", help="texts (embed), image files (embed-image), audio files (embed-audio) or json files (smoke, tokcheck)") + ap.add_argument("--compute", default="ane", choices=["ane", "gpu", "cpu", "default"], help="text asset (and the encoders, unless --image-compute / --audio-compute)") ap.add_argument("--image-compute", default=None, choices=["ane", "gpu", "cpu", "default"], help="image encoder only (default: same as --compute); gpu is ~3x faster per image, ane uses the least power") + ap.add_argument("--audio-compute", default=None, choices=["ane", "gpu", "cpu", "default"], + help="audio encoder only (default: same as --compute)") ap.add_argument("--kind", default="document", help="prompt kind from config.json (document, search_query, ...) or none") ap.add_argument("--exif", action="store_true", help="embed-image: apply the EXIF orientation first (upstream does not)") + ap.add_argument("--long", default="truncate", choices=["truncate", "chunk_mean"], help="embed-audio: audio longer than 30 s") ap.add_argument("--dim", type=int, default=768) ap.add_argument("--trials", type=int, default=50) - ap.add_argument("--text-only", action="store_true", help="latency, prewarm: do not load the vision asset") + ap.add_argument("--text-only", action="store_true", help="latency, prewarm: do not load the vision and audio assets") ap.add_argument("--cleanup-temp", action="store_true", help="remove this process's MPSGraph temp folders at exit") a = ap.parse_args() - code = {"embed": cmd_embed, "embed-image": cmd_embed_image, "smoke": cmd_smoke, "tokcheck": cmd_tokcheck, - "latency": cmd_latency, "prewarm": cmd_prewarm}[a.cmd](a) - if a.cleanup_temp: - import gc - - gc.collect() - n, b = remove_own_mpsgraph_temp_files() - print(f"cleanup-temp: removed {n} MPSGraph temp folder(s), {b / 2**20:.1f} MB") + try: + code = {"embed": cmd_embed, "embed-image": cmd_embed_image, "embed-audio": cmd_embed_audio, "smoke": cmd_smoke, + "tokcheck": cmd_tokcheck, "latency": cmd_latency, "prewarm": cmd_prewarm}[a.cmd](a) + except ValueError as e: # bad input or an unsupported route: a message, not a traceback + print(f"error: {e}", file=sys.stderr) + code = 2 + finally: + if a.cleanup_temp: # also after an error, so that a failed run does not leave its temp folders behind + import gc + + gc.collect() + n, b = remove_own_mpsgraph_temp_files() + print(f"cleanup-temp: removed {n} MPSGraph temp folder(s), {b / 2**20:.1f} MB") sys.exit(code) diff --git a/python/requirements.lock b/python/requirements.lock index 75e755aec42a8bd6587f80f806b78e645548d379..8deae5b6fdb106f0d143489a55b31ee78ffa4937 100644 --- a/python/requirements.lock +++ b/python/requirements.lock @@ -1,10 +1,13 @@ -# Exact versions of the environments this release was validated in (macOS 27.0, Apple silicon). +# Exact versions of the environments this release was validated in (macOS 27, Apple silicon). # Runtime (python/), Python 3.12 (the text path of v1.0 was also validated with Python 3.14): coreai-core==1.0.0b3 numpy==2.4.6 pillow==12.3.0 tokenizers==0.23.3 huggingface-hub==2.2.0 +# audio decoding (installed by requirements.txt; the runner falls back to macOS afconvert without it; the audio +# smoke tests of this release passed both with soundfile and without it, i.e. on the afconvert path): +soundfile==0.14.0 # Exporter (export/), on top of the runtime, Python 3.12: coreai-torch==0.4.3 coreai-opt==0.3.0 @@ -15,7 +18,8 @@ ml-dtypes==0.6.0 networkx==3.7 scipy==1.18.1 packaging==26.3 -# Reference vectors and preprocessing checks (tests/make_*_reference.py, tests/check_preprocess.py), a separate -# environment: +# Reference vectors and preprocessing checks (tests/make_*_reference.py, tests/make_audio_preprocess_cases.py, +# tests/check_preprocess.py), a separate environment: # sentence-transformers==6.1.0 transformers==5.19.0 torch==2.14.1 torchvision==0.29.1 pillow tokenizers==0.23.3 numpy==2.5.3 +# soundfile==0.14.0 (libsndfile 1.2.2) soxr==1.1.0 (libsoxr 0.1.3) + ffmpeg 9.0.1 (AAC decoding of the reference) # (pillow and torchvision are needed because the checkpoint's processor is multimodal, even for text-only use) diff --git a/python/requirements.txt b/python/requirements.txt index 3ea5848b57300764de3b1a944040dd0453b03089..9b998b00ed7b9e6c73fc04571c47b15ce688363e 100644 --- a/python/requirements.txt +++ b/python/requirements.txt @@ -1,8 +1,12 @@ # Runtime requirements for python/ (macOS 27, Apple silicon; validated with Python 3.12). # coreai-core provides the `coreai.runtime` module (Apple's Core AI Python runtime); install it from the same # distribution that provides coreai-torch. The exact versions this release was validated with are in -# requirements.lock. pillow is needed for images only (decoding). +# requirements.lock. pillow is needed for images only (decoding). soundfile (libsndfile) decodes audio files with +# the same library upstream uses (incl. MP3 with gapless trimming); the runner still works without it (it then +# decodes with macOS `afconvert`: Apple's decoder, identical for PCM/FLAC/ALAC/AAC and trimmed for MP3, see README) +# and uses `afconvert` for AAC/M4A in any case. coreai-core==1.0.0b3 numpy>=2.0,<2.6 pillow>=11,<13 tokenizers>=0.22,<0.24 +soundfile>=0.13,<0.15 diff --git a/python/smoke_test.py b/python/smoke_test.py index 8f25d1784c02cd7590ddb9a0280bd139d64f19e2..5237675077b7f99515cafbad01bf1fac2002e3d9 100644 --- a/python/smoke_test.py +++ b/python/smoke_test.py @@ -1,15 +1,15 @@ #!/usr/bin/env python3 # Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). -"""Smoke test: load the bundle, embed the shipped fictional texts and generated test images, compare with the -fp32 reference vectors and check that every query finds its own image first. +"""Smoke test: load the bundle, embed the shipped fictional texts, generated test images and generated audio clips, +compare with the fp32 reference vectors and check that every query finds its own image / clip first. - python3 smoke_test.py [--bundle ../model] [--compute ane] [--image-compute gpu] [--text-only] [--cleanup-temp] - [--reference ../tests/smoke-reference.json --reference ../tests/image-smoke-reference.json] + python3 smoke_test.py [--bundle ../model] [--compute ane] [--image-compute gpu] [--audio-compute gpu] [--text-only] + [--no-audio] [--cleanup-temp] [--reference ../tests/smoke-reference.json ...] -Exit code 0 = every cosine >= its threshold (0.999 texts, 0.998 images), all values finite, every query at rank 1. -`--text-only` runs only the v1.0 text reference and does not load the vision asset. The first run of a new -executable (here: your python binary) specializes the assets for the Neural Engine: expect a few minutes. Later -runs load in about a second. +Exit code 0 = every cosine >= its threshold (0.999 texts, 0.998 images, 0.9995 / 0.995 audio clips), all values +finite, every query at rank 1. `--text-only` runs only the v1.0 text reference and loads neither the vision nor the +audio asset; `--no-audio` skips the audio reference. The first run of a new executable (here: your python binary) +specializes the assets for the Neural Engine: expect a few minutes. Later runs load in about a second. """ from __future__ import annotations @@ -26,22 +26,31 @@ def main() -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--bundle", default=str(HERE.parent / "model")) ap.add_argument("--reference", action="append", default=None, - help="reference file(s); default: tests/smoke-reference.json and tests/image-smoke-reference.json") + help="reference file(s); default: tests/smoke-reference.json, image-smoke-reference.json and audio-smoke-reference.json") ap.add_argument("--compute", default="ane", choices=["ane", "gpu", "cpu", "default"]) ap.add_argument("--image-compute", default=None, choices=["ane", "gpu", "cpu", "default"], help="where the image encoder runs (default: same as --compute)") - ap.add_argument("--text-only", action="store_true", help="only the text reference (the vision asset is not loaded)") + ap.add_argument("--audio-compute", default=None, choices=["ane", "gpu", "cpu", "default"], + help="where the audio encoder runs (default: same as --compute)") + ap.add_argument("--text-only", action="store_true", help="only the text reference (the vision and audio assets are not loaded)") + ap.add_argument("--no-audio", action="store_true", help="skip the audio reference (the audio asset is not loaded)") ap.add_argument("--cleanup-temp", action="store_true", help="remove this process's MPSGraph temp folders at exit") a = ap.parse_args() - refs = a.reference or [str(HERE.parent / "tests" / "smoke-reference.json")] + ( - [] if a.text_only else [str(HERE.parent / "tests" / "image-smoke-reference.json")]) - ok = run_smoke(a.bundle, refs, a.compute, a.image_compute) - if a.cleanup_temp: - import gc - - gc.collect() - n, b = remove_own_mpsgraph_temp_files() - print(f"cleanup-temp: removed {n} MPSGraph temp folder(s), {b / 2**20:.1f} MB") + tests = HERE.parent / "tests" + refs = a.reference or [str(tests / "smoke-reference.json")] + ( + [] if a.text_only else [str(tests / "image-smoke-reference.json")] + ([] if a.no_audio else [str(tests / "audio-smoke-reference.json")])) + try: + ok = run_smoke(a.bundle, refs, a.compute, a.image_compute, a.audio_compute) + except ValueError as e: # e.g. --audio-compute cpu (refused before anything is loaded): a message, not a traceback + print(f"error: {e}", file=sys.stderr) + return 2 + finally: + if a.cleanup_temp: # also after an error + import gc + + gc.collect() + n, b = remove_own_mpsgraph_temp_files() + print(f"cleanup-temp: removed {n} MPSGraph temp folder(s), {b / 2**20:.1f} MB") return 0 if ok else 1 diff --git a/swift/Package.swift b/swift/Package.swift index c3234d990ecea5708610b6a5e7fe4095976a0dbe..d5644c3a84e8f6ab497d72aa755fac81c170dbfc 100644 --- a/swift/Package.swift +++ b/swift/Package.swift @@ -10,14 +10,17 @@ let package = Package( .executable(name: "eg2-cli", targets: ["eg2-cli"]), ], targets: [ - // Library: exact Gemma tokenizer, exact image preprocessing (decode + bicubic resize + patches) and the - // Core AI text + image embedder. No third-party dependencies. + // Library: exact Gemma tokenizer, exact image preprocessing (decode + bicubic resize + patches), the exact + // audio front end (decode + mono + 16 kHz resample + log-mel) and the Core AI text + image + audio embedder. + // No third-party dependencies. .target( name: "EmbeddingGemma2CoreAI", path: "Sources/EmbeddingGemma2CoreAI", - linkerSettings: [.linkedFramework("CoreAI"), .linkedFramework("ImageIO"), .linkedFramework("CoreGraphics")] + linkerSettings: [.linkedFramework("CoreAI"), .linkedFramework("ImageIO"), .linkedFramework("CoreGraphics"), + .linkedFramework("AVFoundation"), .linkedFramework("Accelerate")] ), - // Command-line tool: embed | embed-image | smoke | tokcheck | pixcheck | dump | latency | prewarm | cleanup-temp + // Command-line tool: embed | embed-image | embed-audio | smoke | tokcheck | pixcheck | audiocheck | dump | + // dump-audio | latency | prewarm | cleanup-temp .executableTarget( name: "eg2-cli", dependencies: ["EmbeddingGemma2CoreAI"], diff --git a/swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swift b/swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swift new file mode 100644 index 0000000000000000000000000000000000000000..eb13a373bf80fdd5fea417a369db7bba65eeb52d --- /dev/null +++ b/swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swift @@ -0,0 +1,104 @@ +// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE). +// +// Audio file decoding for the audio embedder: AVAudioFile (Apple's AudioToolbox decoders) at the file's own sample +// rate, as float32, every channel kept. The reference pipeline decodes with libsndfile (what upstream's librosa.load +// uses); Apple's decoder is sample-identical to it for PCM (WAV, AIFF, CAF), FLAC and ALAC files and within 3e-7 for +// AAC. For MP3 files Apple's decoder does not always honour the encoder delay and padding of the LAME/Xing/Info tag +// (whole frames for some files, one or two frames too many at the end for others), so `decode` brings its output to +// the tag's gapless length, after which the samples equal libsndfile's within 3e-5. An MP3 without that tag is +// returned as Apple decodes it (README "Audio: decoding"). + +import AVFoundation +import Foundation + +public struct DecodedAudio: Sendable { + public let sampleRate: Int + public let channelCount: Int + /// Non-interleaved: `channels[c][i]` is sample i of channel c (all channels have the same count). + public let channels: [[Float]] + public var frameCount: Int { channels.first?.count ?? 0 } + + public init(sampleRate: Int, channelCount: Int, channels: [[Float]]) { + self.sampleRate = sampleRate + self.channelCount = channelCount + self.channels = channels + } +} + +public enum AudioDecoder { + /// Decodes a file (anything AVAudioFile reads: WAV, AIFF, CAF, FLAC, ALAC, AAC/M4A, MP3, ...) at its native rate. + public static func decode(url: URL) throws -> DecodedAudio { + let file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatFloat32, interleaved: false) + let format = file.processingFormat + let channelCount = Int(format.channelCount) + guard channelCount > 0 else { throw EmbedderError(description: "\(url.lastPathComponent): no audio channels") } + var channels = [[Float]](repeating: [], count: channelCount) + let chunk: AVAudioFrameCount = 1 << 16 + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunk) else { + throw EmbedderError(description: "\(url.lastPathComponent): cannot allocate a PCM buffer") + } + while true { + try file.read(into: buffer, frameCount: chunk) + let n = Int(buffer.frameLength) + if n == 0 { break } + guard let data = buffer.floatChannelData else { throw EmbedderError(description: "\(url.lastPathComponent): not float32 PCM") } + for c in 0..= file.length { break } + } + if url.pathExtension.lowercased() == "mp3", let info = try? mp3GaplessInfo(url: url) { + // AudioToolbox applies the tag itself for most files (afinfo reports "priming"/"remainder"), returns whole + // frames for some, and for others trims the delay but keeps one or two whole frames too many at the end (it + // counts the Xing/Info frame as audio: afinfo shows one packet more than the tag's frame count). Bring every + // case to libsndfile's gapless length (same rule as the Python front end). + let total = channels[0].count + let full = info.frames * info.samplesPerFrame + let gapless = full - info.delay - info.padding + if total == full { + let start = min(info.delay, total) + let end = max(start, total - info.padding) + channels = channels.map { Array($0[start.. 0, total > gapless, (total - gapless) % info.samplesPerFrame == 0, + total - gapless <= 2 * info.samplesPerFrame { + channels = channels.map { Array($0[0.. (frames: Int, samplesPerFrame: Int, delay: Int, padding: Int)? { + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + let data = try handle.read(upToCount: 1 << 20) ?? Data() + let b = [UInt8](data) + var i = 0 + if b.count > 10, b[0] == 0x49, b[1] == 0x44, b[2] == 0x33 { // "ID3" + i = 10 + ((Int(b[6] & 0x7F) << 21) | (Int(b[7] & 0x7F) << 14) | (Int(b[8] & 0x7F) << 7) | Int(b[9] & 0x7F)) + } + while i + 4 < b.count, !(b[i] == 0xFF && (b[i + 1] & 0xE0) == 0xE0) { i += 1 } + guard i + 4 < b.count else { return nil } + let mpeg1 = ((b[i + 1] >> 3) & 3) == 3 + let mono = ((b[i + 3] >> 6) & 3) == 3 + let side = mpeg1 ? (mono ? 17 : 32) : (mono ? 9 : 17) + var p = i + 4 + side + guard p + 8 <= b.count else { return nil } + let tag = String(decoding: b[p..<(p + 4)], as: UTF8.self) + guard tag == "Xing" || tag == "Info" else { return nil } + let flags = (UInt32(b[p + 4]) << 24) | (UInt32(b[p + 5]) << 16) | (UInt32(b[p + 6]) << 8) | UInt32(b[p + 7]) + p += 8 + guard flags & 1 != 0, p + 4 <= b.count else { return nil } + let frames = (Int(b[p]) << 24) | (Int(b[p + 1]) << 16) | (Int(b[p + 2]) << 8) | Int(b[p + 3]) + p += 4 + if flags & 2 != 0 { p += 4 } + if flags & 4 != 0 { p += 100 } + if flags & 8 != 0 { p += 4 } + guard p + 24 <= b.count else { return nil } + // the encoder tag ("LAME3.100", "Lavc63.1." ...) starts with ASCII letters; delay/padding are 12 bits each at +21 + guard b[p..<(p + 4)].allSatisfy({ ($0 >= 0x41 && $0 <= 0x5A) || ($0 >= 0x61 && $0 <= 0x7A) }) else { return nil } + let d0 = Int(b[p + 21]), d1 = Int(b[p + 22]), d2 = Int(b[p + 23]) + return (frames, mpeg1 ? 1152 : 576, (d0 << 4) | (d1 >> 4), ((d1 & 0x0F) << 8) | d2) + } +} diff --git a/swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swift b/swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swift new file mode 100644 index 0000000000000000000000000000000000000000..8c6c3adf33ad137d76ccf675b11cc36fc8aa4a2d --- /dev/null +++ b/swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swift @@ -0,0 +1,191 @@ +// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE). +// +// Audio front end: samples -> 16 kHz mono -> log-mel frames -> the inputs of `audio_`. The feature extraction +// re-implements the defaults of Gemma4AudioFeatureExtractor (feature_extraction_gemma4.py in Hugging Face +// transformers 5.19, Copyright 2026 Google LLC, Apache-2.0) and the HTK mel filter-bank formula of transformers' +// audio_utils.py (Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio authors, Apache-2.0; the +// formula as in librosa / torchaudio) exactly as python/eg2_audio_frontend.py does in numpy: +// first 30 s (480 000 samples), right pad to a multiple of 128 samples, 160 zeros in front ("semicausal"), +// frames of 320 samples every 160 (the window is periodic Hann), |rfft(512)| in single precision, 128 triangular +// HTK mel filters 0-8000 Hz (no normalization) applied in double precision, ln(mel + 0.001) cast to float32; +// a frame is valid only if its 321-sample analysis window lies in real audio (at most 2999 frames). +// The FFT is Accelerate's; its single-precision rounding differs from numpy's pocketfft by ~1e-6 (README). + +import Accelerate +import Foundation + +/// The inputs of one `audio_` call (see README "How an audio clip becomes a vector"). +public struct AudioInputs: Sendable { + public static let nMels = 128 + public let bucket: Int // frames of the function (192, 384, 1024, 1536 or 3000) + public let frameCount: Int // valid log-mel frames (10 ms each) + public let softTokenCount: Int // ceil(ceil(frames / 2) / 2) + public let features: [Float16] // [bucket * 128], rows >= frameCount are zero + public let frameMask: [Float16] // [bucket] + public let halfMask: [Float16] // [bucket / 2] + public let tokenMask: [Float16] // [bucket / 4] +} + +public enum AudioFrontend { + public static let sampleRate = 16000 + public static let frameLength = 320 + public static let hopLength = 160 + public static let fftLength = 512 + public static let nMels = 128 + public static let melFloor = 1e-3 + public static let maxSamples = 480_000 // 30 s, the upstream default truncation + public static let padMultiple = 128 + public static let maxFrames = 2999 + public static let frameBuckets = [192, 384, 1024, 1536, 3000] + public static let maxSoftTokens = 750 + + // MARK: - Mono mix + + /// Mean of the channels in Float, summed in channel order (the numpy reference does the same). + public static func toMono(_ audio: DecodedAudio) -> [Float] { + guard audio.channelCount > 1 else { return audio.channels.first ?? [] } + var acc = audio.channels[0] + for c in 1.. mono -> 16 kHz, the librosa.load(sr=16000, mono=True) order. + public static func loadMono16k(url: URL) throws -> [Float] { + let d = try AudioDecoder.decode(url: url) + return AudioResampler.resampleTo16k(toMono(d), rate: d.sampleRate) + } + + // MARK: - Frame counts + + /// Frames whose whole 321-sample analysis window (with the 160-sample left pad) lies in real audio. + public static func validFrameCount(samples n: Int) -> Int { + frameCount(samples: min(n, maxSamples)) + } + + /// (n + 160 - 321) floor-div 160 + 1, zero when the first window does not fit (n < 161). + static func frameCount(samples n: Int) -> Int { + let d = n + frameLength / 2 - (frameLength + 1) + return d < 0 ? 0 : d / hopLength + 1 + } + + public static func softTokenCount(frames: Int) -> Int { ((frames + 1) / 2 + 1) / 2 } + + public static func bucket(forFrames n: Int) throws -> Int { + guard let b = frameBuckets.first(where: { $0 >= n }) else { + throw EmbedderError(description: "\(n) frames exceed the largest bucket \(frameBuckets.last ?? 0)") + } + return b + } + + // MARK: - Mel filters and window (computed once, double precision like the reference) + + static let melFilters: [Double] = { // [257 * 128], row-major (bin, mel) + func hzToMel(_ f: Double) -> Double { 2595.0 * log10(1.0 + f / 700.0) } + func melToHz(_ m: Double) -> Double { 700.0 * (pow(10.0, m / 2595.0) - 1.0) } + let nBins = fftLength / 2 + 1 + let mLo = hzToMel(0.0), mHi = hzToMel(8000.0) + var filterFreqs = [Double](repeating: 0, count: nMels + 2) + for i in 0..<(nMels + 2) { // numpy.linspace: start + i * step, last = stop + let step = (mHi - mLo) / Double(nMels + 1) + filterFreqs[i] = melToHz(i == nMels + 1 ? mHi : mLo + Double(i) * step) + } + var fftFreqs = [Double](repeating: 0, count: nBins) + for i in 0.. (features: [Float], frames: Int) { + let x = limit.map { Array(wav16k.prefix($0)) } ?? wav16k + let n = x.count + let m = frameCount(samples: n) + if m <= 0 { return ([], 0) } + let nPad = (n + padMultiple - 1) / padMultiple * padMultiple + var xp = [Float](repeating: 0, count: frameLength / 2 + nPad) + for i in 0.. inputs of `audio_` (first 30 s). Fewer than 161 samples give 0 tokens. + public static func prepare(wav16k: [Float]) throws -> AudioInputs { + let (f, nv) = logMel(wav16k) + let Tb = try bucket(forFrames: max(nv, 1)) + var features = [Float16](repeating: 0, count: Tb * nMels) + for i in 0..<(nv * nMels) { features[i] = Float16(f[i]) } + var frameMask = [Float16](repeating: 0, count: Tb) + for i in 0.. mono -> 16 kHz -> log-mel). + public static func prepare(url: URL) throws -> AudioInputs { + try prepare(wav16k: try loadMono16k(url: url)) + } + + /// Consecutive 30 s windows (the last one shorter) for the optional chunk-mean embedding of long audio. A trailing + /// window too short for one frame (< 161 samples, 0 tokens) is dropped unless it is the only one. + public static func chunks30s(_ wav16k: [Float]) -> [[Float]] { + if wav16k.isEmpty { return [[]] } + let parts = stride(from: 0, to: wav16k.count, by: maxSamples).map { Array(wav16k[$0.. frameLength / 2 }.map { $0.element } + } +} diff --git a/swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swift b/swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swift new file mode 100644 index 0000000000000000000000000000000000000000..871d1d3d4ddee109aa74dba91d53fac279646962 --- /dev/null +++ b/swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swift @@ -0,0 +1,122 @@ +// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE). +// +// Sample-rate conversion to 16 kHz for the audio embedder: a polyphase Kaiser-windowed sinc low-pass computed in +// Double, the same design and the same arithmetic as python/eg2_audio_frontend.py (pass band 0.913 and stop band +// 1.0 of the lower Nyquist, 125 dB attenuation, unity DC gain, output length ceil(n * 16000 / rate) as librosa's +// fix=True). The upstream pipeline uses libsoxr "HQ" instead; README "Audio: decoding and resampling" gives the +// measured difference. Input already at 16 kHz is returned unchanged. + +import Accelerate +import Foundation + +public enum AudioResampler { + public static let targetRate = 16000 + static let passband = 0.913 + static let stopband = 1.0 + static let attenuationDB = 125.0 + + /// Modified Bessel function of order 0 by its power series (identical to the Python version). + static func besselI0(_ x: Double) -> Double { + var s = 1.0, t = 1.0 + var k = 1.0 + let h = x / 2.0 + while true { + t *= (h / k) * (h / k) + s += t + if t < s * 1e-17 { return s } + k += 1 + } + } + + /// Low-pass taps (odd length, unity DC gain) and the delay (len-1)/2 for in_rate -> in_rate*up/down. + static func sincFilter(up: Int, down: Int, inRate: Int) -> (taps: [Double], delay: Int) { + let nyqLow = Double(min(inRate, inRate * up / down)) / 2.0 + let nyqHi = Double(inRate * up) / 2.0 + let fc = 0.5 * (passband + stopband) * nyqLow / nyqHi + let tw = (stopband - passband) * nyqLow / nyqHi + let beta = 0.1102 * (attenuationDB - 8.7) + var n = Int(ceil((attenuationDB - 7.95) / (2.285 * Double.pi * tw))) + n |= 1 + let c = (n - 1) / 2 + let i0b = besselI0(beta) + var h = [Double](repeating: 0, count: n) + var sum = 0.0 + for k in 0.. Polyphase { + let (h, c) = sincFilter(up: up, down: down, inRate: inRate) + var phases: [(j0: Int, rMin: Int, taps: [Double])] = [] + for p in 0.. Int { b == 0 ? a : gcd(b, a % b) } + + /// Float samples at `rate` -> Float samples at 16 kHz. y[j] = up * sum_m x[m] h[c + j*down - m*up] in Double + /// (each output is one vDSP double-precision dot product of a phase's taps with a reversed slice of the input). + public static func resampleTo16k(_ x: [Float], rate: Int) -> [Float] { + if rate == targetRate { return x } + let nOut = Int(ceil(Double(x.count) * Double(targetRate) / Double(rate))) + let g = gcd(targetRate, rate) + let up = targetRate / g, down = rate / g + let key = "\(up)/\(down)/\(rate)" + lock.lock() + var filt = cache[key] + if filt == nil { + filt = polyphase(up: up, down: down, inRate: rate) + cache[key] = filt + } + lock.unlock() + let pf = filt! + let pad = (pf.phases.map { $0.taps.count }.max() ?? 0) + 1 // zero padding so no tap window leaves the buffer + var xd = [Double](repeating: 0, count: x.count + 2 * pad) + for i in 0..= 0 { + let L = vDSP_Length(ph.taps.count) + ph.taps.withUnsafeBufferPointer { hb in + let rMax = ph.rMin + Int(L) - 1 + var j = ph.j0 + while j < nOut { + let q = (j * down - p) / up + // taps (reversed) k = 0 ... L-1 multiply x[q - rMax + k]; the padding keeps every index in range + var acc = 0.0 + vDSP_dotprD(xb.baseAddress! + (pad + q - rMax), 1, hb.baseAddress!, 1, &acc, L) + y[j] = acc * scale + j += up + } + } + } + } + return y.map { Float($0) } + } +} diff --git a/swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift b/swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift index 1a280e8169b0dfb92d35e34c5f7dac9ed2985097..3714d46083a7cfca3a1addef37308aed0f74c763 100644 --- a/swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift +++ b/swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift @@ -1,16 +1,20 @@ // Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE). // -// EmbeddingGemma 2 (text + images) on Apple Core AI, macOS 27. Loads the bundle folder (config.json, tokenizer/, -// the text asset and, on request, the vision asset) and embeds texts and images into the same 768-d space: +// EmbeddingGemma 2 (text + images + audio) on Apple Core AI, macOS 27. Loads the bundle folder (config.json, +// tokenizer/, the text asset and, on request, the vision and audio assets) and embeds texts, images and audio clips +// into the same 768-d space: // text -> exact Gemma tokenizer -> prompt text -> `mm_` with zero soft-token inputs -> embedding // image -> decode (alpha dropped, no EXIF, no colour management) -> exact resize -> patches -> `vision_2520` // -> n soft tokens -> sequence <|image> [n slots] -> `mm_288` -> embedding -// Both outputs are L2-normalized by the graph; Matryoshka prefixes (512/256/128) are re-normalized on the host. +// audio -> decode -> mono -> 16 kHz -> log-mel frames -> `audio_` -> n soft tokens +// -> sequence <|audio> [n slots] -> `mm_` -> embedding +// All outputs are L2-normalized by the graph; Matryoshka prefixes (512/256/128) are re-normalized on the host. // // The v1.0 API (init(bundle:compute:), tokenize, embed(ids:), embed(_:kind:dim:), prewarm) is unchanged and still -// loads the text asset only; pass `loadVision: true` to embed images. `compute` places the text asset and -// `imageCompute` the image encoder (default: the same as `compute`): the Neural Engine uses the least CPU, GPU and -// power, the GPU is about 3x faster per image (README, "Images: Neural Engine or GPU"). +// loads the text asset only; pass `loadVision: true` to embed images and `loadAudio: true` to embed audio. `compute` +// places the text asset, `imageCompute` and `audioCompute` the image and audio encoders (default: the same as +// `compute`): the Neural Engine uses the least CPU, GPU and power, the GPU is faster (README, "Images: Neural Engine +// or GPU" and "Audio: Neural Engine or GPU"). import CoreAI import CoreGraphics @@ -23,12 +27,20 @@ public struct BundleConfig: Decodable, Sendable { public let max_patches: Int public let max_soft_tokens: Int } + public struct Audio: Decodable, Sendable { + public let asset: String + public let functions: [String] + public let frame_buckets: [Int] + public let max_soft_tokens: Int + } /// The text asset (`mm_` functions: text, images, or both in one sequence). public let asset: String public let functions: [String] public let buckets: [Int] public let max_tokens: Int public let vision: Vision + /// The audio asset (`audio_` functions); absent in a 1.1 bundle. + public let audio: Audio? public let hidden_size: Int public let embedding_dim: Int public let matryoshka_dims: [Int] @@ -39,6 +51,17 @@ public struct BundleConfig: Decodable, Sendable { public let boi_token_id: Int32 public let image_token_id: Int32 public let eoi_token_id: Int32 + public let boa_token_id: Int32? + public let audio_token_id: Int32? + public let eoa_token_id: Int32? +} + +/// How audio longer than the model's 30 s window is embedded. +public enum LongAudioPolicy: String, Sendable { + /// The first 30 s only (what the upstream model does). + case truncate + /// The mean of the normalized embeddings of consecutive 30 s windows, re-normalized. + case chunkMean = "chunk_mean" } public enum ComputePreference: String, Sendable { @@ -74,6 +97,8 @@ public final class EmbeddingGemma2 { public let compute: ComputePreference /// Where the image encoder (`vision_2520`) runs; equals `compute` unless set with `imageCompute:`. public let imageCompute: ComputePreference + /// Where the audio encoder (`audio_`) runs; equals `compute` unless set with `audioCompute:`. + public let audioCompute: ComputePreference /// Wall-clock seconds spent in `AIModel(contentsOf:)` + `loadFunction` (specialization) for the loaded assets. /// About 1 s warm; the first load by an executable that has not loaded these assets before takes minutes (README). public let loadSeconds: Double @@ -83,9 +108,15 @@ public final class EmbeddingGemma2 { private let functions: [Int: InferenceFunction] // bucket -> mm_ private let visionModel: AIModel? // nil unless created with loadVision: true private let visionFunction: InferenceFunction? + private let audioModel: AIModel? // nil unless created with loadAudio: true + private let audioFunctions: [Int: InferenceFunction] // frame bucket -> audio_ public var buckets: [Int] { functions.keys.sorted() } + /// Frame buckets of the loaded audio asset (empty unless loaded). + public var audioBuckets: [Int] { audioFunctions.keys.sorted() } /// True when the vision asset is loaded and `embedImage` / `softTokens` can be used. public var hasVision: Bool { visionFunction != nil } + /// True when the audio asset is loaded and `embedAudio` / `audioSoftTokens` can be used. + public var hasAudio: Bool { !audioFunctions.isEmpty } private var hidden: Int { config.hidden_size } /// `loadVision: false` (the default, as in v1.0) loads the text asset only. `loadVision: true` also loads the @@ -93,11 +124,15 @@ public final class EmbeddingGemma2 { /// `imageCompute` places the image encoder independently of the text asset (nil = same as `compute`): /// `.neuralEngine` ~0.37 s per image with ~2 ms CPU and ~1 ms GPU time (lowest power); `.gpu` ~0.13 s per image /// with ~20-35 ms CPU and ~0.1 s GPU time (about 3x the power draw). Both match the reference within float16 noise. + /// `loadAudio: true` also loads the audio asset (~560 MB) so that audio clips can be embedded; `audioCompute` + /// places it independently (nil = same as `compute`), see README "Audio: Neural Engine or GPU". public init(bundle: URL, compute: ComputePreference = .neuralEngine, loadVision: Bool = false, - imageCompute: ComputePreference? = nil) async throws { + imageCompute: ComputePreference? = nil, loadAudio: Bool = false, + audioCompute: ComputePreference? = nil) async throws { bundleURL = bundle self.compute = compute self.imageCompute = imageCompute ?? compute + self.audioCompute = audioCompute ?? compute config = try JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json"))) var t0 = Date() tokenizer = try GemmaTokenizer(contentsOf: bundle.appendingPathComponent("tokenizer/tokenizer.json")) @@ -105,6 +140,13 @@ public final class EmbeddingGemma2 { guard tokenizer.bosID == config.bos_token_id, tokenizer.eosID == config.eos_token_id, tokenizer.padID == config.pad_token_id else { throw EmbedderError(description: "tokenizer special ids do not match config.json") } + // Refuse an unsupported audio request before loading anything (no specialization, no temp files). + if loadAudio { + guard config.audio != nil else { throw EmbedderError(description: "this bundle has no audio asset (config.json \"audio\")") } + guard self.audioCompute != .cpu else { + throw EmbedderError(description: "audioCompute: .cpu is not supported for audio; use .neuralEngine or .gpu") + } + } t0 = Date() textModel = try await AIModel(contentsOf: bundle.appendingPathComponent(config.asset), options: Self.options(compute)) var fns: [Int: InferenceFunction] = [:] @@ -126,6 +168,22 @@ public final class EmbeddingGemma2 { visionModel = nil visionFunction = nil } + if loadAudio { + guard let ac = config.audio else { throw EmbedderError(description: "this bundle has no audio asset (config.json \"audio\")") } + let am = try await AIModel(contentsOf: bundle.appendingPathComponent(ac.asset), options: Self.options(self.audioCompute)) + var afns: [Int: InferenceFunction] = [:] + for name in ac.functions { + guard let tb = Int(name.split(separator: "_").last ?? ""), let fn = try am.loadFunction(named: name) else { + throw EmbedderError(description: "function \(name) missing from \(ac.asset)") + } + afns[tb] = fn + } + audioModel = am + audioFunctions = afns + } else { + audioModel = nil + audioFunctions = [:] + } loadSeconds = Date().timeIntervalSince(t0) } @@ -228,6 +286,89 @@ public final class EmbeddingGemma2 { return MultimodalSequence(ids: ids, softTokens: softTokens, slots: Array(2..<(2 + n))) } + // MARK: - Audio + + /// Embeds an audio file (anything AVAudioFile reads). The clip is decoded, mixed to mono, resampled to 16 kHz + /// and, with `.truncate` (the upstream behaviour), its first 30 s are embedded; `.chunkMean` averages the + /// embeddings of consecutive 30 s windows instead. + public func embedAudio(url: URL, dim: Int = 768, longAudio: LongAudioPolicy = .truncate) async throws -> [Float] { + try await embedAudio(samples16k: try AudioFrontend.loadMono16k(url: url), dim: dim, longAudio: longAudio) + } + + /// Embeds PCM samples (any rate, any channel count: `channels[c][i]`, channel-major, every channel the same + /// length); they are mixed to mono and resampled. Throws for a non-positive rate, channels of different lengths + /// and arrays that look frame-major (more "channels" than samples per channel: pass `channels[c][i]`, not `[i][c]`). + public func embedAudio(samples: [[Float]], sampleRate: Int, dim: Int = 768, longAudio: LongAudioPolicy = .truncate) async throws -> [Float] { + guard sampleRate > 0 else { throw EmbedderError(description: "sampleRate must be positive (got \(sampleRate))") } + guard let n = samples.first?.count, samples.allSatisfy({ $0.count == n }) else { + throw EmbedderError(description: samples.isEmpty ? "samples has no channels" : "every channel must have the same number of samples") + } + guard samples.count <= max(n, 1) else { + throw EmbedderError(description: "samples looks frame-major (\(samples.count) channels of \(n) samples): pass channel-major samples[channel][frame]") + } + let mono = AudioFrontend.toMono(DecodedAudio(sampleRate: sampleRate, channelCount: samples.count, channels: samples)) + return try await embedAudio(samples16k: AudioResampler.resampleTo16k(mono, rate: sampleRate), dim: dim, longAudio: longAudio) + } + + /// Embeds 16 kHz mono samples. + public func embedAudio(samples16k: [Float], dim: Int = 768, longAudio: LongAudioPolicy = .truncate) async throws -> [Float] { + switch longAudio { + case .truncate: + return try await embedAudio(try AudioFrontend.prepare(wav16k: samples16k), dim: dim) + case .chunkMean: + var acc = [Float](repeating: 0, count: config.embedding_dim) + for chunk in AudioFrontend.chunks30s(samples16k) { + let v = try await embedAudio(try AudioFrontend.prepare(wav16k: chunk), dim: config.embedding_dim) + for i in acc.indices { acc[i] += v[i] } + } + return try normalized(acc, dim: dim) + } + } + + /// Embeds already prepared audio inputs (`AudioFrontend.prepare`). + public func embedAudio(_ inputs: AudioInputs, dim: Int = 768) async throws -> [Float] { + let soft = try await audioSoftTokens(inputs) + return try normalized(try await embed(sequence: audioSequence(softTokens: soft)), dim: dim) + } + + /// Soft tokens of one prepared clip (`audio_`): `[n, 512]` as a flat array (n = inputs.softTokenCount). + public func audioSoftTokens(_ inputs: AudioInputs) async throws -> [Float16] { + guard let fn = audioFunctions[inputs.bucket] else { + throw EmbedderError(description: hasAudio ? "no audio function for bucket \(inputs.bucket)" : "audio asset not loaded: create the model with loadAudio: true") + } + let Tb = inputs.bucket, M = AudioInputs.nMels + guard inputs.features.count == Tb * M, inputs.frameMask.count == Tb, inputs.halfMask.count == Tb / 2, inputs.tokenMask.count == Tb / 4 else { + throw EmbedderError(description: "AudioInputs has the wrong size") + } + var features = NDArray(shape: [1, Tb, M], scalarType: .float16) + var frameMask = NDArray(shape: [1, Tb], scalarType: .float16) + var halfMask = NDArray(shape: [1, Tb / 2], scalarType: .float16) + var tokenMask = NDArray(shape: [1, Tb / 4], scalarType: .float16) + fill(&features, inputs.features) + fill(&frameMask, inputs.frameMask) + fill(&halfMask, inputs.halfMask) + fill(&tokenMask, inputs.tokenMask) + var out = try await fn.run(inputs: ["features": features, "frame_mask": frameMask, "half_mask": halfMask, "token_mask": tokenMask]) + guard let soft = out.remove("soft_tokens")?.ndArray else { throw EmbedderError(description: "output 'soft_tokens' missing") } + let n = inputs.softTokenCount + var result = [Float16](repeating: 0, count: n * hidden) + let view = soft.view(as: Float16.self) + view.withUnsafePointer { p, _, _ in + for i in 0..<(n * hidden) { result[i] = p[i] } + } + return result + } + + /// The upstream single-clip sequence: ` <|audio> <|audio|> x n ` (no prompt). + public func audioSequence(softTokens: [Float16]) -> MultimodalSequence { + let n = softTokens.count / hidden + let boa = config.boa_token_id ?? 256000, audio = config.audio_token_id ?? 258881, eoa = config.eoa_token_id ?? 258883 + var ids = [config.bos_token_id, boa] + ids.append(contentsOf: [Int32](repeating: audio, count: n)) + ids.append(contentsOf: [eoa, config.eos_token_id]) + return MultimodalSequence(ids: ids, softTokens: softTokens, slots: Array(2..<(2 + n))) + } + // MARK: - Any sequence /// Runs `mm_` on a sequence (ids with ``/``, right-padded with ``; soft tokens placed at @@ -292,6 +433,13 @@ public final class EmbeddingGemma2 { if visionFunction != nil { _ = try await softTokens(ImagePreprocessor.patchify(resizedRGB: [UInt8](repeating: 128, count: 48 * 48 * 3), width: 48, height: 48)) } + for tb in audioBuckets { + let n = AudioInputs.nMels + let inputs = AudioInputs(bucket: tb, frameCount: 4, softTokenCount: 1, features: [Float16](repeating: 0, count: tb * n), + frameMask: [Float16](repeating: 0, count: tb), halfMask: [Float16](repeating: 0, count: tb / 2), + tokenMask: [Float16](repeating: 0, count: tb / 4)) + _ = try await audioSoftTokens(inputs) + } return Date().timeIntervalSince(t0) } @@ -306,7 +454,7 @@ public final class EmbeddingGemma2 { /// Each Neural Engine load makes MPSGraph write compiled-graph copies into `$TMPDIR/com.apple.MetalPerformance /// ShadersGraph/mpsgraph---/` (~360 MB for the text asset, ~300 MB for the vision asset). With the - /// Swift `CoreAI` framework (macOS 27.0) the runtime deletes that folder itself when the model is released, so this + /// Swift `CoreAI` framework (macOS 27) the runtime deletes that folder itself when the model is released, so this /// usually finds nothing; it is a safety net for a folder that survives (e.g. the process exits while the model is /// alive). It removes only the folders that belong to the CURRENT process (its pid, created after it started). /// Call it after the `EmbeddingGemma2` instance has been released, or at exit. Returns the number of folders diff --git a/swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift b/swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift index 72615a87dbf725d1485b8b2273dfa99c997d03c8..b805a2f9e53f96ce640f839497272ad4cf0814fe 100644 --- a/swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift +++ b/swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift @@ -2,7 +2,7 @@ // // A small, exact JSON reader, written for this package and used to read tokenizer.json. Strings are returned as // the exact UTF-8 bytes they encode (every \uXXXX escape, including surrogate pairs, is decoded to UTF-8; nothing -// is normalized or stripped). It exists because Foundation's JSONSerialization (macOS 27.0) drops a leading U+FEFF +// is normalized or stripped). It exists because Foundation's JSONSerialization (macOS 27) drops a leading U+FEFF // (byte-order mark) from every string VALUE, which turns the vocabulary entries "", "", ... // into "", "", ... and breaks the tokenizer. (JSONDecoder does not have the bug, but a 32 MB vocabulary // decoded through Codable is slow, and this reader keeps the bytes exact by construction.) diff --git a/swift/Sources/eg2-cli/main.swift b/swift/Sources/eg2-cli/main.swift index 6171dc86987e9f9eca3ab4ab1f06b93d7f13dc13..9481024773ec48f74a6744dfbf3787aecb282357 100644 --- a/swift/Sources/eg2-cli/main.swift +++ b/swift/Sources/eg2-cli/main.swift @@ -5,20 +5,24 @@ // eg2-cli embed [--compute ane|gpu|cpu] [--kind document|search_query|...] [--dim 768] "text" ... // eg2-cli embed-image [--compute ...] [--image-compute ane|gpu|cpu] [--exif] [--dim 768] image ... // (one JSON line per image) -// eg2-cli smoke [ ...] [--compute ...] [--image-compute ...] [--cleanup-temp] -// (text references: tests/smoke-reference.json; image references: tests/image-smoke-reference.json) +// eg2-cli embed-audio [--compute ...] [--audio-compute ane|gpu|cpu] [--long truncate|chunk_mean] [--dim 768] clip ... +// (one JSON line per clip) +// eg2-cli smoke [ ...] [--compute ...] [--image-compute ...] [--audio-compute ...] [--cleanup-temp] +// (text: tests/smoke-reference.json; images: tests/image-smoke-reference.json; audio: tests/audio-smoke-reference.json) // eg2-cli tokcheck // eg2-cli pixcheck (decode + resize vs the Python reference, no model needed) +// eg2-cli audiocheck (decode + resample + log-mel vs the Python reference, no model needed) // eg2-cli dump [--exif] (writes .decoded.rgb / .resized.rgb / .json) -// eg2-cli latency [--compute ...] [--image-compute ...] [--trials 50] [--text-only] -// eg2-cli prewarm [--compute ...] [--image-compute ...] [--text-only] +// eg2-cli dump-audio (writes .wave16k.f32 / .features.f32 / .json) +// eg2-cli latency [--compute ...] [--image-compute ...] [--audio-compute ...] [--trials 50] [--text-only] +// eg2-cli prewarm [--compute ...] [--image-compute ...] [--audio-compute ...] [--text-only] // eg2-cli cleanup-temp (removes this process's MPSGraph temp folders; mostly useful after the others) // -// `embed` and `tokcheck` never load the vision asset; `embed-image` always does; `smoke` does when a reference -// file has images; `latency` and `prewarm` do unless --text-only. Every command accepts --cleanup-temp to delete -// the MPSGraph temp folders this process created, after the model is released -// (see EmbeddingGemma2.removeOwnMPSGraphTempFiles). `--compute` places the text asset (and the image encoder unless -// `--image-compute` is given); `--image-compute` places the image encoder only. +// `embed` and `tokcheck` load the text asset only; `embed-image` also loads the vision asset and `embed-audio` the +// audio asset; `smoke` loads what its reference files need; `latency` and `prewarm` load every asset the bundle has +// unless --text-only. Every command accepts --cleanup-temp to delete the MPSGraph temp folders this process created, +// after the model is released (see EmbeddingGemma2.removeOwnMPSGraphTempFiles). `--compute` places the text asset +// (and the image and audio encoders unless `--image-compute` / `--audio-compute` are given). import CryptoKit import EmbeddingGemma2CoreAI @@ -28,8 +32,8 @@ var args = Array(CommandLine.arguments.dropFirst()) @MainActor func usage() -> Never { print(""" - usage: eg2-cli ... [--compute ane|gpu|cpu] - [--image-compute ane|gpu|cpu] [--cleanup-temp] + usage: eg2-cli ... + [--compute ane|gpu|cpu] [--image-compute ane|gpu|cpu] [--audio-compute ane|gpu|cpu] [--cleanup-temp] """) exit(2) } @@ -72,6 +76,13 @@ func percentile(_ xs: [Double], _ p: Double) -> Double { return s[min(s.count - 1, Int(Double(s.count) * p))] } +func floatsData(_ v: [Float]) -> Data { v.withUnsafeBufferPointer { Data(buffer: $0) } } + +func readFloats(_ url: URL) throws -> [Float] { + let d = try Data(contentsOf: url) + return d.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } +} + guard !args.isEmpty else { usage() } let cmd = args.removeFirst() let cleanup = takeFlag("--cleanup-temp") @@ -85,8 +96,14 @@ let cleanup = takeFlag("--cleanup-temp") } let compute = computeOption("--compute") ?? .neuralEngine let imageCompute = computeOption("--image-compute") // nil = same as --compute +let audioCompute = computeOption("--audio-compute") // nil = same as --compute let exif = takeFlag("--exif") let textOnly = takeFlag("--text-only") +let longPolicyRaw = takeOption("--long") ?? "truncate" +guard let longPolicy = LongAudioPolicy(rawValue: longPolicyRaw) else { + print("--long must be truncate or chunk_mean") + exit(2) +} @MainActor func finish(_ code: Int32) -> Never { if cleanup { @@ -103,14 +120,25 @@ struct PixCase: Decodable { let decoded_sha256: String; let resized_sha256: String; let lossy: Bool } -// Smoke reference files: text (v1.0 format, "cases") or images ("images" + "texts"). +/// One entry of tests/audio-preprocess-cases.json: the Python front end's result on a shipped clip, with the +/// 16 kHz waveform and the log-mel features stored next to it as raw float32 files. +struct AudioCase: Decodable { + let file: String; let sample_rate: Int; let channels: Int; let n_samples16k: Int; let n_frames: Int; let n_tokens: Int + let bucket: Int; let wave_file: String; let features_file: String + let wave_tolerance: Float; let feature_tolerance: Float; let note: String? +} + +// Smoke reference files: text (v1.0 format, "cases"), images ("images" + "texts") or audio ("audio" + "texts"). struct TextCase: Decodable { let text: String; let kind: String; let embedding: [Float] } struct ImageCase: Decodable { let file: String; let query: String; let embedding: [Float] } +struct AudioRefCase: Decodable { let file: String; let query: String?; let embedding: [Float]; let threshold_cosine: Double?; let fp32_rank1: Bool? } struct RefFile: Decodable { let threshold_cosine: Double let threshold_cosine_image: Double? + let threshold_cosine_audio: Double? let cases: [TextCase]? let images: [ImageCase]? + let audio: [AudioRefCase]? let texts: [TextCase]? } @@ -144,6 +172,44 @@ do { print("PIXCHECK \(exact)/\(cases.count) bit-identical to the Python reference, \(lossyDiff) lossy-format decoder differences, \(fail) failures, \(fmt(Date().timeIntervalSince(t0), 2)) s") finish(fail == 0 ? 0 : 1) + case "audiocheck": + guard let casesPath = args.first else { usage() } + let url = URL(fileURLWithPath: casesPath) + let cases = try JSONDecoder().decode([AudioCase].self, from: Data(contentsOf: url)) + let base = url.deletingLastPathComponent() + var pass = 0, fail = 0, waveExact = 0 + var worstWave: Float = 0, worstFeat: Float = 0 + let t0 = Date() + for c in cases { + let t1 = Date() + let d = try AudioDecoder.decode(url: base.appendingPathComponent(c.file)) + let wav = AudioResampler.resampleTo16k(AudioFrontend.toMono(d), rate: d.sampleRate) + let inputs = try AudioFrontend.prepare(wav16k: wav) + let ms = Date().timeIntervalSince(t1) * 1000 + let refWave = try readFloats(base.appendingPathComponent(c.wave_file)) + let refFeat = try readFloats(base.appendingPathComponent(c.features_file)) + let counts = d.sampleRate == c.sample_rate && d.channelCount == c.channels && wav.count == c.n_samples16k + && inputs.frameCount == c.n_frames && inputs.softTokenCount == c.n_tokens && inputs.bucket == c.bucket + var wDiff: Float = 0 + if wav.count == refWave.count { for i in 0.. \(wav.count) samples, \(inputs.frameCount) frames, \(inputs.softTokenCount) tokens (bucket \(inputs.bucket)); " + + "wave max diff \(wDiff == 0 ? "0 (exact)" : String(format: "%.2e", wDiff)) (tol \(String(format: "%.0e", c.wave_tolerance))), " + + "features max diff \(String(format: "%.2e", fDiff)) (tol \(String(format: "%.0e", c.feature_tolerance))), \(fmt(ms, 0)) ms\(counts ? "" : " COUNTS DIFFER")") + } + print("AUDIOCHECK \(pass)/\(cases.count) within tolerance of the Python reference (\(waveExact) waveforms bit-identical; worst wave diff \(String(format: "%.2e", worstWave)), worst feature diff \(String(format: "%.2e", worstFeat))), \(fail) failures, \(fmt(Date().timeIntervalSince(t0), 2)) s") + finish(fail == 0 ? 0 : 1) + case "dump": guard args.count >= 2 else { usage() } let img = try ImageDecoder.decodeRGB(url: URL(fileURLWithPath: args[0]), applyEXIFOrientation: exif) @@ -157,6 +223,19 @@ do { print(String(decoding: try JSONSerialization.data(withJSONObject: info), as: UTF8.self)) finish(0) + case "dump-audio": + guard args.count >= 2 else { usage() } + let d = try AudioDecoder.decode(url: URL(fileURLWithPath: args[0])) + let wav = AudioResampler.resampleTo16k(AudioFrontend.toMono(d), rate: d.sampleRate) + let (feats, frames) = AudioFrontend.logMel(wav) + try floatsData(wav).write(to: URL(fileURLWithPath: args[1] + ".wave16k.f32")) + try floatsData(feats).write(to: URL(fileURLWithPath: args[1] + ".features.f32")) + let info: [String: Any] = ["sample_rate": d.sampleRate, "channels": d.channelCount, "decoded_frames": d.frameCount, + "n_samples16k": wav.count, "n_frames": frames, "n_tokens": AudioFrontend.softTokenCount(frames: frames)] + try JSONSerialization.data(withJSONObject: info).write(to: URL(fileURLWithPath: args[1] + ".json")) + print(String(decoding: try JSONSerialization.data(withJSONObject: info), as: UTF8.self)) + finish(0) + default: break } @@ -194,6 +273,26 @@ do { _ = consume eg2 finish(0) + case "embed-audio": + let dim = Int(takeOption("--dim") ?? "768") ?? 768 + let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadAudio: true, audioCompute: audioCompute) + for path in args { + let t0 = Date() + let d = try AudioDecoder.decode(url: URL(fileURLWithPath: path)) + let wav = AudioResampler.resampleTo16k(AudioFrontend.toMono(d), rate: d.sampleRate) + let t1 = Date() + let v = try await eg2.embedAudio(samples16k: wav, dim: dim, longAudio: longPolicy) + let frames = AudioFrontend.validFrameCount(samples: wav.count) + let json: [String: Any] = ["audio": path, "dim": dim, "sample_rate": d.sampleRate, "channels": d.channelCount, + "seconds": Double(wav.count) / 16000.0, "n_frames": frames, "n_soft": AudioFrontend.softTokenCount(frames: frames), + "truncated_to_30s": wav.count > AudioFrontend.maxSamples && longPolicy == .truncate, + "long_audio": longPolicy.rawValue, "decode_ms": Int(t1.timeIntervalSince(t0) * 1000), + "model_ms": Int(Date().timeIntervalSince(t1) * 1000), "embedding": v.map { Double($0) }] + print(String(decoding: try JSONSerialization.data(withJSONObject: json), as: UTF8.self)) + } + _ = consume eg2 + finish(0) + case "smoke": guard !args.isEmpty else { usage() } let refs = try args.map { path -> (URL, RefFile) in @@ -201,10 +300,12 @@ do { return (url, try JSONDecoder().decode(RefFile.self, from: Data(contentsOf: url))) } let needsVision = refs.contains { !($0.1.images ?? []).isEmpty } - let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: needsVision, imageCompute: imageCompute) + let needsAudio = refs.contains { !($0.1.audio ?? []).isEmpty } + let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: needsVision, imageCompute: imageCompute, + loadAudio: needsAudio, audioCompute: audioCompute) print("loaded in \(fmt(eg2.loadSeconds, 1)) s (tokenizer \(fmt(eg2.tokenizerLoadSeconds, 2)) s), compute=\(compute.rawValue), " - + "image-compute=\(eg2.hasVision ? eg2.imageCompute.rawValue : "-"), " - + "buckets=\(eg2.buckets), vision \(eg2.hasVision ? "loaded" : "not loaded")") + + "image-compute=\(eg2.hasVision ? eg2.imageCompute.rawValue : "-"), audio-compute=\(eg2.hasAudio ? eg2.audioCompute.rawValue : "-"), " + + "buckets=\(eg2.buckets), vision \(eg2.hasVision ? "loaded" : "not loaded"), audio \(eg2.hasAudio ? "loaded" : "not loaded")") var ok = true for (refURL, ref) in refs { print("-- \(refURL.lastPathComponent)") @@ -239,6 +340,19 @@ do { imgVecs.append(v) print("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(imgThreshold)) image \(c.file) \(Int(Date().timeIntervalSince(t0) * 1000)) ms") } + // audio clips (per-clip thresholds: resampled and lossy files are allowed more) + let audio = ref.audio ?? [] + var audVecs: [[Float]] = [] + for c in audio { + let t0 = Date() + let v = try await eg2.embedAudio(url: refURL.deletingLastPathComponent().appendingPathComponent(c.file)) + let cos = cosineSimilarity(v, c.embedding) + let thr = c.threshold_cosine ?? ref.threshold_cosine_audio ?? ref.threshold_cosine + let pass = cos >= thr && v.allSatisfy { $0.isFinite } + ok = ok && pass + audVecs.append(v) + print("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(thr)) audio \(c.file) \(Int(Date().timeIntervalSince(t0) * 1000)) ms") + } var queryVecs: [(String, [Float])] = [] for c in ref.texts ?? [] { let v = try await eg2.embed(c.text, kind: c.kind) @@ -261,6 +375,27 @@ do { ok = ok && hits == queryVecs.count print("text -> image: \(hits)/\(queryVecs.count) queries rank their own image first") } + // text -> audio: each query must rank its own clip first (among the clips that have a query), checked only + // where the fp32 reference itself ranks it first (fp32_rank1; synthesized sounds are a hard retrieval case) + if !audio.isEmpty { + let withQuery = audio.indices.filter { audio[$0].query != nil } + var hits = 0, total = 0 + for (q, qv) in queryVecs { + guard let want = audio.firstIndex(where: { $0.query == q }) else { continue } + let scores = withQuery.map { cosineSimilarity(qv, audVecs[$0]) } + let best = withQuery[scores.indices.max(by: { scores[$0] < scores[$1] })!] + let hit = best == want + if audio[want].fp32_rank1 == false { + print("SKIP query \"\(q)\" -> \(audio[best].file) (\(fmt(scores.max()!, 3))) (fp32 does not rank this clip first either)") + continue + } + total += 1 + hits += hit ? 1 : 0 + print("\(hit ? "PASS" : "FAIL") query \"\(q)\" -> \(audio[best].file) (\(fmt(scores.max()!, 3)))") + } + ok = ok && hits == total + print("text -> audio: \(hits)/\(total) queries rank their own clip first (as fp32 does)") + } } let fp = footprints() print("peak footprint \(fmt(fp.physMB, 0)) MB, neural footprint \(fmt(fp.neuralMB, 0)) MB") @@ -303,9 +438,11 @@ do { case "latency": let trials = Int(takeOption("--trials") ?? "50") ?? 50 - let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: !textOnly, imageCompute: imageCompute) + let hasAudioAsset = (try? JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json"))))?.audio != nil + let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: !textOnly, imageCompute: imageCompute, + loadAudio: !textOnly && hasAudioAsset, audioCompute: audioCompute) print("loaded in \(fmt(eg2.loadSeconds, 1)) s, compute=\(compute.rawValue), image-compute=\(eg2.hasVision ? eg2.imageCompute.rawValue : "-"), " - + "vision \(eg2.hasVision ? "loaded" : "not loaded")") + + "audio-compute=\(eg2.hasAudio ? eg2.audioCompute.rawValue : "-"), vision \(eg2.hasVision ? "loaded" : "not loaded"), audio \(eg2.hasAudio ? "loaded" : "not loaded")") let warm = try await eg2.prewarm() print("prewarm \(fmt(warm, 2)) s") if eg2.hasVision { @@ -333,6 +470,46 @@ do { for _ in 0..<5 { _ = try ImagePreprocessor.prepare(DecodedImage(width: 2560, height: 1600, rgb: big)) } print("preprocess (resize 2560x1600 -> 1008x624 + patches): \(fmt(Date().timeIntervalSince(tp0) / 5 * 1000, 1)) ms") } + if eg2.hasAudio { + // synthetic clips of 3 s, 10 s and 30 s (a sum of tones and noise), per frame bucket + let audioTrials = max(5, trials / 2) + print("audio seconds bucket tokens audio_ p50 ms mm_ p50 ms end-to-end p50 ms CPU ms/clip front end ms") + for seconds in [3.0, 10.0, 30.0] { + let n = Int(seconds * 16000) + var wav = [Float](repeating: 0, count: n) + for i in 0.. None: + ap = argparse.ArgumentParser() + ap.add_argument("--audio", default=str(HERE / "audio")) + ap.add_argument("--out", default=str(HERE / "audio-preprocess-cases.json")) + args = ap.parse_args() + audio = Path(args.audio) + ref = audio / "ref" + ref.mkdir(exist_ok=True) + manifest = json.loads((audio / "manifest.json").read_text(encoding="utf-8")) + cases = [] + for it in manifest: + d = fe.decode(audio / it["file"]) + wav = fe.resample_16k(fe.to_mono(d.samples), d.sample_rate) + inputs = fe.prepare_audio_inputs(wav) + feats = fe.log_mel(wav) + wave_file = f"ref/{it['name']}.wave16k.f32" + feat_file = f"ref/{it['name']}.features.f32" + wav.astype(" {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tests/make_audio_smoke_reference.py b/tests/make_audio_smoke_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9cf677de16a0db7782f60637ba468587ae5578 --- /dev/null +++ b/tests/make_audio_smoke_reference.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). +"""Write tests/audio-smoke-reference.json: fp32 reference embeddings of the clips in tests/audio/ (the original model +through sentence-transformers, exactly as upstream does it: decode with libsndfile/ffmpeg, mono, libsoxr "HQ" to +16 kHz, no prompt) plus their captions as search queries and as documents. + + python3 make_audio_smoke_reference.py --model-dir [--audio audio] [--out audio-smoke-reference.json] + +Needs torch, transformers >= 5.19, sentence-transformers >= 6.1, soundfile, soxr (and ffmpeg for AAC files). +Per-clip thresholds: clips already at 16 kHz and lossless keep the model-only tolerance (0.9995); clips the runners +resample with their own sinc filter instead of libsoxr, and MP3 files, get 0.995 (README "Audio: decoding and +resampling"). +""" +from __future__ import annotations + +import argparse +import json +import math +import shutil +import subprocess +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +Q_PROMPT = "task: search result | query: " +D_PROMPT = "title: none | text: " +# measured exceptions (README "Audio: accuracy"): digital silence is the least precise case of the Neural Engine's +# float16 arithmetic (0.9993 vs 0.9999 on the GPU); an MP3 with long near-silent decays amplifies the ~3e-5 difference +# between Apple's MP3 decoder (the runners) and libsndfile/mpg123 (this reference) in the log-mel floor (0.990 on both +# routes; the same clip decoded by libsndfile gives 0.9997). +THRESHOLD_OVERRIDES = {"edge_silence_1s_16k": (0.998, "digital silence: float16 arithmetic on the Neural Engine, ~0.9993"), + "long_melody_35s_16k": (0.985, "mp3 with silent decays: Apple's decoder vs libsndfile/mpg123, ~0.990 (0.9997 if decoded with libsndfile)")} + + +def decode(path: Path) -> tuple[np.ndarray, int]: + import soundfile as sf + try: + x, sr = sf.read(str(path), dtype="float32", always_2d=True) + return x, int(sr) + except Exception: # noqa: BLE001 - AAC: ffmpeg + pass + ffprobe = shutil.which("ffprobe") + info = subprocess.run([ffprobe, "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", + "-of", "csv=p=0", str(path)], check=True, capture_output=True, text=True).stdout.strip().split(",") + sr, ch = int(info[0]), int(info[1]) + raw = subprocess.run(["ffmpeg", "-nostdin", "-loglevel", "error", "-i", str(path), "-f", "f32le", "-acodec", "pcm_f32le", "-"], + check=True, capture_output=True).stdout + return np.frombuffer(raw, dtype=" np.ndarray: + import soxr + x, sr = decode(path) + mono = x[:, 0] if x.shape[1] == 1 else np.mean(x, axis=1, dtype=np.float32) + if sr == 16000: + return mono.astype(np.float32) + y = soxr.resample(mono, sr, 16000, quality="soxr_hq").astype(np.float32) + n_out = int(math.ceil(len(mono) * 16000 / sr)) + return np.pad(y, (0, max(0, n_out - len(y))))[:n_out] + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--model-dir", required=True) + ap.add_argument("--audio", default=str(HERE / "audio")) + ap.add_argument("--out", default=str(HERE / "audio-smoke-reference.json")) + args = ap.parse_args() + import torch + from sentence_transformers import SentenceTransformer + + audio = Path(args.audio) + manifest = json.loads((audio / "manifest.json").read_text(encoding="utf-8")) + m = SentenceTransformer(args.model_dir, device="cpu", model_kwargs={"torch_dtype": torch.float32}, config_kwargs={"vision_config": None}) + clips, texts = [], [] + for it in manifest: + wav = prepare(audio / it["file"]) + if len(wav) <= 128: + continue # the original model cannot embed fewer than 129 samples (the port gives the empty-sequence embedding) + with torch.no_grad(): + e = m.encode([{"array": wav, "sampling_rate": 16000}], normalize_embeddings=True)[0] + thr = 0.9995 if (it["sample_rate"] == 16000 and not it["file"].endswith(".mp3")) else 0.995 + note = None + if it["name"] in THRESHOLD_OVERRIDES: + thr, note = THRESHOLD_OVERRIDES[it["name"]] + clips.append(dict(file=f"audio/{it['file']}", query=it["caption"], seconds=round(len(wav) / 16000, 3), threshold_cosine=thr, + note=note, embedding=[round(float(v), 6) for v in e])) + print(f"{it['file']}: {len(wav) / 16000:.2f} s, threshold {thr}", flush=True) + for it in manifest: + if not it["caption"]: + continue + with torch.no_grad(): + q = m.encode([Q_PROMPT + it["caption"]], normalize_embeddings=True)[0] + d = m.encode([D_PROMPT + it["caption"]], normalize_embeddings=True)[0] + texts.append(dict(text=it["caption"], kind="search_query", embedding=[round(float(v), 6) for v in q])) + texts.append(dict(text=it["caption"], kind="document", embedding=[round(float(v), 6) for v in d])) + # which queries the fp32 reference itself ranks first (the runners check rank 1 only for those) + cap = [(c, np.array(c["embedding"])) for c in clips if c["query"]] + for c, _ in cap: + q = next(np.array(t["embedding"]) for t in texts if t["kind"] == "search_query" and t["text"] == c["query"]) + scores = [(float(q @ a), cc["file"]) for cc, a in cap] + c["fp32_rank1"] = max(scores)[1] == c["file"] + print(f"fp32 ranks its own clip first: {c['fp32_rank1']} {c['query']}", flush=True) + out = dict(note="fp32 reference of google/embeddinggemma-2 through sentence-transformers (audio: libsndfile/ffmpeg + libsoxr HQ, no prompt); " + "per-clip thresholds: 0.9995 for 16 kHz lossless clips, 0.995 for resampled and MP3 clips, two measured exceptions " + "(note fields); fp32_rank1 = the fp32 model ranks the clip first for its own caption (synthesized sounds are a hard " + "retrieval case; the runners check rank 1 only where fp32 succeeds)", + threshold_cosine=0.9995, threshold_cosine_audio=0.9995, audio=clips, texts=texts) + Path(args.out).write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"{len(clips)} clips, {len(texts)} texts -> {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tests/make_test_audio.py b/tests/make_test_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..3f661d53b87dad652195c8197058f516bfc6481e --- /dev/null +++ b/tests/make_test_audio.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE). +"""Generate the audio test clips in tests/audio/ (all synthetic: invented sentences spoken by the eSpeak NG formant +synthesizer, which builds speech from rules and formant parameters, not from voice recordings, and sounds +synthesized with numpy; no recording of a person is included or was used). The shipped files are the reference: +the synthesizer and the encoders may differ between versions and machines, so a regeneration is not guaranteed to be +byte-identical. + + python3 make_test_audio.py [--out audio] + +Needs macOS (`afconvert`), numpy and `espeak-ng` (validated with 1.52.0, e.g. `brew install espeak-ng`; the program +is only used as a tool, nothing of it is included); MP3 files need `ffmpeg` (skipped otherwise). Writes +/. and /manifest.json (name, file, caption, sample_rate, channels, format, lossy, source). +""" +from __future__ import annotations + +import argparse +import json +import shutil +import struct +import subprocess +import tempfile +from pathlib import Path + +import numpy as np + +RNG = np.random.default_rng(20261012) +SPEECH_RNG = np.random.default_rng(20261013) # separate stream, so the synthesized sounds do not depend on the speech + +# fictional sentences (no real people, places are generic, no brands), spoken by eSpeak NG formant voices (a voice +# and optionally a variant: pitch / formant settings, no recordings) at a speaking rate in words per minute. Voice +# and rate were chosen per sentence so that the original model clearly ranks each clip first for its own caption +# (formant speech is less natural than recorded voices). Japanese was tried and dropped: eSpeak NG reads kana only +# and its Japanese was not recognisable enough for the model to match the caption. +SPEECH = [ + ("speech_en_train_16k", "en-us+m7", 150, "en", 16000, "wav", "The night train to the coast stops twice before sunrise."), + ("speech_en_parcel_8k", "en-gb", 130, "en", 8000, "wav", "Please leave the parcel with the neighbour on the second floor."), + ("speech_it_mercato_22k", "it+m1", 130, "it", 22050, "aiff", "Il mercato del sabato apre alle otto e chiude a mezzogiorno."), + ("speech_fr_pont_44k", "fr-fr", 170, "fr", 44100, "m4a", "Le petit pont de bois traverse la rivière derrière le moulin."), + ("speech_de_garten_48k_stereo", "de", 170, "de", 48000, "wav32s", "Der Gärtner gießt die Rosen jeden Abend nach sieben Uhr."), + ("speech_pt_barco_44k", "pt+m1", 130, "pt", 44100, "caf", "O barco pequeno sai do porto todas as manhãs às seis."), + ("speech_es_tienda_16k", "es+f4", 150, "es", 16000, "flac", "La tienda de la esquina vende pan fresco cada mañana."), + ("speech_sv_buss_22k", "sv", 130, "sv", 22050, "mp3", "Bussen till stranden gÃ¥r varje halvtimme pÃ¥ sommaren."), +] +NOISE_FLOOR = 3e-4 # a faint noise floor (about -70 dBFS) under the speech: eSpeak NG pauses are digital silence + + +def write_wav(path: Path, x: np.ndarray, sr: int, float32: bool = False) -> None: + x = np.asarray(x, dtype=np.float32) + if x.ndim == 1: + x = x[:, None] + ch = x.shape[1] + if float32: + data = x.astype(" tuple[np.ndarray, int]: + b = path.read_bytes() + p, fmt, data = 12, None, None + while p + 8 <= len(b): + cid, size = b[p:p + 4], struct.unpack(" np.ndarray: + """Speak `text` with eSpeak NG (22.05 kHz, 16-bit mono), convert to `sr` with afconvert, add the noise floor.""" + raw = tmp / (out.stem + "_espeak.wav") + subprocess.run(["espeak-ng", "-v", voice, "-s", str(rate), "-w", str(raw), text], check=True) + subprocess.run(["afconvert", "-f", "WAVE", "-d", f"LEF32@{sr}", str(raw), str(out)], check=True, capture_output=True) + x, sr2 = read_wav_f32(out) + assert sr2 == sr, (out, sr2) + x = x[:, 0].astype(np.float64) + x = 0.8 * x / max(1e-9, np.abs(x).max()) + return (x + NOISE_FLOOR * SPEECH_RNG.standard_normal(len(x))).astype(np.float32) + + +def convert(src: Path, dst: Path, fmt: str) -> None: + args = {"aiff": ["-f", "AIFF", "-d", "BEI16"], "m4a": ["-f", "m4af", "-d", "aac"], + "caf": ["-f", "caff", "-d", "alac"], "flac": ["-f", "flac", "-d", "flac"]}[fmt] + subprocess.run(["afconvert", *args, str(src), str(dst)], check=True, capture_output=True) + + +def mp3(src: Path, dst: Path) -> bool: + if not shutil.which("ffmpeg"): + return False + subprocess.run(["ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-i", str(src), "-c:a", "libmp3lame", "-b:a", "96k", str(dst)], check=True) + return True + + +# ---- synthesized sounds ----------------------------------------------------------------------------------- +def t_axis(dur: float, sr: int) -> np.ndarray: + return np.arange(int(dur * sr)) / sr + + +def piano(f: float, dur: float, sr: int, amp: float = 0.3) -> np.ndarray: + t = t_axis(dur, sr) + env = np.exp(-3.0 * t) * np.minimum(1.0, t * 200) + return amp * env * (np.sin(2 * np.pi * f * t) + 0.4 * np.sin(4 * np.pi * f * t) + 0.15 * np.sin(6 * np.pi * f * t)) + + +def chord_clip(sr: int) -> np.ndarray: + n = int(3.0 * sr) + x = np.zeros((n, 2), np.float32) + for i, f in enumerate((261.63, 329.63, 392.0)): + y = piano(f, 3.0, sr) + x[:, 0] += y * (0.9 - 0.2 * i) + x[:, 1] += y * (0.5 + 0.2 * i) + return x / max(1.0, np.abs(x).max() * 1.1) + + +def clicks_noise_clip(sr: int) -> np.ndarray: + dur = 4.0 + n = int(dur * sr) + x = 0.05 * RNG.standard_normal(n).astype(np.float32) + for k in range(int(dur * 2.5)): + i = int(k * sr / 2.5) + c = min(n - i, int(0.004 * sr)) + x[i:i + c] += 0.8 * np.exp(-np.arange(c) / (0.0008 * sr)) * (1 if k % 4 else 1.0) + return x + + +def chirp_siren_clip(sr: int) -> np.ndarray: + t = t_axis(2.0, sr) + chirp = 0.3 * np.sin(2 * np.pi * (300 * t + (3000 - 300) / (2 * 2.0) * t ** 2)) + t2 = t_axis(3.0, sr) + f = 700 + 400 * np.sin(2 * np.pi * 0.7 * t2) + siren = 0.3 * np.sin(2 * np.pi * np.cumsum(f) / sr) + return np.concatenate([chirp, siren]).astype(np.float32) + + +def birds_rain_clip(sr: int) -> np.ndarray: + dur = 5.0 + n = int(dur * sr) + rain = 0.08 * RNG.standard_normal((n, 2)).astype(np.float32) + k = np.ones(5, np.float32) / 5 + rain[:, 0] = np.convolve(rain[:, 0], k, "same") + rain[:, 1] = np.convolve(rain[:, 1], k, "same") + x = rain + for _ in range(14): + s = RNG.uniform(0.2, dur - 0.3) + f0, f1 = RNG.uniform(2500, 4500), RNG.uniform(3000, 6000) + t = t_axis(0.12, sr) + y = 0.25 * np.sin(2 * np.pi * (f0 * t + (f1 - f0) / (2 * 0.12) * t ** 2)) * np.sin(np.pi * t / 0.12) + i = int(s * sr) + c = min(len(y), n - i) + pan = RNG.uniform(0.2, 0.8) + x[i:i + c, 0] += y[:c] * pan + x[i:i + c, 1] += y[:c] * (1 - pan) + return x + + +def melody_35s(sr: int) -> np.ndarray: + notes = [261.63, 293.66, 329.63, 349.23, 392.0, 440.0, 493.88, 523.25] + out = [] + dur = 0.35 + for i in range(100): + out.append(piano(notes[(i * 3) % 8], dur, sr, 0.35)) + return np.concatenate(out).astype(np.float32) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=str(Path(__file__).resolve().parent / "audio")) + args = ap.parse_args() + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + manifest = [] + + def add(name, file, caption, sr, ch, fmt, lossy, source): + manifest.append(dict(name=name, file=file, caption=caption, sample_rate=sr, channels=ch, format=fmt, lossy=lossy, source=source)) + + with tempfile.TemporaryDirectory() as td: + tmp = Path(td) + for name, voice, rate, lang, sr, fmt, text in SPEECH: + x = espeak(text, voice, rate, sr, tmp / f"{name}.wav", tmp) + voice = f"{voice} -s {rate}" + if fmt == "wav": + write_wav(out / f"{name}.wav", x, sr) + add(name, f"{name}.wav", text, sr, 1, "wav pcm16", False, f"espeak-ng {voice} ({lang})") + elif fmt == "wav32s": + st = np.stack([x, 0.7 * x], 1) + write_wav(out / f"{name}.wav", st, sr, float32=True) + add(name, f"{name}.wav", text, sr, 2, "wav float32 stereo", False, f"espeak-ng {voice} ({lang}); right channel at 0.7") + elif fmt == "mp3": + write_wav(tmp / f"{name}_16.wav", x, sr) + if mp3(tmp / f"{name}_16.wav", out / f"{name}.mp3"): + add(name, f"{name}.mp3", text, sr, 1, "mp3", True, f"espeak-ng {voice} ({lang}); ffmpeg libmp3lame 96k") + else: + write_wav(out / f"{name}.wav", x, sr) + add(name, f"{name}.wav", text, sr, 1, "wav pcm16 (ffmpeg missing, no mp3)", False, f"espeak-ng {voice} ({lang})") + else: + write_wav(tmp / f"{name}_16.wav", x, sr) + convert(tmp / f"{name}_16.wav", out / f"{name}.{fmt}", fmt) + add(name, f"{name}.{fmt}", text, sr, 1, {"aiff": "aiff pcm16", "m4a": "aac", "caf": "caf alac", "flac": "flac"}[fmt], + fmt == "m4a", f"espeak-ng {voice} ({lang}); afconvert") + # sounds + write_wav(out / "sound_chord_piano_44k_stereo.wav", chord_clip(44100), 44100) + add("sound_chord_piano_44k_stereo", "sound_chord_piano_44k_stereo.wav", "three piano notes played together as a chord", 44100, 2, "wav pcm16 stereo", False, "numpy") + write_wav(out / "sound_clicks_noise_22k.wav", clicks_noise_clip(22050), 22050) + add("sound_clicks_noise_22k", "sound_clicks_noise_22k.wav", "a steady metronome clicking over soft white noise", 22050, 1, "wav pcm16", False, "numpy") + write_wav(tmp / "chirp.wav", chirp_siren_clip(48000), 48000) + convert(tmp / "chirp.wav", out / "sound_chirp_siren_48k.flac", "flac") + add("sound_chirp_siren_48k", "sound_chirp_siren_48k.flac", "a rising chirp followed by a siren sweeping up and down", 48000, 1, "flac", False, "numpy; afconvert") + write_wav(tmp / "birds.wav", birds_rain_clip(16000), 16000) + convert(tmp / "birds.wav", out / "sound_birds_rain_16k_stereo.m4a", "m4a") + add("sound_birds_rain_16k_stereo", "sound_birds_rain_16k_stereo.m4a", "birds chirping in light rain", 16000, 2, "aac stereo", True, "numpy; afconvert") + # edge cases + write_wav(out / "edge_silence_1s_16k.wav", np.zeros(16000, np.float32), 16000) + add("edge_silence_1s_16k", "edge_silence_1s_16k.wav", None, 16000, 1, "wav pcm16", False, "numpy: one second of digital silence") + write_wav(out / "edge_tiny_100smp_16k.wav", 0.5 * np.sin(np.arange(100) * 0.3).astype(np.float32), 16000) + add("edge_tiny_100smp_16k", "edge_tiny_100smp_16k.wav", None, 16000, 1, "wav pcm16", False, "numpy: 100 samples (0 frames, 0 tokens)") + t = t_axis(2.0, 96000) + write_wav(out / "edge_tone_10khz_96k.wav", (0.4 * np.sin(2 * np.pi * 10000 * t) + 0.2 * np.sin(2 * np.pi * 440 * t)).astype(np.float32), 96000) + add("edge_tone_10khz_96k", "edge_tone_10khz_96k.wav", None, 96000, 1, "wav pcm16", False, "numpy: 440 Hz + 10 kHz tones (the 10 kHz is above the 8 kHz Nyquist of the model)") + # long: 35 s (truncated to 30 s by the model) + write_wav(tmp / "mel.wav", melody_35s(16000), 16000) + if mp3(tmp / "mel.wav", out / "long_melody_35s_16k.mp3"): + add("long_melody_35s_16k", "long_melody_35s_16k.mp3", "a simple repeating piano melody", 16000, 1, "mp3", True, "numpy; ffmpeg libmp3lame 96k; 35 s") + else: + convert(tmp / "mel.wav", out / "long_melody_35s_16k.m4a", "m4a") + add("long_melody_35s_16k", "long_melody_35s_16k.m4a", "a simple repeating piano melody", 16000, 1, "aac", True, "numpy; afconvert; 35 s") + (out / "manifest.json").write_text(json.dumps(manifest, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"{len(manifest)} clips written to {out}") + + +if __name__ == "__main__": + main()