v1.1-images
Browse filesFiles changed (47)
- .gitattributes+2
- CHANGELOG.md+56
- CHECKSUMS.sha256+44-16
- NOTICE+214-21
- README.md+462-238
- export/eg2_text_mm.pyAdded+55
- export/eg2_vision.pyAdded+232
- export/export.py+169-101
- model/MODEL-ATTRIBUTION.json+18-12
- model/config.json+46-12
- model/embeddinggemma-2-text-mm.aimodel/main.hashAdded+1
- model/embeddinggemma-2-text.aimodel/main.mlirb → model/embeddinggemma-2-text-mm.aimodel/main.mlirbRenamed+2-2
- model/embeddinggemma-2-text.aimodel/metadata.json → model/embeddinggemma-2-text-mm.aimodel/metadata.jsonRenamed+4-4
- model/embeddinggemma-2-text.aimodel/main.hashDeleted-1
- model/embeddinggemma-2-vision.aimodel/main.hashAdded+2
- model/embeddinggemma-2-vision.aimodel/main.mlirbAdded+3
- model/embeddinggemma-2-vision.aimodel/metadata.jsonAdded+8
- python/eg2_image.pyAdded+220
- python/embeddinggemma2_coreai.py+246-64
- python/requirements.lock+4-2
- python/requirements.txt+4-3
- python/smoke_test.py+17-30
- swift/Package.swift+4-3
- swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift+199-43
- swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swiftAdded+214
- swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swiftAdded+139
- swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swiftAdded+163
- swift/Sources/eg2-cli/main.swift+217-32
- tests/check_preprocess.pyAdded+65
- tests/image-smoke-reference.jsonAdded
- tests/images/chart_bar.pngAdded
- tests/images/diagram_flow.pngAdded
- tests/images/doc_invoice.pngAdded
- tests/images/edge_strip_1x300.pngAdded
- tests/images/edge_tiny_7x5.pngAdded
- tests/images/gray_letter.pngAdded
- tests/images/icon_rgba.pngAdded
- tests/images/manifest.jsonAdded+110
- tests/images/palette_chart.pngAdded
- tests/images/scene_sunset.jpgAdded
- tests/images/shape_red_circle.pngAdded
- tests/images/slide_launch.pngAdded
- tests/images/ui_login.pngAdded
- tests/make_image_smoke_reference.pyAdded+73
- tests/make_preprocess_cases.pyAdded+44
- tests/make_test_images.pyAdded+209
- tests/preprocess-cases.jsonAdded+134
34 unmodified lines35363734 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-text.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textmodel/tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text34 unmodified lines353637383934 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textmodel/embeddinggemma-2-text.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -textmodel/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 -text
12345# Changelog## 1.0 — 2026-10-12First release package.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Changelog## 1.1 — 2026-10-12Images. The vision encoder of google/embeddinggemma-2 is added, so text queries and images share one 768-d space(a text query finds a chart, a screenshot, a slide or a photo).- Model: new `model/embeddinggemma-2-vision.aimodel` (function `vision_2520`: one image as 2520 patches → 280soft tokens; one Neural Engine region plus the position-table gather, or entirely on the GPU). Its `patches`input takes integer pixel values 0–255 (exact in float16): the graph computes P − 127.5 and the 2/255 scale isfolded into the patch-embedding weights, so no input rounding is lost. The text asset is now`model/embeddinggemma-2-text-mm.aimodel` (functions `mm_32 … mm_2048`): the v1.0 text encoder with one addedinput mix for image soft tokens. With no soft tokens its outputs are **bit-identical** to v1.0 (verified on 466texts, every bucket), so text vectors indexed with 1.0 stay valid. It replaces `embeddinggemma-2-text.aimodel`.- Buckets: 32, 64, 128, **288**, 512, 1024, 2048 (288 replaces 256 so one image sequence of ≤ 284 tokens fits;texts of 129–256 tokens now run in the 288 bucket, bit-identical to v1.0's 256).- Two compute routes for images, chosen independently of text: Neural Engine (default; 369 ms per image, 2 msCPU, ~1 ms GPU, +8.3 W, 3.1 J per image) or GPU (125 ms per image, ~3× faster; 21 ms CPU, ~103 ms GPU, +28.5 W,3.8 J per image). Swift `imageCompute:`, CLI `--image-compute`, Python `image_compute=`; default = same as`compute`. README "Images: Neural Engine or GPU" compares them side by side.- Image parity vs fp32 sentence-transformers on the shipped assets (373 generated images, 30 extra tiny images, plus19 files made from 14 public-domain photos, used locally only): median cosine 0.99998 on the Neural Engine and1.00000 on the GPU; on the GPU image route every image ≥ 0.9989 with text on the Neural Engine and ≥ 0.99975 withtext on the GPU too; on the Neural Engine every image ≥ 0.9997 except heavily upscaled tiny images (worst 0.9946,a 16×16 image). An earlier set of 239 generated images was measured on a pre-release build of the image asset(pixel/255 inputs): min 0.99966. Cross-modal retrieval (205 captions, both directions) identical to fp32 at 768dims on all seven tested routes (Python: Neural Engine, GPU, mixed, CPU; Swift: Neural Engine, GPU, mixed):text→image R@1 0.937 / MRR 0.968; within 0.005 of fp32 at 512/256/128.- Exact preprocessing: the upstream size rule and the antialiased bicubic uint8 resize re-implemented in numpy(`python/eg2_image.py`) and Swift (`ImageResampler`), bit-identical to the upstream processor; a Swift raw-sampledecoder (ImageIO) that is bit-identical to the Python reference on lossless files (JPEG: see README).- Swift: same library and tool names as 1.0 (`EmbeddingGemma2CoreAI`, `eg2-cli`); the 1.0 API is unchanged andstill loads the text asset only. New: `EmbeddingGemma2(bundle:compute:loadVision:imageCompute:)`,`imageCompute`, `embedImage(url:)`,`embedImage(cgImage:)`, `softTokens`, `imageSequence`, `embed(sequence:)`, `hasVision`, `ImageDecoder`,`ImagePreprocessor`, `VisionInputs`. New CLI commands `embed-image`, `pixcheck`, `dump`; `smoke` takes severalreference files (text and image); `latency` / `prewarm` load the vision asset unless `--text-only`; everymodel command takes `--image-compute`. An unknown `--compute` value is now an error (1.0 silently used `ane`).- Python: `embeddinggemma2_coreai.py` keeps the 1.0 class and API (`load_vision=False` by default) and adds`embed_image`, `soft_tokens`, `image_sequence`, `embed_sequence`, `image_compute=` / `--image-compute`, the`embed-image` command and multi-file `smoke`; `eg2_image.py` is the reference preprocessing (patches of integerpixel values); `smoke_test.py` runs the text and image references. Pillow is a new requirement.- Tests: 12 images rendered from code (`tests/images/`, fictional content, size and colour-mode edge cases; theshipped files are the reference, a regeneration on another machine is not byte-identical),`image-smoke-reference.json` (fp32 vectors of 10 images, their 10 queries and 2 documents),`preprocess-cases.json` (decode/resize checksums), `check_preprocess.py` and the generators. The 1.0 textfixtures are unchanged.- Exporter: `export/export.py` now builds both assets (`eg2_text.py` unchanged, plus `eg2_text_mm.py` and`eg2_vision.py`).- NOTICE: the image resize is a port of ATen's uint8 antialiased bicubic kernel and the Swift CMYK conversion a portof Pillow's formula; NOTICE credits them as such and reproduces the PyTorch (BSD-3-Clause) and Pillow (MIT-CMU)license notices.Upgrading from 1.0: code that uses the libraries (`EmbeddingGemma2`, `EmbeddingGemma2CoreAI`) needs no change.Code that loads the `.aimodel` directly must use `config.json`'s `asset` / `functions` (now `mm_<S>`) and pass thetwo extra inputs (`mm_embeds` and `mm_mask`, zeros for text). The new asset has a new content hash, so the firstload after the upgrade pays the one-time specialization again.## 1.0 — 2026-10-12First release package.
12345678910111213141516171819202122232425267c059597beb76a3ce4e7cc6e0b08f6aa7e8eeb932ab9b18e13234ca9537809e1 CHANGELOG.mdcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSEdfaaa2df3d3b356d6ab7d37795893ca3916f9855095658700b35f387f8e7d68f NOTICE742bc793350bbe91c402dcdbc339403f671b46a8c953d366a41f803300b3f52b README.mdbb778eee49dab44fb997f67c875a615d754d54477e257d02771e94f250b4cd38 export/eg2_text.py9392857facca6d9b9a735146c72a342ffa8c52c7c752ea2c499acb10686a3cdc export/export.py7ddb494420af4401b1e3c6e0b54f176c218f9d5068079c9ccfa7871fad5f5a19 model/MODEL-ATTRIBUTION.json1791655ef7f1c0c093d200904263989c0f7cfc637869b71c6fc5f90f0f800f18 model/config.jsonc2de75ebee766df0e980f63bc56a60847272cfe393de744e766bee9ba1a8049b model/embeddinggemma-2-text.aimodel/main.hash75d38431abcd2471b0540c863357710d305cb1687295f5b0cf859de6ac9d46eb model/embeddinggemma-2-text.aimodel/main.mlirbc2362545fc6b46be69f394ff0081a6e919a9099b19a84b167fbdeb71ba7c793c model/embeddinggemma-2-text.aimodel/metadata.json4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 model/tokenizer/tokenizer.json17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 model/tokenizer/tokenizer_config.json2559a5e111a31b53e9568c962be2fb51ec84c17912bcfc40f0cafb7f73ca9f01 python/embeddinggemma2_coreai.py3bc2e5931e7dde258a82637e082bf9f12f9a6eed6c4cc703f9b8e4e02a9d3b0c python/requirements.lock2d7b80b555b56787f2a142da1164c359e306b7ad3332661ac158b3a1f114d581 python/requirements.txt3126ad6f90704e025f57632664fe1954a7c88b734a9e695441f471dff79d863e python/smoke_test.pyde934714b85d008c8e56b8027c86c0f1319bb3ca1bb0dec9ffe3ab7ca8c35876 swift/Package.swift5c36c78cf268da78c3a6981bcfd4974b94641f756fa9616950cd39ebe6fc096f swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift7b99edfefc47a343d07df32a3b06a8da2f94a49ae0a8e299e733c1a44c09e38f swift/Sources/EmbeddingGemma2CoreAI/ExactJSON.swift4f5ef8a454a84937e503ba99c9f05e237347178933a442f2352a2c5db0ad87eb swift/Sources/EmbeddingGemma2CoreAI/GemmaTokenizer.swiftf59a75b9eb311777bba3f8b1146b75a11f6587cdca5a2c1dab6fffc40d96a9aa swift/Sources/eg2-cli/main.swift1df8f74c85f4a02be0caaf4b99ee0bb8f4cfc1759ad091fdf65a98fdea917df8 tests/make_smoke_reference.py07daa7415beb15e9049a307aa17bf048ba2edaa0613301293e6250a66ed552b8 tests/make_tokenizer_cases.pydce930ac23f448c55d3e4fbf5e3d1080213395510637d627f67b54a889f339e1 tests/smoke-reference.json0797f417a0fa96270dc2f439478000fe3b3a235eb1e83b3054cf69674e323ae9 tests/tokenizer-cases.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354eba43e8b37c1451b6d52dde5e2d0fec9adf9f8532e25c371cc905b8a7ff74b3c 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.jsonce93c518c185454be41b493738f9ab3d5b662dd0306d1007cd4e12ad4c0baaa5 model/embeddinggemma-2-vision.aimodel/main.hash01e50a398ae9e003fd6bb5f1c74544032474394912b7c7396965f98b15423f19 model/embeddinggemma-2-vision.aimodel/main.mlirb45bb764a8df5e1b2a6ef4260d4dd006a57dc7af4f408f07ed2976022cd39390c 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.png094d8d1a380f8b62ef465771c9268211a6614facc61f7602ffeffbc1588c1ef9 tests/images/diagram_flow.png96aa4aca365749e910f89d07571c5cf962169d29dbcfd33c8a840f55bca56faa tests/images/doc_invoice.png032391242ca26c6855f08a7708a40629479029804140105293e19ae61ee59793 tests/images/edge_strip_1x300.png21da69eb63ba98434ba289b25b4fb2401c17a9b715e44c75110116cfac10e89c tests/images/edge_tiny_7x5.png80288c639feed7150f5998f8a64c699343ca9d64711b7f33ee3ef78786c921ca tests/images/gray_letter.pngd0b2bd592499a3244a337c47bd8ce91c6d77542f0eb4b463c499016e1e3bddce tests/images/icon_rgba.png9dc1916cfa2278a94814e8cfba1f60b69ebaeccb48b577d8dd0c5bafbf786139 tests/images/manifest.json68a420c94d9b0e31cd520ea0a056919560d1a57679cf104806304ce020e7a472 tests/images/palette_chart.png5e4ffaf8045ba649aedabbe46fd6ac1b52c5f4df639f2dd82551c7f7fe898441 tests/images/scene_sunset.jpg363dd39880ce42d00f459466680bd30bee9ab164be4fbddb2411b42937f2aeb6 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.jsondce930ac23f448c55d3e4fbf5e3d1080213395510637d627f67b54a889f339e1 tests/smoke-reference.json0797f417a0fa96270dc2f439478000fe3b3a235eb1e83b3054cf69674e323ae9 tests/tokenizer-cases.json
1234517 unmodified lines2324252627282930313233343536373839404142434445464748493 unmodified lines5354555657585960616263646566676869707 unmodified lines7879808182838485EmbeddingGemma-2-CoreAI-text v1.0=================================This package contains a derivative of the EmbeddingGemma 2 model.17 unmodified linesMODIFICATIONS (Apache License, Section 4(b))--------------------------------------------Changes made to google/embeddinggemma-2, 11-12 October 2026, to produce model/embeddinggemma-2-text.aimodel:2026-10-11 Text encoder only. The vision and audio encoders of the multimodal checkpoint were dropped.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 AIconverter. The weights are the original ones, rounded from bfloat16 to float16; the sqrt(512)token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into the tables.2026-10-11 fp16 handling for the Neural Engine: every RMSNorm and the final L2 normalization divide the rowby its max-abs value before squaring (activations reach ~2000, whose square overflows fp16);in the model code every division is expressed as rsqrt(x)*rsqrt(x); the additive attention-maskvalue is -10000. (The model card advises against float16; this rescaling is what makes fp16safe here, see the parity figures in README.md.)2026-10-11 Pooling, projection and normalization run inside the graph; the output is the final embedding.2026-10-11 Fixed sequence buckets: one function main_<S> per S in 32, 64, 128, 256, 512, 1024, 2048.Input longer than 2048 tokens is not supported by this build (the original accepts 8192).2026-10-12 Attention of the four global (full-attention, single key/value head) layers rewritten from a5-D grouped matmul to an equivalent plain 4-D matmul with the key/value tensors broadcast overthe four query heads, so that the Neural Engine compiler accepts the whole graph. Mathematicallyidentical to the reference (fp32 max abs diff 3e-7).2026-10-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).The exporter in export/ reproduces these changes from the original checkpoint.3 unmodified lines------------------------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 fromtransformers 5.19. No transformers source files are included in this package; the re-authored module carriesits own Apache-2.0 header and credits transformers.FluidInference Core ML port of EmbeddingGemma 2 (Apache-2.0, https://huggingface.co/FluidInference). Theidea of dividing each RMSNorm row by its max-abs value to keep fp16 in range was taken from the README ofthat port and re-derived independently; no code was copied from it. Nothing else in this package derives fromit.Apple Core AI (coreai-torch, coreai-core, the CoreAI framework): used as tools and runtime, not redistributed.Hugging Face tokenizers (Apache-2.0): used by the Python runner and to generate the test fixtures; notredistributed.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 (tests/)and the documentation, isCopyright 2026 EverpaperLicensed under the Apache License, Version 2.0 (LICENSE).1234517 unmodified lines2324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990913 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261277 unmodified lines135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278EmbeddingGemma-2-CoreAI v1.1============================This package contains a derivative of the EmbeddingGemma 2 model.17 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 AIconverter. The weights are the original ones rounded from bfloat16 to float16, except that thesqrt(512) token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into thetables.2026-10-11 fp16 handling for the Neural Engine: every RMSNorm and the final L2 normalization divide the rowby its max-abs value before squaring (activations reach ~2000, whose square overflows fp16);in the model code every division is expressed as rsqrt(x)*rsqrt(x); the additive attention-maskvalue is -10000. (The model card advises against float16; this rescaling is what makes fp16safe here, see the parity figures in README.md.)2026-10-11 Pooling, projection and normalization run inside the graph; the output is the final embedding.2026-10-11 Fixed sequence buckets, one function per bucket. Input longer than 2048 tokens is not supportedby this build (the original accepts 8192).2026-10-12 Attention of the four global (full-attention, single key/value head) layers rewritten from a5-D grouped matmul to an equivalent plain 4-D matmul with the key/value tensors broadcast overthe four query heads, so that the Neural Engine compiler accepts the whole graph. Mathematicallyidentical to the reference (fp32 max abs diff 3e-7).Added in v1.1:2026-10-12 Text: one input mix at the start of the graph, x = embed(input_ids) * (1 - mm_mask) +mm_embeds * mm_mask, so that externally computed image soft tokens replace the <|image|>placeholder embeddings. Soft tokens are not scaled; everything after the mix is the v1.0 textgraph, and with zero soft tokens the outputs are bit-identical to v1.0. The functions are nowmm_<S> for S in 32, 64, 128, 288, 512, 1024, 2048 (288 replaces 256 so that one image sequence ofat most 284 tokens fits). This asset replaces v1.0's model/embeddinggemma-2-text.aimodel.2026-10-12 Vision encoder (Gemma 4 vision model: patch embedder, 16 bidirectional encoder layers with axial2-D RoPE, 3x3 average pooling) and the vision embedder (RMSNorm + 768->512 projection) re-authoredin plain PyTorch for the Core AI converter. The weights are the original ones rounded frombfloat16 to float16, with the scale fold and table cut described in the next entries (the 2/255input scale folded into the patch-embedding projection, the position tables cut to 840 rows).2026-10-12 Vision: one fixed shape, the default budget of 280 soft tokens (2520 patches of 16x16 px). Thepatches are fed in "cell-major" order (the 9 patches of each 3x3 pooling cell contiguous, cellsrow-major, padding last) so that the pooling is a reshape and a mean instead of a one-hot matmul.Attention is permutation-equivariant, so the result is identical.2026-10-12 Vision: the pooler's multiplication by sqrt(768) (computed in float32 upstream because it exceedsthe float16 range) is dropped and the vision embedder's RMSNorm uses eps/768 instead of eps:RMSNorm(x*s, eps) == RMSNorm(x, eps/s^2) exactly.2026-10-12 Vision: the 2-D position-embedding tables (2 x 10240 x 768) are cut to the 840 rows that an imageof this budget can address; the axial-RoPE cos/sin tables and the key mask are inputs computed bythe host instead of being computed in the graph.2026-10-12 Vision fp16 handling for the Neural Engine: every RMSNorm divides the row by its max-abs valuebefore squaring (the vision residual reaches ~1400), divisions are expressed as rsqrt(x)*rsqrt(x),the additive key-mask value is -10000, the 3x3 mean is a sum times 1/9. The attention queries areprocessed in 12 blocks (same result, lower Neural Engine latency).2026-10-12 Vision input scaling: the model takes integer pixel values 0..255 (exact in float16) instead ofpixel/255. The graph computes P - 127.5 and the 2/255 factor is folded into the weights of thepatch-embedding projection, which equals upstream's projection of 2*(P/255) - 1 without roundingthe inputs to float16 (that rounding cost heavily upscaled tiny images up to 0.004 of cosine).2026-10-12 Image preprocessing (host side, not part of the model): the upstream image processor'saspect-preserving size rule and its antialiased bicubic resize on 8-bit pixels (the ATen uint8kernel 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).The exporter in export/ reproduces these changes from the original checkpoint.3 unmodified lines------------------------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 uint8`_upsample_bicubic2d_aa` kernel (aten/src/ATen/native/cpu/UpSampleKernel.cpp: the tap-index and weight helpers`_compute_indices_min_size_weights_aa` / `_compute_index_ranges_int16_weights`, the dynamic int16 precision andthe separable uint8 passes), which torchvision uses for `resize(..., BICUBIC, antialias=True)`. No PyTorchsource file is included; the port is translated to numpy and Swift.Pillow (MIT-CMU / HPND, notice below). The ATen kernel above is itself modelled on Pillow's Resample.c, andthe CMYK -> RGB conversion in swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swift is ported from Pillow'sconversion formula so that CMYK files embed like the reference. No Pillow source file is included. The Pythonrunner uses Pillow to decode images; it is not redistributed.FluidInference Core ML port of EmbeddingGemma 2 (Apache-2.0, https://huggingface.co/FluidInference). The idea ofdividing 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).The parts ported from transformers, PyTorch and Pillow (see THIRD-PARTY ATTRIBUTIONS) also remain subject tothose 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 NOTICES---------------------------Reproduced as their licenses require, for the ported logic described under THIRD-PARTY ATTRIBUTIONS.PyTorch (BSD-3-Clause), from the LICENSE file of PyTorch 2.9.0:From PyTorch:Copyright (c) 2016- Facebook, Inc (Adam Paszke)Copyright (c) 2014- Facebook, Inc (Soumith Chintala)Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)Copyright (c) 2011-2013 NYU (Clement Farabet)Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)Copyright (c) 2006 Idiap Research Institute (Samy Bengio)Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)From Caffe2:Copyright (c) 2016-present, Facebook Inc. All rights reserved.All contributions by Facebook:Copyright (c) 2016 Facebook Inc.All contributions by Google:Copyright (c) 2015 Google Inc.All rights reserved.All contributions by Yangqing Jia:Copyright (c) 2015 Yangqing JiaAll rights reserved.All contributions by Kakao Brain:Copyright 2019-2020 Kakao BrainAll contributions by Cruise LLC:Copyright (c) 2022 Cruise LLC.All rights reserved.All contributions by Tri Dao:Copyright (c) 2024 Tri Dao.All rights reserved.All contributions by Arm:Copyright (c) 2021, 2023-2024 Arm Limited and/or its affiliatesAll contributions from Caffe:Copyright(c) 2013, 2014, 2015, the respective contributorsAll rights reserved.All other contributions:Copyright(c) 2015, 2016 the respective contributorsAll rights reserved.Caffe2 uses a copyright model similar to Caffe: each contributor holdscopyright over their contributions to Caffe2. The project versioning recordsall such contribution and copyright details. If a contributor wants to furthermark their specific copyright on a particular contribution, they shouldindicate their copyright solely in the commit message of the change when it iscommitted.All rights reserved.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:1. Redistributions of source code must retain the above copyrightnotice, this list of conditions and the following disclaimer.2. Redistributions in binary form must reproduce the above copyrightnotice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution.3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories Americaand IDIAP Research Institute nor the names of its contributors may beused to endorse or promote products derived from this software withoutspecific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BELIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESSINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER INCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.Pillow (MIT-CMU / HPND), from the LICENSE file of Pillow 12.3.0:The Python Imaging Library (PIL) isCopyright © 1997-2011 by Secret Labs ABCopyright © 1995-2011 by Fredrik Lundh and contributorsPillow is the friendly PIL fork. It isCopyright © 2010 by Jeffrey 'Alex' Clark and contributorsLike PIL, Pillow is licensed under the open source MIT-CMU License:By obtaining, using, and/or copying this software and/or its associateddocumentation, you agree that you have read, understood, and will complywith the following terms and conditions:Permission to use, copy, modify and distribute this software and itsdocumentation for any purpose and without fee is hereby granted,provided that the above copyright notice appears in all copies, and thatboth that copyright notice and this permission notice appear in supportingdocumentation, and that the name of Secret Labs AB or the author not beused in advertising or publicity pertaining to distribution of the softwarewithout specific, written prior permission.SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THISSOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROMLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCEOR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ORPERFORMANCE OF THIS SOFTWARE.
10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063 unmodified lines31031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534610 unmodified lines- on-device- embeddings- sentence-similarity- gemma- macos---# EmbeddingGemma 2 (text) for Apple Core AIThe text encoder of [google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) (Gemma 4 family,~270 M parameters, 768-d Matryoshka embeddings) converted to Apple's **Core AI** runtime for **macOS 27 on Applesilicon**. One graph does everything `SentenceTransformer("google/embeddinggemma-2").encode()` does for text: tokenembedding, 24 bidirectional encoder layers, final norm, 512→768 projection, masked mean pooling and L2normalization. Every function runs as one Neural Engine region plus the token lookup (a small GPU gather), so adocument costs about **0.3 ms of CPU** and **0.4–0.5 ms of GPU time**; the Neural Engine does the rest.Ported by Everpaper — everpaper.app. Weights are the original ones (bf16 rounded to fp16). Apache-2.0, see[LICENSE](LICENSE) and [NOTICE](NOTICE) (modification list, Gemma Prohibited Use Policy pointer).## Download```bashhf download iannedev/embeddinggemma-2-coreai --local-dir EmbeddingGemma-2-CoreAI-text-v1.0cd EmbeddingGemma-2-CoreAI-text-v1.0```(`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.## What is in the package```EmbeddingGemma-2-CoreAI-text-v1.0/README.md, LICENSE, NOTICE, CHANGELOG.md, CHECKSUMS.sha256model/embeddinggemma-2-text.aimodel/ Core AI asset: functions main_32 … main_2048 (fp16, 631.5 MB = 602 MiB)config.json buckets, prompts, special ids, 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 dependencies)python/ embeddinggemma2_coreai.py (library + CLI), smoke_test.py, requirements(.lock)tests/ smoke-reference.json, tokenizer-cases.json (+ the scripts that generate them)export/ eg2_text.py + export.py: reproduce the .aimodel from the original checkpoint```## Requirements- macOS 27.0 or later on Apple silicon (the package was validated on an M5 with 24 GB; macOS 27.0 build26A5406e, Xcode 27 beta).- Swift: Xcode 27 / Swift 6 toolchain; the `CoreAI` framework is part of the macOS 27 SDK.- Python (runtime): Python 3.12 or 3.14 (both validated), Apple's `coreai-core` Python runtime (provides`coreai.runtime`), `numpy`, `tokenizers` (`python/requirements.txt`; the exact validated versions are in`python/requirements.lock`). Only the exporter (`export/`, optional) needs Python 3.12, for torch 2.9.0.- Disk: 664 MB for `model/` (the `.aimodel` is 631.5 MB, the tokenizer 32 MB); the system keeps a per-executablespecialization cache of about 1.4 GB under `~/Library/Caches/coreai-cache/`.## Inputs and outputs| | ||---|---|| Functions | `main_32`, `main_64`, `main_128`, `main_256`, `main_512`, `main_1024`, `main_2048` (one per sequence bucket S) || `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 || `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 (verified: padded and unpadded runs are bit-identical). || Matryoshka | 512 / 256 / 128 dims: take the first N values and re-normalize (`embed(..., dim:)` does it). |**Task prompts** (exactly the upstream `config_sentence_transformers.json`; the runners prepend them by `kind`):| kind | prefix ||---|---|| `document` | `title: none \| text: ` — for titled documents use `title: {title} \| text: {content}` yourself || `search_query` | `task: search result \| query: ` || `question_answering` | `task: question answering \| query: ` || `fact_checking` | `task: fact checking \| query: ` || `code_retrieval` | `task: code retrieval \| query: ` || `classification` | `task: classification \| query: ` || `clustering` | `task: clustering \| query: ` || `sentence_similarity` | `task: sentence similarity \| query: ` |The tokenizer is the original Gemma `tokenizer.json`. The runners add `<bos>` and `<eos>` themselves, assentence-transformers does. Note that special tokens written literally in a text (e.g. `<eos>`) are recognised asspecial tokens, exactly as in Hugging Face `tokenizers`; strip them if that is not what you want.## Quick start — Swift```swift// Package.swift: .package(path: "…/EmbeddingGemma-2-CoreAI-text-v1.0/swift"), product "EmbeddingGemma2CoreAI"import EmbeddingGemma2CoreAIlet model = try await EmbeddingGemma2(bundle: URL(fileURLWithPath: "…/model"), compute: .neuralEngine)try await model.prewarm() // optional, one call per bucket (~0.4 s warm)let q = try await model.embed("When does the warehouse lease expire?", kind: "search_query") // [Float], 768let d = try await model.embed("The lease runs until the last day of March.", kind: "document", dim: 256)let score = cosineSimilarity(q, try await model.embed("The lease runs until the last day of March.", kind: "document"))// lower level: your own ids -> raw output of one bucketlet ids = model.tokenize("some text", kind: "document") // <bos> + prefix + text + <eos>, truncated to 2048let raw = try await model.embed(ids: ids) // runs main_<smallest bucket that fits>// when the model is released (or at exit) you may delete the temp files this process created, see "Temp files"EmbeddingGemma2.removeOwnMPSGraphTempFiles()````GemmaTokenizer` is public too (`encode`, `encodeWithSpecials`, `decode`): an exact re-implementation of theHugging Face `tokenizers` pipeline for this `tokenizer.json`, with no dependencies (see "Tokenizer" below).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 --compute ane --cleanup-tempeg2-cli embed ../model --kind search_query "When does the warehouse lease expire?"eg2-cli tokcheck ../model ../tests/tokenizer-cases.jsoneg2-cli latency ../model --compute ane --trials 50eg2-cli prewarm ../model```## Quick start — PythonFrom the package folder:```python3 -m venv .venv && .venv/bin/pip install -r python/requirements.txtsource .venv/bin/activatecd python && python3 smoke_test.py --compute ane --cleanup-temp # first run: up to ~145 s to load, see below``````pythonfrom embeddinggemma2_coreai import EmbeddingGemma2CoreAI, remove_own_mpsgraph_temp_filesm = EmbeddingGemma2CoreAI("../model", compute="ane") # ane | gpu | cpu | defaultm.prewarm()q = m.embed("When does the warehouse lease expire?", kind="search_query") # numpy float32 [768]d = m.embed("The lease runs until the last day of March.", kind="document", dim=256)del mremove_own_mpsgraph_temp_files() # the Python runtime leaks ~358 MB per load, see below````python3 embeddinggemma2_coreai.py embed|smoke|tokcheck|latency|prewarm …` mirrors the Swift tool (run it with thevenv's Python, as above).## Accuracy (measured)Reference: sentence-transformers 6.1 / transformers 5.19, fp32, CPU, original checkpoint. Test set: 357 fictionaltexts (English and Italian documents and queries, code, mixed-language, Unicode/number/repetition stress cases, andtexts whose length lands exactly on each bucket boundary), 2 to 2048 tokens. The people, companies and events inthe test material are fictional; a few real place names appear in the multilingual stress texts.**Parity** — cosine similarity between this port and the fp32 reference, full 768 dims (128-dim Matryoshka inbrackets):| route | min | median | worst category ||---|---|---|---|| Neural Engine (`compute: .neuralEngine`), Swift and Python | 0.99992 (0.99995) | 0.99997 (0.99998) | 33-token bucket-boundary text || GPU (`compute: .gpu`) | 0.99998 (0.99999) | 0.999999 (1.000000) | code || CPU only (`compute: .cpu`), Swift and Python | 0.99916 (0.99914) | 0.99996 (0.99998) | 2047-token text (the CPU fp16 path is the least precise) || for scale: the original model itself in bf16 on the GPU (PyTorch MPS) | 0.99956 | 0.99996 | |Per bucket on the Neural Engine the minimum is 0.99992–0.99996 and the median 0.99997–0.99998; no NaN/Inf on anyinput, including fully padded and 1-token inputs. Texts longer than 2048 tokens are truncated by design and theircosine to the full-length reference falls as expected (0.998 at 2100 tokens, 0.98 at 4500).**Independent check.** A second, separate set of 100 new fictional texts (Italian, emoji, CRLF, Thai and otherscripts, NFD accents, code, one-word inputs, long texts, exact bucket boundaries, all 8 prompt kinds) against afreshly downloaded fp32 sentence-transformers reference, Neural Engine route: minimum cosine 0.99985 (an emoji-heavytext), median 0.99997 at 768 dims; 0.99993 / 0.999985 at 128 dims; Swift and Python identical (largest difference2.7e-7). **Expect a cosine ≥ 0.9998 to the fp32 model on the Neural Engine and GPU routes, ≥ 0.999 on the CPU route.****About float16.** The upstream model card says *"Do not use float16"*: the model's activations exceed the fp16range and a naive fp16 run returns NaN or degraded vectors. This port runs in fp16 on purpose (the Neural Engine isfp16-only) and avoids the overflow by dividing every RMSNorm row and the final L2 normalization by its max-abs valuebefore squaring (see NOTICE). The parity figures above are the evidence that this works; if you change the graph, keepthat rescaling.**Retrieval** — 1,712 fictional passages, 53 queries (16 Italian), gold ranks compared rank-by-rank with the fp32reference:| dims | fp32 reference MRR | this port, Neural Engine, MRR | queries with the same first-relevant rank ||---|---|---|---|| 768 | 0.766 | 0.766 | 53 / 53 || 512 | 0.790 | 0.782 | 51 / 53 || 256 | 0.786 | 0.785 | 52 / 53 || 128 | 0.735 | 0.735 | 52 / 53 |The flipped ranks are gold passages moving by one rank among near-tied neighbours (e.g. fp32 scores 0.82757 vs0.82755 at 512 dims) plus one query whose gold passage sits outside the top 10 in fp32 and at rank 10 here.Italian MRR is identical at every size (0.831 / 0.830 / 0.834 / 0.716). The GPU route of this bundle was checkedfor parity (table above) but not re-run on the retrieval benchmark.**Smoke test** (`tests/smoke-reference.json`, 3 fictional sentences, threshold 0.999): Neural Engine cosine0.999948 / 0.999979 / 0.999976 (Swift and Python); Matryoshka 512 / 256 / 128 of the second sentence 0.999979 /0.999981 / 0.999989. GPU route 0.999999 / 0.999999 / 1.000000, CPU route 0.999970 / 0.999966 / 0.999970.Caveats: these are one machine's numbers (M5, macOS 27.0 26A5406e). Core AI specializes the graph per machineand OS build; the CPU-only route in particular depends on the OS's fp16 CPU kernels. Re-run `smoke` and, if youcare about the last digit, `tests/` on your target machines.## Performance (measured, Swift `eg2-cli latency`, 50 trials per bucket, M5)Single runs on one machine; repeated runs differ by a few percent (e.g. 195–199 ms at 2048 tokens on the NeuralEngine).| bucket (tokens) | Neural Engine p50 | CPU ms per call (NE) | GPU route p50 | CPU ms per call (GPU) ||---|---|---|---|---|| 32 | 4.8 ms | 0.24 | 7.6 ms | 10.3 || 64 | 5.3 ms | 0.24 | 7.9 ms | 10.3 || 128 | 6.6 ms | 0.26 | 10.3 ms | 11.1 || 256 | 11.6 ms | 0.27 | 12.2 ms | 11.7 || 512 | 27.8 ms | 0.26 | 21.9 ms | 14.8 || 1024 | 69 ms | 0.33 | 49 ms | 20.1 || 2048 | 195 ms | 0.39 | 142 ms | 30.6 |The Python runner gives the same Neural Engine latencies within a few percent (CPU per call 0.4–0.9 ms). On theNeural Engine route the GPU is used only for the int32 token gather: 0.38–0.54 ms of GPU time per call (32–1024tokens), measured during validation with `task_power_info_v2` over 100-call batches. The GPU route is faster from 512tokens up but burns 10–30 ms of CPU per call (MPSGraph encoding) and 1.5 GB of memory.Throughput on a realistic corpus (1,712 passages, median 194 tokens, one text per call): about 50 passages/s,0.17 CPU-seconds per 100 passages.Memory: process footprint ~230 MB after a warm load (peak ~700 MB during the first-ever load) plus ~600–770 MB ofNeural Engine footprint reported by the kernel; the GPU route peaks at ~1.5 GB.**Load time** (`AIModel(contentsOf:)` + `loadFunction` for the 7 buckets):| situation | time ||---|---|| warm (this executable has loaded this bundle before) | 0.4–1.5 s, plus 0.35 s for `prewarm()` || **first load by an executable that has not loaded this bundle before** (a new app, a new binary name, the Python interpreter, a new machine) | **~140 s** (139–144 s measured with three different executables) || first load by a new executable on a machine where another executable already compiled this exact bundle | can be shorter (~25–30 s observed), do not rely on it || GPU route, first load | ~9–22 s |Recommendation: load and `prewarm()` in the background at app start (or in an installer / first-run step) and showprogress; never on the main thread and never lazily in front of the first query. The cache lives in`~/Library/Caches/coreai-cache/<OS build>/<executable name>/` (about 1.4 GB per bundle per executable name, keyedby the bundle's content hash) and survives reboots but not OS updates, a renamed executable or a re-exportedbundle. The tokenizer loads in 0.22 s (Swift) / 0.23 s (Python).## Temp files (please read)Each Neural Engine load writes ~358 MB of compiled-graph copies to`$TMPDIR/com.apple.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/`. Measured on macOS 27.0:- Swift (`CoreAI` framework): the folder is deleted again by the runtime when the model is released; our CLI, whichreleases the model and then exits, leaves nothing behind in any of our runs. If your app exits or is killed whilethe model is loaded, the folder may remain.- Python (`coreai.runtime`): the folder is **never** deleted, not even after `del model` and a clean interpreter exit(358 MB per load, verified for normal exit, `os._exit`, and `kill -9`). Over a day of development this fills a disk.Both runners therefore ship a cleanup that removes only the folders belonging to the **current process** (its pid,created after the process started): `EmbeddingGemma2.removeOwnMPSGraphTempFiles()` and`remove_own_mpsgraph_temp_files()`, or `--cleanup-temp` on every CLI command. Call it after the model has beenreleased, or at exit. Folders of other processes are never touched; a leftover from a crashed run has to be removedby hand (the folder name carries the pid and date).## TokenizerThe Swift `GemmaTokenizer` re-implements the Hugging Face `tokenizers` pipeline described by `tokenizer.json`(special-token extraction, `Replace " " → "▁"` normalizer, BPE with byte fallback, rank-ordered merges withposition tie-break). It works on Unicode scalars and exact UTF-8 bytes: no grapheme clusters, nocanonical-equivalence string comparisons, and `tokenizer.json` is read with an exact JSON reader because Foundation's`JSONSerialization` strips a leading U+FEFF from string values (which silently corrupts three vocabulary entries).Proof: `tests/tokenizer-cases.json` holds 3,758 fictional texts (608,225 ids) covering CRLF and mixed line endings,NFD / NFKD / mixed-normalization accents, emoji ZWJ sequences, skin tones, flags and keycaps, Arabic and Persianwith diacritics, Hebrew, Thai, Hindi, Bengali, Tamil, Chinese (simplified and traditional), Japanese, Korean,Georgian, Armenian, Amharic and 18 more languages, whitespace runs of 31–500 spaces / newlines / tabs / NBSP /ideographic spaces, control characters and invisible code points, special-token look-alikes (`<bos>`, `<|tool>`,`<start_of_turn>`, `< bos >`, `▁<bos>▁`, …), empty and 1-character inputs, random code points from 23 Unicode blocksincluding unassigned, private-use and non-characters, and inputs of 5,000–80,000 characters. `eg2-cli tokcheck`reports **3758 / 3758 identical** to `tokenizers` 0.23.3, in 0.15 s. The Python runner uses `tokenizers` directly.Regenerate the fixture with `tests/make_tokenizer_cases.py` (needs `tokenizers`) and the reference vectors with`tests/make_smoke_reference.py` (needs sentence-transformers and the original checkpoint).## Known issues and limitations- **2048-token cap.** Longer inputs are truncated by the runners. Buckets of 4096/8192 can be exported(`export.py --buckets …,4096,8192`) but were not validated here and would run on the GPU.- **One text per call.** The functions are batch-1. Throughput for a corpus comes from calling them back to back;running two or four calls concurrently did not increase throughput in our tests (the Neural Engine serializes).- **Short inputs are not faster than ~4.8 ms.** There is a per-call floor in this Core AI build; 32- and 64-tokeninputs cost the same.- **CPU-only route is less precise** (cosine ≥ 0.9991) — use it only as a fallback.- **Latency is not shape-stable across bucket sets.** Core AI specializes the whole function set together; addingor removing buckets changed the 512-token latency by half (22 vs 34 ms) in our experiments. Measure the exactbucket set you ship.- **Specialization cache is per executable name.** Renaming your binary costs one first load of up to ~140 s.- **Temp files** as described above.- **fp16 output.** The embedding is fp16 (relative precision ~5e-4); convert to float32 before accumulating dotproducts over many vectors, 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.3 unmodified lines# a separate environment with Python 3.12 (torch 2.9.0); exact versions in python/requirements.lockpython3.12 -m venv .venv-export && source .venv-export/bin/activatepip install coreai-core==1.0.0b3 torch==2.9.0 coreai-torch==0.4.3 coreai-opt==0.3.0 torchao==0.17.0 \safetensors numpy tokenizers huggingface-hub# the original checkpoint: config.json, model.safetensors, tokenizer.json, tokenizer_config.jsonhf download google/embeddinggemma-2 --local-dir ./embeddinggemma-2cd exportpython3 -W ignore export.py --model-dir ../embeddinggemma-2 --out ../model-rebuilt --name embeddinggemma-2-text \--mode ane --buckets 32,64,128,256,512,1024,2048 --date 2026-10-12````eg2_text.py` is the re-authored encoder (plain PyTorch, `PRECISION_MODE = "ane"`: all fp16, max-abs-rescalednorms, no divides in the model code; `GLOBAL_ATTN_MODE = "mqa4d"`). `export.py` does one dynamic-length `torch.export`, converts with`coreai_torch.TorchConverter`, clones the entry point per bucket with `set_static_shape_config`, and writes thebundle (~20 s). torchao must be 0.17.0 with torch 2.9 (0.18 breaks `import coreai_opt`).The rebuilt bundle is **functionally identical, not byte-identical**: its smoke-test cosines match the shipped bundleto all printed digits (0.999948 / 0.999979 / 0.999976), but the converter names internal graph resources at random,so `main.mlirb` and `main.hash` differ by a few KB, and the runtime writes `metadata.json` with the export time andits own key order. `config.json`, `MODEL-ATTRIBUTION.json` (with `--date 2026-10-12`) and the tokenizer files come outbyte-identical, so those four entries of `CHECKSUMS.sha256` match. Verify a rebuild with `smoke`, not withchecksums. A rebuilt bundle has a new content hash, so its first load takes the full ~140 s again.To check Neural Engine eligibility without running: `xcrun coreai-build compile model/embeddinggemma-2-text.aimodel--output ./compiled --preferred-compute neural-engine --architecture h17g 2>&1 | grep -c ane_validation_message`prints 0 for this bundle (no op rejected; the output folder is about 700 MB, delete it afterwards).## 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 reference: Hugging Face transformers (Apache-2.0).- 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, tokenizer and tests: 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.10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295303 unmodified lines53453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957010 unmodified lines- on-device- embeddings- 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 L2normalization. One Neural Engine region plus the token lookup (a small GPU gather): about **5 ms, 0.3 ms of CPUand 0.4–0.5 ms of GPU time** per short text.- **Images** — the 16-layer vision encoder turns an image into 280 "soft tokens" that go through the same textencoder, exactly as upstream does, plus an exact host-side preprocessing (decode, resize, patches) shipped inSwift 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, see[LICENSE](LICENSE) and [NOTICE](NOTICE) (modification list, Gemma Prohibited Use Policy pointer).## 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)let q = try await model.embed("bar chart of lamp units sold per city", kind: "search_query") // [Float], 768let d = try await model.embed("The lease runs until the last day of March.", kind: "document", dim: 256)// images, same space (two of the package's test images)let imageURL = pkg.appendingPathComponent("tests/images/chart_bar.png")let photoURL = pkg.appendingPathComponent("tests/images/scene_sunset.jpg")let img = try await model.embedImage(url: imageURL) // as stored, no EXIF rotationlet photo = try await model.embedImage(url: photoURL, applyEXIFOrientation: true) // camera photos upright// let shot = try await model.embedImage(cgImage: someCGImage) // raw samples of a CGImagelet score = cosineSimilarity(q, img)// lower levellet ids = model.tokenize("some text", kind: "document") // <bos> + prefix + text + <eos>, truncated to 2048let raw = try await model.embed(ids: ids) // runs mm_<smallest bucket that fits>let inputs = try ImagePreprocessor.prepare(url: imageURL) // decode + exact resize + patches (CPU, ~10 ms typical)let soft = try await model.softTokens(inputs) // [n * 512] Float16 (vision_2520)let rawImage = try await model.embed(sequence: model.imageSequence(softTokens: soft)) // runs mm_288// 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``````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.## Text| | ||---|---|| 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). || Matryoshka | 512 / 256 / 128 dims: take the first N values and re-normalize (`embed(..., dim:)` does it). |**Task prompts** (exactly the upstream `config_sentence_transformers.json`; the runners prepend them by `kind`):| kind | prefix ||---|---|| `document` | `title: none \| text: ` — for titled documents use `title: {title} \| text: {content}` yourself || `search_query` | `task: search result \| query: ` || `question_answering` | `task: question answering \| query: ` || `fact_checking` | `task: fact checking \| query: ` || `code_retrieval` | `task: code retrieval \| query: ` || `classification` | `task: classification \| query: ` || `clustering` | `task: clustering \| query: ` || `sentence_similarity` | `task: sentence similarity \| query: ` |The runners add `<bos>` and `<eos>` themselves, as sentence-transformers does. Special tokens written literally in atext (e.g. `<eos>`) are recognised as special tokens, exactly as in Hugging Face `tokenizers`; strip them if thatis not what you want.## Images### Neural Engine or GPUThe 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** ||---|---|---|| time per image, end to end (excl. decode + resize) | 369 ms | 125 ms (**~3× faster**) || throughput, one process | ~2.7 images/s | ~8 images/s || CPU time per image (Swift / Python) | **2 ms** / 8.5 ms | 21 ms / 27 ms || GPU time per image | **~1 ms** (the GPU stays free) | ~103 ms (the GPU is ~80 % busy while indexing) || whole-machine power while indexing, above idle ¹ | **+8.3 W** | +28.5 W || energy per image, above idle ¹ | **3.1 J** | 3.8 J || memory (Swift, both assets loaded) | 260–275 MB + 608–1061 MB on the Neural Engine | 435–440 MB + 608–766 MB on the Neural Engine (text) || accuracy vs fp32, 373 + 30 tiny + 19 photo files (Python runner) | median 0.99998, min 0.9946 ² | median 0.99998, min **0.9989** ² || cross-modal retrieval (205 captions, both directions) | identical to fp32 at 768 dims | identical to fp32 at 768 dims || first load of the image encoder by a new executable | minutes (3–4 min for both assets; once per app and OS build) | 2–25 s |¹ SMC whole-system power, MacBook on AC power, battery not charging, display on; idle ≈ 8 W. Python runner, 40 sof continuous embedding, two runs each (8.1 / 8.4 W, 28.1 / 28.9 W). Running *everything* on the GPU (`compute:.gpu`) costs +30.8 W and 4.2 J per image for the same speed.² Both routes give median ≥ 0.99998 and ≥ 0.9997 on every ordinary image; the minimum is a 16×16 image upscaled to768×768 (see "Limits"). On the GPU route with text on the GPU too, every image is ≥ 0.99975.**Default: the Neural Engine.** It needs a fraction of the CPU and almost no GPU, draws about a third of the power,and uses less energy per image, so indexing in the background does not heat the Mac, drain the battery or competewith the UI, games or a local LLM on the GPU. **Choose the GPU** when wall-clock time matters more than power: a bulkimport on a plugged-in Mac, or a user waiting for a dropped image. Keep text on the Neural Engine in both cases(text on the GPU is slower for short texts and costs ~10–30 ms of CPU per call).How to switch (the route is fixed when the model is loaded; create a second instance to use both):```swift// Swift: images on the GPU, text on the Neural Enginelet model = try await EmbeddingGemma2(bundle: url, compute: .neuralEngine, loadVision: true, imageCompute: .gpu)model.imageCompute // .gpu (if the `imageCompute:` argument is omitted, it equals `compute`)``````# CLI (Swift eg2-cli and the Python runner take the same flags)eg2-cli embed-image ../model --image-compute gpu ../tests/images/chart_bar.png ../tests/images/scene_sunset.jpgeg2-cli smoke ../model ../tests/smoke-reference.json ../tests/image-smoke-reference.json --image-compute gpupython3 embeddinggemma2_coreai.py embed-image ../model --image-compute gpu ../tests/images/chart_bar.png``````python# Pythonm = EmbeddingGemma2CoreAI("../model", compute="ane", load_vision=True, image_compute="gpu")m.image_compute # "gpu" (if the image_compute= argument is omitted or None, it equals compute)````imageCompute: .cpu` / `--image-compute cpu` also exists (~520 ms per image, the least precise route; for testing).The shipped graph splits the attention queries into 12 blocks, which the Neural Engine needs (560 → 355 ms); anun-split export takes ~10 % less time on the GPU (104 vs 116 ms for `vision_2520`, Python runner medians; `eg2-clilatency` measures the shipped split graph at 109–111 ms) but was not worth a second 300 MB asset(`export.py --qchunks 1` builds it for a GPU-only deployment).### Prompts and cross-modal searchImages take **no prompt** (as the model card prescribes): the image sequence is `<bos> <|image> [soft tokens]<image|> <eos>`. Text keeps its prompts. For "find the image that matches this text", embed the text with`kind: "search_query"` and compare it with the image vectors by cosine (dot product: all vectors areL2-normalized). Image vectors and document vectors live in the same space, so one index can hold both; forimage → text (caption search), embed the captions as `document`. Matryoshka prefixes work for images too.### How an image becomes a vector1. **Decode** to 8-bit RGB the way the reference does: alpha is dropped (not composited), EXIF orientation is**not** applied, no colour management. Palette, gray, gray+alpha, CMYK and 1-bit images are expanded; 16-bitsamples are reduced to their high byte.2. **Size**: the aspect ratio is kept, each side becomes a multiple of 48 px and the image fits 2520 patches of16×16 px (280 soft tokens). Small images are upscaled (1×1 → 768×768); extreme aspect ratios are allowed (a1-px-wide image becomes 48×13440). Most images end up with 250–280 soft tokens.3. **Resize** with the exact antialiased bicubic filter the upstream processor uses on uint8 pixels (torchvision'skernel, width pass then height pass, integer arithmetic). This matters: Lanczos or bilinear resampling (whatCore Image / vImage offer) moves the embedding down to cosine 0.96 (bilinear) or 0.86 (Lanczos) on thevalidation set, and wrong normalisation, BGR order or row-major patch order break it entirely.4. **Patches** 16×16×3 of integer pixel values 0–255 (exact in float16; the graph applies upstream's ×1/255 and2p − 1 itself, folded into its first projection) in "cell-major" order (the 9 patches of each 3×3 pooling cellcontiguous), with (x, y) positions, the axial-RoPE cos/sin tables and a padding mask → `vision_2520` →`[280, 512]` soft tokens, of which the first n are valid.5. **Sequence** `<bos>`=2, `<|image>`=255999, n × `<|image|>`=258880, `<image|>`=258882, `<eos>`=1 (n + 4 ≤ 284tokens → bucket 288), the n soft tokens placed in the placeholder slots → `mm_288` → `[768]`, L2-normalized.The runners do all of this; `VisionInputs` / `prepare_vision_inputs` expose the intermediate step for callers thatwant to run the functions themselves (several images in one sequence, text + image).### `vision_2520` (asset `embeddinggemma-2-vision.aimodel`)| | ||---|---|| `patches` | `[1, 2520, 768]` float16: 16×16×3 patches flattened (py, px, c), **integer pixel values 0–255** (not ÷255), cell-major order, zero padded || `pos_x`, `pos_y` | `[1, 2520]` int32 patch column / row (0 for padding) || `cos`, `sin` | `[1, 1, 2520, 64]` float16 axial RoPE tables: channels 0–31 from x, 32–63 from y, 16 frequencies (θ = 100) duplicated || `patch_mask` | `[1, 2520]` float16, 1 for a patch, 0 for padding || `soft_tokens` | `[1, 280, 512]` float16; rows at index ≥ n are padding and must be ignored |In `mm_<S>` the graph computes `x = embed(input_ids)·(1 − mm_mask) + mm_embeds·mm_mask` and then the text encoder,so the soft tokens go into `mm_embeds` at the placeholder positions (not scaled) with `mm_mask` = 1 there. Any mixfits a bucket: two images = 2·282 + 2 tokens → `mm_1024`, or text followed by an image.### EXIF orientation: a decision for the integratorThe reference embeds a photo as stored: a portrait photo whose EXIF tag says "rotate 90°" is embedded sideways.`applyEXIFOrientation: true` / `apply_exif_orientation=True` / `--exif` rotates it upright first; the uprightvector differs from the as-stored one by cosine ~0.97 and matches the same picture saved upright (0.998). For photosfrom 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.### ImagesCosine between this port and the fp32 reference, 768 dims, on the independent validation set (373 generatedimages, 205 of them with distinct captions, 30 extra tiny images, plus the 19 photo files; 512/256/128 dims behavethe same or better):| route (images / text) | median | min | min, captioned | min, 30 tiny images | photos ||---|---|---|---|---|---|| Neural Engine / Neural Engine (default), Python | 0.99998 | 0.9946 ¹ | 0.99972 | 0.9958 | ≥ 0.99992 || GPU / Neural Engine, Python | 0.99998 | 0.9989 ¹ | 0.99994 | 0.99975 | ≥ 0.99998 || GPU / GPU, Python | 1.00000 | 0.99975 | 0.99996 | 0.99992 | ≥ 0.99998 || CPU only, Python | 0.99993 | 0.946 ¹ | 0.99930 | 0.966 | ≥ 0.99980 || any route, Swift, lossless files (PNG, WebP lossless, GIF, …) | same as Python (cosine to the Python vector ≥ 0.99988) | | | | || any route, Swift, JPEG and lossy WebP files | 0.9998 | 0.982 ² | | | ≥ 0.9981 (median 0.9994) |¹ One 16×16 image upscaled to 768×768 (see "Limits"); every other image of the main set is ≥ 0.9997 on the NeuralEngine route. ² Synthetic charts with saturated colour edges saved as chroma-subsampled JPEG (see "JPEG in Swift").A first, separate set (239 generated images, 77 queries) gave Neural Engine min 0.99966 / median 0.99997; it wasmeasured on an earlier build of the image asset (pixel/255 inputs, attention queries not split), not on the shippedone, which was validated on the set above.The Python preprocessing is bit-identical to the upstream processor on all 389 files upstream can read (itspatches × 1/255 equal the processor's `pixel_values` exactly); the Swift decoder + resampler is bit-identical to thePython one on 280/280 lossless files. The re-authored graphs in fp32 reproduce the reference exactly (embeddingcosine 1.000000).**Cross-modal retrieval** (205 captions ↔ 205 images, captions as `search_query` / `document`):| | text → image R@1 / R@5 / MRR | image → text R@1 / R@5 / MRR ||---|---|---|| fp32 reference, 768 dims | 0.937 / 1.000 / 0.968 | 0.917 / 0.990 / 0.952 || this port, every tested route (Python: Neural Engine, GPU, mixed, CPU; Swift: Neural Engine, GPU, mixed), 768 dims | 0.937 / 1.000 / 0.968 | 0.917 / 0.990 / 0.952 || fp32 reference, 128 dims | 0.912 / 1.000 / 0.956 | 0.888 / 0.966 / 0.922 |At 768 dims all seven routes rank every caption and every image exactly where fp32 does (205/205 in bothdirections); at 512/256/128 dims every metric stays within 0.005 of fp32 and 201–205 of 205 keep their rank.**JPEG in Swift.** ImageIO's JPEG decoder upsamples chroma differently from libjpeg (which the reference uses viaPillow/torchvision), so JPEG pixels differ by 1–4 values on documents and up to 80 at saturated colour edges ofchroma-subsampled charts, before any resizing. Camera photos stay ≥ 0.998 (median 0.9994); JPEGs saved withoutchroma subsampling ≥ 0.9999; retrieval ranks at 768 dims were unchanged for all 205 captions on every route. PNG andevery lossless format are exact. If you need reference-exact JPEG vectors, decode JPEGs with a libjpeg-compatibledecoder (e.g. the Python runner, which uses Pillow) and pass the pixels to `ImagePreprocessor`.### TextUnchanged from 1.0: the text functions give bit-identical outputs to 1.0 on 466 texts across every bucket, so the1.0 figures hold. Cosine to fp32 on 357 fictional texts (English, Italian, code, Unicode stress, bucketboundaries; 2–2048 tokens): Neural Engine min 0.99992 / median 0.99997; GPU min 0.99998; CPU only min 0.99916.A second, independent set of 100 texts: min 0.99985 (an emoji-heavy text). **Expect ≥ 0.9998 on the Neural Engineand GPU routes, ≥ 0.999 on the CPU route.** Retrieval on 1,712 fictional passages / 53 queries: MRR 0.766 at 768dims, identical to fp32 (53/53 same first-relevant rank); 0.782 / 0.785 / 0.735 at 512 / 256 / 128 (fp32 0.790 /0.786 / 0.735). On the image validation set, its 410 captions and documents scored ≥ 0.99993 on the Neural Engine.**About float16.** The upstream model card says *"Do not use float16"*: the activations exceed the fp16 rangeand a naive fp16 run returns NaN or degraded vectors. This port runs in fp16 on purpose (the Neural Engine isfp16-only) and avoids the overflow by dividing every RMSNorm row and the final L2 normalization by its max-absvalue before squaring (see NOTICE). The figures above are the evidence; if you change the graph, keep that rescaling.**Tokenizer.** The Swift `GemmaTokenizer` re-implements the Hugging Face `tokenizers` pipeline described by`tokenizer.json` (special-token extraction, `Replace " " → "▁"`, BPE with byte fallback, rank-ordered merges),on Unicode scalars and exact UTF-8 bytes, and reads `tokenizer.json` with an exact JSON reader (Foundation's`JSONSerialization` strips a leading U+FEFF from string values). `tests/tokenizer-cases.json` holds 3,758fictional texts (608,225 ids: CRLF, NFD/NFKD accents, emoji ZWJ sequences, Arabic with diacritics, Thai, CJK, 30+languages, whitespace runs, control characters, special-token look-alikes, 5,000–80,000-character inputs);`eg2-cli tokcheck` reports **3758 / 3758 identical** to `tokenizers` 0.23.3. The Python runner uses `tokenizers`.### Smoke tests`tests/smoke-reference.json` (3 fictional sentences, threshold 0.999) and `tests/image-smoke-reference.json` (10generated images, their 10 queries and 2 documents; thresholds 0.998 for images and 0.999 for texts; every querymust rank its own image first). This package on the validation machine, all SMOKE PASS:| route (images / text) | images (10) min, Swift / Python | texts (15) min | text → image ||---|---|---|---|| Neural Engine / Neural Engine (default) | 0.99972 (the JPEG; PNGs ≥ 0.99994) / 0.99995 | 0.99995 | 10 / 10 || GPU / Neural Engine (`--image-compute gpu`) | 0.99973 (the JPEG; PNGs ≥ 0.99997) / 0.99997 | 0.99995 | 10 / 10 || 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:| | Neural Engine | GPU ||---|---|---|| `vision_2520` (one image, 273 soft tokens) | 355 ms | 109–111 ms || `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 instancewith images on the Neural Engine for background work and one on the GPU for interactive imports), at the memory costof a second instance.**Load time** (`AIModel(contentsOf:)` + `loadFunction`):| 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 mainthread and never lazily in front of the first query. The cache lives in`~/Library/Caches/coreai-cache/<OS build>/<app>/`, where `<app>` is the executable name for a plain binary such as`eg2-cli` and the bundle identifier for a bundled executable (`org.python.python` for a framework build of Python,e.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()`,or `--cleanup-temp` on every CLI command. Call it after the model has been released, or at exit. Folders of otherprocesses are never touched; a leftover from a crashed run has to be removed by hand (the name carries pid and date).## Limits and known issues- **Very small images upscaled a lot** (a 10–16 px image becomes 768×768, every patch a smooth gradient) are theleast precise case on the Neural Engine. Since 1.1 the graph takes exact integer pixels (the input rounding thatcost such images up to 0.004 is gone). On the GPU image route the worst image is 0.9989 with text on the NeuralEngine (`imageCompute: .gpu`; 30 targeted tiny images ≥ 0.99975) and 0.99975 with text on the GPU too (`compute:.gpu`). On the Neural Engine its own float16 arithmetic remains: worst image 0.9946 (a 16×16 image), 30 targetedtiny images 0.9958–0.99999 (median 0.99993), every other validation image ≥ 0.9997. Retrieval is unaffected. Ifyou index many icons or thumbnails of ≤ 16 px and want the closest match to the reference, put the images on theGPU: `imageCompute: .gpu` (worst 0.9989) or, closest, `compute: .gpu` (worst 0.99975).- **JPEG decoding in Swift** differs from libjpeg (above): photos ≥ 0.998, chroma-subsampled synthetic chartsdown to 0.982; lossless formats are exact. This is the same on every compute route.- **CPU-only route** (`compute: .cpu` / `imageCompute: .cpu`): fine on ordinary images (median 0.99993, captioned≥ 0.9993) and texts (≥ 0.9991) but the least precise route (tiny upscaled images down to 0.946) and the slowest;use the Neural Engine or the GPU.- **One image budget.** Only the default 280-soft-token budget (2520 patches) is exported. The upstream processoralso supports 70, 140 (video frames), 560 and 1120; those need other static shapes (`export/eg2_vision.py`:`MAX_SOFT`), and 1120 is probably GPU-only.- **File formats**: the reference reads only JPEG, PNG, WebP and GIF from a path. The runners also read BMP andTIFF (Swift: also HEIC and anything else ImageIO decodes); there is no upstream vector to compare those with.16-bit images: upstream divides the 16-bit samples by 255 (garbage); the runners take the high byte, on purpose.Premultiplied-alpha CGImages cannot be un-premultiplied exactly; exotic pixel formats (float, Lab, …) fall backto 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.3 unmodified lines# a separate environment with Python 3.12 (torch 2.9.0); exact versions in python/requirements.lockpython3.12 -m venv .venv-export && source .venv-export/bin/activatepip install coreai-core==1.0.0b3 torch==2.9.0 coreai-torch==0.4.3 coreai-opt==0.3.0 torchao==0.17.0 \safetensors numpy pillow tokenizers huggingface-hubhf 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 atrandom (`main.mlirb` / `main.hash` differ by a few bytes) and the runtime writes `metadata.json` with the exporttime. `config.json`, `MODEL-ATTRIBUTION.json` and the tokenizer files come out byte-identical. Verify a rebuildwith `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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""The EmbeddingGemma 2 text encoder with multimodal (soft-token) inputs: `eg2_text.EmbeddingGemma2Text` plus amix of token embeddings and externally computed soft tokens at the start of the graph.
input_ids [1, S] int32 token ids; placeholder slots (<|image|> = 258880) are looked up like any id attention_mask [1, S] fp16 1 = token, 0 = right padding mm_embeds [1, S, 512] fp16 soft tokens placed at their slots (zeros elsewhere); NOT scaled by sqrt(512) mm_mask [1, S] fp16 1 at a soft-token slot, 0 elsewhere -> x = embed(input_ids) * (1 - mm_mask) + mm_embeds * mm_mask, then exactly the text graph (per-layer embeddings, 24 layers, final norm, projection, masked mean pooling over ALL tokens, L2 normalization) -> embedding [1, 768] fp16
With mm_mask all zero this is the text encoder (x * 1 + 0 is exact in fp16). eg2_text.py is unchanged (it is thefile that produced the text-only bundle); this module only re-states its forward with the mix."""from __future__ import annotations
import torch
import eg2_text
class EmbeddingGemma2TextMM(eg2_text.EmbeddingGemma2Text): def forward(self, input_ids, attention_mask, mm_embeds, mm_mask): # noqa: D102 S = input_ids.shape[1] keep = (self.one - mm_mask)[:, :, None] x = self.embed_tokens(input_ids) * keep + mm_embeds * mm_mask[:, :, None] # [1, S, 512] ple = self.per_layer_projection_norm( self.per_layer_model_projection(x).view(1, S, self.cfg.n_layers, self.cfg.ple_dim)) full, sliding = self._biases(attention_mask, S) cs = {} for lt in ("sliding_attention", "full_attention"): cs[lt] = (getattr(self, f"cos_{lt}")[:S].to(x.dtype)[None, None], getattr(self, f"sin_{lt}")[:S].to(x.dtype)[None, None]) for i, layer in enumerate(self.layers): lt = self.cfg.layer_types[i] x = layer(x, ple[:, :, i, :], cs[lt][0], cs[lt][1], sliding if lt == "sliding_attention" else full) x = self.embedding_projection(self.norm(x)) if eg2_text.PRECISION_MODE == "ane": w = attention_mask * eg2_text._recip(attention_mask.sum(-1, keepdim=True)) pooled = torch.matmul(w[:, None, :], x)[:, 0, :] u = pooled * eg2_text._recip(torch.maximum(pooled.abs().amax(-1, keepdim=True), self.floor16)) return u * torch.rsqrt((u * u).sum(-1, keepdim=True)) xf = x.float() wf = attention_mask.float() pooled = (xf * wf[:, :, None]).sum(1) / wf.sum(-1, keepdim=True) return (pooled / pooled.norm(dim=-1, keepdim=True)).to(x.dtype)
def load_model(model_dir: str, dtype: torch.dtype, max_seq: int = 2048) -> EmbeddingGemma2TextMM: """Same weights and folding as eg2_text.load_model, mm forward.""" cfg = eg2_text.Cfg(model_dir) m = EmbeddingGemma2TextMM(cfg, max_seq) base = eg2_text.load_model(model_dir, dtype, max_seq) m.load_state_dict(base.state_dict(), strict=True) return m.to(dtype).eval()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE).## Re-authoring of the Gemma 4 vision encoder (Gemma4VisionModel + the EmbeddingGemma 2 vision 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 vision encoder re-authored for Core AI export: patches -> soft tokens in the text space.
One fixed shape (the default budget of 280 soft tokens = 2520 patches of 16x16 px): patches [1, 2520, 768] fp16, integer pixel values 0..255 (exact in fp16), 16x16x3 flattened (py, px, c), CELL-MAJOR order (the 9 patches of each 3x3 pooling cell contiguous, cells row-major), zero padded pos_x/pos_y [1, 2520] int32 patch coordinates (padding 0) cos/sin [1, 1, 2520, 64] fp16 axial RoPE tables computed on the host (channels 0..31 by x, 32..63 by y) patch_mask [1, 2520] fp16, 1 = real patch, 0 = padding -> (P - 127.5) -> Linear 768->768 (weights x 2/255) + posx[x] + posy[y] -> 16 encoder layers (12 heads x 64, sandwich RMSNorm, q/k/v norms, scale 1.0, bidirectional with a key mask) -> 3x3 average pooling = reshape [280, 9, 768].mean -> RMSNorm without scale -> Linear 768->512 soft_tokens [1, 280, 512] fp16; rows at index >= n_soft (= cells of the image) are padding and must be ignored.
Differences from the upstream graph (all mathematically identical in exact arithmetic): - upstream feeds p = P/255 and computes 2p - 1. P/255 is not representable in fp16 (rounding it alone costs a heavily upscaled tiny image cosine 0.996), so the graph takes the integer pixel P and computes P - 127.5 (exact in fp16) and the 2/255 scale is folded into input_proj's weights: W(2P/255 - 1) == (2W/255)(P - 127.5). - cell-major patch order makes the 3x3 pooling a reshape + mean instead of a one-hot matmul; attention is permutation-equivariant so the layers do not care. - the upstream pooler multiplies by sqrt(768) in fp32 before the projector's RMSNorm (and warns that this exceeds fp16). RMSNorm(x*s, eps) == RMSNorm(x, eps/s^2), so the scale is dropped and eps/768 used instead. - the position-embedding tables are cut to the 840 rows an image of this budget can address (x and y < 840). - fp16 "ane" precision mode as in eg2_text.py: every RMSNorm divides the row by its max-abs value before squaring (the vision residual reaches ~1400), no divides, finite -1e4 key mask."""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-3MAX_SOFT = 280POOL = 3MAX_PATCHES = MAX_SOFT * POOL * POOL # 2520POS_ROWS = MAX_SOFT * POOL # 840 (budget 280); budget 1120 would need 3360# Query chunking of the 2520x2520 attention (QUERY_CHUNKS > 1 splits the score matrix into row blocks so that# no single intermediate exceeds 2520*2520/QUERY_CHUNKS*12 fp16 values); 1 = one matmul per layer.QUERY_CHUNKS = int(__import__("os").environ.get("EG2_VISION_QCHUNKS", "1"))
class Cfg: def __init__(self, model_dir: str): c = json.loads((Path(model_dir) / "config.json").read_text())["vision_config"] t = json.loads((Path(model_dir) / "config.json").read_text())["text_config"] self.hidden = c["hidden_size"] # 768 self.inter = c["intermediate_size"] # 3072 self.n_layers = c["num_hidden_layers"] # 16 self.n_heads = c["num_attention_heads"] # 12 self.head_dim = c["head_dim"] # 64 self.patch = c["patch_size"] # 16 self.pool = c["pooling_kernel_size"] # 3 self.eps = c["rms_norm_eps"] # 1e-6 self.rope_theta = c["rope_parameters"]["rope_theta"] # 100 self.pos_size = c["position_embedding_size"] # 10240 self.text_hidden = t["hidden_size"] # 512 assert c["hidden_activation"] == "gelu_pytorch_tanh" assert c["num_key_value_heads"] == self.n_heads and not c["use_clipped_linears"] and not c["standardize"] assert c["rope_parameters"]["rope_type"] == "axial"
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)
def rope_axial(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """x [1, H, N, 64]: rotate_half inside each 32-channel half (x-half, y-half). cos/sin [1, 1, N, 64].""" B, H, N, D = x.shape xr = x.reshape(B, H, N, 2, D // 2) h = D // 4 rot = torch.cat((-xr[..., h:], xr[..., :h]), dim=-1).reshape(B, H, N, D) return x * cos + rot * sin
class Attention(nn.Module): def __init__(self, cfg: Cfg): super().__init__() self.n_heads, self.hd = cfg.n_heads, cfg.head_dim self.q_proj = nn.Linear(cfg.hidden, cfg.n_heads * cfg.head_dim, bias=False) self.k_proj = nn.Linear(cfg.hidden, cfg.n_heads * cfg.head_dim, bias=False) self.v_proj = nn.Linear(cfg.hidden, cfg.n_heads * cfg.head_dim, bias=False) self.o_proj = nn.Linear(cfg.n_heads * cfg.head_dim, cfg.hidden, bias=False) self.q_norm = RMSNorm(cfg.head_dim, cfg.eps) self.k_norm = RMSNorm(cfg.head_dim, cfg.eps) self.v_norm = RMSNorm(cfg.head_dim, cfg.eps, with_scale=False)
def forward(self, x, cos, sin, bias): B, N, _ = x.shape q = self.q_norm(self.q_proj(x).view(B, N, self.n_heads, self.hd)).transpose(1, 2) k = self.k_norm(self.k_proj(x).view(B, N, self.n_heads, self.hd)).transpose(1, 2) v = self.v_norm(self.v_proj(x).view(B, N, self.n_heads, self.hd)).transpose(1, 2) q, k = rope_axial(q, cos, sin), rope_axial(k, cos, sin) kt = k.transpose(-1, -2) if QUERY_CHUNKS > 1: outs = [] for qc in q.chunk(QUERY_CHUNKS, dim=2): s = torch.matmul(qc, kt) + bias # scale 1.0 p = torch.softmax(s, dim=-1) if PRECISION_MODE == "ane" else torch.softmax(s.float(), dim=-1).to(q.dtype) outs.append(torch.matmul(p, v)) o = torch.cat(outs, dim=2) else: s = torch.matmul(q, kt) + bias # [1, 12, N, N], scale 1.0 p = torch.softmax(s, dim=-1) if PRECISION_MODE == "ane" else torch.softmax(s.float(), dim=-1).to(q.dtype) o = torch.matmul(p, v) return self.o_proj(o.transpose(1, 2).reshape(B, N, self.n_heads * self.hd))
class MLP(nn.Module): def __init__(self, cfg: Cfg): super().__init__() self.gate_proj = nn.Linear(cfg.hidden, cfg.inter, bias=False) self.up_proj = nn.Linear(cfg.hidden, cfg.inter, bias=False) self.down_proj = nn.Linear(cfg.inter, cfg.hidden, bias=False)
def forward(self, x): return self.down_proj(F.gelu(self.gate_proj(x), approximate="tanh") * self.up_proj(x))
class Layer(nn.Module): def __init__(self, cfg: Cfg): super().__init__() self.self_attn = Attention(cfg) self.mlp = MLP(cfg) self.input_layernorm = RMSNorm(cfg.hidden, cfg.eps) self.post_attention_layernorm = RMSNorm(cfg.hidden, cfg.eps) self.pre_feedforward_layernorm = RMSNorm(cfg.hidden, cfg.eps) self.post_feedforward_layernorm = RMSNorm(cfg.hidden, cfg.eps)
def forward(self, x, cos, sin, bias): x = x + self.post_attention_layernorm(self.self_attn(self.input_layernorm(x), cos, sin, bias)) return x + self.post_feedforward_layernorm(self.mlp(self.pre_feedforward_layernorm(x)))
class EmbeddingGemma2Vision(nn.Module): def __init__(self, cfg: Cfg): super().__init__() self.cfg = cfg d = cfg.patch * cfg.patch * 3 self.input_proj = nn.Linear(d, cfg.hidden, bias=False) self.pos_x = nn.Embedding(POS_ROWS, cfg.hidden) self.pos_y = nn.Embedding(POS_ROWS, cfg.hidden) self.layers = nn.ModuleList([Layer(cfg) for _ in range(cfg.n_layers)]) # projector: RMSNorm without scale with eps/768 (replaces x*sqrt(768) followed by RMSNorm(eps)), Linear self.pre_projection_norm = RMSNorm(cfg.hidden, cfg.eps / cfg.hidden, with_scale=False) self.embedding_projection = nn.Linear(cfg.hidden, cfg.text_hidden, bias=False) self.register_buffer("mask_value", _f16(MASK_VALUE), persistent=False) self.register_buffer("one", _f16(1.0), persistent=False) self.register_buffer("c_mid", _f16(127.5), persistent=False) self.register_buffer("inv_pool", _f16(1.0 / (POOL * POOL)), persistent=False)
def forward(self, patches, pos_x, pos_y, cos, sin, patch_mask): B, N, _ = patches.shape # upstream: input_proj(2 * P/255 - 1); here P - 127.5 (exact in fp16) with 2/255 folded into input_proj x = self.input_proj(patches - self.c_mid) + self.pos_x(pos_x) + self.pos_y(pos_y) bias = ((self.one - patch_mask) * self.mask_value)[:, None, None, :] # [1, 1, 1, N] key mask for layer in self.layers: x = layer(x, cos, sin, bias) pooled = x.view(B, N // (POOL * POOL), POOL * POOL, self.cfg.hidden) if PRECISION_MODE == "ane": pooled = pooled.sum(2) * self.inv_pool # 9 values of <= ~1400 each: sum < 13k, fp16-safe else: pooled = pooled.float().mean(2).to(x.dtype) return self.embedding_projection(self.pre_projection_norm(pooled)) # [1, 280, 512]
def load_model(model_dir: str, dtype: torch.dtype) -> EmbeddingGemma2Vision: from safetensors import safe_open
cfg = Cfg(model_dir) m = EmbeddingGemma2Vision(cfg) sd = {} with safe_open(str(Path(model_dir) / "model.safetensors"), "pt") as f: for k in f.keys(): if k.startswith("vision_tower.encoder.layers."): nk = k[len("vision_tower.encoder."):].replace(".linear.weight", ".weight") sd[nk] = f.get_tensor(k).float() elif k == "vision_tower.patch_embedder.input_proj.weight": sd["input_proj.weight"] = f.get_tensor(k).float() * (2.0 / 255.0) # takes P - 127.5, P in 0..255 elif k == "vision_tower.patch_embedder.position_embedding_table": t = f.get_tensor(k).float() sd["pos_x.weight"] = t[0, :POS_ROWS].clone() sd["pos_y.weight"] = t[1, :POS_ROWS].clone() elif k == "embed_vision.embedding_projection.weight": sd["embedding_projection.weight"] = f.get_tensor(k).float() 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", "mask_value", "one", "c_mid", "inv_pool"))] assert not missing and not unexpected, (missing, unexpected) return m.to(dtype).eval()1234567891011121314151617181920212223242526272829303132335 unmodified lines3940414243446 unmodified lines51525354555612 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681694 unmodified lines174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Export the EmbeddingGemma 2 text encoder to a Core AI `.aimodel` with one static entrypoint per sequence bucket.# 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> --name embeddinggemma-2-text \# --mode ane --buckets 32,64,128,256,512,1024,2048 (the released bundle; ~20 s on an M-series Mac)The result is functionally identical to the released bundle (same outputs), not byte-identical: the converter givesinternal graph resources random names, so main.mlirb / main.hash differ, and the runtime writes metadata.json with theexport time and its own key order. config.json, MODEL-ATTRIBUTION.json (with --date 2026-10-12) and the tokenizerfiles come out byte-identical to the released ones.One dynamic-S torch.export -> TorchConverter -> AIProgram.set_static_shape_config("main", {...}) which replaces`main` by `main_<S>` clones (static shapes are what keeps the graph on the Neural Engine).Bundle layout:<out>/<name>.aimodel functions main_<S>: inputs input_ids [1,S] int32, attention_mask [1,S] fp16 -> embedding [1,768] fp16<out>/tokenizer/ tokenizer.json + tokenizer_config.json (unchanged Gemma tokenizer)<out>/config.json buckets, prompts, special tokens, matryoshka dims, precision mode<out>/MODEL-ATTRIBUTION.json base model, checkpoint sha256, exporter versions, modification listRequirements (see ../python/requirements.lock): Python 3.12, torch 2.9.0, coreai-torch 0.4.3, coreai-opt 0.3.0,torchao 0.17.0, coreai-core 1.0.0b3, safetensors."""from __future__ import annotationsimport argparseimport hashlibimport jsonimport osimport shutilimport subprocessimport sys5 unmodified linesLAB = Path(__file__).resolve().parentsys.path.insert(0, str(LAB))import eg2_text # noqa: E402T0 = time.time()PROMPTS = {6 unmodified lines"clustering": "task: clustering | query: ","sentence_similarity": "task: sentence similarity | query: ",}def log(msg: str) -> None:12 unmodified linesreturn sum(f.stat().st_size for f in p.rglob("*") if f.is_file()) if p.is_dir() else p.stat().st_sizedef main() -> None:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--model-dir", required=True, help="folder with the original google/embeddinggemma-2 checkpoint ""(config.json, model.safetensors, tokenizer.json, tokenizer_config.json)")ap.add_argument("--hf-id", default="google/embeddinggemma-2")ap.add_argument("--out", required=True)ap.add_argument("--name", default=None)ap.add_argument("--mode", default="ane", choices=["ane", "gpu"])ap.add_argument("--buckets", default="32,64,128,256,512,1024,2048")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("--no-static", action="store_true", help="keep the single dynamic-S `main` (GPU only)")ap.add_argument("--date", default=None, help="port date written to MODEL-ATTRIBUTION.json (default: today)")args = ap.parse_args()buckets = sorted(int(b) for b in args.buckets.split(","))max_seq = max(buckets)out = Path(args.out)name = args.name or out.nameeg2_text.PRECISION_MODE = args.modelog(f"args {vars(args)}")model = eg2_text.load_model(args.model_dir, torch.float16, max_seq=max_seq)if args.num_layers:model.layers = model.layers[: args.num_layers]model.cfg.layer_types = model.cfg.layer_types[: args.num_layers]log(f"model loaded: {sum(p.numel() for p in model.parameters()) / 1e6:.1f} M params, mode={args.mode}")import coreai_torchfrom torch.export import DimS0 = buckets[min(1, len(buckets) - 1)]ref = {"input_ids": torch.zeros(1, S0, dtype=torch.int32),"attention_mask": torch.ones(1, S0, dtype=torch.float16)}ref["input_ids"][0, :8] = torch.tensor([2, 8071, 236787, 3927, 1354, 1109, 7609, 1], dtype=torch.int32)ref["attention_mask"][0, 8:] = 0S = Dim("S", min=min(8, buckets[0]), max=max_seq)dyn = {"input_ids": {1: S}, "attention_mask": {1: S}}with torch.no_grad():ep = torch.export.export(model, args=(), kwargs=ref, dynamic_shapes=dyn)log("torch.export done")ep = ep.run_decompositions(coreai_torch.get_decomp_table())log("decomposed")mode = coreai_torch.TorchConverter.Mode.DEBUG if args.debug_info else coreai_torch.TorchConverter.Mode.RELEASEconv = coreai_torch.TorchConverter(mode=mode)conv.add_exported_program(ep, input_names=["input_ids", "attention_mask"], output_names=["embedding"],entrypoint_name="main")prog = conv.to_coreai()log("converted to AIProgram")functions = ["main"]if not args.no_static:cfg = {f'"{b}"': {"input_ids": (1, b), "attention_mask": (1, b)} for b in buckets}prog.set_static_shape_config("main", cfg)functions = [f"main_{b}" for b in buckets]log(f"static shape specializations: {functions}")from coreai.runtime import AIModelAssetMetadataout.mkdir(parents=True, exist_ok=True)aimodel = out / f"{name}.aimodel"shutil.rmtree(aimodel, ignore_errors=True)meta = AIModelAssetMetadata()meta.author = "Gemma Team (Google); Core AI port"meta.license = "Apache-2.0"meta.model_description = (f"EmbeddingGemma 2 text encoder ({args.hf_id}) with mean pooling, 768-d projection and L2 "f"normalization in-graph; precision mode {args.mode}; sequence buckets {buckets}.")meta.creation_date = int(time.time())prog.save_asset(aimodel, meta)log(f"saved {aimodel} ({dir_bytes(aimodel) / 2**20:.1f} MiB)")# ---- bundle ---------------------------------------------------------------------tok_dir = out / "tokenizer"tok_dir.mkdir(exist_ok=True)for f in ("tokenizer.json", "tokenizer_config.json"):shutil.copy(Path(args.model_dir) / f, tok_dir / f)cfg_json = {"base_model": args.hf_id, "format": "coreai", "asset": aimodel.name, "functions": functions,"precision_mode": args.mode, "buckets": buckets, "max_tokens": max_seq,"inputs": {"input_ids": "[1, S] int32 (bos=2 ... eos=1, right-padded with pad=0)","attention_mask": "[1, S] float16 (1 = token, 0 = padding)"},"output": {"embedding": "[1, 768] float16, L2-normalized; Matryoshka: keep the first 512/256/128 and re-normalize"},"hidden_size": 512, "embedding_dim": 768, "matryoshka_dims": [768, 512, 256, 128],"bos_token_id": 2, "eos_token_id": 1, "pad_token_id": 0, "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")import coreai_torch as ctfrom importlib.metadata import version as pkg_versionrescale = ("fp16 everywhere (Neural Engine): every RMSNorm and the final L2 normalization divide the row by its ""max-abs value before squaring, so activations (~2000) never overflow fp16; in the model code every ""division is expressed as rsqrt(x)*rsqrt(x) (the Neural Engine compiler rejects divide)."if args.mode == "ane" else "fp16 weights and matmuls; RMSNorm, softmax, pooling and L2 normalization in fp32.")attribution = {"name": "EmbeddingGemma-2-CoreAI-text","version": "1.0","base_model": args.hf_id,"base_model_author": "Gemma Team, Google DeepMind","base_model_source": f"https://huggingface.co/{args.hf_id}",4 unmodified lines"copyright": "2026 Everpaper","license": "Apache-2.0 (see LICENSE); attribution and modification notice in NOTICE","date": args.date or time.strftime("%Y-%m-%d"),"format": "Apple Core AI .aimodel (macOS 27), fp16, static sequence buckets","exporter": {"coreai_torch": ct.__version__,"coreai_core": pkg_version("coreai-core"),"torch": torch.__version__.split("+")[0],"recipe": f"export/export.py --mode {args.mode} --buckets {','.join(map(str, buckets))}","global_attention": eg2_text.GLOBAL_ATTN_MODE,"gqa": eg2_text.GQA_MODE,},},"modifications": ["Text encoder only: the vision and audio encoders of the multimodal checkpoint are not included.","Architecture re-authored in plain PyTorch for Core AI export; weights are the original ones, rounded from bf16 to fp16.","The sqrt(512) token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into the tables.","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).",rescale,"Bidirectional attention masks (padding + sliding window 512) are built inside the graph from attention_mask; ""the additive mask value is -10000 (finite).","Masked mean pooling, the 512->768 embedding projection and the L2 normalization run inside the graph; the ""output is the final sentence embedding.",f"Fixed sequence buckets {', '.join(map(str, buckets))} as functions main_<S>; input longer than {max_seq} ""tokens must be truncated or chunked by the caller (the original model accepts 8192).",],}if args.num_layers:attribution["port"]["exporter"]["num_layers"] = args.num_layers(out / "MODEL-ATTRIBUTION.json").write_text(json.dumps(attribution, indent=2) + "\n")log(f"bundle written: {out} ({dir_bytes(out) / 2**20:.1f} MiB)")try:print(subprocess.run(["xcrun", "coreai-build", "inspect", str(aimodel), "--no-metadata"], capture_output=True, text=True, timeout=120).stdout[:3000])except Exception as e: # noqa: BLE001log(f"inspect failed: {e}")log("DONE")12345678910111213141516171819202122232425262728293031323334355 unmodified lines41424344454647486 unmodified lines5556575859606112 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242254 unmodified lines230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281# 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 theinput (eg2_text_mm.py); with zero soft tokens it is exactly the text encoder.embeddinggemma-2-vision.aimodel function vision_2520: patches [1,2520,768] fp16 (pixel values 0..255), pos_x/pos_y [1,2520] int32,cos/sin [1,1,2520,64] fp16, patch_mask [1,2520] fp16 -> soft_tokens [1,280,512] fp16(eg2_vision.py)tokenizer/ unchanged Gemma tokenizer (text queries and the image sequence ids)config.json, MODEL-ATTRIBUTION.json`--part text` / `--part vision` re-exports one asset and keeps the other one's entry of an existing config.json.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.config.json, MODEL-ATTRIBUTION.json (with --date 2026-10-12) and the tokenizer files come out byte-identical.Requirements: Python 3.12, torch 2.9.0, coreai-torch 0.4.3, coreai-opt 0.3.0, torchao 0.17.0, coreai-core 1.0.0b3,safetensors (see ../python/requirements.lock)."""from __future__ import annotationsimport argparseimport hashlibimport jsonimport shutilimport subprocessimport sys5 unmodified linesLAB = Path(__file__).resolve().parentsys.path.insert(0, str(LAB))import eg2_text # noqa: E402import eg2_text_mm # noqa: E402import eg2_vision # noqa: E402T0 = time.time()PROMPTS = {6 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:12 unmodified linesreturn sum(f.stat().st_size for f in p.rglob("*") if f.is_file()) if p.is_dir() else p.stat().st_sizedef save_asset(prog, path: Path, description: str) -> None:from coreai.runtime import AIModelAssetMetadatashutil.rmtree(path, ignore_errors=True)meta = AIModelAssetMetadata()meta.author = "Gemma Team (Google); Core AI port"meta.license = "Apache-2.0"meta.model_description = descriptionmeta.creation_date = int(time.time())prog.save_asset(path, meta)log(f"saved {path} ({dir_bytes(path) / 2**20:.1f} MiB)")try:print(subprocess.run(["xcrun", "coreai-build", "inspect", str(path), "--no-metadata"], capture_output=True, text=True, timeout=120).stdout[:2500])except Exception as e: # noqa: BLE001log(f"inspect failed: {e}")def export_vision(args, out: Path) -> dict:import coreai_torcheg2_vision.PRECISION_MODE = "ane"eg2_vision.QUERY_CHUNKS = args.qchunksmodel = eg2_vision.load_model(args.model_dir, torch.float16)if args.num_layers:model.layers = model.layers[: args.num_layers]log(f"vision model loaded: {sum(p.numel() for p in model.parameters()) / 1e6:.1f} M params, qchunks={args.qchunks}")N = eg2_vision.MAX_PATCHESex = {"patches": torch.rand(1, N, 768, dtype=torch.float16), "pos_x": torch.zeros(1, N, dtype=torch.int32),"pos_y": torch.zeros(1, N, dtype=torch.int32), "cos": torch.ones(1, 1, N, 64, dtype=torch.float16),"sin": torch.zeros(1, 1, N, 64, dtype=torch.float16), "patch_mask": torch.ones(1, N, dtype=torch.float16)}with torch.no_grad():ep = torch.export.export(model, args=(), kwargs=ex)log("torch.export (vision) 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)fn = f"vision_{N}"conv.add_exported_program(ep, input_names=["patches", "pos_x", "pos_y", "cos", "sin", "patch_mask"], output_names=["soft_tokens"], entrypoint_name=fn)prog = conv.to_coreai()log("converted vision to AIProgram")asset = out / "embeddinggemma-2-vision.aimodel"save_asset(prog, asset, f"EmbeddingGemma 2 vision encoder ({args.hf_id}): 2520 patches -> 280 soft tokens in the text space; "f"fp16, integer pixel inputs (0..255), cell-major pooling, max-abs RMSNorm.")return {"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 Dimeg2_text.PRECISION_MODE = "ane"max_seq = max(buckets)model = eg2_text_mm.load_model(args.model_dir, torch.float16, max_seq=max_seq)if args.num_layers:model.layers = model.layers[: args.num_layers]model.cfg.layer_types = model.cfg.layer_types[: args.num_layers]log(f"text-mm model loaded: {sum(p.numel() for p in model.parameters()) / 1e6:.1f} M params")S0 = buckets[min(1, len(buckets) - 1)]ref = {"input_ids": torch.zeros(1, S0, dtype=torch.int32), "attention_mask": torch.ones(1, S0, dtype=torch.float16),"mm_embeds": torch.zeros(1, S0, 512, dtype=torch.float16), "mm_mask": torch.zeros(1, S0, dtype=torch.float16)}ref["input_ids"][0, :8] = torch.tensor([2, 8071, 236787, 3927, 1354, 1109, 7609, 1], dtype=torch.int32)ref["attention_mask"][0, 8:] = 0S = Dim("S", min=min(8, buckets[0]), max=max_seq)dyn = {"input_ids": {1: S}, "attention_mask": {1: S}, "mm_embeds": {1: S}, "mm_mask": {1: S}}with torch.no_grad():ep = torch.export.export(model, args=(), kwargs=ref, dynamic_shapes=dyn)log("torch.export (text-mm) 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=["input_ids", "attention_mask", "mm_embeds", "mm_mask"], output_names=["embedding"], entrypoint_name="mm")prog = conv.to_coreai()log("converted text-mm to AIProgram")cfg = {f'"{b}"': {"input_ids": (1, b), "attention_mask": (1, b), "mm_embeds": (1, b, 512), "mm_mask": (1, b)} for b in buckets}prog.set_static_shape_config("mm", cfg)functions = [f"mm_{b}" for b in buckets]log(f"static shape specializations: {functions}")asset = out / "embeddinggemma-2-text-mm.aimodel"save_asset(prog, asset, f"EmbeddingGemma 2 text encoder ({args.hf_id}) with soft-token (image) inputs, mean pooling, 768-d "f"projection and L2 normalization in-graph; fp16 (Neural Engine); sequence buckets {buckets}.")return {"asset": asset.name, "functions": functions, "buckets": buckets, "max_tokens": max_seq}def main() -> None:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--model-dir", required=True, help="folder with the original google/embeddinggemma-2 checkpoint")ap.add_argument("--hf-id", default="google/embeddinggemma-2")ap.add_argument("--out", required=True)ap.add_argument("--part", default="all", choices=["all", "text", "vision"])ap.add_argument("--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)")args = ap.parse_args()out = Path(args.out)out.mkdir(parents=True, exist_ok=True)buckets = sorted(int(b) for b in args.buckets.split(","))log(f"args {vars(args)}")existing = json.loads((out / "config.json").read_text()) if (out / "config.json").exists() else {}vision = ({k: existing["vision"][k] for k in ("asset", "function", "max_patches", "max_soft_tokens", "qchunks")}if "vision" in existing else None)text = {k: existing[k] for k in ("asset", "functions", "buckets", "max_tokens")} if "asset" in existing else 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)for f in ("tokenizer.json", "tokenizer_config.json"):shutil.copy(Path(args.model_dir) / f, tok_dir / f)cfg_json = {"base_model": args.hf_id, "format": "coreai", **text, "precision_mode": "ane","inputs": {"input_ids": "[1, S] int32 (bos=2 ... eos=1, right-padded with pad=0; image slots hold 258880)","attention_mask": "[1, S] float16 (1 = token, 0 = padding)","mm_embeds": "[1, S, 512] float16 soft tokens at their slots (zeros elsewhere), unscaled","mm_mask": "[1, S] float16 (1 at a soft-token slot)"},"output": {"embedding": "[1, 768] float16, L2-normalized; Matryoshka: keep the first 512/256/128 and re-normalize"},"text_only_use": "mm_embeds = 0 and mm_mask = 0 give the text embedding (bit-identical to the v1.0 main_<S> functions)","vision": {**vision, "inputs": {"patches": "[1, 2520, 768] float16: 16x16x3 patches (py, px, c), integer pixel values 0..255 (not /255), CELL-MAJOR order, zero padded","pos_x": "[1, 2520] int32 patch column (0 for padding)", "pos_y": "[1, 2520] int32 patch row (0 for padding)","cos": "[1, 1, 2520, 64] float16 axial RoPE cos (channels 0-31 by x, 32-63 by y, 16 freqs theta 100 duplicated)","sin": "[1, 1, 2520, 64] float16", "patch_mask": "[1, 2520] float16 (1 = patch, 0 = padding)"},"output": {"soft_tokens": "[1, 280, 512] float16; rows >= n_soft are padding"},"patch_size": 16, "pooling_kernel": 3, "cell_px": 48, "rope_theta": 100.0, "head_dim": 64,"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")import coreai_torch as ctfrom importlib.metadata import version as pkg_versiontb = 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}",4 unmodified lines"copyright": "2026 Everpaper","license": "Apache-2.0 (see LICENSE); attribution and modification notice in NOTICE","date": args.date or time.strftime("%Y-%m-%d"),"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 ""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).","Text: bidirectional attention masks (padding + sliding window 512) are built inside the graph from ""attention_mask; the additive mask value is -10000 (finite).","Text: masked mean pooling, the 512->768 embedding projection and the L2 normalization run inside the graph; ""the output is the final sentence embedding.","Text: an input mix x = embed(ids)*(1-mm_mask) + mm_embeds*mm_mask at the start of the graph, so that image ""soft tokens replace the <|image|> placeholder embeddings (soft tokens are not scaled); with zero soft tokens ""the graph is the v1.0 text encoder.",f"Text: fixed sequence buckets {', '.join(map(str, tb))} as functions mm_<S>; input longer than "f"{text['max_tokens']} tokens must be truncated or chunked by the caller (the original model accepts 8192).","Vision: encoder (Gemma4VisionModel, 16 layers) and vision embedder, one fixed shape: the default budget of 280 ""soft tokens (2520 patches of 16x16). Patches are fed in cell-major order so that the 3x3 average pooling is a ""reshape + mean instead of a one-hot matmul (attention is permutation-equivariant; identical result).","Vision: the patches are integer pixel values 0..255 (exact in fp16) instead of pixel/255: the graph computes ""P - 127.5 and the 2/255 scale is folded into the patch-embedding projection's weights, which equals upstream's ""projection of 2*(P/255) - 1 without rounding the inputs to fp16 (that rounding cost heavily upscaled tiny ""images up to 0.004 of cosine).","Vision: the pooler's multiplication by sqrt(768) (fp32 upstream, overflows fp16) is dropped and the vision ""embedder's RMSNorm uses eps/768 instead: RMSNorm(x*s, eps) == RMSNorm(x, eps/s^2).","Vision: the 2-D position-embedding tables are cut to the 840 rows reachable at this budget; the axial RoPE ""cos/sin tables and the key mask are inputs computed by the host; the additive key-mask value is -10000.","Image preprocessing (host): the upstream aspect-preserving size rule and the torchvision-exact antialiased ""bicubic resize on uint8 re-implemented in numpy and Swift.",],}if args.num_layers:attribution["port"]["exporter"]["num_layers"] = args.num_layers(out / "MODEL-ATTRIBUTION.json").write_text(json.dumps(attribution, indent=2) + "\n")log(f"bundle written: {out} ({dir_bytes(out) / 2**20:.1f} MiB)")log("DONE")
1234566 unmodified lines131415161718192021222324252627282930313233343536{"name": "EmbeddingGemma-2-CoreAI-text","version": "1.0","base_model": "google/embeddinggemma-2","base_model_author": "Gemma Team, Google DeepMind","base_model_source": "https://huggingface.co/google/embeddinggemma-2",6 unmodified lines"copyright": "2026 Everpaper","license": "Apache-2.0 (see LICENSE); attribution and modification notice in NOTICE","date": "2026-10-12","format": "Apple Core AI .aimodel (macOS 27), fp16, static sequence buckets","exporter": {"coreai_torch": "0.4.3","coreai_core": "1.0.0b3","torch": "2.9.0","recipe": "export/export.py --mode ane --buckets 32,64,128,256,512,1024,2048","global_attention": "mqa4d","gqa": "grouped5d"}},"modifications": ["Text encoder only: the vision and audio encoders of the multimodal checkpoint are not included.","Architecture re-authored in plain PyTorch for Core AI export; weights are the original ones, rounded from bf16 to fp16.","The sqrt(512) token-embedding scale and the 512^-0.5 per-layer-embedding scale are folded into the tables.","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, so activations (~2000) never overflow fp16; in the model code every division is expressed as rsqrt(x)*rsqrt(x) (the Neural Engine compiler rejects divide).","Bidirectional attention masks (padding + sliding window 512) are built inside the graph from attention_mask; the additive mask value is -10000 (finite).","Masked mean pooling, the 512->768 embedding projection and the L2 normalization run inside the graph; the output is the final sentence embedding.","Fixed sequence buckets 32, 64, 128, 256, 512, 1024, 2048 as functions main_<S>; input longer than 2048 tokens must be truncated or chunked by the caller (the original model accepts 8192)."]}1234566 unmodified lines131415161718192021222324252627282930313233343536373839404142{"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",6 unmodified lines"copyright": "2026 Everpaper","license": "Apache-2.0 (see LICENSE); attribution and modification notice in NOTICE","date": "2026-10-12","format": "Apple Core AI .aimodel (macOS 27), fp16, static shapes","exporter": {"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).","Text: bidirectional attention masks (padding + sliding window 512) are built inside the graph from attention_mask; the additive mask value is -10000 (finite).","Text: masked mean pooling, the 512->768 embedding projection and the L2 normalization run inside the graph; the output is the final sentence embedding.","Text: an input mix x = embed(ids)*(1-mm_mask) + mm_embeds*mm_mask at the start of the graph, so that image soft tokens replace the <|image|> placeholder embeddings (soft tokens are not scaled); with zero soft tokens the graph is the v1.0 text encoder.","Text: fixed sequence buckets 32, 64, 128, 288, 512, 1024, 2048 as functions mm_<S>; input longer than 2048 tokens must be truncated or chunked by the caller (the original model accepts 8192).","Vision: encoder (Gemma4VisionModel, 16 layers) and vision embedder, one fixed shape: the default budget of 280 soft tokens (2520 patches of 16x16). Patches are fed in cell-major order so that the 3x3 average pooling is a reshape + mean instead of a one-hot matmul (attention is permutation-equivariant; identical result).","Vision: the patches are integer pixel values 0..255 (exact in fp16) instead of pixel/255: the graph computes P - 127.5 and the 2/255 scale is folded into the patch-embedding projection's weights, which equals upstream's projection of 2*(P/255) - 1 without rounding the inputs to fp16 (that rounding cost heavily upscaled tiny images up to 0.004 of cosine).","Vision: the pooler's multiplication by sqrt(768) (fp32 upstream, overflows fp16) is dropped and the vision embedder's RMSNorm uses eps/768 instead: RMSNorm(x*s, eps) == RMSNorm(x, eps/s^2).","Vision: the 2-D position-embedding tables are cut to the 840 rows reachable at this budget; the axial RoPE cos/sin tables and the key mask are inputs computed by the host; the additive key-mask value is -10000.","Image preprocessing (host): the upstream aspect-preserving size rule and the torchvision-exact antialiased bicubic resize on uint8 re-implemented in numpy and Swift."]}
123456789101112131415161718192021222324252627282930313233345 unmodified lines404142434445{"base_model": "google/embeddinggemma-2","format": "coreai","asset": "embeddinggemma-2-text.aimodel","functions": ["main_32","main_64","main_128","main_256","main_512","main_1024","main_2048"],"precision_mode": "ane","buckets": [32,64,128,256,512,1024,2048],"max_tokens": 2048,"inputs": {"input_ids": "[1, S] int32 (bos=2 ... eos=1, right-padded with pad=0)","attention_mask": "[1, S] float16 (1 = token, 0 = padding)"},"output": {"embedding": "[1, 768] float16, L2-normalized; Matryoshka: keep the first 512/256/128 and re-normalize"},"hidden_size": 512,"embedding_dim": 768,"matryoshka_dims": [5 unmodified lines"bos_token_id": 2,"eos_token_id": 1,"pad_token_id": 0,"prompts": {"document": "title: none | text: ","search_query": "task: search result | query: ",123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263645 unmodified lines70717273747576777879{"base_model": "google/embeddinggemma-2","format": "coreai","asset": "embeddinggemma-2-text-mm.aimodel","functions": ["mm_32","mm_64","mm_128","mm_288","mm_512","mm_1024","mm_2048"],"buckets": [32,64,128,288,512,1024,2048],"max_tokens": 2048,"precision_mode": "ane","inputs": {"input_ids": "[1, S] int32 (bos=2 ... eos=1, right-padded with pad=0; image slots hold 258880)","attention_mask": "[1, S] float16 (1 = token, 0 = padding)","mm_embeds": "[1, S, 512] float16 soft tokens at their slots (zeros elsewhere), unscaled","mm_mask": "[1, S] float16 (1 at a soft-token slot)"},"output": {"embedding": "[1, 768] float16, L2-normalized; Matryoshka: keep the first 512/256/128 and re-normalize"},"text_only_use": "mm_embeds = 0 and mm_mask = 0 give the text embedding (bit-identical to the v1.0 main_<S> functions)","vision": {"asset": "embeddinggemma-2-vision.aimodel","function": "vision_2520","max_patches": 2520,"max_soft_tokens": 280,"qchunks": 12,"inputs": {"patches": "[1, 2520, 768] float16: 16x16x3 patches (py, px, c), integer pixel values 0..255 (not /255), CELL-MAJOR order, zero padded","pos_x": "[1, 2520] int32 patch column (0 for padding)","pos_y": "[1, 2520] int32 patch row (0 for padding)","cos": "[1, 1, 2520, 64] float16 axial RoPE cos (channels 0-31 by x, 32-63 by y, 16 freqs theta 100 duplicated)","sin": "[1, 1, 2520, 64] float16","patch_mask": "[1, 2520] float16 (1 = patch, 0 = padding)"},"output": {"soft_tokens": "[1, 280, 512] float16; rows >= n_soft are padding"},"patch_size": 16,"pooling_kernel": 3,"cell_px": 48,"rope_theta": 100.0,"head_dim": 64,"resize": "aspect-preserving to multiples of 48 px within 2520 patches; antialiased bicubic on uint8 (torchvision-exact)","image_prompt": null,"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": [5 unmodified lines"bos_token_id": 2,"eos_token_id": 1,"pad_token_id": 0,"boi_token_id": 255999,"image_token_id": 258880,"eoi_token_id": 258882,"video_token_id": 258884,"prompts": {"document": "title: none | text: ","search_query": "task: search result | query: ",
1Qc�-yH%�!���H]���A(S� �b:Q��123version https://git-lfs.github.com/spec/v1oid sha256:75d38431abcd2471b0540c863357710d305cb1687295f5b0cf859de6ac9d46ebsize 631529960123version https://git-lfs.github.com/spec/v1oid sha256:0b51638f2d17794825de21def6ab485d968fdf412853ea209617623a51f1bbdesize 632206233
12345678{"assetVersion" : "2.0","producer" : "coreai-core 1.0.0b3","license" : "Apache-2.0","author" : "Gemma Team (Google); Core AI port","creationDate" : "20261012T021653Z","description" : "EmbeddingGemma 2 text encoder (google\/embeddinggemma-2) with mean pooling, 768-d projection and L2 normalization in-graph; precision mode ane; sequence buckets [32, 64, 128, 256, 512, 1024, 2048]."}12345678{"producer" : "coreai-core 1.0.0b3","assetVersion" : "2.0","creationDate" : "20261012T101815Z","description" : "EmbeddingGemma 2 text encoder (google\/embeddinggemma-2) with soft-token (image) inputs, mean pooling, 768-d projection and L2 normalization in-graph; fp16 (Neural Engine); sequence buckets [32, 64, 128, 288, 512, 1024, 2048].","author" : "Gemma Team (Google); Core AI port","license" : "Apache-2.0"}
1uӄ1��$q�T�3Wq
0\�hr���υ�欝F�12�9����k���ED$t9I��9ie��B?123version https://git-lfs.github.com/spec/v1oid sha256:01e50a398ae9e003fd6bb5f1c74544032474394912b7c7396965f98b15423f19size 30702524012345678{ "creationDate" : "20261012T122100Z", "assetVersion" : "2.0", "description" : "EmbeddingGemma 2 vision encoder (google\/embeddinggemma-2): 2520 patches -> 280 soft tokens in the text space; fp16, integer pixel inputs (0..255), cell-major pooling, max-abs RMSNorm.", "author" : "Gemma Team (Google); Core AI port", "producer" : "coreai-core 1.0.0b3", "license" : "Apache-2.0"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE).## Ports the logic of the Gemma 4 image processor (image_processing_gemma4.py in Hugging Face transformers 5.19,# Copyright 2026 The HuggingFace Team, Apache-2.0), and the resize arithmetic of ATen's uint8# `_upsample_bicubic2d_aa` kernel (PyTorch, BSD-3-Clause; itself modelled on Pillow's Resample.c, MIT-CMU/HPND).# See ../NOTICE for the attributions and the PyTorch and Pillow license notices."""Exact host-side image preprocessing for the EmbeddingGemma 2 vision encoder (numpy + Pillow, no torch).
Reproduces what `Gemma4ImageProcessor` (transformers 5.19, torchvision backend) does to an image, bit for bit:
1. decode to 8-bit RGB: PIL `convert("RGB")` (alpha dropped, not composited; palette expanded; EXIF orientation NOT applied; no colour management) - identical to torchvision `decode_image(..., mode=RGB)` for 8-bit files. 2. target size: keep the aspect ratio, each side a multiple of 48 px, at most 2520 patches of 16x16 (budget of 280 soft tokens); tiny images are upscaled (1x1 -> 768x768), extreme aspect ratios go up to 48x13440. 3. resize: antialiased bicubic (a = -0.5) on uint8, the ATen `_upsample_bicubic2d_aa` uint8 kernel: separable, WIDTH pass first then HEIGHT, weights computed in float64 then rounded to int16 with a dynamic precision, each pass accumulated in int32, rounded (+half, arithmetic shift) and clamped to 0..255. Verified bit-identical to torchvision 0.29.1 on 239 images of 1x1 .. 8000x2000 px (tests/check_preprocess.py). 4. 16x16x3 patches flattened in (py, px, c) order. Upstream then multiplies by 1/255 (no mean/std) and the encoder computes 2p - 1; here the patches stay INTEGER pixel values 0..255 (exact in float16) and the graph computes P - 127.5 with the 2/255 scale folded into its first projection (same maths, no input rounding). Upstream's pixel_values == patches * RESCALE.
The vision graph wants the patches in CELL-MAJOR order (the 9 patches of each 3x3 pooling cell contiguous, cellsrow-major), padded to 2520, plus per-patch (x, y) positions, the axial-RoPE cos/sin table and a validity mask; see`VisionInputs` / `prepare_vision_inputs`. The model is otherwise unchanged (see ../NOTICE)."""from __future__ import annotations
import mathfrom dataclasses import dataclassfrom pathlib import Path
import numpy as np
PATCH = 16POOL = 3CELL_PX = PATCH * POOL # 48MAX_SOFT_TOKENS = 280MAX_PATCHES = MAX_SOFT_TOKENS * POOL * POOL # 2520MAX_SIDE_PATCHES = MAX_SOFT_TOKENS * POOL # 840: an image can be at most 840 patches wide or high (48 x 13440 px)HEAD_DIM = 64ROPE_THETA = 100.0ROPE_FREQS = HEAD_DIM // 4 # 16 frequencies per axis
# ---------------------------------------------------------------------------------------------- decodedef load_rgb(image, apply_exif_orientation: bool = False) -> np.ndarray: """`image`: a path or a PIL image. Returns HWC uint8 RGB exactly like the upstream processor (8-bit files).
apply_exif_orientation=True rotates camera photos upright first (NOT what upstream does; the embedding of a rotated photo differs from the upright one by cosine ~0.97, see README).""" from PIL import Image, ImageOps
im = image if isinstance(image, Image.Image) else Image.open(Path(image)) if apply_exif_orientation: im = ImageOps.exif_transpose(im) if im.mode in ("I;16", "I;16B", "I;16L", "I;16N", "I"): # 16-bit images: upstream divides the uint16 samples by 255 and produces garbage, PIL's convert clips at # 255; both runners take the high byte instead (documented divergence, same in Swift). a = np.asarray(im) a = (a >> 8).astype(np.uint8) if a.dtype == np.uint16 else np.clip(a // 256, 0, 255).astype(np.uint8) return np.repeat(a[..., None], 3, axis=-1) return np.asarray(im.convert("RGB"), dtype=np.uint8)
# ---------------------------------------------------------------------------------------------- sizedef target_size(height: int, width: int, max_patches: int = MAX_PATCHES) -> tuple[int, int]: """Gemma4 `get_aspect_ratio_preserving_size`, verbatim logic. Returns (height, width).""" target_px = max_patches * PATCH * PATCH factor = math.sqrt(target_px / (height * width)) th = int(math.floor(factor * height / CELL_PX)) * CELL_PX tw = int(math.floor(factor * width / CELL_PX)) * CELL_PX max_side = (max_patches // (POOL * POOL)) * CELL_PX if th == 0 and tw == 0: raise ValueError("image would resize to 0x0") if th == 0: th, tw = CELL_PX, min(int(math.floor(width / height)) * CELL_PX, max_side) elif tw == 0: tw, th = CELL_PX, min(int(math.floor(height / width)) * CELL_PX, max_side) if th * tw > target_px: raise ValueError("size exceeds the patch budget") return th, tw
# ---------------------------------------------------------------------------------------------- resizedef _cubic(x: float, a: float = -0.5) -> float: x = abs(x) if x < 1.0: return ((a + 2.0) * x - (a + 3.0)) * x * x + 1.0 if x < 2.0: return (((x - 5.0) * x + 8.0) * x - 4.0) * a return 0.0
def aa_int16_weights(in_size: int, out_size: int) -> tuple[np.ndarray, np.ndarray, int]: """Antialiased bicubic taps for one axis, as ATen computes them for uint8 input. Returns (xmin [out] int, weights [out, taps] int32 (0-padded), precision).""" scale = in_size / out_size # float64, align_corners=False, no explicit scale factor support = 2.0 * scale if scale >= 1.0 else 2.0 invscale = 1.0 / scale if scale >= 1.0 else 1.0 taps = int(math.ceil(support)) * 2 + 1 xmin = np.zeros(out_size, dtype=np.int64) wts = np.zeros((out_size, taps), dtype=np.float64) for i in range(out_size): center = scale * (i + 0.5) lo = max(int(center - support + 0.5), 0) size = min(int(center + support + 0.5), in_size) - lo w = [_cubic((j + lo - center + 0.5) * invscale) for j in range(size)] tot = sum(w) if tot != 0.0: w = [v / tot for v in w] xmin[i] = lo wts[i, :size] = w wt_max = float(wts.max()) precision = 0 while precision < 22: if int(0.5 + wt_max * (1 << (precision + 1))) >= (1 << 15): break precision += 1 s = float(1 << precision) # round half away from zero (what both std::round and Pillow do; all three rounding conventions agree on # every weight we have seen, this is the documented one) wi = np.where(wts >= 0, np.floor(wts * s + 0.5), np.ceil(wts * s - 0.5)).astype(np.int32) return xmin, wi, precision
def _resize_axis_u8(img: np.ndarray, axis: int, out_size: int) -> np.ndarray: in_size = img.shape[axis] xmin, wts, precision = aa_int16_weights(in_size, out_size) src = np.moveaxis(img, axis, 0).astype(np.int32) # [in, ...] acc = np.full((out_size,) + src.shape[1:], 1 << (precision - 1), dtype=np.int32) taps = wts.shape[1] for t in range(taps): w = wts[:, t] if not w.any(): continue idx = np.minimum(xmin + t, in_size - 1) # taps beyond the range have weight 0 acc += src[idx] * w.reshape((-1,) + (1,) * (src.ndim - 1)) out = np.clip(acc >> precision, 0, 255).astype(np.uint8) return np.moveaxis(out, 0, axis)
def resize_bicubic_aa_u8(img: np.ndarray, height: int, width: int) -> np.ndarray: """img HWC uint8 -> [height, width, C] uint8, bit-identical to torchvision's uint8 antialiased bicubic.""" if img.shape[0] == height and img.shape[1] == width: return img out = img if img.shape[1] != width: out = _resize_axis_u8(out, 1, width) # width first if img.shape[0] != height: out = _resize_axis_u8(out, 0, height) # then height return out
# ---------------------------------------------------------------------------------------------- patches@dataclassclass VisionInputs: """Everything the `vision_2520` function wants, plus what the text side needs.""" patches: np.ndarray # [1, 2520, 768] float16, integer pixel values 0..255, cell-major, zero padded pos_x: np.ndarray # [1, 2520] int32, padding = 0 pos_y: np.ndarray # [1, 2520] int32, padding = 0 cos: np.ndarray # [1, 1, 2520, 64] float16 axial RoPE sin: np.ndarray # [1, 1, 2520, 64] float16 patch_mask: np.ndarray # [1, 2520] float16, 1 = real patch, 0 = padding n_soft: int # number of valid soft tokens (cells) grid: tuple[int, int] # (patch rows, patch cols) resized: tuple[int, int] # (height, width) px
def rope_tables(pos_x: np.ndarray, pos_y: np.ndarray, dtype=np.float16) -> tuple[np.ndarray, np.ndarray]: """Axial RoPE: channels 0..31 rotate by x (16 freqs, duplicated), 32..63 by y. float32 maths, cast to dtype.""" inv = 1.0 / (ROPE_THETA ** (np.arange(0, ROPE_FREQS * 2, 2, dtype=np.float32) / (ROPE_FREQS * 2))) # [16] fx = pos_x.astype(np.float32)[:, None] * inv[None] fy = pos_y.astype(np.float32)[:, None] * inv[None] f = np.concatenate([fx, fx, fy, fy], -1) # [N, 64] return np.cos(f).astype(dtype), np.sin(f).astype(dtype)
def patchify_cell_major(rgb: np.ndarray, max_patches: int = MAX_PATCHES, rope_dtype=np.float16, patch_dtype=np.float16) -> VisionInputs: """rgb: [H, W, 3] uint8 (pixel values 0..255) with H, W multiples of 48. The patches keep the integer values (the graph takes 0..255). dtypes: float16 for the Core AI functions, float32 for the fp32 correctness gates.""" if rgb.dtype != np.uint8: raise ValueError("patchify_cell_major takes uint8 pixels (0..255)") H, W = rgb.shape[:2] ph, pw = H // PATCH, W // PATCH kh, kw = ph // POOL, pw // POOL n = kh * kw p = rgb.reshape(kh, POOL, PATCH, kw, POOL, PATCH, 3) # ky dy py kx dx px c p = p.transpose(0, 3, 1, 4, 2, 5, 6).reshape(n * POOL * POOL, PATCH * PATCH * 3) # (ky kx dy dx) x (py px c) ky, kx, dy, dx = np.meshgrid(np.arange(kh), np.arange(kw), np.arange(POOL), np.arange(POOL), indexing="ij") x = (kx * POOL + dx).ravel() y = (ky * POOL + dy).ravel() patches = np.zeros((1, max_patches, PATCH * PATCH * 3), patch_dtype) patches[0, : n * 9] = p pos_x = np.zeros((1, max_patches), np.int32) pos_y = np.zeros((1, max_patches), np.int32) pos_x[0, : n * 9] = x pos_y[0, : n * 9] = y mask = np.zeros((1, max_patches), np.float16) mask[0, : n * 9] = 1 cos, sin = rope_tables(pos_x[0], pos_y[0], rope_dtype) return VisionInputs(patches, pos_x, pos_y, cos[None, None], sin[None, None], mask, n, (ph, pw), (H, W))
RESCALE = np.float32(1.0 / 255.0) # upstream pixel_values = patches * RESCALE (the graph folds this scale in)
def prepare_vision_inputs(image, apply_exif_orientation: bool = False, dtype=np.float16) -> VisionInputs: """path or PIL image -> VisionInputs (decode, size, exact resize, cell-major patches of pixel values 0..255).""" rgb = load_rgb(image, apply_exif_orientation) th, tw = target_size(rgb.shape[0], rgb.shape[1]) rgb = resize_bicubic_aa_u8(rgb, th, tw) return patchify_cell_major(rgb, rope_dtype=dtype, patch_dtype=dtype)
def image_sequence(n_soft: int, bos: int, boi: int, image: int, eoi: int, eos: int) -> list[int]: """Token ids of a single image input, as the upstream processor builds them (no prompt).""" return [bos, boi] + [image] * n_soft + [eoi, eos]12345678910111213141516171819202122232425268 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757611 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221234 unmodified lines12812913013113213313413513613740 unmodified lines1781791801811821834 unmodified lines18818919019119219319419519619719819920020120220320420520620720820912 unmodified lines22222322422522622722822916 unmodified lines246247248249250251252253254255256257258259260261262263264265266267268269270#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""EmbeddingGemma 2 (text) 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") # ane | gpu | cpu | defaultm.prewarm() # optional: one call per bucketq = m.embed("When do the cloud credits expire?", kind="search_query") # 768-d, L2-normalizedd = m.embed("The credits expire on the last day of March.", kind="document", dim=256)del mremove_own_mpsgraph_temp_files() # see "Temp files" in the READMECLI:python3 embeddinggemma2_coreai.py embed ../model [--compute ane] [--kind document] [--dim 768] "text" ...python3 embeddinggemma2_coreai.py smoke ../model ../tests/smoke-reference.json [--compute ane] [--cleanup-temp]python3 embeddinggemma2_coreai.py tokcheck ../model ../tests/tokenizer-cases.jsonpython3 embeddinggemma2_coreai.py latency ../model [--compute ane] [--trials 50]python3 embeddinggemma2_coreai.py prewarm ../model [--compute ane]Tokenization uses the Hugging Face `tokenizers` library on the bundle's tokenizer.json (the reference tokenizer)."""from __future__ import annotations8 unmodified linesimport numpy as np_PROCESS_START = time.time()class EmbeddingGemma2CoreAI:"""Loads the bundle folder (config.json, tokenizer/, the .aimodel) and embeds texts."""def __init__(self, bundle: str | os.PathLike, compute: str = "ane", quiet: bool = True):import coreai.runtime as rtfrom tokenizers import Tokenizerself._rt = rtself.bundle = Path(bundle)self.config = json.loads((self.bundle / "config.json").read_text(encoding="utf-8"))t = time.perf_counter()self.tokenizer = Tokenizer.from_file(str(self.bundle / "tokenizer" / "tokenizer.json"))self.tokenizer_load_s = time.perf_counter() - tself.compute = computeif compute == "cpu":opts = rt.SpecializationOptions.cpu_only()elif compute == "gpu":opts = rt.SpecializationOptions.from_preferred_compute_unit_kind(rt.ComputeUnitKind.gpu())elif compute == "ane":opts = rt.SpecializationOptions.from_preferred_compute_unit_kind(rt.ComputeUnitKind.neural_engine())elif compute == "default":opts = rt.SpecializationOptions.default()else:raise ValueError("compute must be ane | gpu | cpu | default")t = time.perf_counter()self.model = asyncio.run(rt.AIModel.load(self.bundle / self.config["asset"], opts))self.functions: dict[int, object] = {}for name in self.config["functions"]:self.functions[int(name.rsplit("_", 1)[1])] = self.model.load_function(name)self.buckets = sorted(self.functions)self.load_s = time.perf_counter() - tif not quiet:print(f"loaded {self.bundle.name} compute={compute} buckets={self.buckets} in {self.load_s:.1f}s", flush=True)# ---- tokenization -------------------------------------------------------------------------------------def tokenize(self, text: str, kind: str | None = "document") -> list[int]:11 unmodified linesreturn braise ValueError(f"{n_tokens} tokens exceeds the largest bucket {self.buckets[-1]}")# ---- inference ----------------------------------------------------------------------------------------def embed_ids(self, ids: list[int], bucket: int | None = None) -> np.ndarray:"""Runs main_<bucket> on ids (with <bos>/<eos>), right-padded with <pad>. Returns the raw 768-d output."""S = bucket or self.bucket(len(ids))if len(ids) > S:raise ValueError(f"{len(ids)} ids do not fit bucket {S}")x = np.full((1, S), self.config["pad_token_id"], dtype=np.int32)x[0, : len(ids)] = idsm = np.zeros((1, S), dtype=np.float16)m[0, : len(ids)] = 1out = asyncio.run(self.functions[S](inputs={"input_ids": self._rt.NDArray(x), "attention_mask": self._rt.NDArray(m)}))return np.array(out["embedding"].numpy(), dtype=np.float32).reshape(-1)def embed(self, text: str, kind: str | None = "document", dim: int = 768) -> np.ndarray:"""L2-normalized embedding. dim 768, or a Matryoshka size (512/256/128): leading dims, re-normalized."""if dim not in self.config["matryoshka_dims"]:raise ValueError(f"dim must be one of {self.config['matryoshka_dims']}")v = self.embed_ids(self.tokenize(text, kind))[:dim]return v / max(float(np.linalg.norm(v)), 1e-12)def prewarm(self) -> float:"""One call per bucket so the first real call pays no specialization/first-call cost. Returns seconds."""t = time.perf_counter()for S in self.buckets:self.embed_ids([self.config["bos_token_id"], self.config["eos_token_id"]], S)return time.perf_counter() - tdef close(self) -> None:self.functions.clear()self.model = None# ---- temp-file hygiene ----------------------------------------------------------------------------------4 unmodified linesdef remove_own_mpsgraph_temp_files(pid: int | None = None, since: float | None = None) -> tuple[int, int]:"""Each Neural Engine load of this model makes MPSGraph write ~358 MB of compiled-graph copies into$TMPDIR/com.apple.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/, and the Python runtime (coreai.runtime,macOS 27.0) does NOT delete them when the model is released or the interpreter exits. This removes the folders of the CURRENT process only (its pid, created afterit started). Call it after the model object has been released, or at exit. Returns (folders, bytes)."""import shutilpid = pid or os.getpid()40 unmodified linesreturn float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))# ---- CLI -------------------------------------------------------------------------------------------------def cmd_embed(a) -> int:m = EmbeddingGemma2CoreAI(a.bundle, a.compute)4 unmodified linesreturn 0def cmd_smoke(a) -> int:ref = json.loads(Path(a.args[0]).read_text(encoding="utf-8"))m = EmbeddingGemma2CoreAI(a.bundle, a.compute)print(f"loaded in {m.load_s:.1f} s (tokenizer {m.tokenizer_load_s:.2f} s), compute={a.compute}, buckets={m.buckets}")ok = Truefor c in ref["cases"]:v = m.embed(c["text"], c["kind"])cos = cosine(v, c["embedding"])passed = cos >= ref["threshold_cosine"] and bool(np.all(np.isfinite(v)))ok = ok and passedprint(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {ref['threshold_cosine']}) {c['kind']}: {c['text'][:60]}")fp, nf = footprints_mb()print(f"peak footprint {fp:.0f} MB, neural footprint {nf:.0f} MB")print("SMOKE PASS" if ok else "SMOKE FAIL")m.close()return 0 if ok else 1def cmd_tokcheck(a) -> int:12 unmodified linesdef cmd_latency(a) -> int:m = EmbeddingGemma2CoreAI(a.bundle, a.compute)print(f"loaded in {m.load_s:.1f} s, compute={a.compute}; prewarm {m.prewarm():.2f} s")print("bucket p50 ms min ms p90 ms CPU ms/call tok/s")for S in m.buckets:ids = [m.config["bos_token_id"]] + [1000 + (i * 7919) % 200000 for i in range(1, S - 1)] + [m.config["eos_token_id"]]16 unmodified linesdef cmd_prewarm(a) -> int:t0 = time.perf_counter()m = EmbeddingGemma2CoreAI(a.bundle, a.compute)w = m.prewarm()print(f"load {m.load_s:.1f} s + prewarm {w:.2f} s = ready in {time.perf_counter() - t0:.1f} s")m.close()return 0def main() -> None:ap = argparse.ArgumentParser(description="EmbeddingGemma 2 (text) on Apple Core AI")ap.add_argument("cmd", choices=["embed", "smoke", "tokcheck", "latency", "prewarm"])ap.add_argument("bundle", help="the model folder (config.json, tokenizer/, *.aimodel)")ap.add_argument("args", nargs="*", help="texts (embed) or a json file (smoke, tokcheck)")ap.add_argument("--compute", default="ane", choices=["ane", "gpu", "cpu", "default"])ap.add_argument("--kind", default="document", help="prompt kind from config.json (document, search_query, ...) or none")ap.add_argument("--dim", type=int, default=768)ap.add_argument("--trials", type=int, default=50)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, "smoke": cmd_smoke, "tokcheck": cmd_tokcheck, "latency": cmd_latency, "prewarm": cmd_prewarm}[a.cmd](a)if a.cleanup_temp:import gc12345678910111213141516171819202122232425262728293031323334353637388 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010111 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062074 unmodified lines21221321421521621721821922022122240 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323334 unmodified lines33833934034134234334434534634734834935035135235335435535635735835936036136212 unmodified lines37537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540616 unmodified lines423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452#!/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 annotations8 unmodified linesimport numpy as npHERE = 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 Tokenizerself._rt = rtself.bundle = Path(bundle)self.config = json.loads((self.bundle / "config.json").read_text(encoding="utf-8"))self.hidden = self.config["hidden_size"]t = time.perf_counter()self.tokenizer = Tokenizer.from_file(str(self.bundle / "tokenizer" / "tokenizer.json"))self.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] = {}for name in self.config["functions"]:self.functions[int(name.rsplit("_", 1)[1])] = self.model.load_function(name)self.buckets = sorted(self.functions)self.vision_model = self.vision_function = Noneif load_vision:vc = self.config["vision"]self.vision_model = asyncio.run(rt.AIModel.load(self.bundle / vc["asset"], image_opts))self.vision_function = self.vision_model.load_function(vc["function"])self.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]:11 unmodified linesreturn braise ValueError(f"{n_tokens} tokens exceeds the largest bucket {self.buckets[-1]}")# ---- text ---------------------------------------------------------------------------------------------def embed_ids(self, ids: list[int], bucket: int | None = None) -> np.ndarray:"""Runs mm_<bucket> on ids (with <bos>/<eos>), right-padded with <pad>, no soft tokens.Returns the raw 768-d output (already L2-normalized by the graph)."""return self.embed_sequence(ids, bucket=bucket)def embed(self, text: str, kind: str | None = "document", dim: int = 768) -> np.ndarray:"""L2-normalized embedding. dim 768, or a Matryoshka size (512/256/128): leading dims, re-normalized."""return self._finish(self.embed_ids(self.tokenize(text, kind)), dim)# ---- images -------------------------------------------------------------------------------------------def embed_image(self, image, apply_exif_orientation: bool = False, dim: int = 768) -> np.ndarray:"""Path or PIL image -> L2-normalized 768-d embedding (or a Matryoshka prefix). The defaultapply_exif_orientation=False reproduces the upstream reference; True embeds camera photos upright."""inputs = eg2_image.prepare_vision_inputs(image, apply_exif_orientation)ids, soft, slots = self.image_sequence(self.soft_tokens(inputs))return self._finish(self.embed_sequence(ids, soft, slots), dim)def soft_tokens(self, inputs: eg2_image.VisionInputs) -> np.ndarray:"""[n_soft, 512] float32 soft tokens of a prepared image (vision_2520)."""if self.vision_function is None:raise RuntimeError("vision asset not loaded: create the model with load_vision=True")rt = self._rtout = asyncio.run(self.vision_function(inputs={"patches": rt.NDArray(inputs.patches), "pos_x": rt.NDArray(inputs.pos_x), "pos_y": rt.NDArray(inputs.pos_y),"cos": rt.NDArray(inputs.cos), "sin": rt.NDArray(inputs.sin), "patch_mask": rt.NDArray(inputs.patch_mask)}))return np.array(out["soft_tokens"].numpy(), dtype=np.float32)[0, : inputs.n_soft]def image_sequence(self, soft: np.ndarray) -> tuple[list[int], np.ndarray, list[int]]:"""(ids, soft tokens, slots) of the upstream single-image sequence <bos> <|image> [n] <image|> <eos>."""c = self.confign = soft.shape[0]ids = eg2_image.image_sequence(n, c["bos_token_id"], c["boi_token_id"], c["image_token_id"], c["eoi_token_id"], c["eos_token_id"])return ids, soft, list(range(2, 2 + n))# ---- 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:"""Runs mm_<bucket> on ids (with <bos>/<eos>), soft tokens [len(slots), 512] placed at `slots` (any mix oftext and images that fits a bucket). Returns the raw 768-d output (already L2-normalized by the graph)."""S = bucket or self.bucket(len(ids))if len(ids) > S:raise ValueError(f"{len(ids)} ids do not fit bucket {S}")rt = self._rtx = np.full((1, S), self.config["pad_token_id"], dtype=np.int32)x[0, : len(ids)] = idsam = np.zeros((1, S), dtype=np.float16)am[0, : len(ids)] = 1mm = np.zeros((1, S, self.hidden), dtype=np.float16)mmm = np.zeros((1, S), dtype=np.float16)if slots:if soft is None or soft.shape != (len(slots), self.hidden):raise ValueError("soft tokens do not match slots")mm[0, slots] = soft.astype(np.float16)mmm[0, slots] = 1out = asyncio.run(self.functions[S](inputs={"input_ids": rt.NDArray(x), "attention_mask": rt.NDArray(am),"mm_embeds": rt.NDArray(mm), "mm_mask": rt.NDArray(mmm)}))return np.array(out["embedding"].numpy(), dtype=np.float32).reshape(-1)def _finish(self, v: np.ndarray, dim: int) -> np.ndarray:if dim not in self.config["matryoshka_dims"]:raise ValueError(f"dim must be one of {self.config['matryoshka_dims']}")v = v[:dim]return v / max(float(np.linalg.norm(v)), 1e-12)def prewarm(self) -> float:"""One call per bucket (and one vision call, if loaded) so the first real call pays no first-call cost."""t = time.perf_counter()for S in self.buckets:self.embed_ids([self.config["bos_token_id"], self.config["eos_token_id"]], S)if self.vision_function is not None:self.soft_tokens(eg2_image.patchify_cell_major(np.full((48, 48, 3), 128, np.uint8)))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):if compute == "cpu":return rt.SpecializationOptions.cpu_only()if compute == "gpu":return rt.SpecializationOptions.from_preferred_compute_unit_kind(rt.ComputeUnitKind.gpu())if compute == "ane":return rt.SpecializationOptions.from_preferred_compute_unit_kind(rt.ComputeUnitKind.neural_engine())if compute == "default":return rt.SpecializationOptions.default()raise ValueError("compute must be ane | gpu | cpu | default")# ---- temp-file hygiene ----------------------------------------------------------------------------------4 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 shutilpid = pid or os.getpid()40 unmodified linesreturn float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))# ---- 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}")thr = ref["threshold_cosine"]for c in ref.get("cases", []):v = m.embed(c["text"], c["kind"])cos = cosine(v, c["embedding"])passed = cos >= thr and bool(np.all(np.isfinite(v)))ok = ok and passedprint(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {thr}) {c['kind']}: {c['text'][:60]}")if len(ref.get("cases", [])) > 1:c = ref["cases"][1] # Matryoshka prefixes vs the truncated + re-normalized referencefor dim in (512, 256, 128):cos = cosine(m.embed(c["text"], c["kind"], dim=dim), c["embedding"][:dim])ok = ok and cos >= thrprint(f"{'PASS' if cos >= thr else 'FAIL'} cosine {cos:.6f} at dim {dim}")images = ref.get("images", [])thr_img = ref.get("threshold_cosine_image", thr)img_vecs = []for c in images:t0 = time.perf_counter()v = m.embed_image(path.parent / c["file"])cos = cosine(v, c["embedding"])passed = cos >= thr_img and bool(np.all(np.isfinite(v)))ok = 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"])cos = cosine(v, c["embedding"])passed = cos >= thr and bool(np.all(np.isfinite(v)))ok = ok and passedif c["kind"] == "search_query":queries.append((c["text"], v))print(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {thr}) {c['kind']}: {c['text'][:60]}")if images:hits = 0for q, qv in queries:scores = [cosine(qv, iv) for iv in img_vecs]best = int(np.argmax(scores))want = next((i for i, c in enumerate(images) if c["query"] == q), -1)hits += best == wantprint(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")m.close()del mreturn ok# ---- CLI -------------------------------------------------------------------------------------------------def cmd_embed(a) -> int:m = EmbeddingGemma2CoreAI(a.bundle, a.compute)4 unmodified linesreturn 0def cmd_embed_image(a) -> int:m = EmbeddingGemma2CoreAI(a.bundle, a.compute, load_vision=True, image_compute=a.image_compute)for p in a.args:t0 = time.perf_counter()inputs = eg2_image.prepare_vision_inputs(p, a.exif)t1 = time.perf_counter()ids, soft, slots = m.image_sequence(m.soft_tokens(inputs))v = m._finish(m.embed_sequence(ids, soft, slots), a.dim)print(json.dumps({"image": p, "dim": a.dim, "n_soft": inputs.n_soft, "resized": [inputs.resized[1], inputs.resized[0]],"exif_orientation_applied": a.exif, "preprocess_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) else 1def cmd_tokcheck(a) -> int:12 unmodified linesdef 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)inputs = eg2_image.patchify_cell_major(px)tv, tt = [], []n = max(5, a.trials // 2)c0 = time.process_time()for _ in range(n):t0 = time.perf_counter()soft = m.soft_tokens(inputs)t1 = time.perf_counter()ids, soft, slots = m.image_sequence(soft)m.embed_sequence(ids, soft, slots)tv.append((t1 - t0) * 1000)tt.append((time.perf_counter() - t1) * 1000)cpu = (time.process_time() - c0) / n * 1000print(f"image (273 soft tokens, {n} trials): vision_2520 p50 {np.median(tv):.1f} ms (min {min(tv):.1f}), mm_288 p50 {np.median(tt):.1f} ms, "f"end-to-end p50 {np.median(np.array(tv) + np.array(tt)):.1f} ms, CPU {cpu:.1f} ms/image (excl. decode+resize)")big = rng.randint(0, 256, (1600, 2560, 3)).astype(np.uint8)t0 = time.perf_counter()for _ in range(3):eg2_image.patchify_cell_major(eg2_image.resize_bicubic_aa_u8(big, 624, 1008))print(f"preprocess (numpy resize 2560x1600 -> 1008x624 + patches): {(time.perf_counter() - t0) / 3 * 1000:.0f} ms")print("bucket p50 ms min ms p90 ms CPU ms/call tok/s")for S in m.buckets:ids = [m.config["bos_token_id"]] + [1000 + (i * 7919) % 200000 for i in range(1, S - 1)] + [m.config["eos_token_id"]]16 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 gc
12345676 unmodified lines141516171819# Exact versions of the environments this release was validated in (macOS 27.0, Apple silicon).# Runtime (python/), Python 3.12 or 3.14:coreai-core==1.0.0b3numpy==2.4.6tokenizers==0.23.3huggingface-hub==2.2.0# Exporter (export/), on top of the runtime, Python 3.12:6 unmodified linesnetworkx==3.7scipy==1.18.1packaging==26.3# Reference vectors (tests/make_smoke_reference.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)123456786 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:6 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)
1234567# Runtime requirements for python/ (macOS 27, Apple silicon; validated with Python 3.12 and 3.14).# 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.coreai-core==1.0.0b3numpy>=2.0,<2.5tokenizers>=0.22,<0.2412345678# 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.24
1234567891011123 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Smoke test: load the bundle, embed three fictional sentences, compare with the shipped fp32 reference vectors.python3 smoke_test.py [--bundle ../model] [--reference ../tests/smoke-reference.json] [--compute ane] [--cleanup-temp]Exit code 0 = every cosine >= threshold (0.999) and all values finite. The first run of a new executable (here: yourpython binary) specializes the model for the Neural Engine: expect up to ~145 s (139-144 s measured). Later runs loadin 0.4-1.5 s."""from __future__ import annotations3 unmodified linesHERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from embeddinggemma2_coreai import EmbeddingGemma2CoreAI, cosine, footprints_mb, remove_own_mpsgraph_temp_files # noqa: E402def main() -> int:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--bundle", default=str(HERE.parent / "model"))ap.add_argument("--reference", default=str(HERE.parent / "tests" / "smoke-reference.json"))ap.add_argument("--compute", default="ane", choices=["ane", "gpu", "cpu", "default"])ap.add_argument("--cleanup-temp", action="store_true", help="remove this process's MPSGraph temp folders at exit")a = ap.parse_args()import jsonref = json.loads(Path(a.reference).read_text(encoding="utf-8"))m = EmbeddingGemma2CoreAI(a.bundle, a.compute)print(f"loaded in {m.load_s:.1f} s (tokenizer {m.tokenizer_load_s:.2f} s), compute={a.compute}, buckets={m.buckets}")ok = Truefor c in ref["cases"]:v = m.embed(c["text"], c["kind"])cos = cosine(v, c["embedding"])passed = cos >= ref["threshold_cosine"] and all(map(lambda x: x == x and abs(x) != float("inf"), v.tolist()))ok = ok and passedprint(f"{'PASS' if passed else 'FAIL'} cosine {cos:.6f} (threshold {ref['threshold_cosine']}) {c['kind']}: {c['text'][:60]}")# Matryoshka prefixes must stay close to the truncated+renormalized reference toofor dim in (512, 256, 128):c = ref["cases"][1]v = m.embed(c["text"], c["kind"], dim=dim)r = c["embedding"][:dim]print(f"{'PASS' if cosine(v, r) >= ref['threshold_cosine'] else 'FAIL'} cosine {cosine(v, r):.6f} at dim {dim}")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")m.close()del mif a.cleanup_temp:import gc1234567891011121314153 unmodified lines1920212223242526272829303132333435363738394041#!/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 annotations3 unmodified linesHERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from embeddinggemma2_coreai import remove_own_mpsgraph_temp_files, run_smoke # noqa: E402def main() -> int:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--bundle", default=str(HERE.parent / "model"))ap.add_argument("--reference", action="append", default=None,help="reference file(s); default: tests/smoke-reference.json and tests/image-smoke-reference.json")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 gc
9 unmodified lines101112131415161718192021229 unmodified lines.executable(name: "eg2-cli", targets: ["eg2-cli"]),],targets: [// Library: exact Gemma tokenizer + Core AI embedder. No third-party dependencies..target(name: "EmbeddingGemma2CoreAI",path: "Sources/EmbeddingGemma2CoreAI",linkerSettings: [.linkedFramework("CoreAI")]),// Command-line tool: embed | smoke | tokcheck | latency | prewarm | cleanup-temp.executableTarget(name: "eg2-cli",dependencies: ["EmbeddingGemma2CoreAI"],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"],
12345678910111213141516171819202122235 unmodified lines293031323334353637383940414243444546474849505152532 unmodified lines5657585960616263646566676869707172737475767778798013 unmodified lines949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE).//// EmbeddingGemma 2 (text) on Apple Core AI, macOS 27. Loads the bundle folder (config.json, tokenizer/, the// .aimodel), tokenizes exactly like Hugging Face `tokenizers`, pads to the smallest sequence bucket, runs the// matching `main_<S>` function and returns the L2-normalized 768-d embedding (or a Matryoshka prefix).import CoreAIimport Foundationpublic struct BundleConfig: Decodable, Sendable {public let asset: Stringpublic let functions: [String]public let buckets: [Int]public let max_tokens: Intpublic let embedding_dim: Intpublic let matryoshka_dims: [Int]public let prompts: [String: String]public let bos_token_id: Int32public let eos_token_id: Int32public let pad_token_id: Int32}public enum ComputePreference: String, Sendable {5 unmodified linespublic struct EmbedderError: Error, CustomStringConvertible {public let description: String}public final class EmbeddingGemma2 {public let bundleURL: URLpublic let config: BundleConfigpublic let tokenizer: GemmaTokenizerpublic let compute: ComputePreference/// Wall-clock seconds spent in `AIModel(contentsOf:)` + `loadFunction` (specialization). 0.4–1.5 s warm;/// the first load by an executable that has not loaded this bundle before takes up to ~145 s (see README).public let loadSeconds: Doublepublic let tokenizerLoadSeconds: Doubleprivate let model: AIModelprivate let functions: [Int: InferenceFunction] // bucket -> main_<S>public var buckets: [Int] { functions.keys.sorted() }public init(bundle: URL, compute: ComputePreference = .neuralEngine) async throws {bundleURL = bundleself.compute = 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"))2 unmodified linesthrow EmbedderError(description: "tokenizer special ids do not match config.json")}t0 = Date()let options: SpecializationOptionsswitch compute {case .gpu: options = SpecializationOptions(preferredComputeUnitKind: .gpu)case .cpu: options = SpecializationOptions.cpuOnlycase .neuralEngine: options = SpecializationOptions(preferredComputeUnitKind: .neuralEngine)case .default: options = SpecializationOptions.default}model = try await AIModel(contentsOf: bundle.appendingPathComponent(config.asset), options: options)var fns: [Int: InferenceFunction] = [:]for name in config.functions {guard let s = Int(name.split(separator: "_").last ?? ""), let fn = try model.loadFunction(named: name) else {throw EmbedderError(description: "function \(name) missing from \(config.asset)")}fns[s] = fn}functions = fnsloadSeconds = Date().timeIntervalSince(t0)}// MARK: - Tokenization/// `<bos>` + prompt prefix + text + `<eos>`, truncated to the largest bucket (2048 tokens: longer input is cut).13 unmodified linesreturn b}// MARK: - Inference/// Runs `main_<bucket>` on already-tokenized ids (with `<bos>`/`<eos>`), right-padded with `<pad>`./// Returns the raw 768-d output (already L2-normalized by the graph), as Float.public func embed(ids: [Int32], bucket: Int? = nil) async throws -> [Float] {let S = try bucket ?? self.bucket(forTokenCount: ids.count)guard let fn = functions[S] else { throw EmbedderError(description: "no function for bucket \(S)") }guard ids.count <= S else { throw EmbedderError(description: "\(ids.count) ids do not fit bucket \(S)") }var inputIDs = NDArray(shape: [1, S], scalarType: .int32)var mask = NDArray(shape: [1, S], scalarType: .float16)do {var v = inputIDs.mutableView(as: Int32.self)var m = mask.mutableView(as: Float16.self)let pad = config.pad_token_idv.withUnsafeMutablePointer { p, _, _ infor i in 0..<S { p[i] = i < ids.count ? ids[i] : pad }}m.withUnsafeMutablePointer { p, _, _ infor i in 0..<S { p[i] = i < ids.count ? 1 : 0 }}}var out = try await fn.run(inputs: ["input_ids": inputIDs, "attention_mask": mask])guard let emb = out.remove("embedding")?.ndArray else { throw EmbedderError(description: "output 'embedding' missing") }let dim = config.embedding_dimvar result = [Float](repeating: 0, count: dim)let view = emb.view(as: Float16.self)view.withUnsafePointer { p, _, _ infor i in 0..<dim { result[i] = Float(p[i]) }}return result}/// Embeds one text. `dim` 768 (full) or a Matryoshka size 512/256/128: the leading dims, re-normalized.public func embed(_ text: String, kind: String? = "document", dim: Int = 768) async throws -> [Float] {guard config.matryoshka_dims.contains(dim) else { throw EmbedderError(description: "dim must be one of \(config.matryoshka_dims)") }var v = Array(try await embed(ids: tokenize(text, kind: kind)).prefix(dim))let norm = max(sqrt(v.reduce(0) { $0 + $1 * $1 }), 1e-12)for i in v.indices { v[i] /= norm }return v}/// Runs every bucket once so the first real call pays no specialization/first-call cost. Call it right after/// init, off the main thread. Returns the seconds it took.@discardableResultpublic func prewarm() async throws -> Double {let t0 = Date()for S in buckets {_ = try await embed(ids: [config.bos_token_id, config.eos_token_id], bucket: S)}return Date().timeIntervalSince(t0)}// MARK: - Temp-file hygiene/// Each Neural Engine load of this model makes MPSGraph write ~358 MB of compiled graph copies into/// `$TMPDIR/com.apple.MetalPerformanceShadersGraph/mpsgraph-<pid>-<date>-<n>/`. 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 or the model is still/// 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/// removed and their total bytes.12345678910111213141516171819202122232425262728293031323334353637383940414243445 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021032 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214313 unmodified lines157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313// 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 CoreGraphicsimport Foundationpublic struct BundleConfig: Decodable, Sendable {public struct Vision: Decodable, Sendable {public let asset: Stringpublic let function: Stringpublic 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]public let prompts: [String: String]public let bos_token_id: Int32public let eos_token_id: Int32public let pad_token_id: Int32public let boi_token_id: Int32public let image_token_id: Int32public let eoi_token_id: Int32}public enum ComputePreference: String, Sendable {5 unmodified linespublic struct EmbedderError: Error, CustomStringConvertible {public let description: Stringpublic init(description: String) { self.description = description }}/// A prepared sequence for `mm_<S>`: token ids with placeholder slots, and the soft tokens that fill them.public struct MultimodalSequence: Sendable {public var ids: [Int32]public var softTokens: [Float16] // [slots * 512] in sequence orderpublic var slots: [Int] // positions in `ids` that receive soft tokens (same count as rows)public init(ids: [Int32], softTokens: [Float16] = [], slots: [Int] = []) {self.ids = idsself.softTokens = softTokensself.slots = slots}}public final class EmbeddingGemma2 {public let bundleURL: URLpublic let config: BundleConfigpublic let tokenizer: GemmaTokenizer/// Where the text asset (texts, and the image sequence after the image encoder) runs.public 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: Doublepublic let tokenizerLoadSeconds: Doubleprivate let textModel: AIModelprivate 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 the/// vision asset (~300 MB more memory, its own first-load specialization) so that images can be embedded./// `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"))2 unmodified linesthrow 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] = [:]for name in config.functions {guard let s = Int(name.split(separator: "_").last ?? ""), let fn = try textModel.loadFunction(named: name) else {throw EmbedderError(description: "function \(name) missing from \(config.asset)")}fns[s] = fn}functions = fnsif loadVision {let vm = try await AIModel(contentsOf: bundle.appendingPathComponent(config.vision.asset), options: Self.options(self.imageCompute))guard let vf = try vm.loadFunction(named: config.vision.function) else {throw EmbedderError(description: "function \(config.vision.function) missing from \(config.vision.asset)")}visionModel = vmvisionFunction = vf} else {visionModel = nilvisionFunction = nil}loadSeconds = Date().timeIntervalSince(t0)}private static func options(_ compute: ComputePreference) -> SpecializationOptions {switch compute {case .gpu: return SpecializationOptions(preferredComputeUnitKind: .gpu)case .cpu: return SpecializationOptions.cpuOnlycase .neuralEngine: return SpecializationOptions(preferredComputeUnitKind: .neuralEngine)case .default: return SpecializationOptions.default}}// MARK: - Tokenization/// `<bos>` + prompt prefix + text + `<eos>`, truncated to the largest bucket (2048 tokens: longer input is cut).13 unmodified linesreturn b}// MARK: - Text/// Runs `mm_<bucket>` on already-tokenized ids (with `<bos>`/`<eos>`), right-padded with `<pad>`, no soft tokens./// Returns the raw 768-d output (already L2-normalized by the graph), as Float.public func embed(ids: [Int32], bucket: Int? = nil) async throws -> [Float] {try await embed(sequence: MultimodalSequence(ids: ids), bucket: bucket)}/// Embeds one text. `dim` 768 (full) or a Matryoshka size 512/256/128: the leading dims, re-normalized.public func embed(_ text: String, kind: String? = "document", dim: Int = 768) async throws -> [Float] {try normalized(try await embed(ids: tokenize(text, kind: kind)), dim: dim)}// MARK: - Images/// Embeds an image file. `applyEXIFOrientation: false` reproduces the upstream reference exactly; `true`/// embeds camera photos upright (what an app usually wants; the two vectors differ by cosine ~0.97).public func embedImage(url: URL, applyEXIFOrientation: Bool = false, dim: Int = 768) async throws -> [Float] {try await embedImage(try ImagePreprocessor.prepare(url: url, applyEXIFOrientation: applyEXIFOrientation), dim: dim)}/// Embeds a CGImage (e.g. a screenshot); its raw samples are used, alpha dropped.public func embedImage(cgImage: CGImage, dim: Int = 768) async throws -> [Float] {try await embedImage(try ImagePreprocessor.prepare(try ImageDecoder.decodeRGB(cgImage: cgImage)), dim: dim)}/// Embeds an already prepared image (`ImagePreprocessor.prepare`).public func embedImage(_ inputs: VisionInputs, dim: Int = 768) async throws -> [Float] {let soft = try await softTokens(inputs)return try normalized(try await embed(sequence: imageSequence(softTokens: soft)), dim: dim)}/// Soft tokens of one prepared image (`vision_2520`): `[n, 512]` as a flat array (n = inputs.softTokenCount).public func softTokens(_ inputs: VisionInputs) async throws -> [Float16] {guard let visionFunction else {throw EmbedderError(description: "vision asset not loaded: create the model with loadVision: true")}let N = VisionInputs.maxPatches, D = VisionInputs.patchDimguard inputs.patches.count == N * D else { throw EmbedderError(description: "VisionInputs has the wrong size") }var patches = NDArray(shape: [1, N, D], scalarType: .float16)var posX = NDArray(shape: [1, N], scalarType: .int32)var posY = NDArray(shape: [1, N], scalarType: .int32)var cos = NDArray(shape: [1, 1, N, VisionInputs.headDim], scalarType: .float16)var sin = NDArray(shape: [1, 1, N, VisionInputs.headDim], scalarType: .float16)var mask = NDArray(shape: [1, N], scalarType: .float16)fill(&patches, inputs.patches)fill(&posX, inputs.posX)fill(&posY, inputs.posY)fill(&cos, inputs.cos)fill(&sin, inputs.sin)fill(&mask, inputs.patchMask)var out = try await visionFunction.run(inputs: ["patches": patches, "pos_x": posX, "pos_y": posY, "cos": cos, "sin": sin, "patch_mask": mask])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-image sequence: `<bos> <|image> <|image|> x n <image|> <eos>` (no prompt).public func imageSequence(softTokens: [Float16]) -> MultimodalSequence {let n = softTokens.count / hiddenvar ids = [config.bos_token_id, config.boi_token_id]ids.append(contentsOf: [Int32](repeating: config.image_token_id, count: n))ids.append(contentsOf: [config.eoi_token_id, 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 at/// `slots`). Any mix of text and images works as long as it fits a bucket (e.g. several images, or text + image)./// Returns the raw 768-d output (L2-normalized by the graph), as Float.public func embed(sequence seq: MultimodalSequence, bucket: Int? = nil) async throws -> [Float] {let S = try bucket ?? self.bucket(forTokenCount: seq.ids.count)guard let fn = functions[S] else { throw EmbedderError(description: "no function for bucket \(S)") }guard seq.ids.count <= S else { throw EmbedderError(description: "\(seq.ids.count) ids do not fit bucket \(S)") }guard seq.slots.count * hidden == seq.softTokens.count else { throw EmbedderError(description: "soft tokens do not match slots") }guard seq.slots.allSatisfy({ $0 >= 0 && $0 < seq.ids.count }) else { throw EmbedderError(description: "slot outside the sequence") }var inputIDs = NDArray(shape: [1, S], scalarType: .int32)var mask = NDArray(shape: [1, S], scalarType: .float16)var mm = NDArray(shape: [1, S, hidden], scalarType: .float16)var mmMask = NDArray(shape: [1, S], scalarType: .float16)do {let v = inputIDs.mutableView(as: Int32.self)let m = mask.mutableView(as: Float16.self)let e = mm.mutableView(as: Float16.self)let em = mmMask.mutableView(as: Float16.self)let pad = config.pad_token_idlet ids = seq.idsv.withUnsafeMutablePointer { p, _, _ in for i in 0..<S { p[i] = i < ids.count ? ids[i] : pad } }m.withUnsafeMutablePointer { p, _, _ in for i in 0..<S { p[i] = i < ids.count ? 1 : 0 } }let h = hiddene.withUnsafeMutablePointer { p, _, _ infor i in 0..<(S * h) { p[i] = 0 }for (r, slot) in seq.slots.enumerated() {for j in 0..<h { p[slot * h + j] = seq.softTokens[r * h + j] }}}em.withUnsafeMutablePointer { p, _, _ infor i in 0..<S { p[i] = 0 }for slot in seq.slots { p[slot] = 1 }}}var out = try await fn.run(inputs: ["input_ids": inputIDs, "attention_mask": mask, "mm_embeds": mm, "mm_mask": mmMask])guard let emb = out.remove("embedding")?.ndArray else { throw EmbedderError(description: "output 'embedding' missing") }let dim = config.embedding_dimvar result = [Float](repeating: 0, count: dim)let view = emb.view(as: Float16.self)view.withUnsafePointer { p, _, _ in for i in 0..<dim { result[i] = Float(p[i]) } }return result}private func normalized(_ v: [Float], dim: Int) throws -> [Float] {guard config.matryoshka_dims.contains(dim) else { throw EmbedderError(description: "dim must be one of \(config.matryoshka_dims)") }var r = Array(v.prefix(dim))let norm = max(sqrt(r.reduce(0) { $0 + $1 * $1 }), 1e-12)for i in r.indices { r[i] /= norm }return r}/// Runs every text bucket (and the vision function, if loaded) once so the first real call pays no/// first-call cost. Call it right after init, off the main thread. Returns the seconds it took.@discardableResultpublic func prewarm() async throws -> Double {let t0 = Date()for S in buckets {_ = try await embed(ids: [config.bos_token_id, config.eos_token_id], bucket: S)}if visionFunction != nil {_ = try await softTokens(ImagePreprocessor.patchify(resizedRGB: [UInt8](repeating: 128, count: 48 * 48 * 3), width: 48, height: 48))}return Date().timeIntervalSince(t0)}private func fill<T: BitwiseCopyable>(_ arr: inout NDArray, _ values: [T]) {let v = arr.mutableView(as: T.self)v.withUnsafeMutablePointer { p, _, _ invalues.withUnsafeBufferPointer { src in p.update(from: src.baseAddress!, count: values.count) }}}// MARK: - Temp-file hygiene/// 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 folders/// removed and their total bytes.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE).// The CMYK -> RGB conversion is ported from Pillow's formula (MIT-CMU/HPND); see ../../../NOTICE for its notice.//// Decodes an image file (or a CGImage) to 8-bit RGB the way the upstream pipeline does (`decode_image` /// Pillow `convert("RGB")`): the stored samples are used as they are — alpha is DROPPED (not composited, not// un-premultiplied), EXIF orientation is NOT applied unless asked, no colour management (ICC profiles are// ignored). Core Graphics drawing would premultiply, composite and colour-match, so the samples are read straight// from the decoded CGImage buffer and unpacked by hand (RGB/RGBA/gray/gray+alpha/indexed/CMYK, 1-16 bits per// component); anything else falls back to a Core Graphics draw into an RGB bitmap (documented tolerance).//// PNG and WebP decode to the same bytes as Pillow/libpng. JPEG does not: ImageIO's decoder differs from libjpeg// by 1-3 per sample without chroma subsampling and by up to ~80 at colour edges of 4:2:0 files (different chroma// upsampling). Embedding effect: cosine >= 0.998 on camera photos, down to ~0.98 on 4:2:0 JPEGs of charts with// saturated colour edges (see README "Accuracy"). Decode with libjpeg if reference-exact JPEG vectors are needed.
import CoreGraphicsimport Foundationimport ImageIO
public struct DecodedImage: Sendable { public var width: Int public var height: Int public var rgb: [UInt8] // interleaved, row-major, width * height * 3
public init(width: Int, height: Int, rgb: [UInt8]) { self.width = width self.height = height self.rgb = rgb }}
public enum ImageDecoder { /// Decodes the first image of a file. `applyEXIFOrientation` rotates/flips to the display orientation /// (the upstream reference does not; see README). public static func decodeRGB(url: URL, applyEXIFOrientation: Bool = false) throws -> DecodedImage { guard let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { throw EmbedderError(description: "cannot open image \(url.path)") } guard let cg = CGImageSourceCreateImageAtIndex(src, 0, [kCGImageSourceShouldCache: false] as CFDictionary) else { throw EmbedderError(description: "cannot decode image \(url.path)") } var img = try decodeRGB(cgImage: cg) if applyEXIFOrientation, let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any], let o = props[kCGImagePropertyOrientation] as? UInt32, let orientation = CGImagePropertyOrientation(rawValue: o) { img = oriented(img, orientation) } return img }
/// Raw samples of a CGImage (e.g. a screenshot) as RGB, alpha dropped. See the header for the rules. public static func decodeRGB(cgImage cg: CGImage) throws -> DecodedImage { let w = cg.width, h = cg.height let bpc = cg.bitsPerComponent, bpp = cg.bitsPerPixel, bpr = cg.bytesPerRow let model = cg.colorSpace?.model let byteOrder = cg.bitmapInfo.intersection(.byteOrderMask) let alpha = cg.alphaInfo let isFloat = cg.bitmapInfo.contains(.floatComponents) guard let data = cg.dataProvider?.data, let base = CFDataGetBytePtr(data), !isFloat, let model else { return try drawFallback(cg) } let n = CFDataGetLength(data) guard n >= bpr * h else { return try drawFallback(cg) } var out = [UInt8](repeating: 0, count: w * h * 3) let components: Int switch model { case .rgb: components = 3 case .monochrome: components = 1 case .cmyk: components = 4 case .indexed: components = 1 default: return try drawFallback(cg) } let hasAlpha = ![CGImageAlphaInfo.none, .noneSkipLast, .noneSkipFirst].contains(alpha) || (model == .rgb && bpp == 32 && bpc == 8) let alphaFirst = alpha == .first || alpha == .premultipliedFirst || alpha == .noneSkipFirst let channelsInPixel = bpp / bpc guard channelsInPixel == components || channelsInPixel == components + 1 else { return try drawFallback(cg) } let little16 = byteOrder == .byteOrder16Little let little32 = byteOrder == .byteOrder32Little
// Sample accessor for 8/16-bit packed pixels: returns the 8-bit value of channel c of pixel (x, y). // Memory layout: big-endian (default) = logical order; 32-bit little-endian reverses the 4 bytes. @inline(__always) func sample8(_ row: UnsafePointer<UInt8>, _ x: Int, _ c: Int) -> UInt8 { var ch = c + (hasAlpha && alphaFirst ? 1 : 0) if bpc == 8 { if little32 && channelsInPixel == 4 { ch = 3 - ch } return row[x * channelsInPixel + ch] } // 16 bits per component: high byte (PIL's convert clips >255 to 255; upstream divides by 255 and // produces garbage — neither is useful, the high byte is the sensible 8-bit rendering) let p = row + (x * channelsInPixel + ch) * 2 return little16 ? p[1] : p[0] } if model == .indexed { var table = [UInt8](repeating: 0, count: 256 * 3) let count = cg.colorSpace?.colorTable?.count ?? 0 // RGB triples if let ct = cg.colorSpace?.colorTable, count > 0 { for i in 0..<min(count, 256 * 3) { table[i] = ct[i] } } else { return try drawFallback(cg) } for y in 0..<h { let row = base + y * bpr for x in 0..<w { let idx = Int(unpack(row, x, bitsPerComponent: bpc, channel: 0, channels: channelsInPixel)) let i = min(idx, 255) * 3 out[(y * w + x) * 3] = table[i] out[(y * w + x) * 3 + 1] = table[i + 1] out[(y * w + x) * 3 + 2] = table[i + 2] } } return DecodedImage(width: w, height: h, rgb: out) } if bpc < 8 { // 1/2/4-bit gray (bilevel PNG): scale to 0...255 like libpng/PIL ("1" -> 0/255) guard model == .monochrome else { return try drawFallback(cg) } let maxv = (1 << bpc) - 1 for y in 0..<h { let row = base + y * bpr for x in 0..<w { let v = UInt8(Int(unpack(row, x, bitsPerComponent: bpc, channel: 0, channels: channelsInPixel)) * 255 / maxv) out[(y * w + x) * 3] = v; out[(y * w + x) * 3 + 1] = v; out[(y * w + x) * 3 + 2] = v } } return DecodedImage(width: w, height: h, rgb: out) } guard bpc == 8 || bpc == 16 else { return try drawFallback(cg) } for y in 0..<h { let row = base + y * bpr let o = y * w * 3 switch model { case .rgb: for x in 0..<w { out[o + x * 3] = sample8(row, x, 0) out[o + x * 3 + 1] = sample8(row, x, 1) out[o + x * 3 + 2] = sample8(row, x, 2) } case .monochrome: for x in 0..<w { let v = sample8(row, x, 0) out[o + x * 3] = v; out[o + x * 3 + 1] = v; out[o + x * 3 + 2] = v } case .cmyk: // Pillow's CMYK -> RGB: nk = 255 - k; c' = nk - c*nk/255 (MULDIV255 rounding). ImageIO's // samples are the inverse of Pillow's ink values (verified on an Adobe CMYK JPEG), so invert. for x in 0..<w { let c = 255 - Int(sample8(row, x, 0)), m = 255 - Int(sample8(row, x, 1)), yy = 255 - Int(sample8(row, x, 2)), k = 255 - Int(sample8(row, x, 3)) let nk = 255 - k @inline(__always) func mul(_ a: Int) -> Int { let t = a * nk + 128; return ((t >> 8) + t) >> 8 } out[o + x * 3] = UInt8(clamping: nk - mul(c)) out[o + x * 3 + 1] = UInt8(clamping: nk - mul(m)) out[o + x * 3 + 2] = UInt8(clamping: nk - mul(yy)) } default: return try drawFallback(cg) } } return DecodedImage(width: w, height: h, rgb: out) }
@inline(__always) private static func unpack(_ row: UnsafePointer<UInt8>, _ x: Int, bitsPerComponent bpc: Int, channel: Int, channels: Int) -> UInt32 { if bpc == 8 { return UInt32(row[x * channels + channel]) } if bpc == 16 { return UInt32(row[(x * channels + channel) * 2]) } let bit = (x * channels + channel) * bpc let byte = row[bit >> 3] let shift = 8 - bpc - (bit & 7) return UInt32((byte >> UInt8(shift)) & UInt8((1 << bpc) - 1)) }
/// Core Graphics draw (colour-managed, alpha composited over black): the fallback for exotic formats. private static func drawFallback(_ cg: CGImage) throws -> DecodedImage { let w = cg.width, h = cg.height var buf = [UInt8](repeating: 0, count: w * h * 4) let ok = buf.withUnsafeMutableBytes { p -> Bool in guard let ctx = CGContext(data: p.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) else { return false } ctx.interpolationQuality = .none ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h)) return true } guard ok else { throw EmbedderError(description: "cannot draw image (\(cg.bitsPerComponent) bpc, \(cg.bitsPerPixel) bpp)") } var out = [UInt8](repeating: 0, count: w * h * 3) for i in 0..<(w * h) { out[i * 3] = buf[i * 4]; out[i * 3 + 1] = buf[i * 4 + 1]; out[i * 3 + 2] = buf[i * 4 + 2] } return DecodedImage(width: w, height: h, rgb: out) }
/// Applies an EXIF orientation (1...8) to an RGB buffer (Pillow `ImageOps.exif_transpose`). public static func oriented(_ img: DecodedImage, _ o: CGImagePropertyOrientation) -> DecodedImage { let w = img.width, h = img.height let swap = [CGImagePropertyOrientation.left, .right, .leftMirrored, .rightMirrored].contains(o) let ow = swap ? h : w, oh = swap ? w : h if o == .up { return img } var out = [UInt8](repeating: 0, count: ow * oh * 3) for y in 0..<h { for x in 0..<w { let (dx, dy): (Int, Int) switch o { case .up: (dx, dy) = (x, y) case .upMirrored: (dx, dy) = (w - 1 - x, y) case .down: (dx, dy) = (w - 1 - x, h - 1 - y) case .downMirrored: (dx, dy) = (x, h - 1 - y) case .leftMirrored: (dx, dy) = (y, x) // transpose case .right: (dx, dy) = (h - 1 - y, x) // rotate 90 CW to display case .rightMirrored: (dx, dy) = (h - 1 - y, w - 1 - x) // transverse case .left: (dx, dy) = (y, w - 1 - x) // rotate 90 CCW @unknown default: (dx, dy) = (x, y) } let s = (y * w + x) * 3, d = (dy * ow + dx) * 3 out[d] = img.rgb[s]; out[d + 1] = img.rgb[s + 1]; out[d + 2] = img.rgb[s + 2] } } return DecodedImage(width: ow, height: oh, rgb: out) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE).//// Ports the logic of the Gemma 4 image processor (image_processing_gemma4.py in Hugging Face transformers 5.19,// Copyright 2026 The HuggingFace Team, Apache-2.0); see ../../../NOTICE.//// Host-side preparation of the `vision_2520` inputs: target size (aspect-preserving, multiples of 48 px, at most// 2520 patches of 16x16), the exact resize, 16x16x3 patches of INTEGER pixel values 0..255 (exact in Float16; the// graph computes P - 127.5 with upstream's 2/255 scale folded into its first projection) in CELL-MAJOR order (the// 9 patches of each 3x3 pooling cell contiguous, cells row-major), (x, y) patch positions, the axial-RoPE cos/sin// tables and the patch mask. Mirrors python/eg2_image.py.
import Foundation
public struct VisionInputs: Sendable { public static let patch = 16 public static let pool = 3 public static let cellPx = 48 public static let maxSoftTokens = 280 public static let maxPatches = 2520 public static let patchDim = 768 // 16 * 16 * 3 public static let headDim = 64 public static let ropeTheta = 100.0
public var patches: [Float16] // [2520 * 768], pixel values 0..255, zero padded public var posX: [Int32] // [2520], 0 for padding public var posY: [Int32] // [2520] public var cos: [Float16] // [2520 * 64] public var sin: [Float16] // [2520 * 64] public var patchMask: [Float16] // [2520], 1 = patch, 0 = padding public var softTokenCount: Int // n: valid rows of the vision output public var gridRows: Int // patch rows public var gridCols: Int // patch cols public var resizedHeight: Int public var resizedWidth: Int}
public enum ImagePreprocessor { /// Gemma4 `get_aspect_ratio_preserving_size` (height, width), verbatim logic. public static func targetSize(height: Int, width: Int, maxPatches: Int = VisionInputs.maxPatches) throws -> (height: Int, width: Int) { let patch = VisionInputs.patch, cell = VisionInputs.cellPx let targetPx = Double(maxPatches * patch * patch) let factor = (targetPx / Double(height * width)).squareRoot() var th = Int((factor * Double(height) / Double(cell)).rounded(.down)) * cell var tw = Int((factor * Double(width) / Double(cell)).rounded(.down)) * cell let maxSide = (maxPatches / (VisionInputs.pool * VisionInputs.pool)) * cell if th == 0 && tw == 0 { throw EmbedderError(description: "image would resize to 0x0") } if th == 0 { th = cell tw = min(Int((Double(width) / Double(height)).rounded(.down)) * cell, maxSide) } else if tw == 0 { tw = cell th = min(Int((Double(height) / Double(width)).rounded(.down)) * cell, maxSide) } if Double(th * tw) > targetPx { throw EmbedderError(description: "size exceeds the patch budget") } return (th, tw) }
/// Resized 8-bit RGB (interleaved, [height][width][3]) of a decoded image, exactly as the upstream processor /// produces it (bicubic antialiased on uint8, width pass then height pass). public static func resized(_ image: DecodedImage) throws -> DecodedImage { let (th, tw) = try targetSize(height: image.height, width: image.width) let px = ImageResampler.resize(image.rgb, width: image.width, height: image.height, channels: 3, toWidth: tw, toHeight: th) return DecodedImage(width: tw, height: th, rgb: px) }
/// Decode (no EXIF orientation unless asked, alpha dropped, no colour management) + resize + patches. public static func prepare(url: URL, applyEXIFOrientation: Bool = false) throws -> VisionInputs { try prepare(try ImageDecoder.decodeRGB(url: url, applyEXIFOrientation: applyEXIFOrientation)) }
public static func prepare(_ decoded: DecodedImage) throws -> VisionInputs { let r = try resized(decoded) return patchify(resizedRGB: r.rgb, width: r.width, height: r.height) }
/// `rgb`: [height][width][3] uint8 with height, width multiples of 48. public static func patchify(resizedRGB rgb: [UInt8], width W: Int, height H: Int) -> VisionInputs { let P = VisionInputs.patch, K = VisionInputs.pool, N = VisionInputs.maxPatches, D = VisionInputs.patchDim let ph = H / P, pw = W / P let kh = ph / K, kw = pw / K let n = kh * kw var patches = [Float16](repeating: 0, count: N * D) var posX = [Int32](repeating: 0, count: N) var posY = [Int32](repeating: 0, count: N) var mask = [Float16](repeating: 0, count: N) var idx = 0 rgb.withUnsafeBufferPointer { sp in patches.withUnsafeMutableBufferPointer { pp in for ky in 0..<kh { for kx in 0..<kw { for dy in 0..<K { for dx in 0..<K { let x = kx * K + dx, y = ky * K + dy posX[idx] = Int32(x) posY[idx] = Int32(y) mask[idx] = 1 let base = idx * D var o = 0 for py in 0..<P { let row = sp.baseAddress! + ((y * P + py) * W + x * P) * 3 for e in 0..<(P * 3) { pp[base + o] = Float16(row[e]) // 0...255, exact o += 1 } } idx += 1 } } } } } } let (cos, sin) = ropeTables(posX: posX, posY: posY) return VisionInputs(patches: patches, posX: posX, posY: posY, cos: cos, sin: sin, patchMask: mask, softTokenCount: n, gridRows: ph, gridCols: pw, resizedHeight: H, resizedWidth: W) }
/// Axial RoPE tables [N, 64]: channels 0..31 rotate by x (16 frequencies, duplicated), 32..63 by y. /// float32 maths like upstream, cast to fp16. public static func ropeTables(posX: [Int32], posY: [Int32]) -> (cos: [Float16], sin: [Float16]) { let F = VisionInputs.headDim / 4 // 16 var inv = [Float](repeating: 0, count: F) for i in 0..<F { inv[i] = Float(1.0 / pow(VisionInputs.ropeTheta, Double(2 * i) / Double(2 * F))) } let N = posX.count var cos = [Float16](repeating: 0, count: N * 64) var sin = [Float16](repeating: 0, count: N * 64) for p in 0..<N { let fx = Float(posX[p]), fy = Float(posY[p]) for i in 0..<F { let ax = fx * inv[i], ay = fy * inv[i] let cx = Float16(cosf(ax)), sx = Float16(sinf(ax)), cy = Float16(cosf(ay)), sy = Float16(sinf(ay)) let b = p * 64 cos[b + i] = cx; cos[b + F + i] = cx; cos[b + 2 * F + i] = cy; cos[b + 3 * F + i] = cy sin[b + i] = sx; sin[b + F + i] = sx; sin[b + 2 * F + i] = sy; sin[b + 3 * F + i] = sy } } return (cos, sin) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163// Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../../../LICENSE).//// Ported from the logic of ATen's uint8 `_upsample_bicubic2d_aa` kernel (PyTorch, aten/src/ATen/native/cpu/// UpSampleKernel.cpp, BSD-3-Clause; itself modelled on Pillow's Resample.c, MIT-CMU/HPND). See ../../../NOTICE for// the PyTorch and Pillow license notices.//// Antialiased bicubic resize on 8-bit pixels, bit-identical to the one the upstream image processor uses// (torchvision `resize(..., BICUBIC, antialias=True)` on a uint8 tensor = ATen's `_upsample_bicubic2d_aa` uint8// kernel): separable, WIDTH pass first then HEIGHT, taps computed in float64 and rounded to int16 with a dynamic// precision, each pass accumulated in int32, rounded (+half, arithmetic shift) and clamped to 0...255.// Lanczos or bilinear resampling (what Core Image / vImage offer) changes the embedding (cosine down to 0.86 for// Lanczos, 0.96 for bilinear on the validation set), hence this port.// Verified against torchvision 0.29.1 pixel for pixel (see tests/preprocess-cases.json and `eg2-cli pixcheck`).
import Foundation
public enum ImageResampler { /// Taps of one axis: for output index i the input window starts at `start[i]` and has `count[i]` taps whose /// int16 weights (as Int32) are `weights[i * taps ..< i * taps + count[i]]`; `precision` is the fixed-point shift. public struct Taps: Sendable { public let start: [Int32] public let count: [Int32] public let weights: [Int32] public let taps: Int public let precision: Int }
@inline(__always) private static func cubic(_ v: Double) -> Double { let a = -0.5 let x = abs(v) if x < 1.0 { return ((a + 2.0) * x - (a + 3.0)) * x * x + 1.0 } if x < 2.0 { return (((x - 5.0) * x + 8.0) * x - 4.0) * a } return 0.0 }
/// ATen `HelperInterpBase::_compute_indices_min_size_weights_aa` + `_compute_index_ranges_int16_weights`. public static func taps(inSize: Int, outSize: Int) -> Taps { let scale = Double(inSize) / Double(outSize) let support = scale >= 1.0 ? 2.0 * scale : 2.0 let invscale = scale >= 1.0 ? 1.0 / scale : 1.0 let taps = Int(ceil(support)) * 2 + 1 var w = [Double](repeating: 0, count: outSize * taps) var start = [Int32](repeating: 0, count: outSize) var count = [Int32](repeating: 0, count: outSize) var wtMax = 0.0 for i in 0..<outSize { let center = scale * (Double(i) + 0.5) let lo = max(Int(center - support + 0.5), 0) // (int64_t) cast: truncation toward zero let size = min(Int(center + support + 0.5), inSize) - lo var total = 0.0 for j in 0..<size { let v = cubic((Double(j + lo) - center + 0.5) * invscale) w[i * taps + j] = v total += v } if total != 0.0 { for j in 0..<size { w[i * taps + j] /= total } } for j in 0..<size { wtMax = max(wtMax, w[i * taps + j]) } start[i] = Int32(lo) count[i] = Int32(size) } var precision = 0 while precision < 22 { if Int(0.5 + wtMax * Double(1 << (precision + 1))) >= (1 << 15) { break } precision += 1 } let s = Double(1 << precision) let wi = w.map { v -> Int32 in v >= 0 ? Int32((v * s + 0.5).rounded(.down)) : Int32((v * s - 0.5).rounded(.up)) } return Taps(start: start, count: count, weights: wi, taps: taps, precision: precision) }
/// Interleaved 8-bit image [height][width][channels] -> [outHeight][outWidth][channels]. public static func resize(_ src: [UInt8], width: Int, height: Int, channels: Int, toWidth outW: Int, toHeight outH: Int) -> [UInt8] { if width == outW && height == outH { return src } var cur = src var curW = width if width != outW { cur = passWidth(cur, width: width, height: height, channels: channels, taps: taps(inSize: width, outSize: outW), outW: outW) curW = outW } if height != outH { cur = passHeight(cur, width: curW, height: height, channels: channels, taps: taps(inSize: height, outSize: outH), outH: outH) } return cur }
private static func passWidth(_ src: [UInt8], width: Int, height: Int, channels: Int, taps t: Taps, outW: Int) -> [UInt8] { var out = [UInt8](repeating: 0, count: outW * height * channels) let half = Int32(1 << (t.precision - 1)) let shift = Int32(t.precision) src.withUnsafeBufferPointer { sp in out.withUnsafeMutableBufferPointer { op in t.weights.withUnsafeBufferPointer { wp in guard let s0 = sp.baseAddress, let o0 = op.baseAddress, let w0 = wp.baseAddress else { return } // Each iteration writes its own output row only; the pointers outlive concurrentPerform. let sb = SharedPointer(s0), ob = SharedMutablePointer(o0), wb = SharedPointer(w0) DispatchQueue.concurrentPerform(iterations: height) { y in let row = sb.p + y * width * channels let orow = ob.p + y * outW * channels for i in 0..<outW { let lo = Int(t.start[i]), n = Int(t.count[i]) let wbase = wb.p + i * t.taps for c in 0..<channels { var acc = half var p = row + lo * channels + c for j in 0..<n { acc &+= Int32(p.pointee) &* wbase[j] p += channels } orow[i * channels + c] = UInt8(clamping: acc >> shift) } } } } } } return out }
private static func passHeight(_ src: [UInt8], width: Int, height: Int, channels: Int, taps t: Taps, outH: Int) -> [UInt8] { var out = [UInt8](repeating: 0, count: width * outH * channels) let half = Int32(1 << (t.precision - 1)) let shift = Int32(t.precision) let rowLen = width * channels src.withUnsafeBufferPointer { sp in out.withUnsafeMutableBufferPointer { op in t.weights.withUnsafeBufferPointer { wp in guard let s0 = sp.baseAddress, let o0 = op.baseAddress, let w0 = wp.baseAddress else { return } // Each iteration writes its own output row only; the pointers outlive concurrentPerform. let sb = SharedPointer(s0), ob = SharedMutablePointer(o0), wb = SharedPointer(w0) DispatchQueue.concurrentPerform(iterations: outH) { i in let lo = Int(t.start[i]), n = Int(t.count[i]) let wbase = wb.p + i * t.taps let orow = ob.p + i * rowLen for x in 0..<rowLen { var acc = half var p = sb.p + lo * rowLen + x for j in 0..<n { acc &+= Int32(p.pointee) &* wbase[j] p += rowLen } orow[x] = UInt8(clamping: acc >> shift) } } } } } return out }}
/// Raw pointers handed to `DispatchQueue.concurrentPerform`, whose iterations read shared input and write disjoint/// output rows; the buffers stay alive for the whole call.private struct SharedPointer<T>: @unchecked Sendable { let p: UnsafePointer<T> init(_ p: UnsafePointer<T>) { self.p = p }}
private struct SharedMutablePointer<T>: @unchecked Sendable { let p: UnsafeMutablePointer<T> init(_ p: UnsafeMutablePointer<T>) { self.p = p }}1 unmodified line2345678910111213141516171 unmodified line1920212223242513 unmodified lines39404142434410 unmodified lines555657585960616263644 unmodified lines69707172737475767778797 unmodified lines8788899091929394959697989910010110210310410510636 unmodified lines1431441451461471481491501511528 unmodified lines1611621631641651661671681692 unmodified lines1721731741751761771781791801 unmodified line//// eg2-cli — command-line front end for the EmbeddingGemma2CoreAI library.//// eg2-cli embed <bundle> [--compute ane|gpu|cpu] [--kind document|search_query|...] [--dim 768] "text" ...// eg2-cli smoke <bundle> <smoke-reference.json> [--compute ane|gpu|cpu] [--cleanup-temp]// eg2-cli tokcheck <bundle> <tokenizer-cases.json>// eg2-cli latency <bundle> [--compute ane|gpu|cpu] [--trials 50]// eg2-cli prewarm <bundle> [--compute ane|gpu|cpu]// eg2-cli cleanup-temp (removes this process's MPSGraph temp folders; mostly useful after the others)//// Every command accepts --cleanup-temp to delete the MPSGraph temp folders this process created, after the// model is released (see EmbeddingGemma2.removeOwnMPSGraphTempFiles).import EmbeddingGemma2CoreAIimport Foundation1 unmodified line@MainActor func usage() -> Never {print("""usage: eg2-cli <embed|smoke|tokcheck|latency|prewarm|cleanup-temp> <bundle> [...] [--compute ane|gpu|cpu] [--cleanup-temp]""")exit(2)}13 unmodified linesfunc fmt(_ x: Double, _ digits: Int = 2) -> String { String(format: "%.\(digits)f", x) }func cpuSeconds() -> Double {var u = rusage()getrusage(RUSAGE_SELF, &u)10 unmodified linesreturn (Double(r.ri_lifetime_max_phys_footprint) / 1048576, Double(r.ri_neural_footprint) / 1048576)}guard !args.isEmpty else { usage() }let cmd = args.removeFirst()let cleanup = takeFlag("--cleanup-temp")let compute = ComputePreference(rawValue: takeOption("--compute") ?? "ane") ?? .neuralEngine@MainActor func finish(_ code: Int32) -> Never {if cleanup {4 unmodified lines}if cmd == "cleanup-temp" { finish(0) }guard let bundlePath = args.first else { usage() }args.removeFirst()let bundle = URL(fileURLWithPath: bundlePath)do {switch cmd {case "embed":let kind = takeOption("--kind") ?? "document"7 unmodified lines_ = consume eg2finish(0)case "smoke":guard let refPath = args.first else { usage() }struct Ref: Decodable { let text: String; let kind: String; let embedding: [Float] }struct RefFile: Decodable { let threshold_cosine: Double; let cases: [Ref] }let ref = try JSONDecoder().decode(RefFile.self, from: Data(contentsOf: URL(fileURLWithPath: refPath)))let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute)print("loaded in \(fmt(eg2.loadSeconds, 1)) s (tokenizer \(fmt(eg2.tokenizerLoadSeconds, 2)) s), compute=\(compute.rawValue), buckets=\(eg2.buckets)")var ok = truefor c in ref.cases {let v = try await eg2.embed(c.text, kind: c.kind)let cos = cosineSimilarity(v, c.embedding)let pass = cos >= ref.threshold_cosine && v.allSatisfy { $0.isFinite }ok = ok && passprint("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(ref.threshold_cosine)) \(c.kind): \(c.text.prefix(60))")}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)print("loaded in \(fmt(eg2.loadSeconds, 1)) s, compute=\(compute.rawValue)")let warm = try await eg2.prewarm()print("prewarm (one call per bucket) \(fmt(warm, 2)) s")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)8 unmodified linests.append(Date().timeIntervalSince(t) * 1000)}let cpu = (cpuSeconds() - cpu0) / Double(trials) * 1000ts.sort()let p50 = ts[ts.count / 2], p90 = ts[min(ts.count - 1, Int(Double(ts.count) * 0.9))]print(String(format: "%5d %7.2f %7.2f %7.2f %11.2f %6.0f", S, p50, ts[0], p90, cpu, Double(S) / p50 * 1000))}let fp = footprints()print("peak footprint \(fmt(fp.physMB, 0)) MB, neural footprint \(fmt(fp.neuralMB, 0)) MB (\(fp.neuralMB > 0 ? "Neural Engine in use" : "Neural Engine NOT used"))")2 unmodified linescase "prewarm":let t0 = Date()let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute)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")_ = consume eg2finish(0)1 unmodified line2345678910111213141516171819202122232425261 unmodified line282930313233343513 unmodified lines495051525354555610 unmodified lines67686970717273747576777879808182838485868788899091924 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691707 unmodified lines17817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526636 unmodified lines3033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373388 unmodified lines3473483493503513523533542 unmodified lines3573583593603613623633643651 unmodified line//// eg2-cli — command-line front end for the EmbeddingGemma2CoreAI library.//// 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 EmbeddingGemma2CoreAIimport Foundation1 unmodified line@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)}13 unmodified linesfunc fmt(_ x: Double, _ digits: Int = 2) -> String { String(format: "%.\(digits)f", x) }func sha256(_ bytes: [UInt8]) -> String { SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined() }func cpuSeconds() -> Double {var u = rusage()getrusage(RUSAGE_SELF, &u)10 unmodified linesreturn (Double(r.ri_lifetime_max_phys_footprint) / 1048576, Double(r.ri_neural_footprint) / 1048576)}func percentile(_ xs: [Double], _ p: Double) -> Double {let s = xs.sorted()return s[min(s.count - 1, Int(Double(s.count) * p))]}guard !args.isEmpty else { usage() }let cmd = args.removeFirst()let cleanup = takeFlag("--cleanup-temp")@MainActor func computeOption(_ name: String) -> ComputePreference? {guard let raw = takeOption(name) else { return nil }guard let c = ComputePreference(rawValue: raw) else {print("\(name) must be ane, gpu, cpu or default")exit(2)}return c}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 {4 unmodified lines}if cmd == "cleanup-temp" { finish(0) }struct PixCase: Decodable {let file: String; let width: Int; let height: Int; let resized_width: Int; let resized_height: Int; let n_soft: Intlet 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]?}do {switch cmd {case "pixcheck":guard let casesPath = args.first else { usage() }let url = URL(fileURLWithPath: casesPath)let cases = try JSONDecoder().decode([PixCase].self, from: Data(contentsOf: url))let base = url.deletingLastPathComponent()var exact = 0, lossyDiff = 0, fail = 0let t0 = Date()for c in cases {let img = try ImageDecoder.decodeRGB(url: base.appendingPathComponent(c.file), applyEXIFOrientation: false)let r = try ImagePreprocessor.resized(img)let inputs = ImagePreprocessor.patchify(resizedRGB: r.rgb, width: r.width, height: r.height)let dims = img.width == c.width && img.height == c.height && r.width == c.resized_width && r.height == c.resized_height && inputs.softTokenCount == c.n_softlet dOK = sha256(img.rgb) == c.decoded_sha256let rOK = sha256(r.rgb) == c.resized_sha256if dims && dOK && rOK {exact += 1print("EXACT \(c.file) \(img.width)x\(img.height) -> \(r.width)x\(r.height), n=\(inputs.softTokenCount)")} else if dims && c.lossy && !dOK {lossyDiff += 1print("DIFFERS \(c.file) (lossy format: decoder differences are expected; resized \(rOK ? "identical" : "differs"))")} else {fail += 1print("FAIL \(c.file) dims \(dims) decoded \(dOK) resized \(rOK) (\(img.width)x\(img.height) -> \(r.width)x\(r.height), n=\(inputs.softTokenCount))")}}print("PIXCHECK \(exact)/\(cases.count) bit-identical to the Python reference, \(lossyDiff) lossy-format decoder differences, \(fail) failures, \(fmt(Date().timeIntervalSince(t0), 2)) s")finish(fail == 0 ? 0 : 1)case "dump":guard args.count >= 2 else { usage() }let img = try ImageDecoder.decodeRGB(url: URL(fileURLWithPath: args[0]), applyEXIFOrientation: exif)let r = try ImagePreprocessor.resized(img)let inputs = ImagePreprocessor.patchify(resizedRGB: r.rgb, width: r.width, height: r.height)try Data(img.rgb).write(to: URL(fileURLWithPath: args[1] + ".decoded.rgb"))try Data(r.rgb).write(to: URL(fileURLWithPath: args[1] + ".resized.rgb"))let info: [String: Any] = ["width": img.width, "height": img.height, "resized_width": r.width, "resized_height": r.height,"n_soft": inputs.softTokenCount, "decoded_sha256": sha256(img.rgb), "resized_sha256": sha256(r.rgb)]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}guard let bundlePath = args.first else { usage() }args.removeFirst()let bundle = URL(fileURLWithPath: bundlePath)switch cmd {case "embed":let kind = takeOption("--kind") ?? "document"7 unmodified lines_ = consume eg2finish(0)case "embed-image":let dim = Int(takeOption("--dim") ?? "768") ?? 768let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: true, imageCompute: imageCompute)for path in args {let t0 = Date()let inputs = try ImagePreprocessor.prepare(url: URL(fileURLWithPath: path), applyEXIFOrientation: exif)let t1 = Date()let v = try await eg2.embedImage(inputs, dim: dim)let json: [String: Any] = ["image": path, "dim": dim, "n_soft": inputs.softTokenCount, "resized": [inputs.resizedWidth, inputs.resizedHeight],"exif_orientation_applied": exif, "preprocess_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) inlet url = URL(fileURLWithPath: path)return (url, try JSONDecoder().decode(RefFile.self, from: Data(contentsOf: url)))}let needsVision = refs.contains { !($0.1.images ?? []).isEmpty }let eg2 = try await EmbeddingGemma2(bundle: bundle, compute: compute, loadVision: needsVision, imageCompute: imageCompute)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)")// text cases (v1.0 format)for c in ref.cases ?? [] {let v = try await eg2.embed(c.text, kind: c.kind)let cos = cosineSimilarity(v, c.embedding)let pass = cos >= ref.threshold_cosine && v.allSatisfy { $0.isFinite }ok = ok && passprint("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(ref.threshold_cosine)) \(c.kind): \(c.text.prefix(60))")}if let first = ref.cases?.dropFirst().first {// Matryoshka prefixes must stay close to the truncated + re-normalized referencefor dim in [512, 256, 128] {let v = try await eg2.embed(first.text, kind: first.kind, dim: dim)let cos = cosineSimilarity(v, Array(first.embedding.prefix(dim)))let pass = cos >= ref.threshold_cosineok = ok && passprint("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) at dim \(dim)")}}// images, their queries and documentslet images = ref.images ?? []var imgVecs: [[Float]] = []let imgThreshold = ref.threshold_cosine_image ?? ref.threshold_cosinefor c in images {let t0 = Date()let v = try await eg2.embedImage(url: refURL.deletingLastPathComponent().appendingPathComponent(c.file))let cos = cosineSimilarity(v, c.embedding)let pass = cos >= imgThreshold && v.allSatisfy { $0.isFinite }ok = ok && passimgVecs.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)let cos = cosineSimilarity(v, c.embedding)let pass = cos >= ref.threshold_cosine && v.allSatisfy { $0.isFinite }ok = ok && passif c.kind == "search_query" { queryVecs.append((c.text, v)) }print("\(pass ? "PASS" : "FAIL") cosine \(fmt(cos, 6)) (threshold \(ref.threshold_cosine)) \(c.kind): \(c.text.prefix(60))")}// text -> image: each query must rank its own image firstif !images.isEmpty {var hits = 0for (q, qv) in queryVecs {let scores = imgVecs.map { cosineSimilarity(qv, $0) }let best = scores.indices.max(by: { scores[$0] < scores[$1] })!let hit = images.firstIndex(where: { $0.query == q }) == besthits += hit ? 1 : 0print("\(hit ? "PASS" : "FAIL") query \"\(q)\" -> \(images[best].file) (\(fmt(scores[best], 3)))")}ok = 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 {// a synthetic 1008x624 image (273 soft tokens, the most common shape)var px = [UInt8](repeating: 0, count: 1008 * 624 * 3)for i in px.indices { px[i] = UInt8((i * 7919) % 251) }let inputs = ImagePreprocessor.patchify(resizedRGB: px, width: 1008, height: 624)var tv: [Double] = [], tt: [Double] = [], te: [Double] = []let imageTrials = max(5, trials / 2)let cpu0 = cpuSeconds()for _ in 0..<imageTrials {let t0 = Date()let soft = try await eg2.softTokens(inputs)let t1 = Date()_ = try await eg2.embed(sequence: eg2.imageSequence(softTokens: soft))let t2 = Date()tv.append(t1.timeIntervalSince(t0) * 1000); tt.append(t2.timeIntervalSince(t1) * 1000); te.append(t2.timeIntervalSince(t0) * 1000)}let cpu = (cpuSeconds() - cpu0) / Double(imageTrials) * 1000print("image (273 soft tokens, \(imageTrials) trials): vision_2520 p50 \(fmt(percentile(tv, 0.5), 1)) ms (min \(fmt(tv.min()!, 1))), "+ "mm_288 p50 \(fmt(percentile(tt, 0.5), 1)) ms, end-to-end p50 \(fmt(percentile(te, 0.5), 1)) ms, CPU \(fmt(cpu, 1)) ms/image (excl. decode+resize)")var big = [UInt8](repeating: 0, count: 2560 * 1600 * 3)for i in big.indices { big[i] = UInt8((i * 31) % 253) }let tp0 = Date()for _ in 0..<5 { _ = try ImagePreprocessor.prepare(DecodedImage(width: 2560, height: 1600, rgb: big)) }print("preprocess (resize 2560x1600 -> 1008x624 + patches): \(fmt(Date().timeIntervalSince(tp0) / 5 * 1000, 1)) ms")}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)8 unmodified linests.append(Date().timeIntervalSince(t) * 1000)}let cpu = (cpuSeconds() - cpu0) / Double(trials) * 1000let p50 = percentile(ts, 0.5)print(String(format: "%5d %7.2f %7.2f %7.2f %11.2f %6.0f", S, p50, ts.min()!, percentile(ts, 0.9), cpu, Double(S) / p50 * 1000))}let fp = footprints()print("peak footprint \(fmt(fp.physMB, 0)) MB, neural footprint \(fmt(fp.neuralMB, 0)) MB (\(fp.neuralMB > 0 ? "Neural Engine in use" : "Neural Engine NOT used"))")2 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)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Check that python/eg2_image.py reproduces the upstream image processor bit for bit on the shipped test images:the target size, the uint8 antialiased bicubic resize (vs torchvision) and the pixel values / patch layout (vstransformers' Gemma4ImageProcessor, if transformers is installed).
python3 check_preprocess.py [--images images] [--model-dir <google/embeddinggemma-2 snapshot>]
Needs torch + torchvision (and transformers for the processor comparison). Exit code 0 = identical everywhere."""from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE.parent / "python"))import eg2_image # noqa: E402
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--images", default=str(HERE / "images")) ap.add_argument("--model-dir", default=None, help="checkpoint folder: also compare with Gemma4ImageProcessor") args = ap.parse_args() import torch from torchvision.transforms.v2 import functional as tvF
proc = None if args.model_dir: from transformers import AutoProcessor
proc = AutoProcessor.from_pretrained(args.model_dir).image_processor items = json.loads((Path(args.images) / "manifest.json").read_text()) bad = 0 for it in items: rgb = eg2_image.load_rgb(Path(args.images) / it["file"]) th, tw = eg2_image.target_size(rgb.shape[0], rgb.shape[1]) mine = eg2_image.resize_bicubic_aa_u8(rgb, th, tw) t = torch.from_numpy(rgb).permute(2, 0, 1).contiguous() ref = tvF.resize(t, [th, tw], interpolation=tvF.InterpolationMode.BICUBIC, antialias=True).permute(1, 2, 0).numpy() if (th, tw) != rgb.shape[:2] else rgb same = mine.shape == ref.shape and bool((mine == ref).all()) msg = f"{it['file']:24s} {rgb.shape[1]}x{rgb.shape[0]} -> {tw}x{th}: resize {'identical' if same else 'DIFFERS'}" if proc is not None: feats = proc(images=[torch.from_numpy(rgb).permute(2, 0, 1)], return_tensors="pt") pv, pos = feats["pixel_values"][0], feats["image_position_ids"][0] vi = eg2_image.prepare_vision_inputs(Path(args.images) / it["file"], dtype=np.float32) valid = pos[:, 0] >= 0 key = {(int(x), int(y)): i for i, (x, y) in enumerate(pos[valid].tolist())} perm = [key[(int(x), int(y))] for x, y in zip(vi.pos_x[0][: vi.n_soft * 9], vi.pos_y[0][: vi.n_soft * 9])] same_pv = bool(np.array_equal(pv[perm].numpy(), vi.patches[0, : vi.n_soft * 9] * eg2_image.RESCALE)) and int(feats["num_soft_tokens_per_image"][0]) == vi.n_soft same = same and same_pv msg += f", processor pixel values {'identical' if same_pv else 'DIFFER'} (n_soft {vi.n_soft})" bad += not same print(msg) print("CHECK_PREPROCESS", "PASS" if bad == 0 else f"FAIL ({bad} differ)") return 0 if bad == 0 else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110[ { "name": "chart_bar", "file": "chart_bar.png", "query": "bar chart of lamp units sold per city", "width": 640, "height": 400, "mode": "RGB", "lossy": false }, { "name": "ui_login", "file": "ui_login.png", "query": "dark mobile login screen with email and password fields", "width": 390, "height": 844, "mode": "RGB", "lossy": false }, { "name": "slide_launch", "file": "slide_launch.png", "query": "presentation slide about a tent product launch plan", "width": 1280, "height": 720, "mode": "RGB", "lossy": false }, { "name": "doc_invoice", "file": "doc_invoice.png", "query": "invoice for fountain pens and ink cartridges", "width": 595, "height": 842, "mode": "RGB", "lossy": false }, { "name": "diagram_flow", "file": "diagram_flow.png", "query": "flow diagram of order fulfilment steps", "width": 800, "height": 500, "mode": "RGB", "lossy": false }, { "name": "scene_sunset", "file": "scene_sunset.jpg", "query": "sunset over the sea with an orange sun", "width": 800, "height": 533, "mode": "RGB", "lossy": true }, { "name": "shape_red_circle", "file": "shape_red_circle.png", "query": "a red circle on a white background", "width": 300, "height": 300, "mode": "RGB", "lossy": false }, { "name": "icon_rgba", "file": "icon_rgba.png", "query": "blue rounded app icon with a white play symbol", "width": 256, "height": 256, "mode": "RGBA", "lossy": false }, { "name": "gray_letter", "file": "gray_letter.png", "query": "letter about a community garden reopening", "width": 600, "height": 800, "mode": "L", "lossy": false }, { "name": "palette_chart", "file": "palette_chart.png", "query": "pie chart of sales channel share", "width": 500, "height": 320, "mode": "P", "lossy": false }, { "name": "edge_tiny_7x5", "file": "edge_tiny_7x5.png", "query": "a red circle on a white background", "width": 7, "height": 5, "mode": "RGB", "lossy": false }, { "name": "edge_strip_1x300", "file": "edge_strip_1x300.png", "query": "a thin vertical strip", "width": 1, "height": 300, "mode": "RGB", "lossy": false }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Regenerate `image-smoke-reference.json`: fp32 reference embeddings of the shipped test images (passed as filepaths, no prompt, exactly as sentence-transformers embeds images), of one search query per image and of twofictional documents, computed with sentence-transformers on the ORIGINAL google/embeddinggemma-2 checkpoint(CPU, float32).
python3 make_image_smoke_reference.py --model google/embeddinggemma-2 --out image-smoke-reference.json
Needs: sentence-transformers >= 6.1, transformers >= 5.19, torch, torchvision, pillow. The shipped file was producedwith sentence-transformers 6.1.0 / transformers 5.19.0 / torch 2.14.1 / torchvision 0.29.1."""from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
HERE = Path(__file__).resolve().parentTEXTS = [ {"kind": "document", "text": "The Lumen lamp range sold best in Westmere this quarter; Lake Tamsin stayed below two hundred units."}, {"kind": "document", "text": "Verbale della riunione: il lancio delle tende Nimbus slitta a marzo, i preordini aprono con sei rivenditori."},]SMOKE_IMAGES = ["chart_bar", "ui_login", "slide_launch", "doc_invoice", "diagram_flow", "scene_sunset", "shape_red_circle", "icon_rgba", "gray_letter", "palette_chart"]
def main() -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--model", default="google/embeddinggemma-2") ap.add_argument("--images", default=str(HERE / "images")) ap.add_argument("--out", default=str(HERE / "image-smoke-reference.json")) ap.add_argument("--threshold", type=float, default=0.999) ap.add_argument("--threshold-image", type=float, default=0.998) args = ap.parse_args() import sentence_transformers import torch import torchvision import transformers from sentence_transformers import SentenceTransformer
m = SentenceTransformer(args.model, device="cpu", model_kwargs={"torch_dtype": torch.float32}, config_kwargs={"audio_config": None}) m.eval() items = {it["name"]: it for it in json.loads((Path(args.images) / "manifest.json").read_text())} out = { "reference": "sentence-transformers fp32 on CPU, original checkpoint; images passed as paths with no prompt", "versions": {"sentence_transformers": sentence_transformers.__version__, "transformers": transformers.__version__, "torch": torch.__version__, "torchvision": torchvision.__version__}, "threshold_cosine": args.threshold, "threshold_cosine_image": args.threshold_image, "images": [], "texts": [], } for name in SMOKE_IMAGES: it = items[name] path = str(Path(args.images) / it["file"]) with torch.no_grad(): v = m.encode([{"image": path}], batch_size=1, normalize_embeddings=True, convert_to_numpy=True)[0] out["images"].append({"file": f"{Path(args.images).name}/{it['file']}", "query": it["query"], "embedding": [round(float(x), 7) for x in v.tolist()]}) print("image", it["file"], len(v)) for name in SMOKE_IMAGES: q = items[name]["query"] v = m.encode(q, prompt_name="query", normalize_embeddings=True, convert_to_numpy=True) out["texts"].append({"kind": "search_query", "text": q, "embedding": [round(float(x), 7) for x in v.tolist()]}) for t in TEXTS: v = m.encode(t["text"], prompt_name="document", normalize_embeddings=True, convert_to_numpy=True) out["texts"].append({**t, "embedding": [round(float(x), 7) for x in v.tolist()]}) Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8") print("wrote", args.out)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Write `preprocess-cases.json`: for every image in tests/images/, the SHA-256 of the decoded 8-bit RGB buffer andof the resized buffer, plus the sizes and the soft-token count, computed with the Python reference preprocessing(python/eg2_image.py, itself bit-identical to torchvision's uint8 bicubic). `eg2-cli pixcheck` compares the Swiftdecoder + resampler against it. Lossy (JPEG) cases are flagged: decoders differ by a few values per sample there.
python3 make_preprocess_cases.py [--images images] [--out preprocess-cases.json]"""from __future__ import annotations
import argparseimport hashlibimport jsonimport sysfrom pathlib import Path
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE.parent / "python"))import eg2_image # noqa: E402
def main() -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--images", default=str(HERE / "images")) ap.add_argument("--out", default=str(HERE / "preprocess-cases.json")) args = ap.parse_args() items = json.loads((Path(args.images) / "manifest.json").read_text()) cases = [] for it in items: rgb = eg2_image.load_rgb(Path(args.images) / it["file"]) th, tw = eg2_image.target_size(rgb.shape[0], rgb.shape[1]) res = eg2_image.resize_bicubic_aa_u8(rgb, th, tw) vi = eg2_image.patchify_cell_major(res) cases.append(dict(file=f"{Path(args.images).name}/{it['file']}", width=int(rgb.shape[1]), height=int(rgb.shape[0]), resized_width=tw, resized_height=th, n_soft=vi.n_soft, lossy=bool(it.get("lossy", False)), decoded_sha256=hashlib.sha256(rgb.tobytes()).hexdigest(), resized_sha256=hashlib.sha256(res.tobytes()).hexdigest())) print(cases[-1]["file"], f"{rgb.shape[1]}x{rgb.shape[0]} -> {tw}x{th}, n={vi.n_soft}") Path(args.out).write_text(json.dumps(cases, indent=1) + "\n") print("wrote", args.out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209#!/usr/bin/env python3# Copyright 2026 Everpaper. Licensed under the Apache License, Version 2.0 (see ../LICENSE)."""Render the small fictional image set shipped in tests/images/ (Pillow only, no randomness): a bar chart, a phonelogin screen, a slide, an invoice, a flow diagram, a sunset scene (JPEG), a red circle, an RGBA icon, a grayscaleletter, a palette chart, plus two edge-size images (7x5 and 1x300 px) that exercise the resampler's upscale andextreme-aspect paths. All names, companies and numbers are invented.
python3 make_test_images.py [--out images] -> <out>/*.png|jpg + <out>/manifest.json
The output is repeatable on one machine but NOT byte-identical across machines: text is drawn with the firstsystem font found in FONT_PATHS (or Pillow's built-in font), and glyph rasterization, PNG compression and JPEGencoding depend on the font files and on the Pillow / FreeType / zlib / libjpeg versions. The shipped files intests/images/ are the reference: image-smoke-reference.json and preprocess-cases.json were computed from them, soregenerate those two fixtures (make_image_smoke_reference.py, make_preprocess_cases.py) if you regenerate the images."""from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
from PIL import Image, ImageDraw, ImageFont
FONT_PATHS = ["/System/Library/Fonts/Helvetica.ttc", "/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
def font(size: int): for p in FONT_PATHS: try: return ImageFont.truetype(p, size) except OSError: continue return ImageFont.load_default()
def chart_bar(w=640, h=400): im = Image.new("RGB", (w, h), "white") d = ImageDraw.Draw(im) d.text((20, 12), "Lumen lamps - units sold per city, Q3", fill="black", font=font(20)) cities = ["Port Avelin", "North Corra", "Westmere", "Lake Tamsin", "Oskaro"] vals = [412, 263, 538, 190, 347] cols = ["#4C78A8", "#F58518", "#54A24B", "#E45756", "#72B7B2"] d.line([(60, h - 50), (w - 20, h - 50)], fill="black", width=2) d.line([(60, 50), (60, h - 50)], fill="black", width=2) bw = (w - 100) // len(cities) for i, (c, v, col) in enumerate(zip(cities, vals, cols)): x0 = 70 + i * bw d.rectangle([x0, h - 50 - v * 0.5, x0 + bw - 20, h - 50], fill=col) d.text((x0, h - 44), c, fill="black", font=font(13)) d.text((x0 + 5, h - 50 - v * 0.5 - 18), str(v), fill="black", font=font(13)) return im
def ui_login(w=390, h=844): im = Image.new("RGB", (w, h), "#111418") d = ImageDraw.Draw(im) d.rounded_rectangle([40, 160, w - 40, 300], 24, fill="#1d2229") d.text((60, 180), "Welcome back", fill="white", font=font(28)) d.text((60, 230), "Sign in to Tidal Boards", fill="#9aa4b1", font=font(16)) for i, label in enumerate(["Email", "Password"]): y = 340 + i * 90 d.rounded_rectangle([40, y, w - 40, y + 56], 14, fill="#1d2229", outline="#2f3842") d.text((56, y + 18), label, fill="#6b7682", font=font(16)) d.rounded_rectangle([40, 540, w - 40, 596], 14, fill="#2f6fed") d.text((150, 556), "Sign in", fill="white", font=font(18)) d.text((110, 620), "Forgot your password?", fill="#9aa4b1", font=font(14)) return im
def slide(w=1280, h=720): im = Image.new("RGB", (w, h), "#f6f3ec") d = ImageDraw.Draw(im) d.rectangle([0, 0, w, 90], fill="#264653") d.text((50, 25), "Nimbus tents: 2027 launch plan", fill="white", font=font(36)) bullets = ["Three sizes, one pole system", "Pre-orders open in March", "Retail partners in six cities", "Target: 18,000 units in the first season"] for i, b in enumerate(bullets): d.ellipse([70, 160 + i * 90, 90, 180 + i * 90], fill="#2a9d8f") d.text((110, 150 + i * 90), b, fill="#222", font=font(30)) d.text((w - 260, h - 50), "slide 4 of 12", fill="#777", font=font(18)) return im
def doc_invoice(w=595, h=842): im = Image.new("RGB", (w, h), "white") d = ImageDraw.Draw(im) d.text((40, 40), "INVOICE No. 2027-0418", fill="black", font=font(22)) d.text((40, 80), "Quill Pens Ltd., 12 Harbour Lane, Port Avelin", fill="black", font=font(13)) d.text((40, 100), "Bill to: Westmere Public Library", fill="black", font=font(13)) y = 160 d.line([(40, y), (w - 40, y)], fill="black") rows = [("Fountain pen, steel nib", 24, "18.00"), ("Ink cartridges (box of 50)", 6, "9.50"), ("Gift boxes", 24, "2.20"), ("Shipping", 1, "14.00")] for name, qty, price in rows: y += 30 d.text((40, y), name, fill="black", font=font(13)) d.text((380, y), str(qty), fill="black", font=font(13)) d.text((460, y), price, fill="black", font=font(13)) y += 50 d.line([(40, y), (w - 40, y)], fill="black") d.text((380, y + 15), "Total: 555.80", fill="black", font=font(15)) d.text((40, h - 80), "Payment within 30 days. Thank you for your order.", fill="black", font=font(12)) return im
def diagram_flow(w=800, h=500): im = Image.new("RGB", (w, h), "white") d = ImageDraw.Draw(im) boxes = [("Order received", 60, 200), ("Check stock", 300, 200), ("Pack", 540, 120), ("Back-order", 540, 280)] for t, x, y in boxes: d.rounded_rectangle([x, y, x + 180, y + 70], 12, fill="#dbeafe", outline="#1e3a8a", width=2) d.text((x + 15, y + 25), t, fill="#1e3a8a", font=font(17)) for a, b in [((240, 235), (300, 235)), ((480, 220), (540, 155)), ((480, 250), (540, 315))]: d.line([a, b], fill="#1e3a8a", width=3) d.polygon([b, (b[0] - 12, b[1] - 6), (b[0] - 12, b[1] + 6)], fill="#1e3a8a") d.text((320, 60), "Fulfilment flow", fill="black", font=font(24)) return im
def scene_sunset(w=800, h=533): im = Image.new("RGB", (w, h)) d = ImageDraw.Draw(im) for y in range(h): t = y / h if t < 0.6: c = (int(40 + 200 * t / 0.6), int(60 + 90 * t / 0.6), int(120 - 80 * t / 0.6)) else: c = (int(20 + 30 * (t - 0.6) / 0.4), int(50 + 40 * (t - 0.6) / 0.4), int(90 + 60 * (t - 0.6) / 0.4)) d.line([(0, y), (w, y)], fill=c) d.ellipse([w // 2 - 60, int(h * 0.6) - 60, w // 2 + 60, int(h * 0.6) + 60], fill="#ffb347") d.rectangle([0, int(h * 0.6), w, h], fill=None) for i in range(0, w, 40): d.line([(i, int(h * 0.62) + (i % 80) // 20), (i + 24, int(h * 0.62) + (i % 80) // 20)], fill="#ffd27f", width=2) return im
def shape_red_circle(w=300, h=300): im = Image.new("RGB", (w, h), "white") ImageDraw.Draw(im).ellipse([50, 50, 250, 250], fill="#d62828") return im
def icon_rgba(w=256, h=256): im = Image.new("RGBA", (w, h), (0, 0, 0, 0)) d = ImageDraw.Draw(im) d.rounded_rectangle([20, 20, 236, 236], 48, fill=(47, 111, 237, 255)) d.polygon([(100, 75), (100, 181), (185, 128)], fill=(255, 255, 255, 255)) return im
def gray_letter(w=600, h=800): im = Image.new("L", (w, h), 245) d = ImageDraw.Draw(im) lines = ["Dear neighbours,", "", "The community garden on Fern Street reopens on the first Saturday of May.", "Plots are assigned in the order of the sign-up sheet at the library.", "Tools stay in the shed; please", "return them before dusk.", "", "With thanks, the garden committee"] for i, l in enumerate(lines): d.text((50, 60 + i * 32), l, fill=20, font=font(16)) return im
def palette_chart(w=500, h=320): im = Image.new("RGB", (w, h), "white") d = ImageDraw.Draw(im) d.text((20, 10), "Sales channel share", fill="black", font=font(18)) start = 0 for frac, col in [(0.45, "#1b9e77"), (0.3, "#d95f02"), (0.25, "#7570b3")]: d.pieslice([120, 60, 380, 300], start, start + frac * 360, fill=col) start += frac * 360 return im.quantize(16)
def build(out: Path) -> list[dict]: out.mkdir(parents=True, exist_ok=True) items = []
def save(name, im, query, fmt="PNG", **kw): fn = f"{name}.{'jpg' if fmt == 'JPEG' else 'png'}" im.save(out / fn, format=fmt, **kw) with Image.open(out / fn) as chk: items.append(dict(name=name, file=fn, query=query, width=chk.width, height=chk.height, mode=chk.mode, lossy=fmt == "JPEG"))
save("chart_bar", chart_bar(), "bar chart of lamp units sold per city") save("ui_login", ui_login(), "dark mobile login screen with email and password fields") save("slide_launch", slide(), "presentation slide about a tent product launch plan") save("doc_invoice", doc_invoice(), "invoice for fountain pens and ink cartridges") save("diagram_flow", diagram_flow(), "flow diagram of order fulfilment steps") save("scene_sunset", scene_sunset(), "sunset over the sea with an orange sun", fmt="JPEG", quality=90) save("shape_red_circle", shape_red_circle(), "a red circle on a white background") save("icon_rgba", icon_rgba(), "blue rounded app icon with a white play symbol") save("gray_letter", gray_letter(), "letter about a community garden reopening") save("palette_chart", palette_chart(), "pie chart of sales channel share") save("edge_tiny_7x5", shape_red_circle().resize((7, 5), Image.BICUBIC), "a red circle on a white background") save("edge_strip_1x300", ui_login().resize((1, 300), Image.BICUBIC), "a thin vertical strip") return items
def main() -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--out", default=str(Path(__file__).resolve().parent / "images")) args = ap.parse_args() items = build(Path(args.out)) (Path(args.out) / "manifest.json").write_text(json.dumps(items, indent=1) + "\n") print(len(items), "images ->", args.out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134[ { "file": "images/chart_bar.png", "width": 640, "height": 400, "resized_width": 1008, "resized_height": 624, "n_soft": 273, "lossy": false, "decoded_sha256": "f1f52a3521c5f025133a3b3ede317e264c3f7156a2939077fe5626f41ef4c3e9", "resized_sha256": "2b18cd29affce8b685e2670742b7822f7d315a10b7f88bd2e83fdfa358807551" }, { "file": "images/ui_login.png", "width": 390, "height": 844, "resized_width": 528, "resized_height": 1152, "n_soft": 264, "lossy": false, "decoded_sha256": "9ec406ca2976cf11b9a76dfd5c33138d206a0708736b6a8200e8bd634c54cd29", "resized_sha256": "78f7671c544f8bd67daf3b7350380805f8756e8ed4b2982a3a492541ba597ba1" }, { "file": "images/slide_launch.png", "width": 1280, "height": 720, "resized_width": 1056, "resized_height": 576, "n_soft": 264, "lossy": false, "decoded_sha256": "cbc7ca7320c880f1adc21bb1f944c35f0aaeebe3d6e559771f0ade23dbeba2d4", "resized_sha256": "3c584dc34237d3868ec0ce6e5bec61625f2e084e1aafb1983a07fd3bdb0a557e" }, { "file": "images/doc_invoice.png", "width": 595, "height": 842, "resized_width": 672, "resized_height": 912, "n_soft": 266, "lossy": false, "decoded_sha256": "1cbd651e729e2b7eeef88f22d8975a0c63cbb4ca4009f1ad6d2c039025302dc3", "resized_sha256": "9f13f5a6f63114a8935ac0cb74b27e8c63908446a3b8bdf5b24b2bc06688b64b" }, { "file": "images/diagram_flow.png", "width": 800, "height": 500, "resized_width": 1008, "resized_height": 624, "n_soft": 273, "lossy": false, "decoded_sha256": "14d6f58dda34b649b08800e1277d3632713f5cd850696f5c90d5f43faf3867f7", "resized_sha256": "3a6264500ec49252b6d2ea676df38c3d134a36b95a9e52007a12abac4d60955d" }, { "file": "images/scene_sunset.jpg", "width": 800, "height": 533, "resized_width": 960, "resized_height": 624, "n_soft": 260, "lossy": true, "decoded_sha256": "ca17b4026c989cb0d3ff19a56755ccb74eb93ef4adc070fca40d597f31a650e2", "resized_sha256": "3f56f74833b222112a6a5928affbb443455e82a7e5fe77d73a23e34b50df8c2a" }, { "file": "images/shape_red_circle.png", "width": 300, "height": 300, "resized_width": 768, "resized_height": 768, "n_soft": 256, "lossy": false, "decoded_sha256": "04a270faa563abc3d1dffa5d6edff9f60c78a175b8064c040de30e0003ee4b7e", "resized_sha256": "5f298e809fa2743291baa363fd8ca7a713f7168ea9d3f5ce6313b9418a35342e" }, { "file": "images/icon_rgba.png", "width": 256, "height": 256, "resized_width": 768, "resized_height": 768, "n_soft": 256, "lossy": false, "decoded_sha256": "e813e801836abf9be401d49ee54bdf85e21d5d927680a7f0afd008644d03dd98", "resized_sha256": "85710c7bb58ebc71c6a7525471ec28d993a1d38712b29c9b125a1c940444d8a9" }, { "file": "images/gray_letter.png", "width": 600, "height": 800, "resized_width": 672, "resized_height": 912, "n_soft": 266, "lossy": false, "decoded_sha256": "69447d70411f0facb5a8be579fdc578de174e303343035341fc9f176692be187", "resized_sha256": "9cfdfdf9ce4f1e31659649c234bafa7fe01b36522aab15e6fe61958f044cb0cf" }, { "file": "images/palette_chart.png", "width": 500, "height": 320, "resized_width": 960, "resized_height": 624, "n_soft": 260, "lossy": false, "decoded_sha256": "1d07de0b8028c3baa4541efecd77c4ae35baa0bbca108f3aeca3cfef592d9c80", "resized_sha256": "720e84cd5aa3745159fe62ae33bfdb5b60e2fc73c0a08c8344b331172f2a23fd" }, { "file": "images/edge_tiny_7x5.png", "width": 7, "height": 5, "resized_width": 912, "resized_height": 672, "n_soft": 266, "lossy": false, "decoded_sha256": "0921ce7b088ae389154a803de95da49f6921c4f86c21712b8705e99fc3b08e39", "resized_sha256": "34a94eb822799098c11821e8bf978f5777534cbd76fc0fd490e5669805e36f8c" }, { "file": "images/edge_strip_1x300.png", "width": 1, "height": 300, "resized_width": 48, "resized_height": 13440, "n_soft": 280, "lossy": false, "decoded_sha256": "532869c406f2d3f38dc25d09560d3dcdcfd8ae568e0c75af54efca666be4c55d", "resized_sha256": "d2fd758e5595f33ea5590ae17f665abd00697dd1cb13d72a48dbf11f911758a7" }].gitattributes+2
CHANGELOG.md+56
CHECKSUMS.sha256+44-16
NOTICE+214-21
README.md+462-238
export/eg2_text_mm.pyAdded+55
export/eg2_vision.pyAdded+232
export/export.py+169-101
model/MODEL-ATTRIBUTION.json+18-12
model/config.json+46-12
model/embeddinggemma-2-text-mm.aimodel/main.hashAdded+1
model/embeddinggemma-2-text.aimodel/main.mlirb → model/embeddinggemma-2-text-mm.aimodel/main.mlirbRenamed+2-2
model/embeddinggemma-2-text.aimodel/metadata.json → model/embeddinggemma-2-text-mm.aimodel/metadata.jsonRenamed+4-4
model/embeddinggemma-2-text.aimodel/main.hashDeleted-1
model/embeddinggemma-2-vision.aimodel/main.hashAdded+2
model/embeddinggemma-2-vision.aimodel/main.mlirbAdded+3
model/embeddinggemma-2-vision.aimodel/metadata.jsonAdded+8
python/eg2_image.pyAdded+220
python/embeddinggemma2_coreai.py+246-64
python/requirements.lock+4-2
python/requirements.txt+4-3
python/smoke_test.py+17-30
swift/Package.swift+4-3
swift/Sources/EmbeddingGemma2CoreAI/Embedder.swift+199-43
swift/Sources/EmbeddingGemma2CoreAI/ImageDecoder.swiftAdded+214
swift/Sources/EmbeddingGemma2CoreAI/ImagePreprocessor.swiftAdded+139
swift/Sources/EmbeddingGemma2CoreAI/ImageResampler.swiftAdded+163
swift/Sources/eg2-cli/main.swift+217-32
tests/check_preprocess.pyAdded+65
tests/image-smoke-reference.jsonAdded
tests/images/chart_bar.pngAdded

tests/images/diagram_flow.pngAdded

tests/images/doc_invoice.pngAdded

tests/images/edge_strip_1x300.pngAdded

tests/images/edge_tiny_7x5.pngAdded

tests/images/gray_letter.pngAdded

tests/images/icon_rgba.pngAdded
tests/images/manifest.jsonAdded+110
tests/images/palette_chart.pngAdded

tests/images/scene_sunset.jpgAdded

tests/images/shape_red_circle.pngAdded

tests/images/slide_launch.pngAdded

tests/images/ui_login.pngAdded

tests/make_image_smoke_reference.pyAdded+73
tests/make_preprocess_cases.pyAdded+44
tests/make_test_images.pyAdded+209
tests/preprocess-cases.jsonAdded+134