v1.2-audio
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+38
- CHANGELOG.md+86
- CHECKSUMS.sha256+76-14
- NOTICE+74-22
- README.md+404-87
- export/eg2_audio.pyAdded+372
- export/export.py+86-12
- model/MODEL-ATTRIBUTION.json+6-3
- model/config.json+44
- model/embeddinggemma-2-audio.aimodel/main.hashAdded+1
- model/embeddinggemma-2-audio.aimodel/main.mlirbAdded+3
- model/embeddinggemma-2-audio.aimodel/metadata.jsonAdded+8
- python/eg2_audio_frontend.pyAdded+373
- python/embeddinggemma2_coreai.py+229-44
- python/requirements.lock+7-3
- python/requirements.txt+5-1
- python/smoke_test.py+28-19
- swift/Package.swift+7-4
- swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swiftAdded+104
- swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swiftAdded+191
- swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swiftAdded+122
- swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift+156-8
- swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift+1-1
- swift/Sources/eg2-cli/main.swift+199-19
- tests/audio-preprocess-cases.jsonAdded+242
- tests/audio-smoke-reference.jsonAdded
- tests/audio/edge_silence_1s_16k.wavAdded
- tests/audio/edge_tiny_100smp_16k.wavAdded
- tests/audio/edge_tone_10khz_96k.wavAdded+3
- tests/audio/long_melody_35s_16k.mp3Added+3
- tests/audio/manifest.jsonAdded+162
- tests/audio/ref/edge_silence_1s_16k.features.f32Added+1
- tests/audio/ref/edge_silence_1s_16k.wave16k.f32Added
- tests/audio/ref/edge_tiny_100smp_16k.features.f32Added
- tests/audio/ref/edge_tiny_100smp_16k.wave16k.f32Added
- tests/audio/ref/edge_tone_10khz_96k.features.f32Added+3
- tests/audio/ref/edge_tone_10khz_96k.wave16k.f32Added+3
- tests/audio/ref/long_melody_35s_16k.features.f32Added+3
- tests/audio/ref/long_melody_35s_16k.wave16k.f32Added+3
- tests/audio/ref/sound_birds_rain_16k_stereo.features.f32Added+3
- tests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f32Added+3
- tests/audio/ref/sound_chirp_siren_48k.features.f32Added+3
- tests/audio/ref/sound_chirp_siren_48k.wave16k.f32Added+3
- tests/audio/ref/sound_chord_piano_44k_stereo.features.f32Added+3
- tests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f32Added+3
- tests/audio/ref/sound_clicks_noise_22k.features.f32Added+3
- tests/audio/ref/sound_clicks_noise_22k.wave16k.f32Added+3
- tests/audio/ref/speech_de_garten_48k_stereo.features.f32Added+3
- tests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32Added+3
- tests/audio/ref/speech_en_parcel_8k.features.f32Added+3
36 unmodified lines37383936 unmodified linesmodel/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-text-mm.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-vision.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text36 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767736 unmodified linesmodel/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-text-mm.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-vision.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-audio.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -texttests/audio/edge_tone_10khz_96k.wav filter=lfs diff=lfs merge=lfs -texttests/audio/long_melody_35s_16k.mp3 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/edge_tone_10khz_96k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/edge_tone_10khz_96k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/long_melody_35s_16k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/long_melody_35s_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_birds_rain_16k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_chirp_siren_48k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_chirp_siren_48k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_chord_piano_44k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_clicks_noise_22k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/sound_clicks_noise_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_de_garten_48k_stereo.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_en_parcel_8k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_en_parcel_8k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_en_train_16k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_en_train_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_es_tienda_16k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_es_tienda_16k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_fr_pont_44k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_fr_pont_44k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_it_mercato_22k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_it_mercato_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_pt_barco_44k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_pt_barco_44k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_sv_buss_22k.features.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/ref/speech_sv_buss_22k.wave16k.f32 filter=lfs diff=lfs merge=lfs -texttests/audio/sound_chirp_siren_48k.flac filter=lfs diff=lfs merge=lfs -texttests/audio/sound_chord_piano_44k_stereo.wav filter=lfs diff=lfs merge=lfs -texttests/audio/sound_clicks_noise_22k.wav filter=lfs diff=lfs merge=lfs -texttests/audio/speech_de_garten_48k_stereo.wav filter=lfs diff=lfs merge=lfs -texttests/audio/speech_en_train_16k.wav filter=lfs diff=lfs merge=lfs -texttests/audio/speech_it_mercato_22k.aiff filter=lfs diff=lfs merge=lfs -texttests/audio/speech_pt_barco_44k.caf filter=lfs diff=lfs merge=lfs -text
12345# Changelog## 1.1 — 2026-10-12Images. The vision encoder of google/embeddinggemma-2 is added, so text queries and images share one 768-d space12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Changelog## 1.2 — 2026-10-12Audio. The audio encoder of google/embeddinggemma-2 is added, so text queries, images and audio clips share one768-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. Thetext asset `model/embeddinggemma-2-text-mm.aimodel` and the image asset are **unchanged** (byte-identical to1.1), so text and image vectors indexed with 1.1 stay valid; the audio sequence `<bos> <|audio> [n soft tokens]<audio|> <eos>` goes through the same `mm_<S>` 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 thevalidation 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 from50+ macOS `say` voices, used for local validation only and not shipped, 42 synthesized sounds, 30 edge cases, 17format copies, 11 long clips, 3 mixtures; features computed by the upstream extractor): embedding cosine median0.99996 on the Neural Engine (min 0.9981, a synthesized chord; speech ≥ 0.9983 across both validation sets) and0.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), MRRwithin 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 losslessfiles). Decoding with Apple's AudioToolbox in Swift (sample-identical to libsndfile for PCM/FLAC/ALAC, AAC within 3e-7; MP3trimmed with the LAME tag, then within 3e-5) and with `soundfile` or `afconvert` in Python. Resampling to 16 kHzwith 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 andresampling").- Long audio: `.truncate` (the first 30 s, upstream's behaviour, default) or `.chunkMean` (mean of the 30 swindows' 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 15clips and 26 caption texts), `audio-preprocess-cases.json` + `tests/audio/ref/` (the Pythonfront 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); othersizes are excluded for compatibility.- Independent validation pass (a second generated set of 287 clips, both runners, every route; README "Audioaccuracy"): Neural Engine median 0.99996 / min 0.9972, GPU min 0.9994; text and image vectors bit-identical to1.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 theend; Swift `AudioDecoder` and the Python `afconvert` fallback now bring every tagged MP3 to the tag's gaplesslength (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 silentlyembedded 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 ofdifferent 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 digitalsilence (0.990–0.9999, not 0.99998 for all speech), tag-less MP3 (529 samples, 0.92–0.993) and Ogg Vorbis (128samples) offsets of Apple's decoder, Swift log-mel within 0.006 of numpy, the audio asset leaves no MPSGraphtemp 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'sJapanese 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 (itused 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 atraceback, 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 allthree assets (~5 min), timings measured on AC power (1.4–1.6× slower on battery with Low Power Mode), stale 1.1paths, 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 tomake 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 audioasset with `loadAudio: true` / `load_audio=True` when you need it; the first load of the new asset pays theone-time specialization (about 90 s for the Neural Engine route on the validation machine).## 1.1 — 2026-10-12Images. The vision encoder of google/embeddinggemma-2 is added, so text queries and images share one 768-d space
123456789101112132 unmodified lines161718192021222324252627282930313233349 unmodified lines444546474849505152eba43e8b37c1451b6d52dde5e2d0fec9adf9f8532e25c371cc905b8a7ff74b3c CHANGELOG.mdcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE452793453512cf94b6bc7ebc472ee3a465088b9a9be6f7e1eee0996ce5b134bc NOTICE6c59634a45192f864cf35e85a298b5c5ca736f046c299a8b71401b1b9873fe53 README.mdbb778eee49dab44fb997f67c875a615d754d54477e257d02771e94f250b4cd38 export/eg2_text.py75b6ef5a3836fa24ecd5601ea2ca999fd222fe68986c0fd1bf47a00392cf04c2 export/eg2_text_mm.py84effb9443f0e3183a71436796998e1d588bfa69d86a2496fb94d4c8c0b42bb6 export/eg2_vision.py46ebe20f907d3b974cd6f82af57487781935c5acb7ded23c45c6f4daf754099d export/export.py3c4b8ff2f44680507323c83e5d1765835edada530765550e6f916fb47d0ae7f2 model/MODEL-ATTRIBUTION.json0e22b6bd07af788f61e0ffa0dd5492e33108250495ce5b2297ce4d83d68efbf5 model/config.jsonea089710e57b22972d6ab4d4b960b385394b81f333ba2f75b4fb4aac1d238e6f model/embeddinggemma-2-text-mm.aimodel/main.hash0b51638f2d17794825de21def6ab485d968fdf412853ea209617623a51f1bbde model/embeddinggemma-2-text-mm.aimodel/main.mlirb8984123cfdb32ba8cf526a1f3a41571205475aff40b3f1d65494f476f115f8a6 model/embeddinggemma-2-text-mm.aimodel/metadata.json2 unmodified lines45bb764a8df5e1b2a6ef4260d4dd006a57dc7af4f408f07ed2976022cd39390c model/embeddinggemma-2-vision.aimodel/metadata.json4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 model/tokenizer/tokenizer.json17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 model/tokenizer/tokenizer_config.json5879dd6a20d7fc66fff212d5c74503ddaa628eef5b8e05e8b974bb5c8659e2f2 python/eg2_image.py3c076b19910efdc741cafadf5565c4205a36aae847102ceba5e5f6176fc9d699 python/embeddinggemma2_coreai.pyfe37b2abfaa762f68e80ecd5ca9ad62968c170b87943d5c27d3fc209cd18245e python/requirements.lock53a450a96e6185a9ea05f9834c7a8e6b227124b90c78ccb9c9f21d9402573042 python/requirements.txt1ee2fe2d6effd6f347d4e5164a8d00e806a280379101cb7c573636bcb70afcda python/smoke_test.py02ed112242f7fad88429c645cddb20bd6fa7797ba8c02fa17a5cacaf80102b55 swift/Package.swift10e088ec01cbba052e8214d3ae87ecea6606227fa5a9fefcb35793a6635f7d7c swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift7b99edfefc47a343d07df32a3b06a8da2f94a49ae0a8e299e733c1a44c09e38f swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift4f5ef8a454a84937e503ba99c9f05e237347178933a442f2352a2c5db0ad87eb swift/Sources/EmbeddingGemma2CoreAI/GemmaTokenizer.swiftce2f6a31d65894386ad90087db4b7eb8e0e0e77f3ad2402d8cba64e94f80d38c swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swift970be86b313ba24206ce7034f2082d71b672dda8e1b7d4da05912b587208d062 swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swiftaf5dd321e1a9f0e7c146f37b21a4b2963cf4c69fe01555568e8b10397003ae26 swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swiftb01a994c45db681fa007709a5311d04befdbfbc0d374cdb1fa91c83cba6c7c0c swift/Sources/eg2-cli/main.swift11f9e4ccd9e8ea626351f7f4b049ced15a74f53f14fe362bf856a15c184631e2 tests/check_preprocess.py15c72e722e5743d9fc21337b3ec9ce92dc4c485c58cedb7385f92281567f1002 tests/image-smoke-reference.json47f27fcdfac105cf72c250c85583ca862137d511840a67e40d547e3b49796af3 tests/images/chart_bar.png9 unmodified lines363dd39880ce42d00f459466680bd30bee9ab164be4fbddb2411b42937f2aeb6 tests/images/shape_red_circle.png0c394a7842a1cf2068ca87cf16341677d8d0008893b73b69cf9281dbf0d515cd tests/images/slide_launch.pngba808ff8c33ef4232aaf13a9736c7c02b57c5881a8456a1344b3d3ac04001828 tests/images/ui_login.png36f3a7c12829aacc5360a0f918c6dccd5584a8805b9ca43f99e0e7b5f6467a3c tests/make_image_smoke_reference.pya0e4c0d5559148d26eb1949316d31bb806a17fca4ed0a7e2f481b075103418bf tests/make_preprocess_cases.py1df8f74c85f4a02be0caaf4b99ee0bb8f4cfc1759ad091fdf65a98fdea917df8 tests/make_smoke_reference.pye78e8cab57918747717bbcce74509f183a2def72a7450cf2a363b1d5f504ac50 tests/make_test_images.py07daa7415beb15e9049a307aa17bf048ba2edaa0613301293e6250a66ed552b8 tests/make_tokenizer_cases.pyb580d5bc45d7fb4039e79e88008d7e40e530afb4f9c504abb0befaf6f46fbaaa tests/preprocess-cases.json12345678910111213141516172 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939 unmodified lines1031041051061071081091101111121131145a51bbf6a3e88dd68bdff18b0f9af0a64c51f60c745ac407be526d7743d0a178 CHANGELOG.mdcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSEb9ac552f2eb418f79dc23cc325a7b8c38ae05c1fcc8c1880014bae281a0963a6 NOTICE35e441a4c6176f40e460371fe0bd3ee85f5e6715f2de9d80d5cc91e191462609 README.mdaf31323d3ac2646a6c520741f36c7816f393c54dfe7ef5ccd0d207e7fe49c2aa export/eg2_audio.pybb778eee49dab44fb997f67c875a615d754d54477e257d02771e94f250b4cd38 export/eg2_text.py75b6ef5a3836fa24ecd5601ea2ca999fd222fe68986c0fd1bf47a00392cf04c2 export/eg2_text_mm.py84effb9443f0e3183a71436796998e1d588bfa69d86a2496fb94d4c8c0b42bb6 export/eg2_vision.py5b1076b875845ee0289c7c68f1209419b50b494d7bda082165c58dcd2690572e export/export.py7951556c4559c8609cf67715acc53e58d8c70f7f62242494d7858406b1bbe2f7 model/MODEL-ATTRIBUTION.json0204c8d4532f6930709c3c8eb7f7b25b54e4be42aa7b8c6c397fc17e872fb7bf model/config.jsone8e6db4dcacc0a21bbc0b981420753b44ab561c516a673fe5e9db986c7266b78 model/embeddinggemma-2-audio.aimodel/main.hash9ca590b09b327f7a8cae94ccace30d151621ae57a4a3f2a8b654145bc1df95f8 model/embeddinggemma-2-audio.aimodel/main.mlirbdc64e3f52ce6778c0c9e5f58157f328a9f081b21deb5eca74e333fcd4b8f15f6 model/embeddinggemma-2-audio.aimodel/metadata.jsonea089710e57b22972d6ab4d4b960b385394b81f333ba2f75b4fb4aac1d238e6f model/embeddinggemma-2-text-mm.aimodel/main.hash0b51638f2d17794825de21def6ab485d968fdf412853ea209617623a51f1bbde model/embeddinggemma-2-text-mm.aimodel/main.mlirb8984123cfdb32ba8cf526a1f3a41571205475aff40b3f1d65494f476f115f8a6 model/embeddinggemma-2-text-mm.aimodel/metadata.json2 unmodified lines45bb764a8df5e1b2a6ef4260d4dd006a57dc7af4f408f07ed2976022cd39390c model/embeddinggemma-2-vision.aimodel/metadata.json4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 model/tokenizer/tokenizer.json17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 model/tokenizer/tokenizer_config.json7fda3a163630254dd777c854b591fa3b290eecf43fc87874dab7a44c34c08343 python/eg2_audio_frontend.py5879dd6a20d7fc66fff212d5c74503ddaa628eef5b8e05e8b974bb5c8659e2f2 python/eg2_image.py56d528a06f0e3023d8014f085202a7669ddfe18151dc663dd02b570e76a10e76 python/embeddinggemma2_coreai.py4810309e44023efe0879465f631a63863d68eb7719ffddcb0df626c58f7c0de2 python/requirements.lock445a1161b6ade113db251b71798b765e751f8aade67405755dbbeaf19bcb62d3 python/requirements.txt3265d3ab97f53a765ca2c56bc62fc89dfd4e2fca5b404d4be34e0f65cbfa0aef python/smoke_test.pyef0b32f69dd40ae0741106429f8fa4fe6851521227ba364334e5d32c03d31782 swift/Package.swiftdeac17f843673a60141c98df5382ca998f5da3d4c71f3bbe7388b0abbbf255a9 swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swift0ff2b33d299e4382ce8f83e89ec8b82e104d417721829f50a450451c09fd474d swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swiftb7c43cc7f0b753a65effd7ad909f7f61b7c62e2b544f4052b58e4f5fee097993 swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swiftc2e94d3a82d2d0829e0182cf258a4eaec1cbece2e26f4d45d8f6c0411d82096a swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift5d73797991ed17635d4aedfbd6c59df19024cf2e8f3c2c7293e6457c23c430b4 swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift4f5ef8a454a84937e503ba99c9f05e237347178933a442f2352a2c5db0ad87eb swift/Sources/EmbeddingGemma2CoreAI/GemmaTokenizer.swiftce2f6a31d65894386ad90087db4b7eb8e0e0e77f3ad2402d8cba64e94f80d38c swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swift970be86b313ba24206ce7034f2082d71b672dda8e1b7d4da05912b587208d062 swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swiftaf5dd321e1a9f0e7c146f37b21a4b2963cf4c69fe01555568e8b10397003ae26 swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swift0415062c5277e66a7a363ce974a9405c25be6718578a9fe168be9105d64e003e swift/Sources/eg2-cli/main.swift643f8a8dc8bd9c19225afffad2becfec5426180b3749cb208abdf1a6c8354efc tests/audio/edge_silence_1s_16k.wav10e19f462aa13cbed8333dac47eaafd349f6d7850118060fbddc777e6b3f9bd3 tests/audio/edge_tiny_100smp_16k.wav381583606c2987aff0e9ae56fc6d2af8d247e125b7ae59d0673c158a9d5fd431 tests/audio/edge_tone_10khz_96k.wav9c9dc64b6d46a70f3a680f3d0e957436f31174fc84618c23fb1abe19920b3b39 tests/audio/long_melody_35s_16k.mp3007cda760aa83100c95dfcc8bb34557cb20a7cca8ea98a87a21f3a94952f3c3b tests/audio/manifest.json686d8f234eec98a082e45c5f291db725fb966aaba896d1e7e7edfe82c27a42ba tests/audio/ref/edge_silence_1s_16k.features.f324f7988030a00d082fe445e00a2ac5dab502300ff1b80e8592dd569867b60ef74 tests/audio/ref/edge_silence_1s_16k.wave16k.f32e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tests/audio/ref/edge_tiny_100smp_16k.features.f3242d99bd225d1e32ad26fe623cfbbe01f0df0aaba3e7966f5055a270d9bea9548 tests/audio/ref/edge_tiny_100smp_16k.wave16k.f3219b6e0b19a4dc3aac04d0e979910d85c83ebb7815c837fb4045a3cebdaf7ee84 tests/audio/ref/edge_tone_10khz_96k.features.f322567b77a52392e8f0dc40bade829a63374eb026bedf494e15ed28c1f0e56c4ba tests/audio/ref/edge_tone_10khz_96k.wave16k.f326f4638c771e3a3b5180a4509e1a55bbc713e3616634ec468cf3812284bfd7d98 tests/audio/ref/long_melody_35s_16k.features.f32d4a6b9daa6f1e4385cf1310f05431fa785da244ca2b0932133016651384c846c tests/audio/ref/long_melody_35s_16k.wave16k.f3253b924a3b71bb2478852a8d1ca493e91308b3359d85ace339e15a2590da946ca tests/audio/ref/sound_birds_rain_16k_stereo.features.f32e425c153bdc58bd84e73dbde653146597cf3ed1606a9fa569ffa59fe007f6934 tests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f322ad38e26bb8bf5c209d1a20468ecdbf1fede29373e9a5d85ae3fcab59a99816b tests/audio/ref/sound_chirp_siren_48k.features.f32bb52eff27889c682d46cbcdc984f7e1b41f59b36fd1671c0d8903a4ce88666e0 tests/audio/ref/sound_chirp_siren_48k.wave16k.f32466751ffa6f1909515eb5693e7375c240ae2ef9130d7e9c8abf54162a8545386 tests/audio/ref/sound_chord_piano_44k_stereo.features.f32e45747d1b1c14a21050f2614c58684be77cb3d85c343e6e697ae996458ff8252 tests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f322e115ff7e33f3f116fd1336f8142d80ced4610b5f9543c5af0932865d883cce9 tests/audio/ref/sound_clicks_noise_22k.features.f3233fd0381a39409fee2e421e90dd353885120268644e7b8ae676e5d550cef26a9 tests/audio/ref/sound_clicks_noise_22k.wave16k.f328bec6c3cafd40c2cfd464fb864da306f32b0eb3a6f8abb6d440251126f555ba4 tests/audio/ref/speech_de_garten_48k_stereo.features.f32c20659bd84f7bfd6fe9e695238cb4917fd981cde5f075e3c81fad3dd1dfa00a3 tests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32790833ec67d07977f1d685f89a8b64897e618dc7d08924c4edd0e94b869db258 tests/audio/ref/speech_en_parcel_8k.features.f32513961580f843da853465b58dd96f1c55f5aeea5e1550b8c0ec9cae7e43a0f3d tests/audio/ref/speech_en_parcel_8k.wave16k.f321b2dc5139da71d6e674078bdb46b29a38b646b539ee496c99928730e16988916 tests/audio/ref/speech_en_train_16k.features.f328e1da811c75c5865f0ceaf6ca163a908acc6adab7d4431e90f2f0cdad8fe586a tests/audio/ref/speech_en_train_16k.wave16k.f3227db536530247de6a9c2129ff539e73ae1cf78529623004414fbd2b744f16bdf tests/audio/ref/speech_es_tienda_16k.features.f3275744fbf5dd270d45ebdd00530e01b614f04682b81f7cefb1c408dcb76973f5f tests/audio/ref/speech_es_tienda_16k.wave16k.f32032bc989d3a63bb10cdd04aa79dd2eb484503e3cc30f94f885a19da1070c27da tests/audio/ref/speech_fr_pont_44k.features.f32c28ab5b7458eceb6aebc3eab40a5dddbf842988401d4ac9fc06858187a1c2a82 tests/audio/ref/speech_fr_pont_44k.wave16k.f32c82d988458dd9c4b1b5654f31865573836dbfe458c53f8679100cbc77416ee9a tests/audio/ref/speech_it_mercato_22k.features.f320cd3fd6073a9613f12eaa2ecd339fb01264b31ef0847a354858e373efc6ccd5f tests/audio/ref/speech_it_mercato_22k.wave16k.f32c02cf5d84f82ec039f7079842ab5881be8d40663da262f8e6044b00bee97f3a5 tests/audio/ref/speech_pt_barco_44k.features.f328a515f30e332f31c86c7f076b9d9a9b9e157bb75b91cc7556fca62637b946506 tests/audio/ref/speech_pt_barco_44k.wave16k.f320e24839f583281e4580159b30b6436fb725d4ad40feb5aec3314ddc0958d4a60 tests/audio/ref/speech_sv_buss_22k.features.f32ac3f69f92163a571ff4e0a067e3b42a12a394376593bf7ea57a8c3edfcc412ee tests/audio/ref/speech_sv_buss_22k.wave16k.f32bb710fc775183d51613c20eda273cef3d934ef8f56033afa1a672d83386beccb tests/audio/sound_birds_rain_16k_stereo.m4a7cfefb8e87712771eab7ec4a077e31cf215933ec57f1006d07155ab153b161fb tests/audio/sound_chirp_siren_48k.flac007af1d5cfe64d8de9773b95ed787360fd3e8e2a12198f8d21a5bb694fdf4a13 tests/audio/sound_chord_piano_44k_stereo.wav4963f45f47e82a95d3fe5dd0b5fc43ae3ffcfb1dee483c7122e3416de85dda58 tests/audio/sound_clicks_noise_22k.wav5dfb55fe58589119faf8af3059480c8dfd50b8f74036c625e96be9afe9bb28fd tests/audio/speech_de_garten_48k_stereo.wav3427d488a828f85ff7e08ea76719f0aa992b81632f0366403ed44973e50001ca tests/audio/speech_en_parcel_8k.wave858470982ce2d7d9b59bf4381a17375234da9007c71f9a17737c7bfc1950949 tests/audio/speech_en_train_16k.wave9186c1f6982efa2f6154e4283cc082b090546708de1b0bd7d9de44278d2f7c8 tests/audio/speech_es_tienda_16k.flac9ddd4783a6a96b5ad47fd07db884089f7c53b8b46960a1e373d9432f3d4e744c tests/audio/speech_fr_pont_44k.m4ae099fec89f94386a59c73b88f71c1d26566ba37d9b0b39ee7fe9e0eb1f801cac tests/audio/speech_it_mercato_22k.aiff90b1561f496f9de9a75229f8424405ac9706e8a716f927f0f4053bd6f1eacf0e tests/audio/speech_pt_barco_44k.cafc763fade16da3626a93580442b5f7a635adbf17299e7e8f13e98ed18e1bc8410 tests/audio/speech_sv_buss_22k.mp3e4a2e6915106767933b58537367ffe8e5ee1ea761f72d048bb9209ceb7608e7e tests/audio-preprocess-cases.json363a092fe6132a6774535a4bfbb851f0cba2c4c5ef812226b273fd4adc4cc99b tests/audio-smoke-reference.json11f9e4ccd9e8ea626351f7f4b049ced15a74f53f14fe362bf856a15c184631e2 tests/check_preprocess.py15c72e722e5743d9fc21337b3ec9ce92dc4c485c58cedb7385f92281567f1002 tests/image-smoke-reference.json47f27fcdfac105cf72c250c85583ca862137d511840a67e40d547e3b49796af3 tests/images/chart_bar.png9 unmodified lines363dd39880ce42d00f459466680bd30bee9ab164be4fbddb2411b42937f2aeb6 tests/images/shape_red_circle.png0c394a7842a1cf2068ca87cf16341677d8d0008893b73b69cf9281dbf0d515cd tests/images/slide_launch.pngba808ff8c33ef4232aaf13a9736c7c02b57c5881a8456a1344b3d3ac04001828 tests/images/ui_login.pngdeaa4467cc00c918973913d294f5ec2c2488708db2684a5dccff83841cbcdc4f tests/make_audio_preprocess_cases.py373918597ab9e095dbf930e03b1b90ddc395f82009fb571ff96eca9ef74cec64 tests/make_audio_smoke_reference.py36f3a7c12829aacc5360a0f918c6dccd5584a8805b9ca43f99e0e7b5f6467a3c tests/make_image_smoke_reference.pya0e4c0d5559148d26eb1949316d31bb806a17fca4ed0a7e2f481b075103418bf tests/make_preprocess_cases.py1df8f74c85f4a02be0caaf4b99ee0bb8f4cfc1759ad091fdf65a98fdea917df8 tests/make_smoke_reference.py1a60f0b6369cc7d063d3c24fdf4498785361f5a8a800d6ac68c95cddac1bdb84 tests/make_test_audio.pye78e8cab57918747717bbcce74509f183a2def72a7450cf2a363b1d5f504ac50 tests/make_test_images.py07daa7415beb15e9049a307aa17bf048ba2edaa0613301293e6250a66ed552b8 tests/make_tokenizer_cases.pyb580d5bc45d7fb4039e79e88008d7e40e530afb4f9c504abb0befaf6f46fbaaa tests/preprocess-cases.json
123418 unmodified lines2324252627282930313233343549 unmodified lines8586878889903 unmodified lines94959697989910010110210310410510610711 unmodified lines1191201211221231241251261277 unmodified lines1351361371381391401411422 unmodified lines145146147148149150151152153154EmbeddingGemma-2-CoreAI v1.1============================This package contains a derivative of the EmbeddingGemma 2 model.18 unmodified linesMODIFICATIONS (Apache License, Section 4(b))--------------------------------------------Changes made to google/embeddinggemma-2, 11-12 October 2026, to produce model/embeddinggemma-2-text-mm.aimodeland model/embeddinggemma-2-vision.aimodel.Text encoder (v1.0, unchanged in v1.1 except where noted):2026-10-11 The audio encoder of the multimodal checkpoint was dropped (v1.0 also dropped the visionencoder; v1.1 adds it back, see below).2026-10-11 The encoder architecture (24 bidirectional Gemma 4 layers, per-layer embeddings, RMSNorm withmax-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 AI49 unmodified lineskernel used by torchvision) re-implemented in numpy and in Swift so that the pixels fed to themodel are identical to the reference pipeline.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).3 unmodified linesTHIRD-PARTY ATTRIBUTIONS------------------------HF transformers (Apache-2.0, Copyright 2026 The HuggingFace Team). export/eg2_text.py re-authors thearchitecture described by modeling_embedding_gemma2.py / configuration_embedding_gemma2.py, andexport/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 filesare included in this package; the re-authored and ported modules carry their own Apache-2.0 header and credittransformers.PyTorch / ATen (BSD-3-Clause, notice below). The integer antialiased bicubic resize in python/eg2_image.py andswift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swift is ported from the logic of ATen's uint811 unmodified linesdividing each RMSNorm row by its max-abs value to keep fp16 in range was taken from the README of that port andre-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 andruntime, not redistributed. Hugging Face tokenizers (Apache-2.0): used by the Python runner and to generate thetest fixtures; not redistributed.TRADEMARKS7 unmodified lines------------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 testimages (tests/) and the documentation, isCopyright 2026 EverpaperLicensed under the Apache License, Version 2.0 (LICENSE).2 unmodified linesthose projects' licenses: Apache-2.0 for transformers (LICENSE), and the PyTorch and Pillow notices reproducedbelow.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 alsobrand names (for example in the chart and invoice test images) appear only as fictional content, with noreference to any real business.THIRD-PARTY LICENSE NOTICES123418 unmodified lines2324252627282930313233343549 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221233 unmodified lines12712812913013113213313413513613713813914014114214314414514614714814915015115211 unmodified lines1641651661671681691701711721731741751761777 unmodified lines1851861871881891901911922 unmodified lines195196197198199200201202203204205206EmbeddingGemma-2-CoreAI v1.2============================This package contains a derivative of the EmbeddingGemma 2 model.18 unmodified linesMODIFICATIONS (Apache License, Section 4(b))--------------------------------------------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 and v1.2 except where noted):2026-10-11 The audio encoder of the multimodal checkpoint was dropped (v1.0 also dropped the visionencoder; 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 withmax-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 AI49 unmodified lineskernel used by torchvision) re-implemented in numpy and in Swift so that the pixels fed to themodel 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 withrelative-position bias, light depthwise convolution, half-step feed-forward and RMSNorm, the1024->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 roundedfrom 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 previoustokens; 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. Thequery 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 keysis an additive -10000; the gradient-clipping clamps (+-1e10, no-ops in inference) are dropped; the120 clipped linears keep their clip bounds. Mathematically identical to the reference (fp32soft-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 theaudio 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_<Tb>);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 thesizes validated on the Neural Engine.2026-10-12 Audio preprocessing (host side, not part of the model): the upstream feature extractor's log-melcomputation (30 s truncation, 160-sample left pad, 320-sample periodic Hann frames every 160samples, 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 thechannels) 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 audiopipeline; 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).3 unmodified linesTHIRD-PARTY ATTRIBUTIONS------------------------HF transformers (Apache-2.0; Copyright 2026 The HuggingFace Team for the modeling, configuration and image-processingfiles 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 thearchitecture described by modeling_embedding_gemma2.py / configuration_embedding_gemma2.py, export/eg2_vision.pythe vision model and vision embedder, and export/eg2_audio.py the audio model (Gemma4AudioModel) and audioembedder, all described by modeling_gemma4.py / modeling_embedding_gemma2.py, from transformers 5.19. Thehost-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 byfeature_extraction_gemma4.py with the defaults sentence-transformers uses for this model, and the HTK mel filterbank formula (as in librosa / torchaudio) of transformers' audio_utils.py (HTK scale, no normalization). Notransformers source files are included in this package; the re-authored and ported modules carry their ownApache-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 alsoimplement (credited through transformers' audio_utils.py). The resampler in this package is our own design (aKaiser-windowed sinc, see MODIFICATIONS); the decode-mono-resample order and the output-length rule follow whatlibrosa.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 andswift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swift is ported from the logic of ATen's uint811 unmodified linesdividing each RMSNorm row by its max-abs value to keep fp16 in range was taken from the README of that port andre-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, Core Graphics, AVFoundation / AudioToolbox(audio decoding) and Accelerate (vDSP FFT and dot products): used as tools and runtime, not redistributed. HuggingFace 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 bypython/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 partof it is included. FFmpeg with libmp3lame (LGPL / GPL): used as a tool to encode the MP3 test clips and to decodeAAC for the reference fixtures; not included.TRADEMARKS7 unmodified lines------------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, testimages and test audio clips (tests/) and the documentation, isCopyright 2026 EverpaperLicensed under the Apache License, Version 2.0 (LICENSE).2 unmodified linesthose projects' licenses: Apache-2.0 for transformers (LICENSE), and the PyTorch and Pillow notices reproducedbelow.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 commonwords that are also brand names (for example in the chart and invoice test images) appear only as fictionalcontent, with no reference to any real business. The spoken clips are invented sentences synthesized with theeSpeak NG formant synthesizer, which generates speech from rules and formant parameters rather than from voicerecordings; no recording of a person is included or was used.THIRD-PARTY LICENSE NOTICES
12 unmodified lines1314151617181920212223242526272829304 unmodified lines3536373839402 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111215 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651 unmodified line1671681691701711721731741751761771781791801811821831841851861872 unmodified lines19019119219319419519623 unmodified lines22022122222322422522699 unmodified lines32632732832933033133233333433533633733833934034134234378 unmodified lines4224234244254264274284294304314324334344354364373 unmodified lines4414424434444454464474484494504514524534545 unmodified lines4604614624634644654663 unmodified lines47047147247347447547647747847948048148248348448548648748848949049149249325 unmodified lines5195205215225235245255265275285295305316 unmodified lines5385395405415425435445455465475485492 unmodified lines55255355455555655755855956056156256356456556656756856957012 unmodified lines- sentence-similarity- image-embeddings- image-feature-extraction- multimodal- text-to-image-retrieval- gemma- macos---# EmbeddingGemma 2 for Apple Core AI (text + images)[google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) (Gemma 4 family, 768-d Matryoshkaembeddings) 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 onevector, and the vector of the query "bar chart of lamp units sold per city" 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 L24 unmodified linesSwift 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").Ported by Everpaper — everpaper.app. Weights are the original ones (bf16 rounded to fp16), with a few constantscales folded in and unused position rows cut (listed in NOTICE). Apache-2.0, see2 unmodified lines## Download```bashhf download iannedev/embeddinggemma-2-coreai --local-dir EmbeddingGemma-2-CoreAI-v1.1cd EmbeddingGemma-2-CoreAI-v1.1```(`hf` comes with `pip install -U huggingface_hub`.) Then run one of the quick starts below; both begin with asmoke 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 imagepreprocessing, 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 ofthe text route (`imageCompute:` / `image_compute=` / `--image-compute`).- **Text is unchanged**: the text asset is now `embeddinggemma-2-text-mm.aimodel` (functions `mm_<S>`, the v1.0encoder plus an input for image soft tokens). With no image in the sequence its outputs are **bit-identical tov1.0** (466 texts, every bucket, including texts that moved from the 256 or 512 bucket to the new 288bucket), 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.## What is in the package```EmbeddingGemma-2-CoreAI-v1.1/README.md, LICENSE, NOTICE, CHANGELOG.md, CHECKSUMS.sha256model/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)config.json assets, buckets, shapes, special ids, prompts, Matryoshka dimstokenizer/ tokenizer.json + tokenizer_config.json, unchanged from google/embeddinggemma-2MODEL-ATTRIBUTION.json base model, checkpoint sha256, exporter versions, modification listswift/ 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)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 generatorsexport/ eg2_text.py, eg2_text_mm.py, eg2_vision.py, export.py: reproduce both 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).## Quick start — Swift```swift// Package.swift: .package(path: "…/EmbeddingGemma-2-CoreAI-v1.1/swift"), product "EmbeddingGemma2CoreAI"import Foundationimport EmbeddingGemma2CoreAIlet pkg = URL(fileURLWithPath: "…/EmbeddingGemma-2-CoreAI-v1.1") // the downloaded package folderlet modelURL = pkg.appendingPathComponent("model")let model = try await EmbeddingGemma2(bundle: modelURL, compute: .neuralEngine, loadVision: 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)try await model.prewarm() // optional, ~1 s warm// text (unchanged from 1.0)15 unmodified lineslet 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// 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, noimage first-load cost); image calls then throw. `compute` places the text asset; `imageCompute` (default: the sameas `compute`) places the image encoder, see "Images: 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-tempeg2-cli embed ../model --kind search_query "bar chart of lamp units sold per city" (text only, no vision 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 tokcheck ../model ../tests/tokenizer-cases.jsoneg2-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]````--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.## Quick start — PythonFrom the package folder:```python3.12 -m venv .venv && .venv/bin/pip install -r python/requirements.txt # 3.12 validated; 3.14 also workssource .venv/bin/activatecd python && python3 smoke_test.py --compute ane --cleanup-temp # first run: a few minutes to specialize, see below```1 unmodified line```pythonfrom embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_filesm = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=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")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 photosd = m.embed("The lease runs until the last day of March.", kind="document", dim=256)score = float(q @ v)del mremove_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 thetext path without loading the image encoder; `smoke_test.py --image-compute gpu` checks the GPU image route.## Text2 unmodified lines| 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: `<bos>`=2, prompt-prefix tokens, text tokens, `<eos>`=1, right-padded with `<pad>`=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) || `embedding` | `[1, 768]` float16, already L2-normalized || Max length | 2048 tokens including `<bos>`/`<eos>` 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). |23 unmodified linesThe image encoder (`vision_2520`, ~0.92 TFLOP per image) runs on either the Neural Engine or the GPU. Both routesuse the same asset, both are validated, and you choose the route **for images independently of text**. Text alwaysruns 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):| | **Neural Engine** (default) | **GPU** ||---|---|---|99 unmodified linesfrom cameras and phones an app almost certainly wants `true`; for screenshots, renders and documents it makes nodifference. The default is `false` for parity with the reference. Pick one and index consistently.### Video and audioNot included. Upstream embeds a video as **one** sequence of frames sampled at 1 fps (up to 32 frames, 140 softtokens per frame, `<|video|>` placeholders), which needs a 140-token vision shape and longer text buckets than thispackage exports. Embedding sampled frames one by one as images works with this package and is a commonapproximation, but it is not what upstream does and was not compared with upstream video vectors. The audioencoder is not ported.## Accuracy (measured)Reference: sentence-transformers 6.1 / transformers 5.19 / torch 2.14.1 / torchvision 0.29.1, fp32, CPU, originalcheckpoint; images passed as paths with no prompt. All test texts and images 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 PNGre-saves) were used for local validation only and are not shipped.78 unmodified lines| 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 /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`smoke` on your targets.## Performance (measured, M5, Swift `eg2-cli latency`)Images: see "Images: Neural Engine or GPU" for the side-by-side comparison (time, CPU, GPU, power, energy,memory). Per function:3 unmodified lines| `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) || 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) |Text-only use (`loadVision` 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 a6000×4000 JPEG (numpy: 45 ms median). The CPU-only route takes ~520 ms per image. The Python runner gives the samemodel latencies within a few percent (8.5 ms CPU per image on the Neural Engine, 27 ms on the GPU).On the Neural Engine the 12 × 2520 × 2520 attention is the cost of the vision graph. Each function is batch-1; theNeural Engine serializes concurrent calls. Nothing stops an app from running two routes at once (e.g. one instance5 unmodified lines| 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 || 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 main3 unmodified linese.g. Homebrew's). It survives reboots but not OS updates, a renamed executable or a re-exported asset (including the1.0 → 1.1 upgrade).## Why two assets (and why `mm_<S>` also serves text)- The image encoder is a separate asset so that text-only users neither download nor load 300 MB they do notneed (`--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. Withzero 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 replaces256 so that an image does not pay for the 512 bucket.## Temp files (please read)Each Neural Engine load writes compiled-graph copies to `$TMPDIR/com.apple.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/` (~360 MB for the text asset, ~300 MB for the image asset). Measured on macOS 27.0:- Swift (`CoreAI` framework): the runtime deletes the folder when the model is released; our CLI leaves nothingbehind. 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 interpreterexit (~650 MB per load with both 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, createdafter the process started): `EmbeddingGemma2.removeOwnMPSGraphTempFiles()`, `remove_own_mpsgraph_temp_files()`,25 unmodified linesto 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 notvalidated and would run on the GPU.- **Batch 1.** Concurrency did not increase throughput (the Neural Engine serializes). Short texts are not fasterthan ~4.8 ms (per-call floor of this Core AI build).- **Latency is not shape-stable across bucket sets**: Core AI specializes the whole function set together; measurethe 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 runtimebehaviour (first-load time, placement, temp files) may change between OS releases.## Reproducing the export6 unmodified lineshf download google/embeddinggemma-2 --local-dir ./embeddinggemma-2cd exportpython3 -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```About 25 s on an M5. `eg2_text.py` is the re-authored text encoder (byte-identical to 1.0), `eg2_text_mm.py` addsthe 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`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 at2 unmodified lineswith `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/<asset>.aimodel --output ./compiled--preferred-compute neural-engine --architecture h17g 2>&1 | grep -c ane_validation_message` prints 0 for bothassets (no op rejected; delete `./compiled` afterwards). The specialized graphs have one Neural Engine region andone GPU region (the token / position-table gather) per function.## 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: portedfrom the logic of ATen's uint8 antialiased bicubic kernel (PyTorch, BSD-3-Clause), itself modelled on Pillow'sresampling; CMYK conversion ported from Pillow's formula (MIT-CMU). Their license notices are in NOTICE.- The max-abs RMSNorm rescaling idea comes from the FluidInference Core ML port of this model (Apache-2.0); no codewas copied.- Port, exporter, runners, Swift tokenizer implementation, preprocessing, tests and test images: Copyright 2026 Everpaper, Apache-2.0.- Gemma and EmbeddingGemma are trademarks of Google LLC; Apple, Core AI, Apple silicon and Neural Engine aretrademarks of Apple Inc. This port is not affiliated with, sponsored by or endorsed by Google or Apple.12 unmodified lines131415161718192021222324252627282930313233344 unmodified lines39404142434445464748492 unmodified lines52535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312321 unmodified line2342352362372382392402412422432442452462472482492502512522532542552562572582 unmodified lines26126226326426526626723 unmodified lines29129229329429529629799 unmodified lines39739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359478 unmodified lines6736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107113 unmodified lines7157167177187197207217227237247257267277287297307317327337347357365 unmodified lines7427437447457467477487493 unmodified lines75375475575675775875976076176276376476576676776876977077177277377477577677777877925 unmodified lines8058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428436 unmodified lines8508518528538548558568578588598608618622 unmodified lines86586686786886987087187287387487587687787887988088188288388488588688712 unmodified lines- 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 + audio)[google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) (Gemma 4 family, 768-d Matryoshkaembeddings) converted to Apple's **Core AI** runtime for **macOS 27 on Apple silicon**: the text encoder, since1.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 percity" (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 L24 unmodified linesSwift 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 gothrough 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 orGPU"). 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 constantscales folded in and unused position rows cut (listed in NOTICE). Apache-2.0, see2 unmodified lines## Download```bashhf download EverPaper/embeddinggemma-2-coreai --local-dir EmbeddingGemma-2-CoreAI-v1.2cd EmbeddingGemma-2-CoreAI-v1.2```(`hf` comes with `pip install -U huggingface_hub`.) Then run one of the quick starts below; both begin with asmoke 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 audioencoder (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 Swiftand 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 oftext 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 with1.1 (and text vectors indexed with 1.0) stay valid. The audio sequence goes through the same `mm_<S>` 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 imagepreprocessing, two image routes); the text asset became `embeddinggemma-2-text-mm.aimodel` (functions `mm_<S>`,bit-identical to the 1.0 text encoder with no image in the sequence; the 256 bucket became 288). Versions 1.0 and1.1 remain available as the repository's earlier revisions; see CHANGELOG.md.## What is in the package```EmbeddingGemma-2-CoreAI-v1.2/README.md, LICENSE, NOTICE, CHANGELOG.md, CHECKSUMS.sha256model/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 dimstokenizer/ tokenizer.json + tokenizer_config.json, unchanged from google/embeddinggemma-2MODEL-ATTRIBUTION.json base model, checkpoint sha256, exporter versions, modification listswift/ SwiftPM package: library `EmbeddingGemma2CoreAI` + tool `eg2-cli` (no third-party dependencies)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, audio/ (16 generated clips+ ref/ front-end references), audio-smoke-reference.json, audio-preprocess-cases.json, and the generatorsexport/ eg2_text.py, eg2_text_mm.py, eg2_vision.py, eg2_audio.py, export.py: reproduce the assets from the checkpoint```## Requirements- 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). macOSdoes 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 upstreamuses; 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, tokenizer0.03 GB (text + image assets 0.94 GB, 0.97 GB with the tokenizer). The system keeps a per-app specializationcache under `~/Library/Caches/coreai-cache/` (about 1.4 GB for the text asset, 5.5 GB with the image and audioassets).- Memory with all three assets loaded on the Neural Engine: Python ~415 MB process footprint plus ~2.1 GB on theNeural 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 — SwiftAdd the package to your app's `Package.swift`. SwiftPM names a local package after its folder, so the packageidentity is `swift`:```swift// swift-tools-version: 6.0import PackageDescriptionlet 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")]),])``````swiftimport Foundationimport EmbeddingGemma2CoreAIlet pkg = URL(fileURLWithPath: "…/EmbeddingGemma-2-CoreAI-v1.2") // the downloaded package folderlet modelURL = pkg.appendingPathComponent("model")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)15 unmodified lineslet 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 upstreamlet 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_<Tb> -> sequence <bos> <|audio> [n] <audio|> <eos> -> mm_<S>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 bucketlet audioSoft = try await model.audioSoftTokens(audioInputs) // [n * 512] Float16 (audio_<bucket>)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` / `loadAudio: true` loads only the text asset (noextra 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 ../tests/audio-smoke-reference.json --compute ane --cleanup-tempeg2-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.jsoneg2-cli pixcheck ../tests/preprocess-cases.json (decode + resize vs the Python reference, no model)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 and audio encoders, unless `--image-compute` /`--audio-compute` are given); `--image-compute` / `--audio-compute ane|gpu` place only that encoder.## Quick start — PythonFrom the package folder. macOS has no Python 3.12 of its own (its `python3` is 3.9 and Homebrew's default isnewer), 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``````source .venv/bin/activatecd python && python3 smoke_test.py --compute ane --cleanup-temp # first run: a few minutes to specialize, see below```1 unmodified line```pythonfrom embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_filesm = 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 photosa = m.embed_audio("../tests/audio/speech_en_train_16k.wav") # path, or (samples array, sample_rate=...); first 30 slong = m.embed_audio("../tests/audio/long_melody_35s_16k.mp3", long_audio="chunk_mean") # mean of the 30 s windowsd = m.embed("The lease runs until the last day of March.", kind="document", dim=256)score = float(q @ v)del mremove_own_mpsgraph_temp_files() # the Python runtime leaks ~650 MB per load, see below````python3 embeddinggemma2_coreai.py embed|embed-image|embed-audio|smoke|tokcheck|latency|prewarm …` mirrors theSwift 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` skipsthe audio reference; `smoke_test.py --image-compute gpu --audio-compute gpu` checks the GPU routes.## Text2 unmodified lines| 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: `<bos>`=2, prompt-prefix tokens, text tokens, `<eos>`=1, right-padded with `<pad>`=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" and "Audio" for what goes there) || `embedding` | `[1, 768]` float16, already L2-normalized || Max length | 2048 tokens including `<bos>`/`<eos>` 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). |23 unmodified linesThe image encoder (`vision_2520`, ~0.92 TFLOP per image) runs on either the Neural Engine or the GPU. Both routesuse the same asset, both are validated, and you choose the route **for images independently of text**. Text alwaysruns 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) for one typical image (273 soft tokens):| | **Neural Engine** (default) | **GPU** ||---|---|---|99 unmodified linesfrom cameras and phones an app almost certainly wants `true`; for screenshots, renders and documents it makes nodifference. The default is `false` for parity with the reference. Pick one and index consistently.### VideoNot included. Upstream embeds a video as **one** sequence of frames sampled at 1 fps (up to 32 frames, 140 softtokens per frame, `<|video|>` placeholders), which needs a 140-token vision shape and longer text buckets than thispackage exports. Embedding sampled frames one by one as images works with this package and is a commonapproximation, but it is not what upstream does and was not compared with upstream video vectors.## Audio### Neural Engine or GPUThe audio encoder (`audio_<Tb>`, ~0.6 GFLOP per soft token, ~450 GFLOP for 30 s) runs on either the Neural Engineor the GPU; the clip's final pass through the text encoder (`mm_<S>`, 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_<Tb>` Neural Engine | `audio_<Tb>` GPU | `mm_<S>` (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 onlong 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 theGPU 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 isloaded: the CPU route is not supported for audio.```swiftlet 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.wavpython3 embeddinggemma2_coreai.py embed-audio ../model --audio-compute gpu ../tests/audio/speech_en_train_16k.wav```### How an audio clip becomes a vector1. **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 every160 (periodic Hann), |FFT 512|, 128 triangular HTK mel bands 0–8 kHz, ln(mel + 0.001). A frame counts only ifits whole window lies in real audio: n frames = ⌊(samples − 161) / 160⌋ + 1 (2999 for 30 s; fewer than 161samples 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>` → `[Tb/4, 512]` soft tokens, of which the first ⌈⌈n/2⌉/2⌉ are valid (25 persecond; 750 for 30 s).7. **Sequence** `<bos>`=2, `<|audio>`=256000, n × `<|audio|>`=258881, `<audio|>`=258883, `<eos>`=1 (n + 4 ≤ 754tokens → up to bucket 1024), the soft tokens placed in the placeholder slots → `mm_<S>` → `[768]`, L2-normalized.Audio takes **no prompt** (as the model card prescribes). Text queries use `search_query`; captions as documentsuse `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 ownbucket and through `audio_3000` gives bit-identical soft tokens on the Neural Engine and tokens within float16noise, cosine ≥ 0.99999, on the GPU).### `audio_<Tb>` (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); othersizes 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**: correctnesswith `eg2-cli smoke` and placement with the Neural Engine footprint that `eg2-cli latency` prints, not only that itloads.### Audio: decoding and resamplingThe reference (`sentence-transformers` → `librosa.load(sr=16000)`) decodes with **libsndfile**, mixes to mono andresamples 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 tolibsndfile 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 outgapless, some as whole frames (encoder delay and padding still in place), and some with the delay removed but oneor two whole frames too many at the end (`afinfo` then counts one packet more than the tag). The Swift decoder andthe Python fallback read the tag and bring every case to its gapless length, after which the samples matchlibsndfile/mpg123 within 3e-5 (all 55 tagged MP3s tested: 16–48 kHz, mono/stereo, CBR/VBR). The residue sitswhere 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 (synthesizedspeech with pauses, synthesized sounds with silent decays) scored 0.990–0.9999 against the libsndfile-decodedreference (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. InSwift, decode MP3 with another decoder and pass the samples to `embedAudio(samples:sampleRate:)`. **MP3 fileswithout a LAME/Xing tag** cannot be trimmed: Apple's decoder removes the 529-sample decoder delay and libsndfiledoes 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 onspeech).- **Resampler.** libsoxr is LGPL and its "HQ" / "VHQ" settings already differ from each other by cosine up to0.004, so the package ships its own Kaiser-windowed sinc (polyphase, pass band 0.913 and stop band 1.0 of thelower Nyquist, 125 dB attenuation, unity DC gain, output length ⌈n·16000/rate⌉ like librosa), computed in doubleprecision by the same formulas in Swift and numpy: the two give **bit-identical** 16 kHz waveforms on all 147resampled 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 below0.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-melfloor); Swift and numpy were bit-identical on 191 of its 201 resampled clips and within 4e-15 on the rest (the AACones 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 theindependent set). The Swift log-mel (Accelerate single-precision FFT) differs from numpy's by at most 0.006 pervalue (same waveform), which costs ≤ 0.0005 of cosine on the Neural Engine route (Swift vs Python vectors on 287clips: median 0.999996, min 0.99954).### Long audioThe model's window is 30 s (`processor` default, 480 000 samples): upstream silently drops the rest. The runnersoffer two policies: **`truncate`** (default; the first 30 s, exactly upstream) and **`chunk_mean`** (the mean ofthe L2-normalized embeddings of consecutive 30 s windows, re-normalized; a trailing window too short for oneframe 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.95vs 0.94 at 130 s). Neither is what upstream returns for long audio, which is the truncated vector. For retrievalover long recordings consider indexing each 30 s window as its own document.### Audio accuracyParity 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 andrates, 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 retrievalbenchmark: fp32 itself ranks only a third of them first.) The re-authored graph run in fp32 reproduces thereference 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 andlanguage 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 18languages from 84 macOS `say` voices and rates (local only, not shipped), 46 synthesized sounds, 74 copies of two sentences in 17 containers/codecsat 7.35–192 kHz, 54 edge cases (1 sample to 40 s, every bucket boundary, silence, clipping, DC offset, a 30 kHztone 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 theGPU) against the same policy in fp32. Retrieval with the 146 captions (100sentences, 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 excepttext → 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 infp32.End to end against upstream's own file path (libsndfile + libsoxr), the decoder and resampler effects describedabove 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, originalcheckpoint; images passed as paths with no prompt; audio as 16 kHz arrays (libsndfile/ffmpeg + libsoxr HQ) withno 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 PNGre-saves) were used for local validation only and are not shipped.78 unmodified lines| 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 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.**Audio smoke** (`tests/audio-smoke-reference.json`: 15 generated clips — 8 invented sentences in 7 languagesspoken by the eSpeak NG formant synthesizer, 4 synthesized sounds, silence, a tone and a 35 s MP3 melody — withtheir 13 captions as queries and documents; per-clip thresholds 0.9995 for 16 kHz lossless clips, 0.995 forresampled and MP3 clips, two measured exceptions carried in the file: digital silence 0.998 and the MP3 melody0.985; a query must rank its own clip first wherever fp32 does, which is 11 of 13 — fp32 itself misses twosynthesized 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 exceptthe 96 kHz tone, which is within 4e-17, and the two AAC files in some runs: Apple's AAC decoder varies by about onefloat32 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 took1.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 msinstead of 69 ms).Images: see "Images: Neural Engine or GPU" for the side-by-side comparison (time, CPU, GPU, power, energy,memory). Per function:3 unmodified lines| `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 (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` 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 a6000×4000 JPEG (numpy: 45 ms median). Audio front end (Swift, one core): 14 ms median per clip over the 215validation 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 sfor that resample, 6 ms log-mel). The CPU-only route takes ~520 ms per image and does not work for audio. ThePython 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; theNeural Engine serializes concurrent calls. Nothing stops an app from running two routes at once (e.g. one instance5 unmodified lines| 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 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 main3 unmodified linese.g. Homebrew's). It survives reboots but not OS updates, a renamed executable or a re-exported asset (including the1.0 → 1.1 upgrade).## Why three assets (and why `mm_<S>` also serves text)- The image and audio encoders are separate assets so that users neither download nor load what they do notneed (`--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. Withzero soft tokens it is the 1.0 encoder, bit for bit, so there is no reason to ship both.- The text buckets are 32, 64, 128, **288**, 512, 1024, 2048: 288 holds one image sequence (≤ 284 tokens) andreplaces 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_<Tb>`".## Temp files (please read)Each Neural Engine load writes compiled-graph copies to `$TMPDIR/com.apple.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/` (~360 MB for the text asset, ~300 MB for the image asset; the audio asset addednothing 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 nothingbehind. 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 interpreterexit (~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, createdafter the process started): `EmbeddingGemma2.removeOwnMPSGraphTempFiles()`, `remove_own_mpsgraph_temp_files()`,25 unmodified linesto 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 notvalidated 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 oraveraged 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 MP3smatch the reference decoder within ~3e-5 per sample after the gapless trim; inaudible, but digitally silentpassages 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 fileswithout 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 formatsyourself when that matters.- **Audio: resampling** uses the package's sinc instead of libsoxr: ≤ 0.00012 of cosine on speech, up to 0.006 onsynthesized 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 GPUroute is ≥ 0.9994 on everything. Only the shipped frame buckets are supported (see "Audio: `audio_<Tb>`"), andthe 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 achannel-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 embeddedas near-empty audio or crashed).- **Audio asset memory**: ~1.4 GB on the Neural Engine for the five functions (the runtime does not share theweights 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 theper-app cache entry unusable, so later loads of that asset fail in `loadFunction`. Delete`~/Library/Caches/coreai-cache/<OS build>/<app>/<asset hash>/` and reload (one more first-load specialization).- **Batch 1.** Concurrency did not increase throughput (the Neural Engine serializes). Short texts are not fasterthan ~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; measurethe 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 (macOS 27). Core AI is new in macOS 27 and its runtimebehaviour (first-load time, placement, temp files) may change between OS releases.## Reproducing the export6 unmodified lineshf download google/embeddinggemma-2 --local-dir ./embeddinggemma-2cd exportpython3 -W ignore export.py --model-dir ../embeddinggemma-2 --out ../model-rebuilt \--buckets 32,64,128,288,512,1024,2048 --qchunks 12 --audio-buckets 192,384,1024,1536,3000 --date 2026-10-12```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 imageencoder, `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 at2 unmodified lineswith `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/<asset>.aimodel --output ./compiled--preferred-compute neural-engine --architecture h17g 2>&1 | grep -c ane_validation_message` prints 0 for thetext and image assets (no op rejected; delete `./compiled` afterwards). The specialized text and image graphs haveone Neural Engine region and one GPU region (the token / position-table gather) per function; each audio functionis a single Neural Engine region. For the audio asset this offline check is not sufficient: verify placement withthe 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, 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 licensenotices 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 codewas copied.- Port, exporter, runners, Swift tokenizer implementation, preprocessing and audio front end, tests, test imagesand test audio: Copyright 2026 Everpaper, Apache-2.0.- Gemma and EmbeddingGemma are trademarks of Google LLC; Apple, Core AI, Apple silicon and Neural Engine aretrademarks of Apple Inc. This port is not affiliated with, sponsored by or endorsed by Google or Apple.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372# 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_<Tb>`): 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 depthwiseconvolution, 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 jsonimport mathfrom pathlib import Path
import torchimport torch.nn as nnimport torch.nn.functional as F
PRECISION_MODE = "ane" # "ane" (all fp16, Neural Engine) | "fp32" (correctness gate of the re-authoring)MASK_VALUE = -10000.0NORM_FLOOR = 1e-3CTX = 12 # keys per query: self + 11 pastN_MELS = 128FRAME_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()12345678910114 unmodified lines1617181920212217 unmodified lines4041424344459 unmodified lines5556575859606157 unmodified lines11912012112212312435 unmodified lines1601611621631641651661671681696 unmodified lines17617717817918018118218318418518618718 unmodified lines2062072082092102112122132142153 unmodified lines2192202212222232242257 unmodified lines233234235236237238239240241242243244245246# 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.# 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 <bundle folder> \# --buckets 32,64,128,288,512,1024,2048 --qchunks 12 --date 2026-10-12 (the released bundle, ~2 min)Written to <out> (see README "Why two assets"):embeddinggemma-2-text-mm.aimodel functions mm_<S>: 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 the4 unmodified linestokenizer/ 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.The result is functionally identical to the released bundle, not byte-identical: the converter names internal graphresources at random (main.mlirb / main.hash differ) and the runtime writes metadata.json with the export time.17 unmodified linesLAB = Path(__file__).resolve().parentsys.path.insert(0, str(LAB))import eg2_text # noqa: E402import eg2_text_mm # noqa: E402import eg2_vision # noqa: E4029 unmodified lines"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}def log(msg: str) -> None:57 unmodified linesreturn {"asset": asset.name, "function": fn, "max_patches": N, "max_soft_tokens": eg2_vision.MAX_SOFT, "qchunks": args.qchunks}def export_text_mm(args, out: Path, buckets: list[int]) -> dict:import coreai_torchfrom torch.export import Dim35 unmodified linesap.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("--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("--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)")6 unmodified linesvision = ({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 Noneif 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")tok_dir = out / "tokenizer"tok_dir.mkdir(exist_ok=True)18 unmodified lines"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": "<bos> <|image> <|image|> x n_soft <image|> <eos> (n_soft + 4 tokens, at most 284 -> bucket 288)","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,"tokenizer": "tokenizer/tokenizer.json (unchanged Gemma tokenizer; the runner adds <bos> and <eos>)",}(out / "config.json").write_text(json.dumps(cfg_json, indent=2) + "\n")3 unmodified linestb = text["buckets"]attribution = {"name": "EmbeddingGemma-2-CoreAI","version": "1.1","base_model": args.hf_id,"base_model_author": "Gemma Team, Google DeepMind","base_model_source": f"https://huggingface.co/{args.hf_id}",7 unmodified lines"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']}","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.","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.","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 "1234567891011121314154 unmodified lines202122232425262717 unmodified lines454647484950519 unmodified lines616263646566676857 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616735 unmodified lines2032042052062072082092102112122132142156 unmodified lines22222322422522622722822923023123223323423523623723818 unmodified lines2572582592602612622632642652662672682692702712722732742752762772783 unmodified lines2822832842852862872887 unmodified lines296297298299300301302303304305306307308309310311312313314315316317318319320# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""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 <bundle folder> \# --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 <out> (see README "Why three assets"):embeddinggemma-2-audio.aimodel functions audio_<Tb>: 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_<S>: 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 the4 unmodified linestokenizer/ unchanged Gemma tokenizer (text queries and the image sequence ids)config.json, MODEL-ATTRIBUTION.json`--part text` / `--part vision` / `--part audio` re-exports one asset and keeps the others' entries of an existingconfig.json.The result is functionally identical to the released bundle, not byte-identical: the converter names internal graphresources at random (main.mlirb / main.hash differ) and the runtime writes metadata.json with the export time.17 unmodified linesLAB = Path(__file__).resolve().parentsys.path.insert(0, str(LAB))import eg2_audio # noqa: E402import eg2_text # noqa: E402import eg2_text_mm # noqa: E402import eg2_vision # noqa: E4029 unmodified lines"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,"boa": 256000, "audio": 258881, "eoa": 258883}def log(msg: str) -> None:57 unmodified linesreturn {"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_<Tb>."""import coreai_torchfrom torch.export import Dimeg2_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) >= 2names = ["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_torchfrom torch.export import Dim35 unmodified linesap.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", "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)")6 unmodified linesvision = ({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 Noneaudio = ({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 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)18 unmodified lines"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": "<bos> <|image> <|image|> x n_soft <image|> <eos> (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": "<bos> <|audio> <|audio|> x n_tokens <audio|> <eos> (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"], "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 <bos> and <eos>)",}(out / "config.json").write_text(json.dumps(cfg_json, indent=2) + "\n")3 unmodified linestb = text["buckets"]attribution = {"name": "EmbeddingGemma-2-CoreAI","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}",7 unmodified lines"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']} "f"--audio-buckets {','.join(map(str, audio['frame_buckets']))}","global_attention": eg2_text.GLOBAL_ATTN_MODE, "gqa": eg2_text.GQA_MODE,},},"modifications": ["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_<Tb>; ""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 "
12345611 unmodified lines1819202122232425262728293031{"name": "EmbeddingGemma-2-CoreAI","version": "1.1","base_model": "google/embeddinggemma-2","base_model_author": "Gemma Team, Google DeepMind","base_model_source": "https://huggingface.co/google/embeddinggemma-2",11 unmodified lines"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","global_attention": "mqa4d","gqa": "grouped5d"}},"modifications": ["Text and image encoders only: the audio encoder of the multimodal checkpoint is not included.","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.","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).",12345611 unmodified lines1819202122232425262728293031323334{"name": "EmbeddingGemma-2-CoreAI","version": "1.2","base_model": "google/embeddinggemma-2","base_model_author": "Gemma Team, Google DeepMind","base_model_source": "https://huggingface.co/google/embeddinggemma-2",11 unmodified lines"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 --audio-buckets 192,384,1024,1536,3000","global_attention": "mqa4d","gqa": "grouped5d"}},"modifications": ["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_<Tb>; 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).",
58 unmodified lines5960616263649 unmodified lines74757677787958 unmodified lines"exif_orientation": "not applied (upstream parity); optional in the runners"},"image_sequence": "<bos> <|image> <|image|> x n_soft <image|> <eos> (n_soft + 4 tokens, at most 284 -> bucket 288)","hidden_size": 512,"embedding_dim": 768,"matryoshka_dims": [9 unmodified lines"image_token_id": 258880,"eoi_token_id": 258882,"video_token_id": 258884,"prompts": {"document": "title: none | text: ","search_query": "task: search result | query: ",58 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041059 unmodified lines11511611711811912012112212358 unmodified lines"exif_orientation": "not applied (upstream parity); optional in the runners"},"image_sequence": "<bos> <|image> <|image|> x n_soft <image|> <eos> (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": "<bos> <|audio> <|audio|> x n_tokens <audio|> <eos> (n_tokens + 4 tokens, at most 754 -> bucket 1024)","hidden_size": 512,"embedding_dim": 768,"matryoshka_dims": [9 unmodified lines"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: ",
1�����2z���̬�
!�W���T[�ߕ�123version https://git-lfs.github.com/spec/v1oid sha256:9ca590b09b327f7a8cae94ccace30d151621ae57a4a3f2a8b654145bc1df95f8size 58933213512345678{ "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"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373# 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 ownKaiser-windowed sinc (polyphase, 125 dB stop band, pass band 0.913 of 8 kHz), implemented identically here and inSwift (`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_<Tb> function ids = eg2_audio_frontend.audio_sequence(inputs.n_tokens, ...) # <bos> <boa> [n] <eoa> <eos>
Decoders: `soundfile` (libsndfile, the decoder upstream's librosa uses: WAV, AIFF, FLAC, OGG, CAF/ALAC, MP3 withgapless trimming) when it is installed, otherwise, and for AAC/M4A always, macOS `afconvert` (Apple's AudioToolboxdecoder; MP3 files are trimmed with the LAME/Info tag here so that they match libsndfile; see README)."""from __future__ import annotations
import mathimport osimport shutilimport structimport subprocessimport tempfilefrom dataclasses import dataclassfrom pathlib import Path
import numpy as np
SAMPLE_RATE = 16000FRAME_LENGTH = 320 # 20 msHOP_LENGTH = 160 # 10 msFFT_LENGTH = 512N_MELS = 128F_MIN, F_MAX = 0.0, 8000.0MEL_FLOOR = 1e-3MAX_SAMPLES = 480_000 # 30 s: the upstream default (truncation=True)PAD_MULTIPLE = 128 # samplesFRAME_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.0RESAMPLE_ATTEN_DB = 125.0
# ------------------------------------------------------------------------------------------------ decoding@dataclassclass 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("<I", b[p + 4:p + 8])[0] body = b[p + 8:p + 8 + size] if cid == b"fmt ": fmt = struct.unpack("<HHIIHH", body[:16]) elif cid == b"data": data = body p += 8 + size + (size & 1) assert fmt is not None and data is not None tag, ch, sr, _, _, bits = fmt assert bits == 32 and tag in (3, 0xFFFE), "expected float32 WAVE" return np.frombuffer(data, dtype="<f4").reshape(-1, ch).copy(), sr
def mp3_gapless_info(path: Path) -> 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)
# ------------------------------------------------------------------------------------------------ resamplingdef _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)
# ------------------------------------------------------------------------------------------------ featuresdef _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@dataclassclass 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_<bucket>. 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): <bos> <|audio> <|audio|> x n <audio|> <eos>.""" 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]123456789101112131415161718192021222324252627282930313233343536373810 unmodified lines49505152535455565758596061626364656667686 unmodified lines75767778798081825 unmodified lines88899091929394959697989910010110245 unmodified lines14814915015115215331 unmodified lines18518618718818919019119219319419518 unmodified lines21421521621721821922043 unmodified lines26426526626726826927027127227327427527627727827921 unmodified lines30130230330430530613 unmodified lines32032132232332432527 unmodified lines35335435535635735835936036136211 unmodified lines37437537637737837938038138238339 unmodified lines423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458#!/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).Library:from embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_filesm = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=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)q = m.embed("bar chart of lamp units sold per city", kind="search_query") # 768-d, L2-normalizedv = m.embed_image("chart.png") # path or PIL image, same 768-d spaced = m.embed("The credits expire on the last day of March.", kind="document", dim=256)score = float(q @ v)del mremove_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`).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 tokcheck ../model ../tests/tokenizer-cases.jsonpython3 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]Text goes through `mm_<S>` with zero soft-token inputs (identical to the v1.0 text graph). Images are decoded withPillow (`convert("RGB")`: alpha dropped, EXIF orientation not applied unless --exif), resized with thetorchvision-exact bicubic in eg2_image.py and fed to `vision_2520`; the soft tokens then go through `mm_288` insidethe sequence <bos> <|image> [n slots] <image|> <eos>. Tokenization uses the Hugging Face `tokenizers` library on thebundle's tokenizer.json (the reference tokenizer)."""from __future__ import annotations10 unmodified linesHERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))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 embedstexts and images 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 encoderruns, independently (None = same as compute). "ane" uses the least CPU, GPU and power; "gpu" is about 3xfaster per image (README, "Images: Neural Engine or GPU")."""import coreai.runtime as rtfrom tokenizers import Tokenizer6 unmodified linesself.tokenizer_load_s = time.perf_counter() - tself.compute = computeself.image_compute = image_compute or computeopts = _specialization_options(rt, compute)image_opts = _specialization_options(rt, self.image_compute)t = time.perf_counter()self.model = asyncio.run(rt.AIModel.load(self.bundle / self.config["asset"], opts))self.functions: dict[int, object] = {}5 unmodified linesvc = 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.load_s = time.perf_counter() - tif 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)@propertydef has_vision(self) -> bool:return self.vision_function is not None# ---- tokenization -------------------------------------------------------------------------------------def tokenize(self, text: str, kind: str | None = "document") -> list[int]:"""<bos> + prompt prefix + text + <eos>, truncated to the largest bucket (longer input is cut)."""45 unmodified linesids = 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))# ---- 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:31 unmodified linesself.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)))return time.perf_counter() - tdef close(self) -> None:self.functions.clear()self.model = self.vision_model = self.vision_function = Nonedef _specialization_options(rt, compute: str):18 unmodified linesdef 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.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/ (~360 MB for the text asset, ~300 MB for the vision asset), and thePython runtime (coreai.runtime, macOS 27.0) does NOT delete them when the model is released or the interpreterexits. This removes the folders of the CURRENT process only (its pid, created after it started). Call it afterthe model object has been released, or at exit. Returns (folders, bytes)."""import shutil43 unmodified lines# ---- 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 ownimage 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)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'}")ok = Truefor path, ref in refs:print(f"-- {path.name}")21 unmodified linesok = ok and passedimg_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")queries = []for c in ref.get("texts", []):v = m.embed(c["text"], c["kind"])13 unmodified linesprint(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")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")27 unmodified linesreturn 0def 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 1def cmd_tokcheck(a) -> int:11 unmodified linesreturn 0 if same == len(cases) else 1def cmd_latency(a) -> int:m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=not a.text_only, image_compute=a.image_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")if m.has_vision:rng = np.random.RandomState(0)px = rng.randint(0, 256, (624, 1008, 3)).astype(np.uint8)39 unmodified linesdef 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)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'})")m.close()return 0def 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.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("--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("--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("--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("--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 gcgc.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)123456789101112131415161718192021222324252627282930313233343536373839404142434410 unmodified lines555657585960616263646566676869707172737475766 unmodified lines8384858687888990919293949596975 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913045 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723831 unmodified lines27027127227327427527627727827928028128228318 unmodified lines30230330430530630730843 unmodified lines35235335435535635735835936036136236336436536636736836921 unmodified lines39139239339439539639739839940040140240340440540640713 unmodified lines42142242342442542642742842943043143243343443543643743843944044144244327 unmodified lines47147247347447547647747847948048148248348448548648748848949049149249349449549649749849911 unmodified lines51151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755839 unmodified lines598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""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_filesm = 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")# 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-normalizedv = m.embed_image("chart.png") # path or PIL image, same 768-d spacea = 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 mremove_own_mpsgraph_temp_files() # see "Temp files" in the README`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 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.jsonpython3 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_<S>` with zero soft-token inputs (identical to the v1.0 text graph). Images are decoded withPillow (`convert("RGB")`: alpha dropped, EXIF orientation not applied unless --exif), resized with thetorchvision-exact bicubic in eg2_image.py and fed to `vision_2520`; the soft tokens then go through `mm_288` insidethe sequence <bos> <|image> [n slots] <image|> <eos>. Audio is decoded, mixed to mono, resampled to 16 kHz and turnedinto log-mel frames by eg2_audio_frontend.py (numpy; soundfile or macOS afconvert for decoding), fed to`audio_<Tb>` and then through `mm_<S>` inside <bos> <|audio> [n slots] <audio|> <eos>. Tokenization uses the HuggingFace `tokenizers` library on the bundle's tokenizer.json (the reference tokenizer)."""from __future__ import annotations10 unmodified linesHERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))import eg2_audio_frontend # noqa: E402import eg2_image # noqa: E402_PROCESS_START = time.time()class EmbeddingGemma2CoreAI:"""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, load_audio: bool = False, audio_compute: str | None = None):"""compute: where the text asset runs (ane | gpu | cpu | default). image_compute / audio_compute: where theimage and audio encoders run, independently (None = same as compute). "ane" uses the least CPU, GPU andpower; "gpu" is about 3x faster per image (README, "Images: Neural Engine or GPU") and about 2x faster per30 s of audio (README, "Audio: Neural Engine or GPU")."""import coreai.runtime as rtfrom tokenizers import Tokenizer6 unmodified linesself.tokenizer_load_s = time.perf_counter() - tself.compute = computeself.image_compute = image_compute or computeself.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] = {}5 unmodified linesvc = 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 = Noneself.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() - tif not quiet:print(f"loaded {self.bundle.name} compute={compute} image_compute={self.image_compute if load_vision else '-'} "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)@propertydef has_vision(self) -> bool:return self.vision_function is not None@propertydef has_audio(self) -> bool:return bool(self.audio_functions)# ---- tokenization -------------------------------------------------------------------------------------def tokenize(self, text: str, kind: str | None = "document") -> list[int]:"""<bos> + prompt prefix + text + <eos>, truncated to the largest bucket (longer input is cut)."""45 unmodified linesids = 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_<S> (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_<bucket>)."""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_functionselse f"no audio function for bucket {inputs.bucket}")rt = self._rtout = 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 <bos> <|audio> [n] <audio|> <eos> (no prompt)."""c = self.confign = 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:31 unmodified linesself.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() - tdef close(self) -> None:self.functions.clear()self.audio_functions.clear()self.model = self.vision_model = self.vision_function = self.audio_model = Nonedef _specialization_options(rt, compute: str):18 unmodified linesdef 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.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/ (~360 MB for the text asset, ~300 MB for the vision asset), and thePython runtime (coreai.runtime, macOS 27) does NOT delete them when the model is released or the interpreterexits. This removes the folders of the CURRENT process only (its pid, created after it started). Call it afterthe model object has been released, or at exit. Returns (folders, bytes)."""import shutil43 unmodified lines# ---- 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, audio_compute: str | None = None) -> bool:"""Runs every reference file: text files (v1.0 format, "cases"), image files ("images" + "texts") and audiofiles ("audio" + "texts"). Returns True when every cosine is above its threshold, all values are finite andevery 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)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 '-'}, 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 = Truefor path, ref in refs:print(f"-- {path.name}")21 unmodified linesok = ok and passedimg_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 passedaud_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"])13 unmodified linesprint(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 = 0for q, qv in queries:want = next((i for i, c in enumerate(audio) if c.get("query") == q), -1)if want < 0:continuescores = [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 firstprint(f"SKIP query \"{q}\" -> {audio[best]['file']} ({max(scores):.3f}) (fp32 does not rank this clip first either)")continuetotal += 1hits += best == wantprint(f"{'PASS' if best == want else 'FAIL'} query \"{q}\" -> {audio[best]['file']} ({max(scores):.3f})")ok = ok and hits == totalprint(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")27 unmodified linesreturn 0def 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 0def 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, a.audio_compute) else 1def cmd_tokcheck(a) -> int:11 unmodified linesreturn 0 if same == len(cases) else 1def _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,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"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_<Tb> p50 ms mm_<S> 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.0wav = (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) * 1000for _ 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 * 1000print(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 * 48000st = 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)39 unmodified linesdef 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,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 "f"(vision {'loaded' if m.has_vision else 'not loaded'}, audio {'loaded' if m.has_audio else 'not loaded'})")m.close()return 0def main() -> None: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), 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 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()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 tracebackprint(f"error: {e}", file=sys.stderr)code = 2finally:if a.cleanup_temp: # also after an error, so that a failed run does not leave its temp folders behindimport gcgc.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)
123456789104 unmodified lines15161718192021# Exact versions of the environments this release was validated in (macOS 27.0, Apple silicon).# Runtime (python/), Python 3.12 (the text path of v1.0 was also validated with Python 3.14):coreai-core==1.0.0b3numpy==2.4.6pillow==12.3.0tokenizers==0.23.3huggingface-hub==2.2.0# Exporter (export/), on top of the runtime, Python 3.12:coreai-torch==0.4.3coreai-opt==0.3.04 unmodified linesnetworkx==3.7scipy==1.18.1packaging==26.3# Reference vectors and preprocessing checks (tests/make_*_reference.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# (pillow and torchvision are needed because the checkpoint's processor is multimodal, even for text-only use)123456789101112134 unmodified lines1819202122232425# 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.0b3numpy==2.4.6pillow==12.3.0tokenizers==0.23.3huggingface-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.3coreai-opt==0.3.04 unmodified linesnetworkx==3.7scipy==1.18.1packaging==26.3# 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)
12345678# 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).coreai-core==1.0.0b3numpy>=2.0,<2.6pillow>=11,<13tokenizers>=0.22,<0.24123456789101112# 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). 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.0b3numpy>=2.0,<2.6pillow>=11,<13tokenizers>=0.22,<0.24soundfile>=0.13,<0.15
12345678910111213141510 unmodified lines26272829303132333435363738394041424344454647#!/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 thefp32 reference vectors and check that every query finds its own image 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]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 newexecutable (here: your python binary) specializes the assets for the Neural Engine: expect a few minutes. Laterruns load in about a second."""from __future__ import annotations10 unmodified linesap = 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")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("--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 gcgc.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 112345678910111213141510 unmodified lines26272829303132333435363738394041424344454647484950515253545556#!/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, 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] [--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, 0.9995 / 0.995 audio clips), all valuesfinite, every query at rank 1. `--text-only` runs only the v1.0 text reference and loads neither the vision nor theaudio 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 annotations10 unmodified linesap = 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, 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("--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()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 tracebackprint(f"error: {e}", file=sys.stderr)return 2finally:if a.cleanup_temp: # also after an errorimport gcgc.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
9 unmodified lines10111213141516171819202122239 unmodified lines.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..target(name: "EmbeddingGemma2CoreAI",path: "Sources/EmbeddingGemma2CoreAI",linkerSettings: [.linkedFramework("CoreAI"), .linkedFramework("ImageIO"), .linkedFramework("CoreGraphics")]),// Command-line tool: embed | embed-image | smoke | tokcheck | pixcheck | dump | latency | prewarm | cleanup-temp.executableTarget(name: "eg2-cli",dependencies: ["EmbeddingGemma2CoreAI"],9 unmodified lines10111213141516171819202122232425269 unmodified lines.executable(name: "eg2-cli", targets: ["eg2-cli"]),],targets: [// 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"),.linkedFramework("AVFoundation"), .linkedFramework("Accelerate")]),// 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"],
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104// 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 AVFoundationimport 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..<channelCount { channels[c].append(contentsOf: UnsafeBufferPointer(start: data[c], count: n)) } if file.framePosition >= 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..<end]) } } else if gapless > 0, total > gapless, (total - gapless) % info.samplesPerFrame == 0, total - gapless <= 2 * info.samplesPerFrame { channels = channels.map { Array($0[0..<gapless]) } } } return DecodedAudio(sampleRate: Int(format.sampleRate.rounded()), channelCount: channelCount, channels: channels) }
/// Frame count, samples per frame and the (encoder delay, padding) in samples from the Xing/Info + LAME tag of /// the first MPEG frame; nil without the tag or its frame count. public static func mp3GaplessInfo(url: URL) throws -> (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) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191// 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_<Tb>`. 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 Accelerateimport Foundation
/// The inputs of one `audio_<bucket>` 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..<audio.channelCount { let ch = audio.channels[c] for i in 0..<acc.count { acc[i] += ch[i] } } let inv = Float(audio.channelCount) for i in 0..<acc.count { acc[i] /= inv } return acc }
/// decode -> 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..<nBins { let step = Double(sampleRate / 2) / Double(nBins - 1) fftFreqs[i] = i == nBins - 1 ? Double(sampleRate / 2) : Double(i) * step } var diff = [Double](repeating: 0, count: nMels + 1) for i in 0..<(nMels + 1) { diff[i] = filterFreqs[i + 1] - filterFreqs[i] } var w = [Double](repeating: 0, count: nBins * nMels) for b in 0..<nBins { for m in 0..<nMels { let down = -(filterFreqs[m] - fftFreqs[b]) / diff[m] let up = (filterFreqs[m + 2] - fftFreqs[b]) / diff[m + 1] w[b * nMels + m] = max(0.0, min(down, up)) } } return w }()
static let hannWindow: [Float] = (0..<frameLength).map { n in Float(0.5 - 0.5 * cos(2.0 * Double.pi * Double(n) / Double(frameLength))) }
// MARK: - Log-mel
/// Log-mel features of a 16 kHz mono signal: [validFrames * 128] Float, row-major, at most 2999 frames. public static func logMel(_ wav16k: [Float], maxSamples limit: Int? = maxSamples) -> (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..<n { xp[frameLength / 2 + i] = x[i] } let nBins = fftLength / 2 + 1 guard let dft = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftLength), .FORWARD) else { return ([], 0) } defer { vDSP_DFT_DestroySetup(dft) } var inRe = [Float](repeating: 0, count: fftLength), inIm = [Float](repeating: 0, count: fftLength) var outRe = [Float](repeating: 0, count: fftLength), outIm = [Float](repeating: 0, count: fftLength) var mag = [Double](repeating: 0, count: m * nBins) for t in 0..<m { let s = t * hopLength for i in 0..<frameLength { inRe[i] = xp[s + i] * hannWindow[i] } for i in frameLength..<fftLength { inRe[i] = 0 } vDSP_DFT_Execute(dft, inRe, inIm, &outRe, &outIm) for b in 0..<nBins { let re = outRe[b], im = outIm[b] mag[t * nBins + b] = Double((re * re + im * im).squareRoot()) // magnitude in Float, like numpy complex64 } } var mel = [Double](repeating: 0, count: m * nMels) melFilters.withUnsafeBufferPointer { f in mag.withUnsafeBufferPointer { a in mel.withUnsafeMutableBufferPointer { c in // [m x 257] x [257 x 128] in double precision (row-major) vDSP_mmulD(a.baseAddress!, 1, f.baseAddress!, 1, c.baseAddress!, 1, vDSP_Length(m), vDSP_Length(nMels), vDSP_Length(nBins)) } } } var feats = [Float](repeating: 0, count: m * nMels) for i in 0..<(m * nMels) { feats[i] = Float(log(mel[i] + melFloor)) } return (feats, m) }
// MARK: - Model inputs
/// 16 kHz mono samples -> inputs of `audio_<bucket>` (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..<nv { frameMask[i] = 1 } var halfMask = [Float16](repeating: 0, count: Tb / 2) for i in 0..<((nv + 1) / 2) { halfMask[i] = 1 } let nt = softTokenCount(frames: nv) var tokenMask = [Float16](repeating: 0, count: Tb / 4) for i in 0..<nt { tokenMask[i] = 1 } return AudioInputs(bucket: Tb, frameCount: nv, softTokenCount: nt, features: features, frameMask: frameMask, halfMask: halfMask, tokenMask: tokenMask) }
/// Decode a file and prepare the inputs (decode -> 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..<min($0 + maxSamples, wav16k.count)]) } return parts.enumerated().filter { $0.offset == 0 || $0.element.count > frameLength / 2 }.map { $0.element } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// 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 Accelerateimport 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..<n { let m = Double(k - c) let sinc = (k == c) ? fc : sin(Double.pi * fc * m) / (Double.pi * m) let r = 2.0 * Double(k) / Double(n - 1) - 1.0 let w = besselI0(beta * sqrt(max(0.0, 1.0 - r * r))) / i0b h[k] = sinc * w sum += h[k] } for k in 0..<n { h[k] /= sum } return (h, c) }
/// Per-phase tap vectors: phase p (= (j*down) % up) uses h[c + p + r*up] for r = rMin(p) ... rMax(p), stored in /// increasing r and applied to x[q - r] (decreasing sample index), q = (j*down - p) / up. struct Polyphase { let phases: [(j0: Int, rMin: Int, taps: [Double])] // j0 = first output index of the phase, -1 = unused }
static func polyphase(up: Int, down: Int, inRate: Int) -> Polyphase { let (h, c) = sincFilter(up: up, down: down, inRate: inRate) var phases: [(j0: Int, rMin: Int, taps: [Double])] = [] for p in 0..<up { var j0 = -1 for j in 0..<up where (j * down) % up == p { j0 = j; break } let rMin = -((c + p) / up) let rMax = (h.count - 1 - c - p) / up // stored REVERSED (r = rMax first) so that the dot product walks the input forward from x[q - rMax] phases.append((j0, rMin, j0 < 0 ? [] : (rMin...rMax).reversed().map { h[c + p + $0 * up] })) } return Polyphase(phases: phases) }
// guarded by `lock` (filters are computed once per input rate and shared) nonisolated(unsafe) private static var cache: [String: Polyphase] = [:] private static let lock = NSLock()
static func gcd(_ a: Int, _ b: Int) -> 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..<x.count { xd[pad + i] = Double(x[i]) } var y = [Double](repeating: 0, count: nOut) let scale = Double(up) xd.withUnsafeBufferPointer { xb in for (p, ph) in pf.phases.enumerated() where ph.j0 >= 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) } }}123456789101112131415166 unmodified lines2324252627282930313233344 unmodified lines39404142434429 unmodified lines7475767778793 unmodified lines8384858687888990911 unmodified line939495969798991001011021031 unmodified line10510610710810911015 unmodified lines12612712812913013196 unmodified lines22822923023123223358 unmodified lines2922932942952962978 unmodified lines306307308309310311312// 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:// text -> exact Gemma tokenizer -> <bos> prompt text <eos> -> `mm_<S>` with zero soft-token inputs -> embedding// image -> decode (alpha dropped, no EXIF, no colour management) -> exact resize -> patches -> `vision_2520`// -> n soft tokens -> sequence <bos> <|image> [n slots] <image|> <eos> -> `mm_288` -> embedding// Both 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").import CoreAIimport CoreGraphics6 unmodified linespublic let max_patches: Intpublic let max_soft_tokens: Int}/// The text asset (`mm_<S>` functions: text, images, or both in one sequence).public let asset: Stringpublic let functions: [String]public let buckets: [Int]public let max_tokens: Intpublic let vision: Visionpublic let hidden_size: Intpublic let embedding_dim: Intpublic let matryoshka_dims: [Int]4 unmodified linespublic let boi_token_id: Int32public let image_token_id: Int32public let eoi_token_id: Int32}public enum ComputePreference: String, Sendable {29 unmodified linespublic let compute: ComputePreference/// Where the image encoder (`vision_2520`) runs; equals `compute` unless set with `imageCompute:`.public let imageCompute: 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: Double3 unmodified linesprivate let functions: [Int: InferenceFunction] // bucket -> mm_<S>private let visionModel: AIModel? // nil unless created with loadVision: trueprivate let visionFunction: InferenceFunction?public var buckets: [Int] { functions.keys.sorted() }/// True when the vision asset is loaded and `embedImage` / `softTokens` can be used.public var hasVision: Bool { visionFunction != nil }private var hidden: Int { config.hidden_size }/// `loadVision: false` (the default, as in v1.0) loads the text asset only. `loadVision: true` also loads the1 unmodified line/// `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.public init(bundle: URL, compute: ComputePreference = .neuralEngine, loadVision: Bool = false,imageCompute: ComputePreference? = nil) async throws {bundleURL = bundleself.compute = computeself.imageCompute = imageCompute ?? computeconfig = try JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json")))var t0 = Date()tokenizer = try GemmaTokenizer(contentsOf: bundle.appendingPathComponent("tokenizer/tokenizer.json"))1 unmodified lineguard 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")}t0 = Date()textModel = try await AIModel(contentsOf: bundle.appendingPathComponent(config.asset), options: Self.options(compute))var fns: [Int: InferenceFunction] = [:]15 unmodified linesvisionModel = nilvisionFunction = nil}loadSeconds = Date().timeIntervalSince(t0)}96 unmodified linesreturn MultimodalSequence(ids: ids, softTokens: softTokens, slots: Array(2..<(2 + n)))}// MARK: - Any sequence/// Runs `mm_<bucket>` on a sequence (ids with `<bos>`/`<eos>`, right-padded with `<pad>`; soft tokens placed at58 unmodified linesif visionFunction != nil {_ = try await softTokens(ImagePreprocessor.patchify(resizedRGB: [UInt8](repeating: 128, count: 48 * 48 * 3), width: 48, height: 48))}return Date().timeIntervalSince(t0)}8 unmodified lines/// Each Neural Engine load makes MPSGraph write compiled-graph copies into `$TMPDIR/com.apple.MetalPerformance/// ShadersGraph/mpsgraph-<pid>-<date>-<n>/` (~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/// 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 folders12345678910111213141516171819206 unmodified lines27282930313233343536373839404142434445464 unmodified lines515253545556575859606162636465666729 unmodified lines9798991001011021031043 unmodified lines1081091101111121131141151161171181191201211221 unmodified line1241251261271281291301311321331341351361371381 unmodified line14014114214314414514614714814915015115215 unmodified lines16816917017117217317417517617717817918018118218318418518618718818996 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337458 unmodified lines4334344354364374384394404414424434444458 unmodified lines454455456457458459460// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE).//// 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 -> <bos> prompt text <eos> -> `mm_<S>` with zero soft-token inputs -> embedding// image -> decode (alpha dropped, no EXIF, no colour management) -> exact resize -> patches -> `vision_2520`// -> n soft tokens -> sequence <bos> <|image> [n slots] <image|> <eos> -> `mm_288` -> embedding// audio -> decode -> mono -> 16 kHz -> log-mel frames -> `audio_<Tb>` -> n soft tokens// -> sequence <bos> <|audio> [n slots] <audio|> <eos> -> `mm_<S>` -> 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 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 CoreAIimport CoreGraphics6 unmodified linespublic let max_patches: Intpublic let max_soft_tokens: Int}public struct Audio: Decodable, Sendable {public let asset: Stringpublic let functions: [String]public let frame_buckets: [Int]public let max_soft_tokens: Int}/// The text asset (`mm_<S>` functions: text, images, or both in one sequence).public let asset: Stringpublic let functions: [String]public let buckets: [Int]public let max_tokens: Intpublic let vision: Vision/// The audio asset (`audio_<Tb>` functions); absent in a 1.1 bundle.public let audio: Audio?public let hidden_size: Intpublic let embedding_dim: Intpublic let matryoshka_dims: [Int]4 unmodified linespublic let boi_token_id: Int32public let image_token_id: Int32public let eoi_token_id: Int32public 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 {29 unmodified linespublic 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_<Tb>`) 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: Double3 unmodified linesprivate let functions: [Int: InferenceFunction] // bucket -> mm_<S>private let visionModel: AIModel? // nil unless created with loadVision: trueprivate let visionFunction: InferenceFunction?private let audioModel: AIModel? // nil unless created with loadAudio: trueprivate let audioFunctions: [Int: InferenceFunction] // frame bucket -> audio_<Tb>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 the1 unmodified line/// `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, loadAudio: Bool = false,audioCompute: ComputePreference? = nil) async throws {bundleURL = bundleself.compute = computeself.imageCompute = imageCompute ?? computeself.audioCompute = audioCompute ?? computeconfig = try JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json")))var t0 = Date()tokenizer = try GemmaTokenizer(contentsOf: bundle.appendingPathComponent("tokenizer/tokenizer.json"))1 unmodified lineguard 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] = [:]15 unmodified linesvisionModel = nilvisionFunction = 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 = amaudioFunctions = afns} else {audioModel = nilaudioFunctions = [:]}loadSeconds = Date().timeIntervalSince(t0)}96 unmodified linesreturn 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_<bucket>`): `[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.nMelsguard 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.softTokenCountvar result = [Float16](repeating: 0, count: n * hidden)let view = soft.view(as: Float16.self)view.withUnsafePointer { p, _, _ infor i in 0..<(n * hidden) { result[i] = p[i] }}return result}/// The upstream single-clip sequence: `<bos> <|audio> <|audio|> x n <audio|> <eos>` (no prompt).public func audioSequence(softTokens: [Float16]) -> MultimodalSequence {let n = softTokens.count / hiddenlet boa = config.boa_token_id ?? 256000, audio = config.audio_token_id ?? 258881, eoa = config.eoa_token_id ?? 258883var 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_<bucket>` on a sequence (ids with `<bos>`/`<eos>`, right-padded with `<pad>`; soft tokens placed at58 unmodified linesif 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.nMelslet 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)}8 unmodified lines/// Each Neural Engine load makes MPSGraph write compiled-graph copies into `$TMPDIR/com.apple.MetalPerformance/// ShadersGraph/mpsgraph-<pid>-<date>-<n>/` (~360 MB for the text asset, ~300 MB for the vision asset). With the/// 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
1 unmodified line23456781 unmodified line//// 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// (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.)1 unmodified line23456781 unmodified line//// 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) 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.)
4 unmodified lines567891011121314151617181920212223243 unmodified lines282930313233343536 unmodified lines7273747576777 unmodified lines858687888990919210 unmodified lines10310410510610710810911011111211311411511627 unmodified lines1441451461471481497 unmodified lines15715815916016116231 unmodified lines1941951961971981991 unmodified line20120220320420520620720820921028 unmodified lines23924024124224324416 unmodified lines26126226326426526636 unmodified lines30330430530630730830931031121 unmodified lines33333433533633733818 unmodified lines3573583593603613623633643654 unmodified lines// eg2-cli embed <bundle> [--compute ane|gpu|cpu] [--kind document|search_query|...] [--dim 768] "text" ...// eg2-cli embed-image <bundle> [--compute ...] [--image-compute ane|gpu|cpu] [--exif] [--dim 768] image ...// (one JSON line per image)// eg2-cli smoke <bundle> <reference.json> [<reference.json> ...] [--compute ...] [--image-compute ...] [--cleanup-temp]// (text references: tests/smoke-reference.json; image references: tests/image-smoke-reference.json)// eg2-cli tokcheck <bundle> <tokenizer-cases.json>// eg2-cli pixcheck <preprocess-cases.json> (decode + resize vs the Python reference, no model needed)// eg2-cli dump <image> <out-prefix> [--exif] (writes <prefix>.decoded.rgb / .resized.rgb / .json)// eg2-cli latency <bundle> [--compute ...] [--image-compute ...] [--trials 50] [--text-only]// eg2-cli prewarm <bundle> [--compute ...] [--image-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.import CryptoKitimport EmbeddingGemma2CoreAI3 unmodified lines@MainActor func usage() -> Never {print("""usage: eg2-cli <embed|embed-image|smoke|tokcheck|pixcheck|dump|latency|prewarm|cleanup-temp> ... [--compute ane|gpu|cpu][--image-compute ane|gpu|cpu] [--cleanup-temp]""")exit(2)}36 unmodified linesreturn s[min(s.count - 1, Int(Double(s.count) * p))]}guard !args.isEmpty else { usage() }let cmd = args.removeFirst()let cleanup = takeFlag("--cleanup-temp")7 unmodified lines}let compute = computeOption("--compute") ?? .neuralEnginelet imageCompute = computeOption("--image-compute") // nil = same as --computelet exif = takeFlag("--exif")let textOnly = takeFlag("--text-only")@MainActor func finish(_ code: Int32) -> Never {if cleanup {10 unmodified lineslet decoded_sha256: String; let resized_sha256: String; let lossy: Bool}// Smoke reference files: text (v1.0 format, "cases") or images ("images" + "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 RefFile: Decodable {let threshold_cosine: Doublelet threshold_cosine_image: Double?let cases: [TextCase]?let images: [ImageCase]?let texts: [TextCase]?}27 unmodified linesprint("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 "dump":guard args.count >= 2 else { usage() }let img = try ImageDecoder.decodeRGB(url: URL(fileURLWithPath: args[0]), applyEXIFOrientation: exif)7 unmodified linesprint(String(decoding: try JSONSerialization.data(withJSONObject: info), as: UTF8.self))finish(0)default:break}31 unmodified lines_ = consume eg2finish(0)case "smoke":guard !args.isEmpty else { usage() }let refs = try args.map { path -> (URL, RefFile) in1 unmodified linereturn (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)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")")var ok = truefor (refURL, ref) in refs {print("-- \(refURL.lastPathComponent)")28 unmodified linesimgVecs.append(v)print("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(imgThreshold)) image \(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)16 unmodified linesok = ok && hits == queryVecs.countprint("text -> image: \(hits)/\(queryVecs.count) queries rank their own image first")}}let fp = footprints()print("peak footprint \(fmt(fp.physMB, 0)) MB, neural footprint \(fmt(fp.neuralMB, 0)) MB")36 unmodified linescase "latency":let trials = Int(takeOption("--trials") ?? "50") ?? 50let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: !textOnly, imageCompute: imageCompute)print("loaded in \(fmt(eg2.loadSeconds, 1)) s, compute=\(compute.rawValue), image-compute=\(eg2.hasVision ? eg2.imageCompute.rawValue : "-"), "+ "vision \(eg2.hasVision ? "loaded" : "not loaded")")let warm = try await eg2.prewarm()print("prewarm \(fmt(warm, 2)) s")if eg2.hasVision {21 unmodified linesfor _ 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")}print("bucket p50 ms min ms p90 ms CPU ms/call tok/s")for S in eg2.buckets {var ids = [Int32](repeating: 0, count: S)18 unmodified linescase "prewarm":let t0 = Date()let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: !textOnly, imageCompute: imageCompute)let warm = try await eg2.prewarm()print("load \(fmt(eg2.loadSeconds, 1)) s + prewarm \(fmt(warm, 2)) s = ready in \(fmt(Date().timeIntervalSince(t0), 1)) s (vision \(eg2.hasVision ? "loaded" : "not loaded"))")_ = consume eg2finish(0)4 unmodified lines56789101112131415161718192021222324252627283 unmodified lines323334353637383936 unmodified lines767778798081828384858687887 unmodified lines9697989910010110210310410510610710810910 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314427 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142157 unmodified lines22322422522622722822923023123223323423523623723823924024131 unmodified lines2732742752762772782792802812822832842852862872882892902912922932942952962972981 unmodified line30030130230330430530630730830931031128 unmodified lines34034134234334434534634734834935035135235335435535635735816 unmodified lines37537637737837938038138238338438538638738838939039139239339439539639739839940040136 unmodified lines43843944044144244344444544644744821 unmodified lines47047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451518 unmodified lines5345355365375385395405415425435445454 unmodified lines// eg2-cli embed <bundle> [--compute ane|gpu|cpu] [--kind document|search_query|...] [--dim 768] "text" ...// eg2-cli embed-image <bundle> [--compute ...] [--image-compute ane|gpu|cpu] [--exif] [--dim 768] image ...// (one JSON line per image)// eg2-cli embed-audio <bundle> [--compute ...] [--audio-compute ane|gpu|cpu] [--long truncate|chunk_mean] [--dim 768] clip ...// (one JSON line per clip)// eg2-cli smoke <bundle> <reference.json> [<reference.json> ...] [--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 <bundle> <tokenizer-cases.json>// eg2-cli pixcheck <preprocess-cases.json> (decode + resize vs the Python reference, no model needed)// eg2-cli audiocheck <audio-preprocess-cases.json> (decode + resample + log-mel vs the Python reference, no model needed)// eg2-cli dump <image> <out-prefix> [--exif] (writes <prefix>.decoded.rgb / .resized.rgb / .json)// eg2-cli dump-audio <clip> <out-prefix> (writes <prefix>.wave16k.f32 / .features.f32 / .json)// eg2-cli latency <bundle> [--compute ...] [--image-compute ...] [--audio-compute ...] [--trials 50] [--text-only]// eg2-cli prewarm <bundle> [--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` 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 CryptoKitimport EmbeddingGemma2CoreAI3 unmodified lines@MainActor func usage() -> Never {print("""usage: eg2-cli <embed|embed-image|embed-audio|smoke|tokcheck|pixcheck|audiocheck|dump|dump-audio|latency|prewarm|cleanup-temp> ...[--compute ane|gpu|cpu] [--image-compute ane|gpu|cpu] [--audio-compute ane|gpu|cpu] [--cleanup-temp]""")exit(2)}36 unmodified linesreturn 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")7 unmodified lines}let compute = computeOption("--compute") ?? .neuralEnginelet imageCompute = computeOption("--image-compute") // nil = same as --computelet audioCompute = computeOption("--audio-compute") // nil = same as --computelet 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 {10 unmodified lineslet decoded_sha256: String; let resized_sha256: String; let lossy: Bool}/// 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: Intlet bucket: Int; let wave_file: String; let features_file: Stringlet 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: Doublelet threshold_cosine_image: Double?let threshold_cosine_audio: Double?let cases: [TextCase]?let images: [ImageCase]?let audio: [AudioRefCase]?let texts: [TextCase]?}27 unmodified linesprint("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 = 0var worstWave: Float = 0, worstFeat: Float = 0let 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) * 1000let 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.bucketvar wDiff: Float = 0if wav.count == refWave.count { for i in 0..<wav.count { wDiff = max(wDiff, abs(wav[i] - refWave[i])) } } else { wDiff = .infinity }var fDiff: Float = 0let n = inputs.frameCount * AudioInputs.nMelsif refFeat.count == n {let (feats, _) = AudioFrontend.logMel(wav)for i in 0..<n { fDiff = max(fDiff, abs(feats[i] - refFeat[i])) }} else { fDiff = .infinity }let ok = counts && wDiff <= c.wave_tolerance && fDiff <= c.feature_toleranceif ok { pass += 1 } else { fail += 1 }if wDiff == 0 { waveExact += 1 }worstWave = max(worstWave, wDiff == .infinity ? worstWave : wDiff)worstFeat = max(worstFeat, fDiff == .infinity ? worstFeat : fDiff)print("\(ok ? "PASS" : "FAIL") \(c.file) \(d.sampleRate) Hz x\(d.channelCount) -> \(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)7 unmodified linesprint(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}31 unmodified lines_ = consume eg2finish(0)case "embed-audio":let dim = Int(takeOption("--dim") ?? "768") ?? 768let 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 eg2finish(0)case "smoke":guard !args.isEmpty else { usage() }let refs = try args.map { path -> (URL, RefFile) in1 unmodified linereturn (url, try JSONDecoder().decode(RefFile.self, from: Data(contentsOf: url)))}let needsVision = refs.contains { !($0.1.images ?? []).isEmpty }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 : "-"), audio-compute=\(eg2.hasAudio ? eg2.audioCompute.rawValue : "-"), "+ "buckets=\(eg2.buckets), vision \(eg2.hasVision ? "loaded" : "not loaded"), audio \(eg2.hasAudio ? "loaded" : "not loaded")")var ok = truefor (refURL, ref) in refs {print("-- \(refURL.lastPathComponent)")28 unmodified linesimgVecs.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_cosinelet pass = cos >= thr && v.allSatisfy { $0.isFinite }ok = ok && passaudVecs.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)16 unmodified linesok = ok && hits == queryVecs.countprint("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 = 0for (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 == wantif 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 += 1hits += hit ? 1 : 0print("\(hit ? "PASS" : "FAIL") query \"\(q)\" -> \(audio[best].file) (\(fmt(scores.max()!, 3)))")}ok = ok && hits == totalprint("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")36 unmodified linescase "latency":let trials = Int(takeOption("--trials") ?? "50") ?? 50let hasAudioAsset = (try? JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json"))))?.audio != nillet 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 : "-"), "+ "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 {21 unmodified linesfor _ 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 bucketlet audioTrials = max(5, trials / 2)print("audio seconds bucket tokens audio_<Tb> p50 ms mm_<S> 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..<n {let t = Float(i) / 16000wav[i] = 0.3 * sin(2 * .pi * 220 * t) + 0.2 * sin(2 * .pi * 1375 * t + 0.5 * sin(2 * .pi * 3 * t)) + 0.05 * Float((i * 7919) % 1000) / 1000 - 0.025}let tf0 = Date()let inputs = try AudioFrontend.prepare(wav16k: wav)let frontMs = Date().timeIntervalSince(tf0) * 1000var ta: [Double] = [], tt: [Double] = [], te: [Double] = []for _ in 0..<3 { _ = try await eg2.embedAudio(inputs) }let cpu0 = cpuSeconds()for _ in 0..<audioTrials {let t0 = Date()let soft = try await eg2.audioSoftTokens(inputs)let t1 = Date()_ = try await eg2.embed(sequence: eg2.audioSequence(softTokens: soft))let t2 = Date()ta.append(t1.timeIntervalSince(t0) * 1000); tt.append(t2.timeIntervalSince(t1) * 1000); te.append(t2.timeIntervalSince(t0) * 1000)}let cpu = (cpuSeconds() - cpu0) / Double(audioTrials) * 1000print(String(format: " %7.1f %6d %6d %17.1f %14.1f %18.1f %12.1f %12.1f", seconds, inputs.bucket, inputs.softTokenCount,percentile(ta, 0.5), percentile(tt, 0.5), percentile(te, 0.5), cpu, frontMs))}// the front end on a 48 kHz stereo 30 s clip (decode excluded): resample + log-mellet n48 = 30 * 48000var l = [Float](repeating: 0, count: n48), r = [Float](repeating: 0, count: n48)for i in 0..<n48 { l[i] = sin(Float(i) * 0.01); r[i] = sin(Float(i) * 0.013) }let tp0 = Date()let mono = AudioFrontend.toMono(DecodedAudio(sampleRate: 48000, channelCount: 2, channels: [l, r]))let w16 = AudioResampler.resampleTo16k(mono, rate: 48000)let tp1 = Date()_ = try AudioFrontend.prepare(wav16k: w16)print("audio front end, 30 s stereo 48 kHz: mono + resample \(fmt(tp1.timeIntervalSince(tp0) * 1000, 0)) ms, log-mel + inputs \(fmt(Date().timeIntervalSince(tp1) * 1000, 0)) ms")}print("bucket p50 ms min ms p90 ms CPU ms/call tok/s")for S in eg2.buckets {var ids = [Int32](repeating: 0, count: S)18 unmodified linescase "prewarm":let t0 = Date()let hasAudioAsset = (try? JSONDecoder().decode(BundleConfig.self, from: Data(contentsOf: bundle.appendingPathComponent("config.json"))))?.audio != nillet eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: !textOnly, imageCompute: imageCompute,loadAudio: !textOnly && hasAudioAsset, audioCompute: audioCompute)let warm = try await eg2.prewarm()print("load \(fmt(eg2.loadSeconds, 1)) s + prewarm \(fmt(warm, 2)) s = ready in \(fmt(Date().timeIntervalSince(t0), 1)) s "+ "(vision \(eg2.hasVision ? "loaded" : "not loaded"), audio \(eg2.hasAudio ? "loaded" : "not loaded"))")_ = consume eg2finish(0)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242[ { "file": "audio/speech_en_train_16k.wav", "sample_rate": 16000, "channels": 1, "n_samples16k": 61749, "n_frames": 385, "n_tokens": 97, "bucket": 1024, "wave_file": "audio/ref/speech_en_train_16k.wave16k.f32", "features_file": "audio/ref/speech_en_train_16k.features.f32", "wave_tolerance": 0.0, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_en_parcel_8k.wav", "sample_rate": 8000, "channels": 1, "n_samples16k": 66558, "n_frames": 415, "n_tokens": 104, "bucket": 1024, "wave_file": "audio/ref/speech_en_parcel_8k.wave16k.f32", "features_file": "audio/ref/speech_en_parcel_8k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_it_mercato_22k.aiff", "sample_rate": 22050, "channels": 1, "n_samples16k": 74743, "n_frames": 467, "n_tokens": 117, "bucket": 1024, "wave_file": "audio/ref/speech_it_mercato_22k.wave16k.f32", "features_file": "audio/ref/speech_it_mercato_22k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_fr_pont_44k.m4a", "sample_rate": 44100, "channels": 1, "n_samples16k": 48751, "n_frames": 304, "n_tokens": 76, "bucket": 384, "wave_file": "audio/ref/speech_fr_pont_44k.wave16k.f32", "features_file": "audio/ref/speech_fr_pont_44k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "afconvert", "note": null }, { "file": "audio/speech_de_garten_48k_stereo.wav", "sample_rate": 48000, "channels": 2, "n_samples16k": 50307, "n_frames": 314, "n_tokens": 79, "bucket": 384, "wave_file": "audio/ref/speech_de_garten_48k_stereo.wave16k.f32", "features_file": "audio/ref/speech_de_garten_48k_stereo.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_pt_barco_44k.caf", "sample_rate": 44100, "channels": 1, "n_samples16k": 73981, "n_frames": 462, "n_tokens": 116, "bucket": 1024, "wave_file": "audio/ref/speech_pt_barco_44k.wave16k.f32", "features_file": "audio/ref/speech_pt_barco_44k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_es_tienda_16k.flac", "sample_rate": 16000, "channels": 1, "n_samples16k": 58569, "n_frames": 366, "n_tokens": 92, "bucket": 384, "wave_file": "audio/ref/speech_es_tienda_16k.wave16k.f32", "features_file": "audio/ref/speech_es_tienda_16k.features.f32", "wave_tolerance": 0.0, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/speech_sv_buss_22k.mp3", "sample_rate": 22050, "channels": 1, "n_samples16k": 68097, "n_frames": 425, "n_tokens": 107, "bucket": 1024, "wave_file": "audio/ref/speech_sv_buss_22k.wave16k.f32", "features_file": "audio/ref/speech_sv_buss_22k.features.f32", "wave_tolerance": 0.0001, "feature_tolerance": 1.0, "python_decoder": "libsndfile", "note": "mp3: libsndfile (Python) vs Apple (Swift) decoders differ by ~3e-5 per sample" }, { "file": "audio/sound_chord_piano_44k_stereo.wav", "sample_rate": 44100, "channels": 2, "n_samples16k": 48000, "n_frames": 299, "n_tokens": 75, "bucket": 384, "wave_file": "audio/ref/sound_chord_piano_44k_stereo.wave16k.f32", "features_file": "audio/ref/sound_chord_piano_44k_stereo.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/sound_clicks_noise_22k.wav", "sample_rate": 22050, "channels": 1, "n_samples16k": 64000, "n_frames": 399, "n_tokens": 100, "bucket": 1024, "wave_file": "audio/ref/sound_clicks_noise_22k.wave16k.f32", "features_file": "audio/ref/sound_clicks_noise_22k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/sound_chirp_siren_48k.flac", "sample_rate": 48000, "channels": 1, "n_samples16k": 80000, "n_frames": 499, "n_tokens": 125, "bucket": 1024, "wave_file": "audio/ref/sound_chirp_siren_48k.wave16k.f32", "features_file": "audio/ref/sound_chirp_siren_48k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/sound_birds_rain_16k_stereo.m4a", "sample_rate": 16000, "channels": 2, "n_samples16k": 80000, "n_frames": 499, "n_tokens": 125, "bucket": 1024, "wave_file": "audio/ref/sound_birds_rain_16k_stereo.wave16k.f32", "features_file": "audio/ref/sound_birds_rain_16k_stereo.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "afconvert", "note": null }, { "file": "audio/edge_silence_1s_16k.wav", "sample_rate": 16000, "channels": 1, "n_samples16k": 16000, "n_frames": 99, "n_tokens": 25, "bucket": 192, "wave_file": "audio/ref/edge_silence_1s_16k.wave16k.f32", "features_file": "audio/ref/edge_silence_1s_16k.features.f32", "wave_tolerance": 0.0, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/edge_tiny_100smp_16k.wav", "sample_rate": 16000, "channels": 1, "n_samples16k": 100, "n_frames": 0, "n_tokens": 0, "bucket": 192, "wave_file": "audio/ref/edge_tiny_100smp_16k.wave16k.f32", "features_file": "audio/ref/edge_tiny_100smp_16k.features.f32", "wave_tolerance": 0.0, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/edge_tone_10khz_96k.wav", "sample_rate": 96000, "channels": 1, "n_samples16k": 32000, "n_frames": 199, "n_tokens": 50, "bucket": 384, "wave_file": "audio/ref/edge_tone_10khz_96k.wave16k.f32", "features_file": "audio/ref/edge_tone_10khz_96k.features.f32", "wave_tolerance": 1e-06, "feature_tolerance": 0.02, "python_decoder": "libsndfile", "note": null }, { "file": "audio/long_melody_35s_16k.mp3", "sample_rate": 16000, "channels": 1, "n_samples16k": 560000, "n_frames": 2999, "n_tokens": 750, "bucket": 3000, "wave_file": "audio/ref/long_melody_35s_16k.wave16k.f32", "features_file": "audio/ref/long_melody_35s_16k.features.f32", "wave_tolerance": 0.0001, "feature_tolerance": 1.0, "python_decoder": "libsndfile", "note": "mp3: libsndfile (Python) vs Apple (Swift) decoders differ by ~3e-5 per sample" }]123version https://git-lfs.github.com/spec/v1oid sha256:381583606c2987aff0e9ae56fc6d2af8d247e125b7ae59d0673c158a9d5fd431size 384044123version https://git-lfs.github.com/spec/v1oid sha256:9c9dc64b6d46a70f3a680f3d0e957436f31174fc84618c23fb1abe19920b3b39size 421676123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162[ { "name": "speech_en_train_16k", "file": "speech_en_train_16k.wav", "caption": "The night train to the coast stops twice before sunrise.", "sample_rate": 16000, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "espeak-ng en-us+m7 -s 150 (en)" }, { "name": "speech_en_parcel_8k", "file": "speech_en_parcel_8k.wav", "caption": "Please leave the parcel with the neighbour on the second floor.", "sample_rate": 8000, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "espeak-ng en-gb -s 130 (en)" }, { "name": "speech_it_mercato_22k", "file": "speech_it_mercato_22k.aiff", "caption": "Il mercato del sabato apre alle otto e chiude a mezzogiorno.", "sample_rate": 22050, "channels": 1, "format": "aiff pcm16", "lossy": false, "source": "espeak-ng it+m1 -s 130 (it); afconvert" }, { "name": "speech_fr_pont_44k", "file": "speech_fr_pont_44k.m4a", "caption": "Le petit pont de bois traverse la rivière derrière le moulin.", "sample_rate": 44100, "channels": 1, "format": "aac", "lossy": true, "source": "espeak-ng fr-fr -s 170 (fr); afconvert" }, { "name": "speech_de_garten_48k_stereo", "file": "speech_de_garten_48k_stereo.wav", "caption": "Der Gärtner gießt die Rosen jeden Abend nach sieben Uhr.", "sample_rate": 48000, "channels": 2, "format": "wav float32 stereo", "lossy": false, "source": "espeak-ng de -s 170 (de); right channel at 0.7" }, { "name": "speech_pt_barco_44k", "file": "speech_pt_barco_44k.caf", "caption": "O barco pequeno sai do porto todas as manhãs às seis.", "sample_rate": 44100, "channels": 1, "format": "caf alac", "lossy": false, "source": "espeak-ng pt+m1 -s 130 (pt); afconvert" }, { "name": "speech_es_tienda_16k", "file": "speech_es_tienda_16k.flac", "caption": "La tienda de la esquina vende pan fresco cada mañana.", "sample_rate": 16000, "channels": 1, "format": "flac", "lossy": false, "source": "espeak-ng es+f4 -s 150 (es); afconvert" }, { "name": "speech_sv_buss_22k", "file": "speech_sv_buss_22k.mp3", "caption": "Bussen till stranden går varje halvtimme på sommaren.", "sample_rate": 22050, "channels": 1, "format": "mp3", "lossy": true, "source": "espeak-ng sv -s 130 (sv); ffmpeg libmp3lame 96k" }, { "name": "sound_chord_piano_44k_stereo", "file": "sound_chord_piano_44k_stereo.wav", "caption": "three piano notes played together as a chord", "sample_rate": 44100, "channels": 2, "format": "wav pcm16 stereo", "lossy": false, "source": "numpy" }, { "name": "sound_clicks_noise_22k", "file": "sound_clicks_noise_22k.wav", "caption": "a steady metronome clicking over soft white noise", "sample_rate": 22050, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "numpy" }, { "name": "sound_chirp_siren_48k", "file": "sound_chirp_siren_48k.flac", "caption": "a rising chirp followed by a siren sweeping up and down", "sample_rate": 48000, "channels": 1, "format": "flac", "lossy": false, "source": "numpy; afconvert" }, { "name": "sound_birds_rain_16k_stereo", "file": "sound_birds_rain_16k_stereo.m4a", "caption": "birds chirping in light rain", "sample_rate": 16000, "channels": 2, "format": "aac stereo", "lossy": true, "source": "numpy; afconvert" }, { "name": "edge_silence_1s_16k", "file": "edge_silence_1s_16k.wav", "caption": null, "sample_rate": 16000, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "numpy: one second of digital silence" }, { "name": "edge_tiny_100smp_16k", "file": "edge_tiny_100smp_16k.wav", "caption": null, "sample_rate": 16000, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "numpy: 100 samples (0 frames, 0 tokens)" }, { "name": "edge_tone_10khz_96k", "file": "edge_tone_10khz_96k.wav", "caption": null, "sample_rate": 96000, "channels": 1, "format": "wav pcm16", "lossy": false, "source": "numpy: 440 Hz + 10 kHz tones (the 10 kHz is above the 8 kHz Nyquist of the model)" }, { "name": "long_melody_35s_16k", "file": "long_melody_35s_16k.mp3", "caption": "a simple repeating piano melody", "sample_rate": 16000, "channels": 1, "format": "mp3", "lossy": true, "source": "numpy; ffmpeg libmp3lame 96k; 35 s" }]1U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��U��123version https://git-lfs.github.com/spec/v1oid sha256:19b6e0b19a4dc3aac04d0e979910d85c83ebb7815c837fb4045a3cebdaf7ee84size 101888123version https://git-lfs.github.com/spec/v1oid sha256:2567b77a52392e8f0dc40bade829a63374eb026bedf494e15ed28c1f0e56c4basize 128000123version https://git-lfs.github.com/spec/v1oid sha256:6f4638c771e3a3b5180a4509e1a55bbc713e3616634ec468cf3812284bfd7d98size 1535488123version https://git-lfs.github.com/spec/v1oid sha256:d4a6b9daa6f1e4385cf1310f05431fa785da244ca2b0932133016651384c846csize 2240000123version https://git-lfs.github.com/spec/v1oid sha256:53b924a3b71bb2478852a8d1ca493e91308b3359d85ace339e15a2590da946casize 255488123version https://git-lfs.github.com/spec/v1oid sha256:e425c153bdc58bd84e73dbde653146597cf3ed1606a9fa569ffa59fe007f6934size 320000123version https://git-lfs.github.com/spec/v1oid sha256:2ad38e26bb8bf5c209d1a20468ecdbf1fede29373e9a5d85ae3fcab59a99816bsize 255488123version https://git-lfs.github.com/spec/v1oid sha256:bb52eff27889c682d46cbcdc984f7e1b41f59b36fd1671c0d8903a4ce88666e0size 320000123version https://git-lfs.github.com/spec/v1oid sha256:466751ffa6f1909515eb5693e7375c240ae2ef9130d7e9c8abf54162a8545386size 153088123version https://git-lfs.github.com/spec/v1oid sha256:e45747d1b1c14a21050f2614c58684be77cb3d85c343e6e697ae996458ff8252size 192000123version https://git-lfs.github.com/spec/v1oid sha256:2e115ff7e33f3f116fd1336f8142d80ced4610b5f9543c5af0932865d883cce9size 204288123version https://git-lfs.github.com/spec/v1oid sha256:33fd0381a39409fee2e421e90dd353885120268644e7b8ae676e5d550cef26a9size 256000123version https://git-lfs.github.com/spec/v1oid sha256:8bec6c3cafd40c2cfd464fb864da306f32b0eb3a6f8abb6d440251126f555ba4size 160768123version https://git-lfs.github.com/spec/v1oid sha256:c20659bd84f7bfd6fe9e695238cb4917fd981cde5f075e3c81fad3dd1dfa00a3size 201228123version https://git-lfs.github.com/spec/v1oid sha256:790833ec67d07977f1d685f89a8b64897e618dc7d08924c4edd0e94b869db258size 212480.gitattributes+38
CHANGELOG.md+86
CHECKSUMS.sha256+76-14
NOTICE+74-22
README.md+404-87
export/eg2_audio.pyAdded+372
export/export.py+86-12
model/MODEL-ATTRIBUTION.json+6-3
model/config.json+44
model/embeddinggemma-2-audio.aimodel/main.hashAdded+1
model/embeddinggemma-2-audio.aimodel/main.mlirbAdded+3
model/embeddinggemma-2-audio.aimodel/metadata.jsonAdded+8
python/eg2_audio_frontend.pyAdded+373
python/embeddinggemma2_coreai.py+229-44
python/requirements.lock+7-3
python/requirements.txt+5-1
python/smoke_test.py+28-19
swift/Package.swift+7-4
swift/Sources/EmbeddingGemma2CoreAI/AudioDecoder.swiftAdded+104
swift/Sources/EmbeddingGemma2CoreAI/AudioFrontend.swiftAdded+191
swift/Sources/EmbeddingGemma2CoreAI/AudioResampler.swiftAdded+122
swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift+156-8
swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift+1-1
swift/Sources/eg2-cli/main.swift+199-19
tests/audio-preprocess-cases.jsonAdded+242
tests/audio-smoke-reference.jsonAdded
tests/audio/edge_silence_1s_16k.wavAdded
tests/audio/edge_tiny_100smp_16k.wavAdded
tests/audio/edge_tone_10khz_96k.wavAdded+3
tests/audio/long_melody_35s_16k.mp3Added+3
tests/audio/manifest.jsonAdded+162
tests/audio/ref/edge_silence_1s_16k.features.f32Added+1
tests/audio/ref/edge_silence_1s_16k.wave16k.f32Added
tests/audio/ref/edge_tiny_100smp_16k.features.f32Added
tests/audio/ref/edge_tiny_100smp_16k.wave16k.f32Added
tests/audio/ref/edge_tone_10khz_96k.features.f32Added+3
tests/audio/ref/edge_tone_10khz_96k.wave16k.f32Added+3
tests/audio/ref/long_melody_35s_16k.features.f32Added+3
tests/audio/ref/long_melody_35s_16k.wave16k.f32Added+3
tests/audio/ref/sound_birds_rain_16k_stereo.features.f32Added+3
tests/audio/ref/sound_birds_rain_16k_stereo.wave16k.f32Added+3
tests/audio/ref/sound_chirp_siren_48k.features.f32Added+3
tests/audio/ref/sound_chirp_siren_48k.wave16k.f32Added+3
tests/audio/ref/sound_chord_piano_44k_stereo.features.f32Added+3
tests/audio/ref/sound_chord_piano_44k_stereo.wave16k.f32Added+3
tests/audio/ref/sound_clicks_noise_22k.features.f32Added+3
tests/audio/ref/sound_clicks_noise_22k.wave16k.f32Added+3
tests/audio/ref/speech_de_garten_48k_stereo.features.f32Added+3
tests/audio/ref/speech_de_garten_48k_stereo.wave16k.f32Added+3
tests/audio/ref/speech_en_parcel_8k.features.f32Added+3