Shorten model card and bundle reproducible conversion source
Browse files- README.md +26 -158
- SHA256SUMS +24 -2
- conversion/NOTICE +30 -0
- conversion/README.md +65 -0
- conversion/buckets.py +3 -0
- conversion/convert.py +79 -0
- conversion/eg2.py +114 -0
- conversion/fetch_stock.py +31 -0
- conversion/fixtures/SHA256SUMS +1 -0
- conversion/fixtures/tokens.json.gz +3 -0
- conversion/parity.py +106 -0
- conversion/provenance.py +15 -0
- conversion/requirements.lock +43 -0
- conversion/source-manifest.json +22 -0
- conversion/source-snapshot.json +48 -0
- conversion/upstream/modeling_embedding_gemma2.py +933 -0
- conversion/upstream/qvac/LICENSE +21 -0
- conversion/upstream/qvac/README.md +126 -0
- conversion/upstream/qvac/export_coreml.py +320 -0
- conversion/upstream/qvac/requirements.txt +6 -0
- conversion/upstream/transformers-LICENSE +203 -0
- conversion/validate.swift +151 -0
- docs/technical-notes.md +64 -0
- docs/usage.md +82 -0
- release-manifest.json +95 -4
README.md
CHANGED
|
@@ -12,172 +12,40 @@ tags:
|
|
| 12 |
- text-only
|
| 13 |
---
|
| 14 |
|
| 15 |
-
# EmbeddingGemma 2
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
Encoder weights and compute use FP16; final L2 normalization uses FP32.
|
| 20 |
-
The output is a normalized 768-dimensional embedding.
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
The original weights, configuration and tokenizer are pinned to
|
| 25 |
-
[`google/embeddinggemma-2@914f7f89142e33e77833254d9c9b90c3cef7303b`](https://huggingface.co/google/embeddinggemma-2/tree/914f7f89142e33e77833254d9c9b90c3cef7303b).
|
| 26 |
-
The original tokenizer files are included unchanged. No training, pruning,
|
| 27 |
-
application head removal or integer weight quantization was applied.
|
| 28 |
-
Only the text encoder is included.
|
| 29 |
-
|
| 30 |
-
## Files
|
| 31 |
-
|
| 32 |
-
| File | Purpose |
|
| 33 |
|---|---|
|
| 34 |
-
|
|
| 35 |
-
|
|
| 36 |
-
|
|
| 37 |
-
|
|
| 38 |
-
|
|
| 39 |
-
| `validation/2026-11-12-four-bucket/` | Historical baseline; not results for the new artifact |
|
| 40 |
-
| `LICENSE`, `NOTICE`, `licenses/` | License and attribution |
|
| 41 |
|
| 42 |
-
|
| 43 |
-
compiled artifact in an application-owned directory.
|
| 44 |
-
|
| 45 |
-
## Download and use
|
| 46 |
|
| 47 |
```sh
|
| 48 |
-
hf download anylab/embeddinggemma-2-coreml
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
```
|
| 52 |
-
|
| 53 |
-
For deployed applications, pin an immutable HF revision and verify the manifest.
|
| 54 |
-
The immutable HF commit identifies exact package bytes; the release manifest
|
| 55 |
-
also records the converter source and per-function build provenance.
|
| 56 |
-
|
| 57 |
-
The native Swift validator and complete reproduction instructions are in
|
| 58 |
-
[`anyproto/any` at commit `6424fab8`](https://github.com/anyproto/any/tree/6424fab8cb6bd2874ce08e85d9081e24ff96902f/scripts/embedbench/research/eg2_coreml).
|
| 59 |
-
Native inference uses Core ML and does not need a Python runtime.
|
| 60 |
-
|
| 61 |
-
For an interactive Python check on an Apple Silicon Mac, use Python 3.12 with
|
| 62 |
-
Core ML Tools 9.0, NumPy and `tokenizers`:
|
| 63 |
-
|
| 64 |
-
```python
|
| 65 |
-
from pathlib import Path
|
| 66 |
-
import coremltools as ct
|
| 67 |
-
import numpy as np
|
| 68 |
-
from tokenizers import Tokenizer
|
| 69 |
-
|
| 70 |
-
root = Path("embeddinggemma-2-coreml")
|
| 71 |
-
tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
|
| 72 |
-
text = "task: search result | query: How do bond prices respond to interest rates?"
|
| 73 |
-
ids = tokenizer.encode(text).ids
|
| 74 |
-
if not ids or ids[0] != 2:
|
| 75 |
-
ids.insert(0, 2)
|
| 76 |
-
if ids[-1] != 1:
|
| 77 |
-
ids.append(1)
|
| 78 |
-
|
| 79 |
-
length = next((n for n in (128, 256, 512, 1024, 2048) if len(ids) <= n), None)
|
| 80 |
-
if length is None:
|
| 81 |
-
raise ValueError("Input exceeds this package's 2048-token limit")
|
| 82 |
-
input_ids = np.zeros((1, length), dtype=np.int32)
|
| 83 |
-
attention_mask = np.zeros((1, length), dtype=np.float32)
|
| 84 |
-
input_ids[0, :len(ids)] = ids
|
| 85 |
-
attention_mask[0, :len(ids)] = 1
|
| 86 |
-
|
| 87 |
-
model = ct.models.MLModel(
|
| 88 |
-
str(root / "EmbeddingGemma2Owned.mlpackage"),
|
| 89 |
-
function_name=f"s{length}",
|
| 90 |
-
compute_units=ct.ComputeUnit.CPU_AND_NE,
|
| 91 |
-
)
|
| 92 |
-
embedding = model.predict({
|
| 93 |
-
"input_ids": input_ids,
|
| 94 |
-
"attention_mask": attention_mask,
|
| 95 |
-
})["embedding"][0]
|
| 96 |
-
assert embedding.shape == (768,) and np.isfinite(embedding).all()
|
| 97 |
```
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
| `s128` | int32 `[1,128]` | float32 `[1,128]` | float32 `[1,768]` |
|
| 104 |
-
| `s256` | int32 `[1,256]` | float32 `[1,256]` | float32 `[1,768]` |
|
| 105 |
-
| `s512` | int32 `[1,512]` | float32 `[1,512]` | float32 `[1,768]` |
|
| 106 |
-
| `s1024` | int32 `[1,1024]` | float32 `[1,1024]` | float32 `[1,768]` |
|
| 107 |
-
| `s2048` | int32 `[1,2048]` | float32 `[1,2048]` | float32 `[1,768]` |
|
| 108 |
-
|
| 109 |
-
- Choose the smallest fitting bucket after adding prompts and special tokens.
|
| 110 |
-
- Document prefix: `title: none | text: `, or the actual title.
|
| 111 |
-
- Query prefix: `task: search result | query: `.
|
| 112 |
-
- BOS=2, EOS=1, pad=0; right-pad with mask 0. Real tokens, including prompt and
|
| 113 |
-
special tokens, have mask 1 and participate in mean pooling.
|
| 114 |
-
- Reject or route inputs over 2048 tokens elsewhere. The package does not choose
|
| 115 |
-
an application truncation policy. Long functions preserve the source model's
|
| 116 |
-
sliding-window behavior.
|
| 117 |
-
- Output is the raw normalized model embedding. Application-specific head
|
| 118 |
-
projection and Matryoshka truncation/renormalization are downstream operations.
|
| 119 |
-
|
| 120 |
-
## Validation
|
| 121 |
-
|
| 122 |
-
See the [current report](validation/2026-11-16-five-bucket/REPORT.txt) and
|
| 123 |
-
[release validation summary](validation/2026-11-16-five-bucket/release-validation.json).
|
| 124 |
-
|
| 125 |
-
| Measurement | Result |
|
| 126 |
-
|---|---|
|
| 127 |
-
| Rewritten forward vs stock HF FP32, 16 fixtures | Minimum cosine 0.999999999997; max absolute error 2.82e-7 |
|
| 128 |
-
| Native Core ML vs fresh stock HF FP32, 16 fixtures | Minimum cosine 0.99992672; max absolute error 0.00221308 |
|
| 129 |
-
| Long fixtures | 1151-token document, 1630-token multilingual text, exact 2048 tokens, plus short text padded to 2048 |
|
| 130 |
-
| Corpus | 1,499/1,500 FiQA documents; one 2212-token document excluded without truncation |
|
| 131 |
-
| Corpus norms | 0.999999893–1.000000097; finite, nonzero 768-dimensional vectors |
|
| 132 |
-
| Previous owned output overlap | All 1,491 overlapping outputs exactly unchanged |
|
| 133 |
-
| Sequential corpus inference, excluding tokenization | 56.64 documents/s; p50 7.34 ms; p95 35.73 ms |
|
| 134 |
-
| Five-function cold / cached load | 164.93 s / 3.95 s; package compilation separately 2.38 s |
|
| 135 |
-
| Matched long-input calls, 55 measured | ANE mean 300.24 ms; Metal Q8 mean 435.10 ms; aggregate 1.45× |
|
| 136 |
-
| Exact 2048-token median | ANE 299.55 ms; Metal Q8 726.67 ms (2.43×) |
|
| 137 |
-
| Exact 1025-token median | Essentially tied: ANE 299.53 ms; Metal Q8 299.22 ms |
|
| 138 |
-
|
| 139 |
-
The matched benchmark uses identical complete token IDs, two warmup rounds and five measured rounds over 11 inputs. It includes input allocation, prediction and normalized output copying, and excludes tokenization/model loading. Metal uses llama.cpp b11600, yzma 1.30.0, direct `llama_encode`, and Q8_0 weights; ANE uses FP16 weights with FP32 final normalization. These are direct runtime paths with different precision and host APIs, not exact application wrappers. No downstream head projection is applied. The comparison does not show an ANE advantage at every length.
|
| 140 |
-
|
| 141 |
-
Core ML compute plans report preferred placement and estimated cost, not an
|
| 142 |
-
Instruments runtime trace or a guarantee of ANE-only execution on other systems.
|
| 143 |
-
`cpuAndNeuralEngine` permits CPU operations; validation checks the transformer
|
| 144 |
-
core separately. Fresh stock-HF checks are bounded fixtures. Historical results
|
| 145 |
-
are labeled separately. These measure conversion fidelity, not broad retrieval
|
| 146 |
-
quality or suitability for every application.
|
| 147 |
-
|
| 148 |
-
Final FP32 normalization is intentional: the initial all-FP16 output failed a
|
| 149 |
-
strict unit-norm gate on one 413-token document. Keeping only the final L2
|
| 150 |
-
arithmetic in FP32 fixed it; that document remains a regression fixture.
|
| 151 |
-
|
| 152 |
-
## Reproduction and limitations
|
| 153 |
-
|
| 154 |
-
The converter uses Python 3.12.9, Torch 2.7.0, Transformers 5.19.0, Core ML Tools
|
| 155 |
-
9.0, NumPy 2.2.6 and safetensors 0.8.0. Full pins, source hashes, fixtures and
|
| 156 |
-
instructions are in the [source repository](https://github.com/anyproto/any/tree/6424fab8cb6bd2874ce08e85d9081e24ff96902f/scripts/embedbench/research/eg2_coreml).
|
| 157 |
-
This artifact merges the four exports retained from the validated November 12
|
| 158 |
-
build with a new s2048 export from November 16. The forward implementation,
|
| 159 |
-
source weights and dependency pins are unchanged. Individual conversion
|
| 160 |
-
fingerprints are preserved; they are not presented as one identical build.
|
| 161 |
-
The final merged package is validated directly. A fresh s2048 rebuild reproduced
|
| 162 |
-
identical weight-file bytes and an identical parsed model graph; the historical
|
| 163 |
-
s128 rebuild did too. Whole-package byte identity across rebuilds is not claimed:
|
| 164 |
-
UUIDs and protobuf map ordering vary.
|
| 165 |
-
|
| 166 |
-
Adding s2048 increased package size by 16,489,148 bytes (15.73 MiB, 2.96%).
|
| 167 |
-
Merely downloading a function does not load it. Applications should load larger
|
| 168 |
-
functions on demand and explicitly release idle functions; lazy loading without
|
| 169 |
-
eviction eventually retains the full set.
|
| 170 |
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
memory/fallback implementation.
|
| 178 |
|
| 179 |
-
The
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
See `NOTICE`, `LICENSE` and `licenses/`. This is an independent conversion, not
|
| 183 |
-
an official Google release.
|
|
|
|
| 12 |
- text-only
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# EmbeddingGemma 2 for Core ML
|
| 16 |
|
| 17 |
+
AnyLab's conversion of [Google's EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2)
|
| 18 |
+
text encoder for Apple Silicon, targeting macOS 15 or later.
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
| | |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|---|---|
|
| 22 |
+
| Output | 768-dimensional, L2-normalized embeddings |
|
| 23 |
+
| Precision | FP16 encoder; FP32 final normalization |
|
| 24 |
+
| Functions | `s128`, `s256`, `s512`, `s1024`, `s2048` |
|
| 25 |
+
| Package | 574.4 MB, with shared weights |
|
| 26 |
+
| License | Apache-2.0 |
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
Download the model and tokenizer:
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
```sh
|
| 31 |
+
hf download anylab/embeddinggemma-2-coreml \
|
| 32 |
+
--include 'EmbeddingGemma2Owned.mlpackage/**' --include 'tokenizer*.json' \
|
| 33 |
+
--local-dir embeddinggemma-2-coreml
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
```
|
| 35 |
|
| 36 |
+
Choose the smallest function that fits the input **after prompts and special
|
| 37 |
+
tokens**. Load larger functions on demand and release them when idle; sharing
|
| 38 |
+
weights on disk does not share their runtime allocations. First loading can
|
| 39 |
+
take minutes. Core ML's `cpuAndNeuralEngine` setting still permits CPU work.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
Validated on an M2 Air with 16 GB RAM: minimum cosine **0.999927** against
|
| 42 |
+
16 stock-model reference inputs. Full-app safety on 8 GB remains unmeasured.
|
| 43 |
|
| 44 |
+
- [Usage, prompts and input shapes](docs/usage.md)
|
| 45 |
+
- [Conversion source and reproduction instructions](conversion/README.md)
|
| 46 |
+
- [Measurements and limitations](docs/technical-notes.md)
|
| 47 |
+
- [Source pins and model hashes](release-manifest.json)
|
|
|
|
| 48 |
|
| 49 |
+
The converter and detailed reports live in this repository. For deployments,
|
| 50 |
+
pin an immutable HF revision and verify file hashes. This is an independent
|
| 51 |
+
conversion, not an official Google release; see [NOTICE](NOTICE).
|
|
|
|
|
|
SHA256SUMS
CHANGED
|
@@ -3,9 +3,31 @@
|
|
| 3 |
8f494dc20af594dd81ca1082c50d0db80eae392a84621955de1d1c5c0e99aed2 EmbeddingGemma2Owned.mlpackage/Manifest.json
|
| 4 |
77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049 LICENSE
|
| 5 |
75c1febc3806782ec847a8216b43b0dea15a57ee2f7c498523613397ab5b89dd NOTICE
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d licenses/QVAC-MIT.txt
|
| 8 |
-
|
| 9 |
b8f1e9931b57fbc054acdb445c41765d55b0074c58d145fa82839941ad1b5bb3 source-config.json
|
| 10 |
4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 tokenizer.json
|
| 11 |
17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 tokenizer_config.json
|
|
|
|
| 3 |
8f494dc20af594dd81ca1082c50d0db80eae392a84621955de1d1c5c0e99aed2 EmbeddingGemma2Owned.mlpackage/Manifest.json
|
| 4 |
77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049 LICENSE
|
| 5 |
75c1febc3806782ec847a8216b43b0dea15a57ee2f7c498523613397ab5b89dd NOTICE
|
| 6 |
+
9f2e50a30d595ce16b13a1c35301df84caa664392af9886da34ba36b5eba83cd README.md
|
| 7 |
+
f37332d719ec2d4c5f93b1a7ce41c42017a1d7666f533f92d51b08d78f28b4bb conversion/NOTICE
|
| 8 |
+
dd2d3f813fbc87dfe30f9e58c8294870feba95489d5b66138d9e7f18869e38a4 conversion/README.md
|
| 9 |
+
ff2261663941716c9b6884bb11a9cbaa75d660d6c41061d03c9ce0a0c473656a conversion/buckets.py
|
| 10 |
+
432a26fb6bea8e7f943a783592c3f6c8bdecf56bce4d78c465d3f203c05ea5ca conversion/convert.py
|
| 11 |
+
773b5fd8a36388fd484d3113ac09d258c6136f1577141a29bc84c028c7bd8410 conversion/eg2.py
|
| 12 |
+
cfb7629e2b6e0f3d847b2accf3b9ff56394d73740c5c31258e67ffca93f7b65b conversion/fetch_stock.py
|
| 13 |
+
6ff7b41f33e878630ad7fbab24ae2eb0e8a888b120aca1ca4eb62be1b92945c6 conversion/fixtures/SHA256SUMS
|
| 14 |
+
3319a38f4dafccde2ed4c0eec5d3445e7b25716c0befd59f0332e6eefd6a5cb1 conversion/fixtures/tokens.json.gz
|
| 15 |
+
2c680ea416ddde788df7b68ef08d53a7565264a7224f6b04ba592fdbaa61b27c conversion/parity.py
|
| 16 |
+
ab05275c8da35cd35847e14fac38c31aa3142adb2cfa0f351f3fbbebfd693330 conversion/provenance.py
|
| 17 |
+
448293cf8031689a3a57035f0620e375b6eb18f684b621ef35df556b51b51efd conversion/requirements.lock
|
| 18 |
+
1cb8409645fbb2187f61781193a7fd89c53af34b0c2cd9d7d081715b674ce071 conversion/source-manifest.json
|
| 19 |
+
cb12bc2fd35c70027b760a6db087b22035bb4cf3a2b18383b40751ad6ffc472f conversion/source-snapshot.json
|
| 20 |
+
132d8714852fa8f0c376af797229e7b48fe94e0cf6cae6f6640681e934062923 conversion/upstream/modeling_embedding_gemma2.py
|
| 21 |
+
94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d conversion/upstream/qvac/LICENSE
|
| 22 |
+
b87b9d24bb4f27cf644022950d7070930b9fae625d1563cfff3d2838f494828a conversion/upstream/qvac/README.md
|
| 23 |
+
5069938b448ae1469edea758140f4710883c1317b1f889778e24e57d07f0d638 conversion/upstream/qvac/export_coreml.py
|
| 24 |
+
b33c80ea0f097c533acb68b9d310d795cce7f262acae78ffd70a07fa71d029b9 conversion/upstream/qvac/requirements.txt
|
| 25 |
+
77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049 conversion/upstream/transformers-LICENSE
|
| 26 |
+
49c2540dcf1df164a259b820cf09f5adcfc70314984f1a2a8fe7c8b09fc32cad conversion/validate.swift
|
| 27 |
+
7404e73a675163ddf54221a32add5321daf2f4c84ebdab89065abf309413fe59 docs/technical-notes.md
|
| 28 |
+
9be904fe551a4f2a8316920eb76c92880c59c224c98cfc43a7d40f74060c854f docs/usage.md
|
| 29 |
94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d licenses/QVAC-MIT.txt
|
| 30 |
+
4adacf5b3d86d1fd6049793a0acbe0de0c65ada1ce9f7865c933ec0243194072 release-manifest.json
|
| 31 |
b8f1e9931b57fbc054acdb445c41765d55b0074c58d145fa82839941ad1b5bb3 source-config.json
|
| 32 |
4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4 tokenizer.json
|
| 33 |
17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874 tokenizer_config.json
|
conversion/NOTICE
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
EmbeddingGemma 2 owned Core ML conversion
|
| 2 |
+
|
| 3 |
+
Source weights: Google DeepMind, google/embeddinggemma-2, revision
|
| 4 |
+
914f7f89142e33e77833254d9c9b90c3cef7303b, Apache License 2.0.
|
| 5 |
+
|
| 6 |
+
eg2.py is an independently organized fixed-shape/channel-first adaptation of
|
| 7 |
+
the text forward defined in Hugging Face Transformers v5.19.0:
|
| 8 |
+
Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 9 |
+
Apache License 2.0. Upstream source and license are preserved in upstream/.
|
| 10 |
+
|
| 11 |
+
Overflow-safe RMS and L2 rescaling formulas are adapted from
|
| 12 |
+
tetherto/qvac-fabric-llm.cpp/examples/embedding-coreml/export_coreml.py,
|
| 13 |
+
commit 2ed826df0c0eefc7135e9c3acc45aaa277f9b6ff, MIT license.
|
| 14 |
+
The source file, recipe, requirements and full copyright/license text are
|
| 15 |
+
preserved in upstream/qvac/.
|
| 16 |
+
|
| 17 |
+
Modifications: text-only weights; fixed 128/256/512/1024/2048 sequence lengths;
|
| 18 |
+
int32 token input plus float32 right-padding mask; fixed FP32-generated RoPE;
|
| 19 |
+
channel-first activations and 1x1 convolutions; explicit attention heads;
|
| 20 |
+
inclusive bidirectional sliding-window radius 512; finite -10000 mask;
|
| 21 |
+
masked mean including prompt and special tokens before bias-free projection;
|
| 22 |
+
overflow-safe normalization; FP16 Core ML encoder weights/compute and FP32
|
| 23 |
+
final L2 normalization over the 768 output values; shared-weight
|
| 24 |
+
multifunction packaging. Original 768-dimensional normalized embeddings are
|
| 25 |
+
preserved. No downstream head projection, truncation, pruning or weight
|
| 26 |
+
quantization is applied.
|
| 27 |
+
|
| 28 |
+
Nemosine and CoreAI cards were consulted as research only. No weights or
|
| 29 |
+
converter code from those packages are included in this conversion.
|
| 30 |
+
This work is not endorsed by Google, Hugging Face, Apple or Tether.
|
conversion/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproduce the conversion
|
| 2 |
+
|
| 3 |
+
This directory contains the tested converter, dependency lock, source-weight
|
| 4 |
+
pins, fixtures and native validator. It is self-contained; no GitHub branch
|
| 5 |
+
checkout is required. The implementation files match the five-bucket export
|
| 6 |
+
recorded in [source-snapshot.json](source-snapshot.json).
|
| 7 |
+
|
| 8 |
+
Use Apple Silicon macOS with Python 3.12.9. Download the conversion directory
|
| 9 |
+
and enter it:
|
| 10 |
+
|
| 11 |
+
```sh
|
| 12 |
+
hf download anylab/embeddinggemma-2-coreml --include 'conversion/**' --local-dir eg2
|
| 13 |
+
cd eg2/conversion
|
| 14 |
+
gzip -dc fixtures/tokens.json.gz > tokens.json
|
| 15 |
+
shasum -a 256 -c fixtures/SHA256SUMS
|
| 16 |
+
mkdir -p evidence
|
| 17 |
+
python3.12 -m venv .venv
|
| 18 |
+
.venv/bin/python -m pip install -r requirements.lock
|
| 19 |
+
.venv/bin/python fetch_stock.py
|
| 20 |
+
.venv/bin/python parity.py > evidence/torch-parity.log 2>&1
|
| 21 |
+
.venv/bin/python convert.py --lengths 128 256 512 1024 2048 --merge > evidence/convert-all.log 2>&1
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
`fetch_stock.py` retrieves and verifies the exact Google checkpoint and tokenizer
|
| 25 |
+
pinned in [source-manifest.json](source-manifest.json). `parity.py` checks the
|
| 26 |
+
rewritten FP32 forward against the stock model before export. Conversion refuses
|
| 27 |
+
to proceed without a passing gate for the current source and dependencies.
|
| 28 |
+
|
| 29 |
+
The output is `models/EmbeddingGemma2Owned.mlpackage`: five functions with shared
|
| 30 |
+
FP16 encoder weights and FP32 final L2 normalization. Prompts, special tokens
|
| 31 |
+
and input/output shapes are described in [usage](../docs/usage.md).
|
| 32 |
+
|
| 33 |
+
## Validate on a Mac
|
| 34 |
+
|
| 35 |
+
These are the commands used with the macOS 27 SDK for the recorded M2 Air run:
|
| 36 |
+
|
| 37 |
+
```sh
|
| 38 |
+
xcrun swiftc -parse-as-library -O -target arm64-apple-macos27.0 validate.swift -o validate
|
| 39 |
+
./validate "$PWD" cold multi 128,256,512,1024,2048 > evidence/air-cold.log 2>&1
|
| 40 |
+
./validate "$PWD" warm multi 128,256,512,1024,2048 > evidence/air-warm.log 2>&1
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Run one validation process at a time. For a separate target Mac, copy `models/`,
|
| 44 |
+
`evidence/hf-reference.json`, `tokens.json` and the validator into a fresh directory.
|
| 45 |
+
The runner creates and reuses an adjacent `.mlmodelc`; replacing package bytes
|
| 46 |
+
requires a fresh compiled artifact.
|
| 47 |
+
|
| 48 |
+
The validator records reference parity, compute-plan placement, corpus outputs,
|
| 49 |
+
timings and memory ledgers. It uses `cpuAndNeuralEngine`, which allows CPU work.
|
| 50 |
+
Record the actual hardware and OS when repeating the run.
|
| 51 |
+
|
| 52 |
+
## Reproducibility scope
|
| 53 |
+
|
| 54 |
+
The distributed package combines four retained November 12 exports with the
|
| 55 |
+
November 16 s2048 export. All five were validated together. These commands rebuild
|
| 56 |
+
all five from the current tested converter; per-function provenance for the
|
| 57 |
+
distributed artifact remains in the [release manifest](../release-manifest.json).
|
| 58 |
+
|
| 59 |
+
A clean s2048 rebuild reproduced the weight bytes and parsed model graph.
|
| 60 |
+
Whole-package byte identity is not promised: package UUIDs and protobuf map
|
| 61 |
+
ordering can differ. The [validation report](../validation/2026-11-16-five-bucket/REPORT.txt)
|
| 62 |
+
records the exact tested artifact and limitations.
|
| 63 |
+
|
| 64 |
+
The forward adapts Transformers and QVAC's overflow-safe normalization. See
|
| 65 |
+
[NOTICE](NOTICE) and the included upstream license files.
|
conversion/buckets.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The exported fixed sequence lengths, including BOS/EOS and prompt tokens."""
|
| 2 |
+
LENGTHS = (128, 256, 512, 1024, 2048)
|
| 3 |
+
MAX_LENGTH = LENGTHS[-1]
|
conversion/convert.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import platform
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import coremltools as ct
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from coremltools.converters.mil.mil.scope import ScopeSource
|
| 12 |
+
|
| 13 |
+
from eg2 import EG2
|
| 14 |
+
from fetch_stock import verify
|
| 15 |
+
from provenance import fingerprint
|
| 16 |
+
from buckets import LENGTHS
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
p = argparse.ArgumentParser()
|
| 21 |
+
p.add_argument("--stock", type=Path, default=Path("stock"))
|
| 22 |
+
p.add_argument("--output", type=Path, default=Path("models"))
|
| 23 |
+
p.add_argument("--lengths", type=int, nargs="+", default=list(LENGTHS))
|
| 24 |
+
p.add_argument("--merge", action="store_true")
|
| 25 |
+
a = p.parse_args()
|
| 26 |
+
assert a.lengths==sorted(set(a.lengths)) and set(a.lengths)<=set(LENGTHS), "Use sorted supported lengths without duplicates"
|
| 27 |
+
verify(a.stock)
|
| 28 |
+
gate = json.loads(Path("evidence/torch-parity.json").read_text())
|
| 29 |
+
assert gate["passed"], "Stock HF parity must pass before conversion"
|
| 30 |
+
assert gate["provenance"]==fingerprint(), "Stale parity gate: rerun parity.py after source/toolchain changes"
|
| 31 |
+
provenance=fingerprint(conversion=True)
|
| 32 |
+
torch.set_num_threads(4)
|
| 33 |
+
a.output.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
for length in a.lengths:
|
| 35 |
+
path = a.output / f"s{length}.mlpackage"
|
| 36 |
+
metadata=a.output / f"s{length}.provenance.json"
|
| 37 |
+
if path.exists():
|
| 38 |
+
assert metadata.exists() and json.loads(metadata.read_text())==provenance, f"Stale export: use a fresh output directory for {path}"
|
| 39 |
+
print("Existing", path, flush=True)
|
| 40 |
+
continue
|
| 41 |
+
start = time.monotonic()
|
| 42 |
+
model = EG2(a.stock, length).eval()
|
| 43 |
+
ids = torch.zeros((1, length), dtype=torch.int32)
|
| 44 |
+
ids[0, :3] = torch.tensor([2, 9259, 1])
|
| 45 |
+
mask = (ids != 0).float()
|
| 46 |
+
with torch.inference_mode():
|
| 47 |
+
traced = torch.jit.trace(model, (ids, mask), check_trace=False)
|
| 48 |
+
fp32_ops=[]
|
| 49 |
+
def use_fp16(op):
|
| 50 |
+
keep_fp32="output_normalize" in op.scopes.get(ScopeSource.TORCHSCRIPT_MODULE_NAME,[])
|
| 51 |
+
if keep_fp32:fp32_ops.append({"name":op.name,"type":op.op_type})
|
| 52 |
+
return not keep_fp32
|
| 53 |
+
ml = ct.convert(traced, convert_to="mlprogram", minimum_deployment_target=ct.target.macOS15,
|
| 54 |
+
inputs=[ct.TensorType(name="input_ids", shape=(1, length), dtype=np.int32),
|
| 55 |
+
ct.TensorType(name="attention_mask", shape=(1, length), dtype=np.float32)],
|
| 56 |
+
outputs=[ct.TensorType(name="embedding", dtype=np.float32)],
|
| 57 |
+
compute_precision=ct.transform.FP16ComputePrecision(op_selector=use_fp16),
|
| 58 |
+
compute_units=ct.ComputeUnit.CPU_AND_NE, skip_model_load=True)
|
| 59 |
+
assert len(fp32_ops)>=3, "FP32 final-normalization scope was lost during conversion"
|
| 60 |
+
ml.author = "Owned conversion from Google stock EG2; see NOTICE"
|
| 61 |
+
ml.license = "Apache-2.0"
|
| 62 |
+
ml.short_description = "Stock EG2 text; FP16 encoder; masked mean including prompt; FP32 final L2"
|
| 63 |
+
ml.user_defined_metadata["stock_revision"] = "914f7f89142e33e77833254d9c9b90c3cef7303b"
|
| 64 |
+
ml.user_defined_metadata["conversion_fingerprint"]=provenance["fingerprint"]
|
| 65 |
+
ml.save(str(path))
|
| 66 |
+
metadata.write_text(json.dumps(provenance,indent=2)+"\n")
|
| 67 |
+
(a.output/f"s{length}.precision.json").write_text(json.dumps({"encoder":"FP16","finalNormalization":"FP32","excludedFromFP16":fp32_ops},indent=2)+"\n")
|
| 68 |
+
print(json.dumps({"length": length, "seconds": time.monotonic() - start, "path": str(path)}), flush=True)
|
| 69 |
+
del model, traced, ml
|
| 70 |
+
if a.merge:
|
| 71 |
+
desc = ct.utils.MultiFunctionDescriptor()
|
| 72 |
+
for length in a.lengths:
|
| 73 |
+
desc.add_function(str(a.output / f"s{length}.mlpackage"), "main", f"s{length}")
|
| 74 |
+
desc.default_function_name = f"s{a.lengths[0]}"
|
| 75 |
+
ct.utils.save_multifunction(desc, str(a.output / "EmbeddingGemma2Owned.mlpackage"))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
main()
|
conversion/eg2.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fixed-shape text-only EG2, derived from Transformers v5.19.0 (Apache-2.0).
|
| 2 |
+
|
| 3 |
+
Uses stock weights without quantization, pruning, or downstream head removal.
|
| 4 |
+
Channel-first activations and 1x1 convolutions are export transformations;
|
| 5 |
+
pooling before the bias-free projection is algebraically equivalent.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from safetensors import safe_open
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def stock_state(root):
|
| 16 |
+
with safe_open(str(Path(root) / "model.safetensors"), framework="pt") as f:
|
| 17 |
+
return {k.removeprefix("language_model."): f.get_tensor(k).float()
|
| 18 |
+
for k in f.keys() if k.startswith("language_model.")}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class OutputNormalize(torch.nn.Module):
|
| 22 |
+
"""Kept in FP32 by the converter: 768 values only, after the FP16 encoder."""
|
| 23 |
+
def forward(self, x):
|
| 24 |
+
x = x / x.abs().amax(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 25 |
+
return x / torch.sqrt((x * x).sum(-1, keepdim=True))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class EG2(torch.nn.Module):
|
| 29 |
+
def __init__(self, root, length):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.cfg = json.loads((Path(root) / "config.json").read_text())["text_config"]
|
| 32 |
+
self.length = length
|
| 33 |
+
self.eps = self.cfg["rms_norm_eps"]
|
| 34 |
+
self.output_normalize = OutputNormalize()
|
| 35 |
+
self.weights = torch.nn.ParameterDict({k.replace(".", "__"): torch.nn.Parameter(v, requires_grad=False)
|
| 36 |
+
for k, v in stock_state(root).items()})
|
| 37 |
+
for kind, dim in [("sliding_attention", 256), ("full_attention", 512)]:
|
| 38 |
+
theta = self.cfg["rope_parameters"][kind]["rope_theta"]
|
| 39 |
+
inv = 1.0 / theta ** (torch.arange(0, dim, 2).float() / dim)
|
| 40 |
+
phase = torch.arange(length).float()[:, None] * inv[None]
|
| 41 |
+
phase = torch.cat([phase, phase], dim=1).T[None, :, None, :]
|
| 42 |
+
self.register_buffer(kind + "_cos", phase.cos())
|
| 43 |
+
self.register_buffer(kind + "_sin", phase.sin())
|
| 44 |
+
r = torch.arange(length)
|
| 45 |
+
self.register_buffer("band", ((r[:, None] - r[None, :]).abs() > self.cfg["sliding_window"]).float()[None, None] * -10000)
|
| 46 |
+
|
| 47 |
+
def w(self, key):
|
| 48 |
+
return self.weights[key.replace(".", "__")]
|
| 49 |
+
|
| 50 |
+
def linear(self, x, key):
|
| 51 |
+
return F.conv2d(x, self.w(key + ".weight")[:, :, None, None])
|
| 52 |
+
|
| 53 |
+
def norm(self, x, key=None):
|
| 54 |
+
# Overflow-safe RMS rewrite adapted from qvac-fabric-llm.cpp
|
| 55 |
+
# export_coreml.py, commit 2ed826df0c0eefc7135e9c3acc45aaa277f9b6ff (MIT).
|
| 56 |
+
scale = x.abs().amax(dim=1, keepdim=True).clamp_min(1.0)
|
| 57 |
+
scaled = x / scale
|
| 58 |
+
y = scaled * torch.rsqrt((scaled * scaled).mean(1, keepdim=True) + self.eps / scale / scale)
|
| 59 |
+
if key:
|
| 60 |
+
y = y * self.w(key + ".weight")[None, :, None, None]
|
| 61 |
+
return y
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def rotate(x):
|
| 65 |
+
a, b = x.chunk(2, dim=1)
|
| 66 |
+
return torch.cat([-b, a], dim=1)
|
| 67 |
+
|
| 68 |
+
def forward(self, input_ids, attention_mask):
|
| 69 |
+
x = F.embedding(input_ids, self.w("embed_tokens.weight")).transpose(1, 2).unsqueeze(2)
|
| 70 |
+
x = x * self.cfg["hidden_size"] ** 0.5
|
| 71 |
+
embedding = x
|
| 72 |
+
pad = (1.0 - attention_mask[:, None, None, :]) * -10000
|
| 73 |
+
for i, kind in enumerate(self.cfg["layer_types"]):
|
| 74 |
+
base = f"layers.{i}"
|
| 75 |
+
att = base + ".self_attn"
|
| 76 |
+
xn = self.norm(x, base + ".input_layernorm")
|
| 77 |
+
dim = 512 if kind == "full_attention" else 256
|
| 78 |
+
nk = 1 if kind == "full_attention" else 2
|
| 79 |
+
q = self.linear(xn, att + ".q_proj").split(dim, dim=1)
|
| 80 |
+
k = self.linear(xn, att + ".k_proj").split(dim, dim=1)
|
| 81 |
+
v = self.linear(xn, att + ".v_proj").split(dim, dim=1)
|
| 82 |
+
cos, sin = getattr(self, kind + "_cos"), getattr(self, kind + "_sin")
|
| 83 |
+
ks, vs = [], []
|
| 84 |
+
for j in range(nk):
|
| 85 |
+
kj = self.norm(k[j], att + ".k_norm")
|
| 86 |
+
ks.append((kj * cos + self.rotate(kj) * sin).permute(0, 2, 1, 3))
|
| 87 |
+
vs.append(self.norm(v[j]).permute(0, 2, 1, 3))
|
| 88 |
+
mask = pad + self.band if kind == "sliding_attention" else pad
|
| 89 |
+
heads = []
|
| 90 |
+
for j in range(4):
|
| 91 |
+
qj = self.norm(q[j], att + ".q_norm")
|
| 92 |
+
qj = qj * cos + self.rotate(qj) * sin
|
| 93 |
+
scores = torch.matmul(qj.permute(0, 2, 3, 1), ks[j // (4 // nk)])
|
| 94 |
+
prob = torch.softmax(scores + mask, dim=-1)
|
| 95 |
+
h = torch.matmul(vs[j // (4 // nk)], prob.transpose(-1, -2))
|
| 96 |
+
heads.append(h.permute(0, 2, 1, 3))
|
| 97 |
+
a = self.linear(torch.cat(heads, dim=1), att + ".o_proj")
|
| 98 |
+
x = x + self.norm(a, base + ".post_attention_layernorm")
|
| 99 |
+
xn = self.norm(x, base + ".pre_feedforward_layernorm")
|
| 100 |
+
m = F.gelu(self.linear(xn, base + ".mlp.gate_proj"), approximate="tanh") * self.linear(xn, base + ".mlp.up_proj")
|
| 101 |
+
x = x + self.norm(self.linear(m, base + ".mlp.down_proj"), base + ".post_feedforward_layernorm")
|
| 102 |
+
# Split the large PLE projection by layer; preserves stock arithmetic.
|
| 103 |
+
pw = self.w("ple.per_layer_model_projection.weight")[i * 512:(i + 1) * 512]
|
| 104 |
+
ple = F.conv2d(embedding, pw[:, :, None, None]) * self.cfg["hidden_size"] ** -0.5
|
| 105 |
+
ple = self.norm(ple, "ple.per_layer_projection_norm")
|
| 106 |
+
gate = F.gelu(self.linear(x, base + ".ple_block.per_layer_input_gate"), approximate="tanh")
|
| 107 |
+
y = self.linear(gate * ple, base + ".ple_block.per_layer_projection")
|
| 108 |
+
x = (x + self.norm(y, base + ".ple_block.post_per_layer_input_norm")) * self.w(base + ".layer_scalar")
|
| 109 |
+
x = self.norm(x, "norm")
|
| 110 |
+
mask = attention_mask[:, None, None, :]
|
| 111 |
+
x = (x * mask).sum(-1, keepdim=True) / mask.sum(-1, keepdim=True)
|
| 112 |
+
x = self.linear(x, "embedding_projection").flatten(1)
|
| 113 |
+
# Overflow-safe L2 rewrite from the same MIT-licensed exporter.
|
| 114 |
+
return self.output_normalize(x)
|
conversion/fetch_stock.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download the pinned public checkpoint, then verify every source byte."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import urllib.request
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def verify(root=Path("stock")):
|
| 9 |
+
manifest=json.loads(Path("source-manifest.json").read_text())
|
| 10 |
+
for name, expected in manifest["files"].items():
|
| 11 |
+
p=root/name
|
| 12 |
+
h=hashlib.sha256()
|
| 13 |
+
with p.open("rb") as f:
|
| 14 |
+
for chunk in iter(lambda:f.read(8*1024*1024),b""):h.update(chunk)
|
| 15 |
+
if p.stat().st_size!=expected["bytes"] or h.hexdigest()!=expected["sha256"]:
|
| 16 |
+
raise ValueError(f"Stock file integrity failed: {p}")
|
| 17 |
+
return manifest
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__=="__main__":
|
| 21 |
+
manifest=json.loads(Path("source-manifest.json").read_text())
|
| 22 |
+
root=Path("stock");root.mkdir(exist_ok=True)
|
| 23 |
+
for name, expected in manifest["files"].items():
|
| 24 |
+
p=root/name
|
| 25 |
+
if not p.exists():
|
| 26 |
+
url=f'https://huggingface.co/{manifest["repo"]}/resolve/{manifest["revision"]}/{name}'
|
| 27 |
+
temporary=p.with_suffix(p.suffix+".partial")
|
| 28 |
+
print("Downloading",name,flush=True)
|
| 29 |
+
urllib.request.urlretrieve(url,temporary)
|
| 30 |
+
temporary.replace(p)
|
| 31 |
+
print(json.dumps(verify(),indent=2))
|
conversion/fixtures/SHA256SUMS
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ff7f41a9586d566abf33f14aa9033f40e6d701698baa1d552b2f12f8f742a13a tokens.json
|
conversion/fixtures/tokens.json.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3319a38f4dafccde2ed4c0eec5d3445e7b25716c0befd59f0332e6eefd6a5cb1
|
| 3 |
+
size 1099170
|
conversion/parity.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gate the export forward against the pinned stock Transformers forward."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from tokenizers import Tokenizer
|
| 10 |
+
from transformers.models.embedding_gemma2.configuration_embedding_gemma2 import EmbeddingGemma2TextConfig
|
| 11 |
+
from transformers.models.embedding_gemma2.modeling_embedding_gemma2 import EmbeddingGemma2TextModel
|
| 12 |
+
|
| 13 |
+
from eg2 import EG2, stock_state
|
| 14 |
+
from fetch_stock import verify
|
| 15 |
+
from provenance import fingerprint
|
| 16 |
+
from buckets import LENGTHS, MAX_LENGTH
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def stats(a, b):
|
| 20 |
+
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
| 21 |
+
return {"cosine": float(np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b)),
|
| 22 |
+
"max_abs": float(np.max(np.abs(a-b))), "finite": bool(np.isfinite(a).all() and np.isfinite(b).all())}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
p = argparse.ArgumentParser()
|
| 27 |
+
p.add_argument("--stock", type=Path, default=Path("stock"))
|
| 28 |
+
a = p.parse_args()
|
| 29 |
+
verify(a.stock)
|
| 30 |
+
torch.set_num_threads(4)
|
| 31 |
+
cfg = EmbeddingGemma2TextConfig(**json.loads((a.stock / "config.json").read_text())["text_config"])
|
| 32 |
+
cfg._attn_implementation = "eager"
|
| 33 |
+
hf = EmbeddingGemma2TextModel(cfg).eval()
|
| 34 |
+
hf.load_state_dict(stock_state(a.stock), strict=True)
|
| 35 |
+
tok = Tokenizer.from_file(str(a.stock / "tokenizer.json"))
|
| 36 |
+
texts = ["title: none | text: ", "task: search result | query: How do bond prices respond to interest rates?",
|
| 37 |
+
"title: Привет | text: Москва, Berlin, 東京 — مرحبا بالعالم. Ελληνικά, हिन्दी, café 🚀.",
|
| 38 |
+
"title: Financial report | text: " + "The borrower repays the loan and interest. " * 68,
|
| 39 |
+
"task: search result | query: " + "雪が降っています。 金融市場。 " * 55]
|
| 40 |
+
cases = []
|
| 41 |
+
for text in texts:
|
| 42 |
+
ids = tok.encode(text).ids
|
| 43 |
+
if ids[0] != 2: ids.insert(0, 2)
|
| 44 |
+
if ids[-1] != 1: ids.append(1)
|
| 45 |
+
length = next(x for x in LENGTHS if x >= len(ids))
|
| 46 |
+
cases.append({"text": text, "tokens": ids, "length": length})
|
| 47 |
+
# Same short input in every bucket, plus exact-length stress and realistic long rows.
|
| 48 |
+
cases += [dict(cases[1], length=x) for x in [256, 512, 1024]]
|
| 49 |
+
rows = json.loads(Path("tokens.json").read_text())
|
| 50 |
+
# Retained regression: all-FP16 final L2 produced norm 0.99876078
|
| 51 |
+
# for FiQA document52 on the M2 Air. It must be exercised before corpus.
|
| 52 |
+
cases.append(dict(rows[52*2],length=512))
|
| 53 |
+
for lower, length in [(128,256),(256,512),(512,1024)]:
|
| 54 |
+
row = next(r for r in rows[:3000:2] if lower < len(r["tokens"]) <= length)
|
| 55 |
+
cases.append(dict(row, length=length))
|
| 56 |
+
# Extended-context gates: actual long text, fully occupied 2048 input,
|
| 57 |
+
# and a short input whose far padding rows have no unmasked local keys.
|
| 58 |
+
cases.append(dict(cases[1],length=MAX_LENGTH,kind="short-padded-2048"))
|
| 59 |
+
long_row=next(r for r in rows[:3000:2] if 1024<len(r["tokens"])<=MAX_LENGTH)
|
| 60 |
+
cases.append(dict(long_row,length=MAX_LENGTH,kind="long-fiqa"))
|
| 61 |
+
def encode(text):
|
| 62 |
+
ids=tok.encode(text).ids
|
| 63 |
+
if ids[0]!=2:ids.insert(0,2)
|
| 64 |
+
if ids[-1]!=1:ids.append(1)
|
| 65 |
+
return ids
|
| 66 |
+
multilingual="task: search result | query: "+"雪が降っています。 金融市場。 "*180
|
| 67 |
+
multilingual_ids=encode(multilingual)
|
| 68 |
+
assert 1024<len(multilingual_ids)<MAX_LENGTH
|
| 69 |
+
cases.append(dict(text=multilingual,tokens=multilingual_ids,length=MAX_LENGTH,kind="long-multilingual"))
|
| 70 |
+
prefix="title: Exact boundary | text:"
|
| 71 |
+
repetitions=MAX_LENGTH-len(encode(prefix))
|
| 72 |
+
for _ in range(8):
|
| 73 |
+
boundary=prefix+" x"*repetitions
|
| 74 |
+
boundary_ids=encode(boundary)
|
| 75 |
+
if len(boundary_ids)==MAX_LENGTH:break
|
| 76 |
+
repetitions+=MAX_LENGTH-len(boundary_ids)
|
| 77 |
+
assert len(boundary_ids)==MAX_LENGTH and boundary_ids[0]==2 and boundary_ids[-1]==1
|
| 78 |
+
cases.append(dict(text=boundary,tokens=boundary_ids,length=MAX_LENGTH,kind="exact-2048-text"))
|
| 79 |
+
report, reference = [], []
|
| 80 |
+
for length in LENGTHS:
|
| 81 |
+
own = EG2(a.stock, length).eval()
|
| 82 |
+
for n, case in enumerate(cases):
|
| 83 |
+
if case["length"] != length: continue
|
| 84 |
+
ids = torch.zeros((1,length), dtype=torch.long)
|
| 85 |
+
ids[0,:len(case["tokens"])] = torch.tensor(case["tokens"])
|
| 86 |
+
mask = torch.zeros((1,length));mask[0,:len(case["tokens"])]=1
|
| 87 |
+
with torch.inference_mode():
|
| 88 |
+
h = hf(input_ids=ids, attention_mask=mask).last_hidden_state
|
| 89 |
+
expected = F.normalize((h*mask[:,:,None]).sum(1)/mask.sum(1,keepdim=True), dim=-1)[0].numpy()
|
| 90 |
+
actual = own(ids.to(torch.int32),mask)[0].numpy()
|
| 91 |
+
s = dict(case=n,length=length,tokens=len(case["tokens"]),kind=case.get("kind","existing-fixture"),**stats(expected,actual))
|
| 92 |
+
print(json.dumps(s),flush=True);report.append(s)
|
| 93 |
+
reference.append(dict(case=n,**case,vector=expected.tolist()))
|
| 94 |
+
del own
|
| 95 |
+
out=Path("evidence");out.mkdir(exist_ok=True)
|
| 96 |
+
passed=all(r["finite"] and r["cosine"]>0.9999999 and r["max_abs"]<2e-5 for r in report)
|
| 97 |
+
assert any(r["length"]==1024 and r["tokens"]>513 for r in report)
|
| 98 |
+
assert any(r["length"]==MAX_LENGTH and r["tokens"]==MAX_LENGTH for r in report)
|
| 99 |
+
assert any(r["length"]==MAX_LENGTH and r["tokens"]<128 for r in report)
|
| 100 |
+
assert sum(r["length"]==MAX_LENGTH and r["tokens"]>1024 for r in report)>=3
|
| 101 |
+
(out/"torch-parity.json").write_text(json.dumps({"passed":passed,"provenance":fingerprint(),"reference":"Transformers 5.19.0 stock weights, FP32 eager, raw masked mean then L2", "cases":report},indent=2)+"\n")
|
| 102 |
+
(out/"hf-reference.json").write_text(json.dumps(reference)+"\n")
|
| 103 |
+
assert passed, "Stock forward parity failed"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__": main()
|
conversion/provenance.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import importlib.metadata
|
| 3 |
+
import json
|
| 4 |
+
import platform
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def fingerprint(conversion=False):
|
| 9 |
+
names=["eg2.py","parity.py","buckets.py","tokens.json","fetch_stock.py","source-manifest.json","provenance.py"]
|
| 10 |
+
if conversion:names.append("convert.py")
|
| 11 |
+
data={"files":{n:hashlib.sha256(Path(n).read_bytes()).hexdigest() for n in names},
|
| 12 |
+
"versions":{n:importlib.metadata.version(n) for n in ["torch","transformers","coremltools","numpy","safetensors","tokenizers"]},
|
| 13 |
+
"python":platform.python_version()}
|
| 14 |
+
data["fingerprint"]=hashlib.sha256(json.dumps(data,sort_keys=True).encode()).hexdigest()
|
| 15 |
+
return data
|
conversion/requirements.lock
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
annotated-doc==0.0.6
|
| 2 |
+
annotated-types==0.8.0
|
| 3 |
+
anyio==4.16.0
|
| 4 |
+
attrs==26.1.0
|
| 5 |
+
cattrs==26.2.1
|
| 6 |
+
click==8.5.1
|
| 7 |
+
coremltools==9.0
|
| 8 |
+
filelock==4.2.10
|
| 9 |
+
fsspec==2026.9.0
|
| 10 |
+
h11==0.16.0
|
| 11 |
+
hf-xet==1.8.0
|
| 12 |
+
httpcore2==2.16.0
|
| 13 |
+
httpx2==2.16.0
|
| 14 |
+
huggingface-hub==2.4.0
|
| 15 |
+
idna==3.20
|
| 16 |
+
jinja2==3.1.6
|
| 17 |
+
markdown-it-py==4.3.0
|
| 18 |
+
markupsafe==3.0.4
|
| 19 |
+
mdurl==0.1.2
|
| 20 |
+
mpmath==1.3.0
|
| 21 |
+
networkx==3.7
|
| 22 |
+
numpy==2.2.6
|
| 23 |
+
packaging==26.3
|
| 24 |
+
protobuf==7.36.2
|
| 25 |
+
pyaml==26.7.0
|
| 26 |
+
pydantic==2.14.3
|
| 27 |
+
pydantic-core==2.50.4
|
| 28 |
+
pygments==2.21.0
|
| 29 |
+
pyyaml==6.0.3
|
| 30 |
+
regex==2026.11.9
|
| 31 |
+
rich==15.0.0
|
| 32 |
+
safetensors==0.8.0
|
| 33 |
+
setuptools==84.2.1
|
| 34 |
+
shellingham==1.5.4
|
| 35 |
+
sympy==1.14.0
|
| 36 |
+
tokenizers==0.23.3
|
| 37 |
+
torch==2.7.0
|
| 38 |
+
tqdm==4.70.1
|
| 39 |
+
transformers==5.19.0
|
| 40 |
+
truststore==0.10.5
|
| 41 |
+
typer==0.29.1
|
| 42 |
+
typing-extensions==4.16.0
|
| 43 |
+
typing-inspection==0.4.5
|
conversion/source-manifest.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo": "google/embeddinggemma-2",
|
| 3 |
+
"revision": "914f7f89142e33e77833254d9c9b90c3cef7303b",
|
| 4 |
+
"files": {
|
| 5 |
+
"config.json": {
|
| 6 |
+
"sha256": "b8f1e9931b57fbc054acdb445c41765d55b0074c58d145fa82839941ad1b5bb3",
|
| 7 |
+
"bytes": 4455
|
| 8 |
+
},
|
| 9 |
+
"model.safetensors": {
|
| 10 |
+
"sha256": "197a32965d4b1105faf060417baa899e193fb73cd401f42ec9295234d5553d79",
|
| 11 |
+
"bytes": 1488915288
|
| 12 |
+
},
|
| 13 |
+
"tokenizer.json": {
|
| 14 |
+
"sha256": "4d777ef5bdc1aa36227abdfb77c3e49e7b9c892d16e1b6bda41c393504828be4",
|
| 15 |
+
"bytes": 32170510
|
| 16 |
+
},
|
| 17 |
+
"tokenizer_config.json": {
|
| 18 |
+
"sha256": "17bd5d6e9364ca49a534e1502076593317c298d4a663623091ed45388f004874",
|
| 19 |
+
"bytes": 1599
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
}
|
conversion/source-snapshot.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"originalRepository": "anyproto/any",
|
| 3 |
+
"originalCommit": "6424fab8cb6bd2874ce08e85d9081e24ff96902f",
|
| 4 |
+
"originalPath": "scripts/embedbench/research/eg2_coreml",
|
| 5 |
+
"origin": "Previously published, tested five-bucket converter; implementation copied without edits. README is adapted for this self-contained HF directory.",
|
| 6 |
+
"exportProvenance": {
|
| 7 |
+
"files": {
|
| 8 |
+
"eg2.py": "773b5fd8a36388fd484d3113ac09d258c6136f1577141a29bc84c028c7bd8410",
|
| 9 |
+
"parity.py": "2c680ea416ddde788df7b68ef08d53a7565264a7224f6b04ba592fdbaa61b27c",
|
| 10 |
+
"buckets.py": "ff2261663941716c9b6884bb11a9cbaa75d660d6c41061d03c9ce0a0c473656a",
|
| 11 |
+
"tokens.json": "ff7f41a9586d566abf33f14aa9033f40e6d701698baa1d552b2f12f8f742a13a",
|
| 12 |
+
"fetch_stock.py": "cfb7629e2b6e0f3d847b2accf3b9ff56394d73740c5c31258e67ffca93f7b65b",
|
| 13 |
+
"source-manifest.json": "1cb8409645fbb2187f61781193a7fd89c53af34b0c2cd9d7d081715b674ce071",
|
| 14 |
+
"provenance.py": "ab05275c8da35cd35847e14fac38c31aa3142adb2cfa0f351f3fbbebfd693330",
|
| 15 |
+
"convert.py": "432a26fb6bea8e7f943a783592c3f6c8bdecf56bce4d78c465d3f203c05ea5ca"
|
| 16 |
+
},
|
| 17 |
+
"versions": {
|
| 18 |
+
"torch": "2.7.0",
|
| 19 |
+
"transformers": "5.19.0",
|
| 20 |
+
"coremltools": "9.0",
|
| 21 |
+
"numpy": "2.2.6",
|
| 22 |
+
"safetensors": "0.8.0",
|
| 23 |
+
"tokenizers": "0.23.3"
|
| 24 |
+
},
|
| 25 |
+
"python": "3.12.9",
|
| 26 |
+
"fingerprint": "b2707f2f48091d50d70fb4d52181924aedf0e5ea23521d123914d0775db69e33"
|
| 27 |
+
},
|
| 28 |
+
"files": {
|
| 29 |
+
"eg2.py": "773b5fd8a36388fd484d3113ac09d258c6136f1577141a29bc84c028c7bd8410",
|
| 30 |
+
"parity.py": "2c680ea416ddde788df7b68ef08d53a7565264a7224f6b04ba592fdbaa61b27c",
|
| 31 |
+
"buckets.py": "ff2261663941716c9b6884bb11a9cbaa75d660d6c41061d03c9ce0a0c473656a",
|
| 32 |
+
"fetch_stock.py": "cfb7629e2b6e0f3d847b2accf3b9ff56394d73740c5c31258e67ffca93f7b65b",
|
| 33 |
+
"source-manifest.json": "1cb8409645fbb2187f61781193a7fd89c53af34b0c2cd9d7d081715b674ce071",
|
| 34 |
+
"provenance.py": "ab05275c8da35cd35847e14fac38c31aa3142adb2cfa0f351f3fbbebfd693330",
|
| 35 |
+
"convert.py": "432a26fb6bea8e7f943a783592c3f6c8bdecf56bce4d78c465d3f203c05ea5ca",
|
| 36 |
+
"validate.swift": "49c2540dcf1df164a259b820cf09f5adcfc70314984f1a2a8fe7c8b09fc32cad",
|
| 37 |
+
"requirements.lock": "448293cf8031689a3a57035f0620e375b6eb18f684b621ef35df556b51b51efd",
|
| 38 |
+
"NOTICE": "f37332d719ec2d4c5f93b1a7ce41c42017a1d7666f533f92d51b08d78f28b4bb",
|
| 39 |
+
"fixtures/SHA256SUMS": "6ff7b41f33e878630ad7fbab24ae2eb0e8a888b120aca1ca4eb62be1b92945c6",
|
| 40 |
+
"fixtures/tokens.json.gz": "3319a38f4dafccde2ed4c0eec5d3445e7b25716c0befd59f0332e6eefd6a5cb1",
|
| 41 |
+
"upstream/modeling_embedding_gemma2.py": "132d8714852fa8f0c376af797229e7b48fe94e0cf6cae6f6640681e934062923",
|
| 42 |
+
"upstream/transformers-LICENSE": "77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049",
|
| 43 |
+
"upstream/qvac/LICENSE": "94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d",
|
| 44 |
+
"upstream/qvac/README.md": "b87b9d24bb4f27cf644022950d7070930b9fae625d1563cfff3d2838f494828a",
|
| 45 |
+
"upstream/qvac/export_coreml.py": "5069938b448ae1469edea758140f4710883c1317b1f889778e24e57d07f0d638",
|
| 46 |
+
"upstream/qvac/requirements.txt": "b33c80ea0f097c533acb68b9d310d795cce7f262acae78ffd70a07fa71d029b9"
|
| 47 |
+
}
|
| 48 |
+
}
|
conversion/upstream/modeling_embedding_gemma2.py
ADDED
|
@@ -0,0 +1,933 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/embedding_gemma2/modular_embedding_gemma2.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_embedding_gemma2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
from collections.abc import Callable
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from ... import initialization as init
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...configuration_utils import PreTrainedConfig
|
| 29 |
+
from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
|
| 30 |
+
from ...masking_utils import create_bidirectional_mask, create_bidirectional_sliding_window_mask
|
| 31 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 32 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 33 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 34 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 35 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import (
|
| 38 |
+
TransformersKwargs,
|
| 39 |
+
auto_docstring,
|
| 40 |
+
can_return_tuple,
|
| 41 |
+
torch_compilable_check,
|
| 42 |
+
)
|
| 43 |
+
from ...utils.generic import merge_with_config_defaults
|
| 44 |
+
from ...utils.output_capturing import capture_outputs
|
| 45 |
+
from ..auto import AutoModel
|
| 46 |
+
from .configuration_embedding_gemma2 import EmbeddingGemma2Config, EmbeddingGemma2TextConfig
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class EmbeddingGemma2RMSNorm(nn.Module):
|
| 50 |
+
def __init__(self, dim: int, eps: float = 1e-6, with_scale: bool = True):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.eps = eps
|
| 53 |
+
self.with_scale = with_scale
|
| 54 |
+
|
| 55 |
+
if self.with_scale:
|
| 56 |
+
self.weight = nn.Parameter(torch.ones(dim), requires_grad=True)
|
| 57 |
+
|
| 58 |
+
def _norm(self, hidden_states: torch.Tensor):
|
| 59 |
+
mean_squared = hidden_states.pow(2).mean(-1, keepdim=True) + self.eps
|
| 60 |
+
# Use torch.pow() (over torch.sqrt() or torch.rsqrt()) to address compiler differences between Torch and JAX
|
| 61 |
+
return hidden_states * torch.pow(mean_squared, -0.5)
|
| 62 |
+
|
| 63 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 64 |
+
normed_output = self._norm(hidden_states.float())
|
| 65 |
+
if self.with_scale:
|
| 66 |
+
normed_output = normed_output * self.weight.float()
|
| 67 |
+
return normed_output.type_as(hidden_states)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class EmbeddingGemma2RotaryEmbedding(nn.Module):
|
| 71 |
+
def __init__(self, config: EmbeddingGemma2TextConfig, device=None):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 74 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 75 |
+
|
| 76 |
+
self.config = config
|
| 77 |
+
self.layer_types = sorted(set(config.layer_types))
|
| 78 |
+
self.rope_init_fns: dict[str, Callable[..., tuple[torch.Tensor, float]]] = {}
|
| 79 |
+
self.rope_type: dict[str, str] = {}
|
| 80 |
+
|
| 81 |
+
for layer_type in self.layer_types:
|
| 82 |
+
rope_params = self.config.rope_parameters[layer_type]
|
| 83 |
+
if rope_params is None:
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
if (rope_type := rope_params["rope_type"]) != "default":
|
| 87 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
|
| 88 |
+
else:
|
| 89 |
+
rope_init_fn = self.compute_default_rope_parameters
|
| 90 |
+
|
| 91 |
+
self.rope_init_fns[layer_type] = rope_init_fn
|
| 92 |
+
self.rope_type[layer_type] = rope_type
|
| 93 |
+
|
| 94 |
+
# `inv_freq` depends on the head dim, which varies by layer type, so initialise
|
| 95 |
+
# from a config resolved for this layer type rather than the global one.
|
| 96 |
+
rope_config = config.per_layer_config[layer_type]
|
| 97 |
+
curr_inv_freq, curr_attention_scaling = rope_init_fn(rope_config, device, layer_type=layer_type)
|
| 98 |
+
setattr(self, f"{layer_type}_inv_freq", nn.Buffer(curr_inv_freq, persistent=False))
|
| 99 |
+
setattr(self, f"{layer_type}_original_inv_freq", nn.Buffer(curr_inv_freq.clone(), persistent=False))
|
| 100 |
+
setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def compute_default_rope_parameters(
|
| 104 |
+
config: EmbeddingGemma2TextConfig, device=None, layer_type: str | None = None, **kwargs
|
| 105 |
+
) -> tuple[torch.Tensor, float]:
|
| 106 |
+
"""
|
| 107 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 108 |
+
Args:
|
| 109 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 110 |
+
The model configuration.
|
| 111 |
+
layer_type (`str`):
|
| 112 |
+
The current layer type if the model has different RoPE parameters per type.
|
| 113 |
+
Should not be used unless `config.layer_types is not None`
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 117 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 118 |
+
"""
|
| 119 |
+
# For backward compatibility standardize the `rope_parameters_dict` if it uses old format
|
| 120 |
+
base = config.rope_parameters[layer_type]["rope_theta"]
|
| 121 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 122 |
+
|
| 123 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 124 |
+
# Compute the inverse frequencies
|
| 125 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 126 |
+
return inv_freq.to(device), attention_factor
|
| 127 |
+
|
| 128 |
+
@torch.no_grad()
|
| 129 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 130 |
+
def forward(self, x, position_ids, layer_type):
|
| 131 |
+
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
| 132 |
+
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
|
| 133 |
+
|
| 134 |
+
freqs = position_ids[..., None].float() * inv_freq.to(device=x.device, dtype=torch.float)
|
| 135 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 136 |
+
cos = emb.cos() * attention_scaling
|
| 137 |
+
sin = emb.sin() * attention_scaling
|
| 138 |
+
|
| 139 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class EmbeddingGemma2TextScaledWordEmbedding(nn.Embedding):
|
| 143 |
+
"""
|
| 144 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
|
| 148 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 149 |
+
self.scalar_embed_scale = embed_scale
|
| 150 |
+
self.embed_scale = nn.Buffer(torch.tensor(embed_scale), persistent=False)
|
| 151 |
+
|
| 152 |
+
def forward(self, input_ids: torch.Tensor):
|
| 153 |
+
return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class EmbeddingGemma2MLP(nn.Module):
|
| 157 |
+
def __init__(self, config: EmbeddingGemma2TextConfig):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.config = config
|
| 160 |
+
self.hidden_size = config.hidden_size
|
| 161 |
+
self.intermediate_size = config.intermediate_size
|
| 162 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 163 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 164 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 165 |
+
self.act_fn = ACT2FN[config.hidden_activation]
|
| 166 |
+
|
| 167 |
+
def forward(self, x):
|
| 168 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 169 |
+
return down_proj
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class EmbeddingGemma2TextPLE(nn.Module):
|
| 173 |
+
"""Produces the per-layer embeddings (PLE) that every decoder layer is gated with.
|
| 174 |
+
|
| 175 |
+
EmbeddingGemma 2 uses *projection-only* PLE: the signal is derived from `inputs_embeds` alone,
|
| 176 |
+
with no token-identity lookup and no blending scale.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def __init__(self, config: EmbeddingGemma2TextConfig):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 182 |
+
self.hidden_size_per_layer_input = config.hidden_size_per_layer_input
|
| 183 |
+
self.per_layer_model_projection = nn.Linear(
|
| 184 |
+
config.hidden_size,
|
| 185 |
+
config.num_hidden_layers * config.hidden_size_per_layer_input,
|
| 186 |
+
bias=False,
|
| 187 |
+
)
|
| 188 |
+
self.per_layer_model_projection_scale = config.hidden_size**-0.5
|
| 189 |
+
self.per_layer_projection_norm = EmbeddingGemma2RMSNorm(
|
| 190 |
+
config.hidden_size_per_layer_input, eps=config.rms_norm_eps
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def forward(self, inputs_embeds: torch.Tensor) -> torch.Tensor:
|
| 194 |
+
per_layer_projection = self.per_layer_model_projection(inputs_embeds) * self.per_layer_model_projection_scale
|
| 195 |
+
per_layer_projection = per_layer_projection.reshape(
|
| 196 |
+
*inputs_embeds.shape[:-1],
|
| 197 |
+
self.num_hidden_layers,
|
| 198 |
+
self.hidden_size_per_layer_input,
|
| 199 |
+
)
|
| 200 |
+
return self.per_layer_projection_norm(per_layer_projection)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class EmbeddingGemma2TextPLEBlock(nn.Module):
|
| 204 |
+
"""Mixes one layer's slice of the per-layer embeddings into the residual stream.
|
| 205 |
+
|
| 206 |
+
The third residual sub-block of a decoder layer, after attention and the MLP. The defining
|
| 207 |
+
operation is the elementwise gate against `per_layer_input`; the two linears are a bottleneck
|
| 208 |
+
down to `hidden_size_per_layer_input` and back.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def __init__(self, config: EmbeddingGemma2TextConfig):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.hidden_size = config.hidden_size
|
| 214 |
+
self.hidden_size_per_layer_input = config.hidden_size_per_layer_input
|
| 215 |
+
self.act_fn = ACT2FN[config.hidden_activation]
|
| 216 |
+
self.per_layer_input_gate = nn.Linear(self.hidden_size, self.hidden_size_per_layer_input, bias=False)
|
| 217 |
+
self.per_layer_projection = nn.Linear(self.hidden_size_per_layer_input, self.hidden_size, bias=False)
|
| 218 |
+
self.post_per_layer_input_norm = EmbeddingGemma2RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
| 219 |
+
|
| 220 |
+
def forward(self, hidden_states: torch.Tensor, per_layer_input: torch.Tensor) -> torch.Tensor:
|
| 221 |
+
residual = hidden_states
|
| 222 |
+
hidden_states = self.per_layer_input_gate(hidden_states)
|
| 223 |
+
hidden_states = self.act_fn(hidden_states)
|
| 224 |
+
hidden_states = hidden_states * per_layer_input
|
| 225 |
+
hidden_states = self.per_layer_projection(hidden_states)
|
| 226 |
+
hidden_states = self.post_per_layer_input_norm(hidden_states)
|
| 227 |
+
return residual + hidden_states
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def rotate_half(x):
|
| 231 |
+
"""Rotates half the hidden dims of the input."""
|
| 232 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 233 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 234 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@use_kernel_forward_from_hub("rotary_pos_emb")
|
| 238 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 239 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
q (`torch.Tensor`): The query tensor.
|
| 243 |
+
k (`torch.Tensor`): The key tensor.
|
| 244 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 245 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 246 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 247 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 248 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 249 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 250 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 251 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 252 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 253 |
+
Returns:
|
| 254 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 255 |
+
"""
|
| 256 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 257 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 258 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 259 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 260 |
+
return q_embed, k_embed
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 264 |
+
"""
|
| 265 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 266 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 267 |
+
"""
|
| 268 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 269 |
+
if n_rep == 1:
|
| 270 |
+
return hidden_states
|
| 271 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 272 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def eager_attention_forward(
|
| 276 |
+
module: nn.Module,
|
| 277 |
+
query: torch.Tensor,
|
| 278 |
+
key: torch.Tensor,
|
| 279 |
+
value: torch.Tensor,
|
| 280 |
+
attention_mask: torch.Tensor | None,
|
| 281 |
+
dropout: float | int = 0.0,
|
| 282 |
+
scaling: float | None = None,
|
| 283 |
+
softcap: float | None = None,
|
| 284 |
+
**kwargs,
|
| 285 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 286 |
+
if scaling is None:
|
| 287 |
+
scaling = module.head_dim**-0.5
|
| 288 |
+
|
| 289 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 290 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 291 |
+
|
| 292 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 293 |
+
|
| 294 |
+
if softcap is not None:
|
| 295 |
+
attn_weights = attn_weights / softcap
|
| 296 |
+
attn_weights = torch.tanh(attn_weights)
|
| 297 |
+
attn_weights = attn_weights * softcap
|
| 298 |
+
if attention_mask is not None:
|
| 299 |
+
attn_weights = attn_weights + attention_mask
|
| 300 |
+
|
| 301 |
+
# upcast attention to fp32
|
| 302 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 303 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 304 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 305 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 306 |
+
return attn_output, attn_weights
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 310 |
+
class EmbeddingGemma2Attention(nn.Module):
|
| 311 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper.
|
| 312 |
+
|
| 313 |
+
EmbeddingGemma 2 is an encoder: attention is bidirectional on every layer and no key-value
|
| 314 |
+
state is carried between calls.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
def __init__(self, config: EmbeddingGemma2TextConfig, layer_idx: int):
|
| 318 |
+
super().__init__()
|
| 319 |
+
self.config = config
|
| 320 |
+
self.layer_idx = layer_idx
|
| 321 |
+
# +1 is needed because flash attention sets inclusive boundaries (see modeling_flash_attention_utils.py)
|
| 322 |
+
self.sliding_window = (
|
| 323 |
+
config.sliding_window + 1 if config.layer_types[layer_idx] == "sliding_attention" else None
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
layer_config = config.per_layer_config[layer_idx]
|
| 327 |
+
self.head_dim = layer_config.head_dim
|
| 328 |
+
self.num_key_value_groups = config.num_attention_heads // layer_config.num_key_value_heads
|
| 329 |
+
self.scaling = 1.0
|
| 330 |
+
self.attention_dropout = config.attention_dropout
|
| 331 |
+
self.is_causal = False
|
| 332 |
+
|
| 333 |
+
self.q_proj = nn.Linear(
|
| 334 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 335 |
+
)
|
| 336 |
+
self.k_proj = nn.Linear(
|
| 337 |
+
config.hidden_size, layer_config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 338 |
+
)
|
| 339 |
+
self.v_proj = nn.Linear(
|
| 340 |
+
config.hidden_size, layer_config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 341 |
+
)
|
| 342 |
+
self.o_proj = nn.Linear(
|
| 343 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
self.q_norm = EmbeddingGemma2RMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
|
| 347 |
+
self.k_norm = EmbeddingGemma2RMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
|
| 348 |
+
self.v_norm = EmbeddingGemma2RMSNorm(dim=self.head_dim, eps=config.rms_norm_eps, with_scale=False)
|
| 349 |
+
|
| 350 |
+
def forward(
|
| 351 |
+
self,
|
| 352 |
+
hidden_states: torch.Tensor,
|
| 353 |
+
attention_mask: torch.Tensor | None = None,
|
| 354 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 355 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 356 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 357 |
+
input_shape = hidden_states.shape[:-1]
|
| 358 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 359 |
+
|
| 360 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 361 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 362 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 363 |
+
|
| 364 |
+
query_states = self.q_norm(query_states)
|
| 365 |
+
key_states = self.k_norm(key_states)
|
| 366 |
+
value_states = self.v_norm(value_states)
|
| 367 |
+
|
| 368 |
+
cos, sin = position_embeddings
|
| 369 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 370 |
+
|
| 371 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 372 |
+
self.config._attn_implementation, eager_attention_forward
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
attn_output, attn_weights = attention_interface(
|
| 376 |
+
self,
|
| 377 |
+
query_states,
|
| 378 |
+
key_states,
|
| 379 |
+
value_states,
|
| 380 |
+
attention_mask,
|
| 381 |
+
dropout=self.attention_dropout if self.training else 0.0,
|
| 382 |
+
scaling=self.scaling,
|
| 383 |
+
sliding_window=self.sliding_window,
|
| 384 |
+
**kwargs,
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 388 |
+
attn_output = self.o_proj(attn_output)
|
| 389 |
+
return attn_output, attn_weights
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class EmbeddingGemma2EncoderLayer(GradientCheckpointingLayer):
|
| 393 |
+
"""A single transformer block. Named an *encoder* layer because attention is bidirectional."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, config: EmbeddingGemma2TextConfig, layer_idx: int):
|
| 396 |
+
super().__init__()
|
| 397 |
+
self.config = config
|
| 398 |
+
self.hidden_size = config.hidden_size
|
| 399 |
+
self.layer_idx = layer_idx
|
| 400 |
+
self.self_attn = EmbeddingGemma2Attention(config=config, layer_idx=layer_idx)
|
| 401 |
+
self.mlp = EmbeddingGemma2MLP(config)
|
| 402 |
+
self.input_layernorm = EmbeddingGemma2RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
| 403 |
+
self.post_attention_layernorm = EmbeddingGemma2RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
| 404 |
+
self.pre_feedforward_layernorm = EmbeddingGemma2RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
| 405 |
+
self.post_feedforward_layernorm = EmbeddingGemma2RMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
| 406 |
+
self.layer_scalar = nn.Buffer(torch.ones(1))
|
| 407 |
+
self.ple_block = EmbeddingGemma2TextPLEBlock(config)
|
| 408 |
+
|
| 409 |
+
def forward(
|
| 410 |
+
self,
|
| 411 |
+
hidden_states: torch.Tensor,
|
| 412 |
+
per_layer_input: torch.Tensor,
|
| 413 |
+
attention_mask: torch.Tensor | None = None,
|
| 414 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 415 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 416 |
+
) -> torch.Tensor:
|
| 417 |
+
residual = hidden_states
|
| 418 |
+
|
| 419 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 420 |
+
hidden_states, _ = self.self_attn(
|
| 421 |
+
hidden_states=hidden_states,
|
| 422 |
+
attention_mask=attention_mask,
|
| 423 |
+
position_embeddings=position_embeddings,
|
| 424 |
+
**kwargs,
|
| 425 |
+
)
|
| 426 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 427 |
+
hidden_states = residual + hidden_states
|
| 428 |
+
|
| 429 |
+
residual = hidden_states
|
| 430 |
+
hidden_states = self.pre_feedforward_layernorm(hidden_states)
|
| 431 |
+
hidden_states = self.mlp(hidden_states)
|
| 432 |
+
hidden_states = self.post_feedforward_layernorm(hidden_states)
|
| 433 |
+
hidden_states = residual + hidden_states
|
| 434 |
+
|
| 435 |
+
hidden_states = self.ple_block(hidden_states, per_layer_input)
|
| 436 |
+
|
| 437 |
+
hidden_states *= self.layer_scalar
|
| 438 |
+
return hidden_states
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
@auto_docstring
|
| 442 |
+
class EmbeddingGemma2PreTrainedModel(PreTrainedModel):
|
| 443 |
+
config: EmbeddingGemma2Config
|
| 444 |
+
base_model_prefix = "model"
|
| 445 |
+
supports_gradient_checkpointing = True
|
| 446 |
+
_no_split_modules = ["EmbeddingGemma2EncoderLayer"]
|
| 447 |
+
_supports_flash_attn = True
|
| 448 |
+
_supports_sdpa = True
|
| 449 |
+
_supports_flex_attn = True
|
| 450 |
+
|
| 451 |
+
_can_compile_fullgraph = True
|
| 452 |
+
_supports_attention_backend = True
|
| 453 |
+
_can_record_outputs = None # override
|
| 454 |
+
input_modalities = ("image", "text", "video", "audio")
|
| 455 |
+
|
| 456 |
+
@torch.no_grad()
|
| 457 |
+
def _init_weights(self, module):
|
| 458 |
+
super()._init_weights(module)
|
| 459 |
+
if isinstance(module, EmbeddingGemma2RotaryEmbedding):
|
| 460 |
+
for layer_type, rope_init_fn in module.rope_init_fns.items():
|
| 461 |
+
rope_config = module.config.per_layer_config[layer_type]
|
| 462 |
+
curr_inv_freq, _ = rope_init_fn(rope_config, layer_type=layer_type)
|
| 463 |
+
init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
|
| 464 |
+
init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
|
| 465 |
+
elif isinstance(module, EmbeddingGemma2TextScaledWordEmbedding):
|
| 466 |
+
init.constant_(module.embed_scale, module.scalar_embed_scale)
|
| 467 |
+
elif isinstance(module, EmbeddingGemma2EncoderLayer):
|
| 468 |
+
init.ones_(module.layer_scalar)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@auto_docstring(
|
| 472 |
+
custom_intro="""
|
| 473 |
+
The EmbeddingGemma 2 text backbone. It owns the `embedding_projection` that maps the final hidden states
|
| 474 |
+
down to `config.embedding_dim`, so that the composite model needs no `forward` override.
|
| 475 |
+
"""
|
| 476 |
+
)
|
| 477 |
+
class EmbeddingGemma2TextModel(EmbeddingGemma2PreTrainedModel):
|
| 478 |
+
config: EmbeddingGemma2TextConfig
|
| 479 |
+
input_modalities = ("text",)
|
| 480 |
+
_can_record_outputs = {
|
| 481 |
+
"hidden_states": EmbeddingGemma2EncoderLayer,
|
| 482 |
+
"attentions": EmbeddingGemma2Attention,
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
def __init__(self, config: EmbeddingGemma2TextConfig):
|
| 486 |
+
super().__init__(config)
|
| 487 |
+
self.padding_idx = config.pad_token_id
|
| 488 |
+
self.vocab_size = config.vocab_size
|
| 489 |
+
|
| 490 |
+
# bfloat16 rounding turns sqrt(512)=22.6274 into 22.625; see https://github.com/huggingface/transformers/pull/29402
|
| 491 |
+
self.embed_tokens = EmbeddingGemma2TextScaledWordEmbedding(
|
| 492 |
+
config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
|
| 493 |
+
)
|
| 494 |
+
self.layers = nn.ModuleList(
|
| 495 |
+
[EmbeddingGemma2EncoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 496 |
+
)
|
| 497 |
+
self.norm = EmbeddingGemma2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 498 |
+
self.rotary_emb = EmbeddingGemma2RotaryEmbedding(config)
|
| 499 |
+
self.gradient_checkpointing = False
|
| 500 |
+
|
| 501 |
+
self.unique_layer_types = set(self.config.layer_types)
|
| 502 |
+
self.ple = EmbeddingGemma2TextPLE(config)
|
| 503 |
+
|
| 504 |
+
# Projecting per token is equivalent to projecting after mean pooling
|
| 505 |
+
self.embedding_projection = nn.Linear(config.hidden_size, config.embedding_dim, bias=False)
|
| 506 |
+
|
| 507 |
+
# Initialize weights and apply final processing
|
| 508 |
+
self.post_init()
|
| 509 |
+
|
| 510 |
+
@merge_with_config_defaults
|
| 511 |
+
@capture_outputs
|
| 512 |
+
@auto_docstring
|
| 513 |
+
def forward(
|
| 514 |
+
self,
|
| 515 |
+
input_ids: torch.LongTensor | None = None,
|
| 516 |
+
attention_mask: torch.Tensor | None = None,
|
| 517 |
+
position_ids: torch.LongTensor | None = None,
|
| 518 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 519 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 520 |
+
) -> BaseModelOutput:
|
| 521 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 522 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 523 |
+
|
| 524 |
+
if input_ids is not None:
|
| 525 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 526 |
+
|
| 527 |
+
per_layer_inputs = self.ple(inputs_embeds)
|
| 528 |
+
|
| 529 |
+
if position_ids is None:
|
| 530 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 531 |
+
|
| 532 |
+
# It may already have been prepared as a mapping by the caller
|
| 533 |
+
if not isinstance(attention_mask_mapping := attention_mask, dict):
|
| 534 |
+
mask_kwargs = {
|
| 535 |
+
"config": self.config,
|
| 536 |
+
"inputs_embeds": inputs_embeds,
|
| 537 |
+
"attention_mask": attention_mask,
|
| 538 |
+
}
|
| 539 |
+
attention_mask_mapping = {
|
| 540 |
+
"full_attention": create_bidirectional_mask(**mask_kwargs),
|
| 541 |
+
"sliding_attention": create_bidirectional_sliding_window_mask(**mask_kwargs),
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
# embed positions
|
| 545 |
+
hidden_states = inputs_embeds
|
| 546 |
+
position_embeddings = {}
|
| 547 |
+
for layer_type in self.unique_layer_types:
|
| 548 |
+
position_embeddings[layer_type] = self.rotary_emb(hidden_states, position_ids, layer_type)
|
| 549 |
+
|
| 550 |
+
for i, encoder_layer in enumerate(self.layers):
|
| 551 |
+
hidden_states = encoder_layer(
|
| 552 |
+
hidden_states,
|
| 553 |
+
per_layer_inputs[:, :, i, :],
|
| 554 |
+
attention_mask=attention_mask_mapping[self.config.layer_types[i]],
|
| 555 |
+
position_embeddings=position_embeddings[self.config.layer_types[i]],
|
| 556 |
+
**kwargs,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
hidden_states = self.norm(hidden_states)
|
| 560 |
+
hidden_states = self.embedding_projection(hidden_states)
|
| 561 |
+
|
| 562 |
+
return BaseModelOutput(last_hidden_state=hidden_states)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
class EmbeddingGemma2MultimodalEmbedder(nn.Module):
|
| 566 |
+
"""Embeds token ids or soft tokens for multimodal content into language model space."""
|
| 567 |
+
|
| 568 |
+
def __init__(
|
| 569 |
+
self,
|
| 570 |
+
multimodal_config: PreTrainedConfig,
|
| 571 |
+
text_config: EmbeddingGemma2TextConfig,
|
| 572 |
+
):
|
| 573 |
+
super().__init__()
|
| 574 |
+
|
| 575 |
+
self.multimodal_hidden_size = getattr(multimodal_config, "output_proj_dims", multimodal_config.hidden_size)
|
| 576 |
+
self.eps = multimodal_config.rms_norm_eps
|
| 577 |
+
self.text_hidden_size = text_config.hidden_size
|
| 578 |
+
self.embedding_projection = nn.Linear(self.multimodal_hidden_size, self.text_hidden_size, bias=False)
|
| 579 |
+
self.embedding_pre_projection_norm = EmbeddingGemma2RMSNorm(
|
| 580 |
+
self.multimodal_hidden_size, eps=self.eps, with_scale=False
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
def forward(self, inputs_embeds: torch.Tensor) -> torch.Tensor:
|
| 584 |
+
"""Embeds token ids or soft tokens for multimodal content into language model space.
|
| 585 |
+
Args:
|
| 586 |
+
inputs_embeds: A torch.Tensor containing the soft tokens to embed.
|
| 587 |
+
Returns:
|
| 588 |
+
A torch.Tensor of embeddings with shape `[batch_size, seq_len, self.config.text_config.hidden_size]`.
|
| 589 |
+
"""
|
| 590 |
+
embs_normed = self.embedding_pre_projection_norm(inputs_embeds)
|
| 591 |
+
return self.embedding_projection(embs_normed)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
@auto_docstring
|
| 595 |
+
@dataclass
|
| 596 |
+
class EmbeddingGemma2AudioModelOutput(BaseModelOutputWithPooling):
|
| 597 |
+
r"""
|
| 598 |
+
attention_mask (`torch.BoolTensor`, *optional*):
|
| 599 |
+
A torch.BoolTensor of shape `(batch_size, num_frames)`. True for valid positions, False for padding.
|
| 600 |
+
"""
|
| 601 |
+
|
| 602 |
+
attention_mask: torch.BoolTensor | None = None
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
@auto_docstring(
|
| 606 |
+
custom_intro="""
|
| 607 |
+
Base class for EmbeddingGemma2 outputs, with hidden states and attentions.
|
| 608 |
+
"""
|
| 609 |
+
)
|
| 610 |
+
@dataclass
|
| 611 |
+
class EmbeddingGemma2ModelOutput(BaseModelOutput):
|
| 612 |
+
r"""
|
| 613 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 614 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 615 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 616 |
+
audio_hidden_states (`torch.FloatTensor`, *optional*):
|
| 617 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 618 |
+
audio_hidden_states of the model produced by the audio encoder and after projecting the last hidden state.
|
| 619 |
+
"""
|
| 620 |
+
|
| 621 |
+
image_hidden_states: torch.FloatTensor | None = None
|
| 622 |
+
|
| 623 |
+
audio_hidden_states: torch.FloatTensor | None = None
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@auto_docstring(
|
| 627 |
+
custom_intro="""
|
| 628 |
+
The EmbeddingGemma 2 model: a vision backbone, an audio backbone and a text backbone whose final hidden
|
| 629 |
+
states are projected to `config.text_config.embedding_dim`. Intended to be wrapped by SentenceTransformers'
|
| 630 |
+
mean pooling and normalization.
|
| 631 |
+
"""
|
| 632 |
+
)
|
| 633 |
+
class EmbeddingGemma2Model(EmbeddingGemma2PreTrainedModel):
|
| 634 |
+
# we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
|
| 635 |
+
accepts_loss_kwargs = False
|
| 636 |
+
config: EmbeddingGemma2Config
|
| 637 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 638 |
+
r"(^|\.)vision_tower\.",
|
| 639 |
+
r"(^|\.)embed_vision\.",
|
| 640 |
+
r"(^|\.)audio_tower\.",
|
| 641 |
+
r"(^|\.)embed_audio\.",
|
| 642 |
+
]
|
| 643 |
+
|
| 644 |
+
def __init__(self, config: EmbeddingGemma2Config):
|
| 645 |
+
super().__init__(config)
|
| 646 |
+
self.vision_tower = AutoModel.from_config(config.vision_config) if config.vision_config is not None else None
|
| 647 |
+
self.vocab_size = config.text_config.vocab_size
|
| 648 |
+
|
| 649 |
+
language_model = AutoModel.from_config(config=config.text_config)
|
| 650 |
+
self.language_model = language_model
|
| 651 |
+
self.audio_tower = AutoModel.from_config(config.audio_config) if config.audio_config is not None else None
|
| 652 |
+
self.embed_vision = (
|
| 653 |
+
EmbeddingGemma2MultimodalEmbedder(config.vision_config, config.text_config)
|
| 654 |
+
if config.vision_config is not None
|
| 655 |
+
else None
|
| 656 |
+
)
|
| 657 |
+
self.embed_audio = (
|
| 658 |
+
EmbeddingGemma2MultimodalEmbedder(config.audio_config, config.text_config)
|
| 659 |
+
if config.audio_config is not None
|
| 660 |
+
else None
|
| 661 |
+
)
|
| 662 |
+
self.post_init()
|
| 663 |
+
|
| 664 |
+
@can_return_tuple
|
| 665 |
+
@auto_docstring(custom_intro="Projects the last hidden state from the vision model into language model space.")
|
| 666 |
+
def get_image_features(
|
| 667 |
+
self,
|
| 668 |
+
pixel_values: torch.FloatTensor,
|
| 669 |
+
image_position_ids: torch.LongTensor | None = None,
|
| 670 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 671 |
+
) -> BaseModelOutputWithPooling:
|
| 672 |
+
r"""
|
| 673 |
+
image_position_ids (`torch.LongTensor` of shape `(batch_size, max_patches, 2)`, *optional*):
|
| 674 |
+
The patch positions as (x, y) coordinates in the image. Padding patches are indicated by (-1, -1).
|
| 675 |
+
"""
|
| 676 |
+
if self.vision_tower is None:
|
| 677 |
+
raise ValueError(
|
| 678 |
+
"Image features were requested, but the model was initialized without a vision_config. "
|
| 679 |
+
"Cannot process images without a vision tower and vision embedder."
|
| 680 |
+
)
|
| 681 |
+
vision_outputs = self.vision_tower(
|
| 682 |
+
pixel_values=pixel_values,
|
| 683 |
+
pixel_position_ids=image_position_ids,
|
| 684 |
+
**kwargs,
|
| 685 |
+
)
|
| 686 |
+
last_hidden_state = vision_outputs.last_hidden_state
|
| 687 |
+
pooler_output = self.embed_vision(inputs_embeds=last_hidden_state)
|
| 688 |
+
|
| 689 |
+
output_length = pixel_values.shape[-2] // (self.config.vision_config.pooling_kernel_size**2)
|
| 690 |
+
k_squared = int((image_position_ids.shape[1] // output_length) ** 0.5) ** 2
|
| 691 |
+
non_pad_mask = (image_position_ids != -1).all(dim=-1)
|
| 692 |
+
split_sizes = (non_pad_mask.sum(dim=-1) // k_squared).tolist()
|
| 693 |
+
vision_outputs.pooler_output = torch.split(pooler_output, split_sizes)
|
| 694 |
+
return vision_outputs
|
| 695 |
+
|
| 696 |
+
def get_placeholder_mask(
|
| 697 |
+
self,
|
| 698 |
+
input_ids: torch.LongTensor | None = None,
|
| 699 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 700 |
+
) -> tuple[torch.BoolTensor, torch.BoolTensor, torch.BoolTensor]:
|
| 701 |
+
"""
|
| 702 |
+
Obtains mask for multimodal placeholders (replaced by soft tokens) and hard text tokens.
|
| 703 |
+
|
| 704 |
+
Masks will be obtained from `mm_token_type_ids`, `input_ids`, or `inputs_embeds` as available and in that
|
| 705 |
+
precedence order. If passing `input_ids` or `inputs_embeds`, the image mask will be derived using
|
| 706 |
+
`config.image_token_id`. Same goes for audio and video masks
|
| 707 |
+
|
| 708 |
+
Args:
|
| 709 |
+
input_ids: A tensor containing the hard token IDs from the text tokenizer.
|
| 710 |
+
inputs_embeds: A tensor containing the embeddings for all hard text tokens.
|
| 711 |
+
|
| 712 |
+
Returns:
|
| 713 |
+
image_mask, video_mask, audio_mask
|
| 714 |
+
"""
|
| 715 |
+
if input_ids is not None:
|
| 716 |
+
special_image_mask = input_ids == self.config.image_token_id
|
| 717 |
+
special_video_mask = input_ids == self.config.video_token_id
|
| 718 |
+
special_audio_mask = input_ids == self.config.audio_token_id
|
| 719 |
+
else:
|
| 720 |
+
special_image_mask = (
|
| 721 |
+
inputs_embeds
|
| 722 |
+
== self.get_input_embeddings()(
|
| 723 |
+
torch.full((), self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 724 |
+
)
|
| 725 |
+
).all(-1)
|
| 726 |
+
special_video_mask = (
|
| 727 |
+
inputs_embeds
|
| 728 |
+
== self.get_input_embeddings()(
|
| 729 |
+
torch.full((), self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 730 |
+
)
|
| 731 |
+
).all(-1)
|
| 732 |
+
special_audio_mask = (
|
| 733 |
+
inputs_embeds
|
| 734 |
+
== self.get_input_embeddings()(
|
| 735 |
+
torch.full((), self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
|
| 736 |
+
)
|
| 737 |
+
).all(-1)
|
| 738 |
+
|
| 739 |
+
return special_image_mask, special_video_mask, special_audio_mask
|
| 740 |
+
|
| 741 |
+
@merge_with_config_defaults
|
| 742 |
+
@can_return_tuple
|
| 743 |
+
@auto_docstring
|
| 744 |
+
def forward(
|
| 745 |
+
self,
|
| 746 |
+
input_ids: torch.LongTensor | None = None,
|
| 747 |
+
pixel_values: torch.FloatTensor | None = None,
|
| 748 |
+
pixel_values_videos: torch.FloatTensor | None = None,
|
| 749 |
+
input_features: torch.FloatTensor | None = None,
|
| 750 |
+
attention_mask: torch.Tensor | None = None,
|
| 751 |
+
input_features_mask: torch.Tensor | None = None,
|
| 752 |
+
position_ids: torch.LongTensor | None = None,
|
| 753 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 754 |
+
image_position_ids: torch.LongTensor | None = None,
|
| 755 |
+
video_position_ids: torch.LongTensor | None = None,
|
| 756 |
+
num_frames_per_video: torch.LongTensor | None = None,
|
| 757 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 758 |
+
) -> EmbeddingGemma2ModelOutput:
|
| 759 |
+
r"""
|
| 760 |
+
input_features_mask (`torch.FloatTensor` of shape `(num_images, seq_length)`):
|
| 761 |
+
The attention mask for the input audio.
|
| 762 |
+
image_position_ids (`torch.LongTensor` of shape `(batch_size, max_patches, 2)`, *optional*):
|
| 763 |
+
2D patch position coordinates from the image processor, with `(-1, -1)` indicating padding.
|
| 764 |
+
Passed through to the vision encoder for positional embedding computation.
|
| 765 |
+
video_position_ids (`torch.LongTensor` of shape `(total_num_frames, max_patches, 2)`, *optional*):
|
| 766 |
+
2D patch position coordinates from the video processor, with `(-1, -1)` indicating padding.
|
| 767 |
+
Passed through to the vision encoder for positional embedding computation.
|
| 768 |
+
num_frames_per_video (`torch.LongTensor` of shape `(num_videos,)`, *optional*):
|
| 769 |
+
Number of frames belonging to each video. Required whenever `pixel_values_videos` is passed,
|
| 770 |
+
since the frames of all videos are concatenated along a single axis.
|
| 771 |
+
"""
|
| 772 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 773 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 774 |
+
|
| 775 |
+
image_mask, video_mask, audio_mask = self.get_placeholder_mask(input_ids, inputs_embeds)
|
| 776 |
+
multimodal_mask = image_mask | video_mask | audio_mask
|
| 777 |
+
|
| 778 |
+
# Replace image id with PAD if the image token if OOV, to avoid index-errors
|
| 779 |
+
if inputs_embeds is None:
|
| 780 |
+
llm_input_ids = torch.where(multimodal_mask, self.config.text_config.pad_token_id, input_ids)
|
| 781 |
+
inputs_embeds = self.get_input_embeddings()(llm_input_ids)
|
| 782 |
+
|
| 783 |
+
# Merge text and images
|
| 784 |
+
if pixel_values is not None:
|
| 785 |
+
image_features = self.get_image_features(pixel_values, image_position_ids, return_dict=True).pooler_output
|
| 786 |
+
image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 787 |
+
|
| 788 |
+
# Confirm the number of soft tokens from the vision tower matches the number of slots in the embeddings.
|
| 789 |
+
n_image_tokens = image_mask.sum()
|
| 790 |
+
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 791 |
+
torch_compilable_check(
|
| 792 |
+
inputs_embeds[image_mask].numel() == image_features.numel(),
|
| 793 |
+
f"Image features and image tokens do not match, tokens: {n_image_tokens}, features:"
|
| 794 |
+
f" {image_features.shape[0]}",
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
inputs_embeds = inputs_embeds.masked_scatter(
|
| 798 |
+
image_mask.to(inputs_embeds.device), image_features.to(inputs_embeds.device)
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
if pixel_values_videos is not None:
|
| 802 |
+
video_features = self.get_video_features(
|
| 803 |
+
pixel_values_videos, video_position_ids, num_frames_per_video, return_dict=True
|
| 804 |
+
).pooler_output
|
| 805 |
+
video_features = torch.cat(video_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 806 |
+
|
| 807 |
+
# Confirm the number of soft tokens from the vision tower matches the number of slots in the embeddings.
|
| 808 |
+
n_video_tokens = video_mask.sum()
|
| 809 |
+
video_mask = video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 810 |
+
torch_compilable_check(
|
| 811 |
+
inputs_embeds[video_mask].numel() == video_features.numel(),
|
| 812 |
+
f"Video features and video tokens do not match, tokens: {n_video_tokens}, features:"
|
| 813 |
+
f" {video_features.shape[0]}",
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
inputs_embeds = inputs_embeds.masked_scatter(
|
| 817 |
+
video_mask.to(inputs_embeds.device), video_features.to(inputs_embeds.device)
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
# Merge text and audio
|
| 821 |
+
if input_features is not None and input_features_mask is not None:
|
| 822 |
+
audio_output = self.get_audio_features(input_features, input_features_mask, return_dict=True)
|
| 823 |
+
audio_features = audio_output.pooler_output
|
| 824 |
+
audio_mask_from_encoder = audio_output.attention_mask # True = valid
|
| 825 |
+
|
| 826 |
+
# Keep only real audio soft tokens, mirroring the vision encoder's padding stripping.
|
| 827 |
+
audio_features = audio_features[audio_mask_from_encoder.to(audio_features.device)]
|
| 828 |
+
|
| 829 |
+
n_audio_tokens = audio_mask.sum()
|
| 830 |
+
audio_mask = audio_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 831 |
+
torch_compilable_check(
|
| 832 |
+
inputs_embeds[audio_mask].numel() == audio_features.numel(),
|
| 833 |
+
f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, features:"
|
| 834 |
+
f" {audio_features.shape[0] * audio_features.shape[1]}",
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
inputs_embeds = inputs_embeds.masked_scatter(
|
| 838 |
+
audio_mask.to(inputs_embeds.device), audio_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
outputs = self.language_model(
|
| 842 |
+
attention_mask=attention_mask,
|
| 843 |
+
position_ids=position_ids,
|
| 844 |
+
inputs_embeds=inputs_embeds,
|
| 845 |
+
return_dict=True,
|
| 846 |
+
**kwargs,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
return EmbeddingGemma2ModelOutput(
|
| 850 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 851 |
+
hidden_states=outputs.hidden_states,
|
| 852 |
+
attentions=outputs.attentions,
|
| 853 |
+
image_hidden_states=image_features if pixel_values is not None else None,
|
| 854 |
+
audio_hidden_states=audio_features if input_features is not None else None,
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
@can_return_tuple
|
| 858 |
+
@auto_docstring(custom_intro="Projects the last hidden state from the audio encoder into language model space.")
|
| 859 |
+
def get_audio_features(
|
| 860 |
+
self,
|
| 861 |
+
input_features: torch.Tensor,
|
| 862 |
+
input_features_mask: torch.Tensor,
|
| 863 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 864 |
+
) -> tuple | EmbeddingGemma2AudioModelOutput:
|
| 865 |
+
r"""
|
| 866 |
+
input_features (`torch.FloatTensor` of shape `(num_images, seq_length, num_features)`):
|
| 867 |
+
The tensors corresponding to the input audio.
|
| 868 |
+
input_features_mask (`torch.FloatTensor` of shape `(num_images, seq_length)`):
|
| 869 |
+
The attention mask for the input audio.
|
| 870 |
+
"""
|
| 871 |
+
if self.audio_tower is None:
|
| 872 |
+
raise ValueError(
|
| 873 |
+
"Audio features were requested, but the model was initialized without an audio_config. "
|
| 874 |
+
"Cannot process audio without an audio tower and audio embedder."
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
audio_outputs = self.audio_tower(input_features, input_features_mask, return_dict=True, **kwargs)
|
| 878 |
+
audio_outputs.pooler_output = self.embed_audio(inputs_embeds=audio_outputs.last_hidden_state)
|
| 879 |
+
|
| 880 |
+
return audio_outputs
|
| 881 |
+
|
| 882 |
+
@can_return_tuple
|
| 883 |
+
@auto_docstring(custom_intro="Projects the last hidden state from the vision encoder into language model space.")
|
| 884 |
+
def get_video_features(
|
| 885 |
+
self,
|
| 886 |
+
pixel_values_videos: torch.FloatTensor,
|
| 887 |
+
video_position_ids: torch.LongTensor | None = None,
|
| 888 |
+
num_frames_per_video: torch.LongTensor | None = None,
|
| 889 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 890 |
+
) -> BaseModelOutputWithPooling:
|
| 891 |
+
r"""
|
| 892 |
+
pixel_values_videos (`torch.FloatTensor` of shape `(total_num_frames, max_patches, patch_pixels)`):
|
| 893 |
+
The frames of every video in the batch, concatenated along the frame axis rather than stacked
|
| 894 |
+
on a separate video axis, so that videos of different lengths can be batched together.
|
| 895 |
+
video_position_ids (`torch.LongTensor` of shape `(total_num_frames, max_patches, 2)`, *optional*):
|
| 896 |
+
2D patch position coordinates from the video processor, with `(-1, -1)` indicating padding.
|
| 897 |
+
Passed through to the vision encoder for positional embedding computation.
|
| 898 |
+
num_frames_per_video (`torch.LongTensor` of shape `(num_videos,)`):
|
| 899 |
+
Number of frames belonging to each video, used to split the flat frame sequence back per video.
|
| 900 |
+
"""
|
| 901 |
+
if self.vision_tower is None:
|
| 902 |
+
raise ValueError(
|
| 903 |
+
"Video features were requested, but the model was initialized without a vision_config. "
|
| 904 |
+
"Cannot process video without a vision tower and vision embedder."
|
| 905 |
+
)
|
| 906 |
+
if num_frames_per_video is None:
|
| 907 |
+
raise ValueError(
|
| 908 |
+
"`num_frames_per_video` is required when passing `pixel_values_videos`. The frames of all "
|
| 909 |
+
"videos are concatenated along a single axis, so the per-video frame counts are the only "
|
| 910 |
+
"way to split the result back per video. The video processor returns them."
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
vision_outputs = self.vision_tower(
|
| 914 |
+
pixel_values=pixel_values_videos,
|
| 915 |
+
pixel_position_ids=video_position_ids,
|
| 916 |
+
**kwargs,
|
| 917 |
+
)
|
| 918 |
+
last_hidden_state = vision_outputs.last_hidden_state
|
| 919 |
+
pooler_output = self.embed_vision(inputs_embeds=last_hidden_state)
|
| 920 |
+
|
| 921 |
+
k_squared = self.config.vision_config.pooling_kernel_size**2
|
| 922 |
+
non_pad_mask = (video_position_ids != -1).all(dim=-1) # (total_num_frames, max_patches)
|
| 923 |
+
num_tokens_per_frame = non_pad_mask.sum(dim=-1) // k_squared
|
| 924 |
+
split_sizes = [
|
| 925 |
+
int(video_frames.sum())
|
| 926 |
+
for video_frames in torch.split(num_tokens_per_frame, num_frames_per_video.tolist())
|
| 927 |
+
]
|
| 928 |
+
|
| 929 |
+
vision_outputs.pooler_output = torch.split(pooler_output, split_sizes)
|
| 930 |
+
return vision_outputs
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
__all__ = ["EmbeddingGemma2Model", "EmbeddingGemma2PreTrainedModel", "EmbeddingGemma2TextModel"]
|
conversion/upstream/qvac/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2023-2026 The ggml authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
conversion/upstream/qvac/README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core ML EmbeddingGemma 2 support
|
| 2 |
+
|
| 3 |
+
Optional Core ML acceleration for the existing EmbeddingGemma 2 embedding API, CLI, and server. The runtime is built into `llama`; the exporter, benchmark, and compute-plan tools live in this directory. Requires macOS 15 / iOS 18 and Apple silicon for ANE acceleration.
|
| 4 |
+
|
| 5 |
+
The package already contains the fixed-shape graph and overflow-safe FP16 RMSNorm. The adapter reuses model objects and input buffers, memory maps the original BF16 token table, chooses the smallest fixed function that fits, and packs adjacent short texts into 256 tokens, using the package's eight or sixteen output slots. Attention blocks and positions are independent for each packed text. A single-text bin uses its smaller fixed function. Output order matches input order. Calls on one context are serialized. Set `llama_coreml_embedding_set_max_inflight(ctx, 8)` to pipeline predictions asynchronously on shared models within an encode call; the default is one synchronous prediction at a time. Each pending request owns reusable input buffers. Encode waits for all callbacks before returning, including on error. Separate contexts remain available for independent callers. Core ML selects CPU/ANE placement; selecting CPU + ANE does not prove that every operation runs on ANE.
|
| 6 |
+
|
| 7 |
+
## Build on Apple silicon
|
| 8 |
+
|
| 9 |
+
```sh
|
| 10 |
+
cmake -S . -B build-ane -DCMAKE_BUILD_TYPE=Release -DLLAMA_COREML=ON
|
| 11 |
+
cmake --build build-ane --target llama llama-embedding llama-server llama-coreml-embedding-bench -j 8
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
The option is off by default. Core ML support remains in the installed `llama` library when examples, common utilities, and tools are disabled. Use `llama.h` for the existing API integration or the installed `llama-coreml.h` for the lower-level adapter. Feature-off builds retain the configuration API and report Core ML unavailable.
|
| 15 |
+
|
| 16 |
+
## Existing embedding API, CLI, and server
|
| 17 |
+
|
| 18 |
+
Load a matching GGUF normally, create an embedding context with mean pooling, then configure the sidecar before calling `llama_encode()` or `llama_decode()`:
|
| 19 |
+
|
| 20 |
+
```cpp
|
| 21 |
+
if (!llama_set_coreml_model(ctx, "../embeddinggemma-2-coreml", 8)) {
|
| 22 |
+
// The existing ggml path remains available.
|
| 23 |
+
}
|
| 24 |
+
llama_encode(ctx, batch);
|
| 25 |
+
const float * embedding = llama_get_embeddings_seq(ctx, seq_id);
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
The sidecar must come from the same checkpoint as the GGUF. Returned vectors are raw, mean-pooled embeddings, preserving the existing API's normalization contract. Callers can apply their usual normalization or Matryoshka truncation. Pass a null directory to disable the sidecar; a failed configuration leaves the previous configuration unchanged. `llama_supports_coreml()` reports build-time availability. Context calls retain the usual caller-side synchronization requirements.
|
| 29 |
+
|
| 30 |
+
The CLI and server accept `--coreml-model DIR` (or `LLAMA_ARG_COREML_MODEL`). Set `--coreml-max-inflight N` (or `LLAMA_ARG_COREML_MAX_INFLIGHT`) to 1..8 predictions; the default is one. They retain their existing output formats, tokenization, and `--embd-normalize` behavior:
|
| 31 |
+
|
| 32 |
+
```sh
|
| 33 |
+
build-ane/bin/llama-embedding -m ../embeddinggemma-2-BF16.gguf \
|
| 34 |
+
--coreml-model ../embeddinggemma-2-coreml --pooling mean \
|
| 35 |
+
-p 'title: none | text: Example document' --embd-normalize 2
|
| 36 |
+
build-ane/bin/llama-server -m ../embeddinggemma-2-BF16.gguf \
|
| 37 |
+
--embedding --pooling mean --coreml-model ../embeddinggemma-2-coreml --coreml-max-inflight 8 \
|
| 38 |
+
-np 32 -c 16384 -b 1024 -ub 1024
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
For short-text throughput, tune `-np` together with `-b` and `-ub`. The server default of four parallel sequences often produces only one packed prediction per encode, leaving asynchronous slots idle. Larger parallelism allows multiple predictions to overlap when enough requests are queued; benchmark the memory and latency tradeoff on the target device.
|
| 42 |
+
|
| 43 |
+
Setup rejects non-mean pooling and RoPE/YaRN or attention settings that differ from the sidecar. Compatible batches contain independent token sequences starting at position zero, at most 512 tokens each, with mean pooling. Longer sequences, shared token rows, supplied embeddings, position offsets, adapters, callbacks, and feature extraction use ggml. A prediction failure disables that context's sidecar and retries the batch with ggml. Keep the GGUF weights available for fallback; this optimization does not eliminate their memory use.
|
| 44 |
+
|
| 45 |
+
This integration requires an `embedding_raw` output. Re-export older normalized-only packages with the exporter below. The pinned FluidInference package remains usable through the lower-level normalized adapter; the existing embedding API rejects it and the CLI/server continue with ggml.
|
| 46 |
+
|
| 47 |
+
## Model assets
|
| 48 |
+
|
| 49 |
+
Download from [FluidInference/embeddinggemma-2-coreml](https://huggingface.co/FluidInference/embeddinggemma-2-coreml), revision `3f978ddf92cac9aa07eb2dcf6eb36cf450f3dba4`:
|
| 50 |
+
|
| 51 |
+
- `EmbeddingGemma2Text.mlpackage/` (all files)
|
| 52 |
+
- `embeddings.bf16`
|
| 53 |
+
|
| 54 |
+
Pass their containing directory to `llama_coreml_embedding_load`. The first load compiles the package and copies the result to `EmbeddingGemma2Text.mlmodelc` in that directory. The directory must be writable for this initial step. When replacing the `.mlpackage` or switching checkpoint revisions, stop callers and delete the adjacent `EmbeddingGemma2Text.mlmodelc` before loading again. An existing compiled cache is reused without checking the package; the compatibility probe is not a cache invalidation mechanism. Precompiled assets can instead be supplied in a read-only directory. The integrated API loads and validates all seven functions at setup and compares a short fixed text against ggml with a minimum cosine of 0.998. Setup can take minutes on first use. This numerical probe detects incompatible output but does not prove weight identity; matching checkpoints remain the caller's responsibility. The lower-level normalized adapter still loads functions lazily. Warm the workload before measuring throughput.
|
| 55 |
+
|
| 56 |
+
The token table must have exactly 262144 rows of 512 little-endian BF16 values. It is converted to FP16 and scaled by sqrt(512) during input preparation. This is the original token table, not a GGUF quantized table. Model weights and tokenizer must come from matching checkpoints. The adapter checks file size and model input/output contracts; it does not authenticate downloaded files. Pin revisions and verify checksums when distributing assets.
|
| 57 |
+
|
| 58 |
+
## Export from a local checkpoint
|
| 59 |
+
|
| 60 |
+
`export_coreml.py` converts the text encoder from the original Hugging Face safetensors checkpoint. Each function provides `embedding` (L2-normalized FP16) and `embedding_raw` (unnormalized FP32 mean pooling). It writes `EmbeddingGemma2Text.mlpackage`, the unscaled original `embeddings.bf16`, `tokenizer.json`, `source-config.json`, and an `export.json` manifest with source hashes, tool versions, and function shapes. Audio and vision weights are not loaded. The destination must not exist; conversion failures remove temporary output.
|
| 61 |
+
|
| 62 |
+
Use a separate Python 3.11 environment on an Apple silicon Mac. The requirements pin Core ML Tools 9, its supported PyTorch 2.7 release, and a Transformers revision with EmbeddingGemma 2 support. Do not combine these requirements with the repository's GGUF conversion environment.
|
| 63 |
+
|
| 64 |
+
```sh
|
| 65 |
+
python3.11 -m venv .venv-coreml
|
| 66 |
+
.venv-coreml/bin/python -m pip install -r examples/embedding-coreml/requirements.txt
|
| 67 |
+
|
| 68 |
+
# Accept the source model's access terms and authenticate with Hugging Face first.
|
| 69 |
+
.venv-coreml/bin/hf download google/embeddinggemma-2 \
|
| 70 |
+
--revision 914f7f89142e33e77833254d9c9b90c3cef7303b \
|
| 71 |
+
--include config.json tokenizer.json '*.safetensors' '*.safetensors.index.json' \
|
| 72 |
+
--local-dir ../embeddinggemma-2-hf
|
| 73 |
+
|
| 74 |
+
.venv-coreml/bin/python examples/embedding-coreml/export_coreml.py \
|
| 75 |
+
../embeddinggemma-2-hf ../embeddinggemma-2-coreml --pack-slots 8
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
The exporter also accepts a compatible local fine-tuned checkpoint with the same text architecture. It uses no remote Python code and supports single-file or sharded safetensors. The six single-text functions use lengths 32/48/64/128/256/512; `pack_256` has eight output slots by default. Pass `--pack-slots 16` to export sixteen slots directly. RMSNorm and final L2 normalization rescale before squaring to avoid FP16 overflow. Rotary tables are computed in FP32 before conversion; the packed function looks up positions that restart for each text.
|
| 79 |
+
|
| 80 |
+
Export traces the text encoder on CPU and converts the graphs; it does not execute Core ML predictions or prove Neural Engine placement. Allow substantial memory, time, and temporary disk space for seven intermediate packages. Core ML Tools merges them with shared weights into the final package. This is an independent export, not a byte-identical reproduction of FluidInference's package.
|
| 81 |
+
|
| 82 |
+
Validate a new export on the target Mac before using it: build the benchmark above, convert the same source checkpoint to a BF16 GGUF in the normal GGUF conversion environment, then compare the two paths. Include short texts, lengths crossing every bucket, and enough short texts to fill all packing slots. The benchmark checks cosine agreement and normalization. For raw-output exports, it also verifies the existing encode/decode API, raw vector magnitudes, sequence ID mapping, disabling the sidecar, and ggml fallback. Run the compute-plan tool to inspect anticipated device placement; ANE placement is not guaranteed by export alone.
|
| 83 |
+
|
| 84 |
+
```sh
|
| 85 |
+
# Use the existing GGUF conversion environment, not .venv-coreml.
|
| 86 |
+
python convert_hf_to_gguf.py ../embeddinggemma-2-hf \
|
| 87 |
+
--outtype bf16 --outfile ../embeddinggemma-2-BF16.gguf
|
| 88 |
+
build-ane/bin/llama-coreml-embedding-bench \
|
| 89 |
+
../embeddinggemma-2-BF16.gguf ../embeddinggemma-2-coreml \
|
| 90 |
+
examples/embedding-coreml/benchmark-texts.txt 5 metal 1 32 1024 8
|
| 91 |
+
|
| 92 |
+
# These checks use metadata, temporary files, and synthetic normalization tensors.
|
| 93 |
+
# They do not load model weights or run the encoder.
|
| 94 |
+
python3 -m unittest discover -s examples/embedding-coreml -p 'test_export_coreml.py'
|
| 95 |
+
|
| 96 |
+
# C++ packing, grouping, and context contract checks need no model assets.
|
| 97 |
+
ctest --test-dir build-ane -R '^coreml-contract$' --output-on-failure
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
BF16 GGUF provides a reference close to the original checkpoint. Also validate the official Q8_0 GGUF with the same corpus and batching arguments when deploying that quantization. Core ML uses the original checkpoint through its FP16 sidecar, independently of GGUF quantization; the raw output is exposed as FP32. The selected GGUF controls ggml execution and fallback.
|
| 101 |
+
|
| 102 |
+
The adapter compiles `.mlpackage` to `.mlmodelc` on first load. Use `--pack-slots 16` for a sixteen-slot local export.
|
| 103 |
+
|
| 104 |
+
## Lower-level adapter and tokenization
|
| 105 |
+
|
| 106 |
+
Reuse llama.cpp's GGUF vocabulary with `llama_model_params.vocab_only = true`. Apply the task prefix before tokenization, for example `title: none | text: ` for documents or `task: search result | query: ` for queries. Tokenize with `add_special=false` and `parse_special=false`, then explicitly prepend BOS (2) and append EOS (1). Do not rely on the GGUF's generation defaults to insert EOS.
|
| 107 |
+
|
| 108 |
+
Pass an array of `llama_coreml_embedding_sequence` to `llama_coreml_embedding_encode` with packing enabled. Each sequence includes its BOS/EOS and must contain 1..512 tokens. The adapter rejects overlength inputs; the caller owns any truncation policy and must preserve EOS. The default `llama_coreml_embedding_load` produces 768 floats per text, already mean-pooled and L2-normalized by the model. `llama_coreml_embedding_load_raw` instead selects unnormalized mean-pooled output from a compatible local export. For Matryoshka output, keep the first 512/256/128 components and renormalize. Errors return through a caller-owned buffer; no C++ exceptions cross the C API. A failure may leave partial output, which the caller must discard.
|
| 109 |
+
|
| 110 |
+
## Accuracy and throughput
|
| 111 |
+
|
| 112 |
+
Use the BF16 model from [ggml-org/embeddinggemma-2-GGUF](https://huggingface.co/ggml-org/embeddinggemma-2-GGUF), revision `bfcd298762cc34d0357ece5ebdd31791a3a374d8`. The benchmark reads one already-prefixed text per line, uses the same llama.cpp token IDs for both paths, warms the models, compares packed versus single embeddings and Core ML versus GGUF cosine similarity, tests rejected token IDs/lengths/buffer capacities, then measures repeated inference. Model loading and first-use compilation are excluded. Tokenization is excluded from throughput for all paths. CPU/Metal sequence count and token batch capacity are configurable.
|
| 113 |
+
|
| 114 |
+
```sh
|
| 115 |
+
build-ane/bin/llama-coreml-embedding-bench \
|
| 116 |
+
../llama-coreml-assets/gguf/embeddinggemma-2-BF16.gguf \
|
| 117 |
+
../llama-coreml-assets/coreml examples/embedding-coreml/benchmark-texts.txt 5 metal 1 32 1024 8
|
| 118 |
+
# Repeat with 64 sequences / 2048 tokens to compare a larger Metal batch.
|
| 119 |
+
# Replace metal with cpu for the CPU comparison.
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
The optional arguments after the execution path are Core ML workers (1..8, default 1), reference parallel sequences (1..64, default 8), reference token batch capacity (32..2048, default 512), and Core ML calls in flight (1..8, default 1). Values above one worker add a concurrent Core ML throughput measurement. Each context owns its input buffers; the model package and mapped token table remain the same. The benchmark exits with an error when any cosine similarity is below 0.998 or normalized outputs are non-finite or not L2 normalized. With a raw-output package it additionally checks raw relative L2 error below 3% and reports `coreml_integrated` throughput through the normal API. A normalized-only package reports `integrated_api=unavailable` and tests only the lower-level adapter. `benchmark-texts.txt` supplies a small multilingual/code smoke corpus. Include lengths crossing 32/48/64/128/256/512 token boundaries when validating a deployment. This is a smoke/accuracy check, not an embedding quality evaluation. Measure your real corpus and target hardware before claiming an application speedup.
|
| 123 |
+
|
| 124 |
+
Build `llama-coreml-embedding-plan` and run it with the compiled `.mlmodelc` directory to report Core ML's preferred device for every non-constant operation of each function. Constants are excluded because they do not execute and have no device usage entry. A compute plan describes anticipated placement; actual execution can be inspected with Core ML profiling in Instruments.
|
| 125 |
+
|
| 126 |
+
The runtime input contract was checked against [FluidUse's EmbeddingGemma2Manager](https://github.com/FluidInference/FluidUse/blob/main/Sources/FluidUse/EmbeddingGemma2/EmbeddingGemma2Manager.swift) (Apache-2.0). Audio and vision encoders are outside this adapter's scope.
|
conversion/upstream/qvac/export_coreml.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export a local EmbeddingGemma 2 safetensors checkpoint for the Core ML adapter."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import shutil
|
| 8 |
+
import tempfile
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
LENGTHS = (32, 48, 64, 128, 256, 512)
|
| 12 |
+
TOKEN_TABLE = "language_model.embed_tokens.weight"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def rms_normalize(values, eps: float):
|
| 16 |
+
# Scale before squaring so FP16 activations cannot overflow.
|
| 17 |
+
scale = values.abs().amax(dim=-1, keepdim=True).clamp_min(1.0)
|
| 18 |
+
scaled = values / scale
|
| 19 |
+
variance = (scaled * scaled).mean(dim=-1, keepdim=True) + eps / scale / scale
|
| 20 |
+
return scaled * variance.rsqrt()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def l2_normalize(values):
|
| 24 |
+
scaled = values / values.abs().amax(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 25 |
+
return scaled / (scaled * scaled).sum(dim=-1, keepdim=True).sqrt().clamp_min(1e-6)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def read_config(source: Path) -> dict:
|
| 29 |
+
config = json.loads((source / "config.json").read_text())
|
| 30 |
+
if config.get("model_type") != "embedding_gemma2":
|
| 31 |
+
raise ValueError("Expected an EmbeddingGemma 2 checkpoint")
|
| 32 |
+
text = config.get("text_config", {})
|
| 33 |
+
expected = {
|
| 34 |
+
"hidden_size": 512, "embedding_dim": 768, "vocab_size": 262144,
|
| 35 |
+
"hidden_size_per_layer_input": 512, "num_hidden_layers": 24,
|
| 36 |
+
"num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 256,
|
| 37 |
+
"intermediate_size": 2048, "sliding_window": 512, "rms_norm_eps": 1e-6,
|
| 38 |
+
"hidden_activation": "gelu_pytorch_tanh", "attention_bias": False,
|
| 39 |
+
"bos_token_id": 2, "eos_token_id": 1, "pad_token_id": 0,
|
| 40 |
+
}
|
| 41 |
+
for name, value in expected.items():
|
| 42 |
+
if text.get(name) != value:
|
| 43 |
+
raise ValueError(f"Unsupported text_config.{name}: {text.get(name)!r}; expected {value!r}")
|
| 44 |
+
layer_types = ["full_attention" if i % 6 == 5 else "sliding_attention" for i in range(24)]
|
| 45 |
+
if text.get("layer_types") != layer_types:
|
| 46 |
+
raise ValueError("Unsupported attention layer layout")
|
| 47 |
+
per_layer = {int(key): value for key, value in text.get("per_layer_config", {}).items()}
|
| 48 |
+
if per_layer != {i: {"head_dim": 512, "num_key_value_heads": 1} for i in (5, 11, 17, 23)}:
|
| 49 |
+
raise ValueError("Unsupported per-layer head configuration")
|
| 50 |
+
for name, theta in (("full_attention", 1000000.0), ("sliding_attention", 10000.0)):
|
| 51 |
+
if text.get("rope_parameters", {}).get(name) != {"rope_type": "default", "rope_theta": theta}:
|
| 52 |
+
raise ValueError(f"Unsupported {name} rotary configuration")
|
| 53 |
+
return text
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def function_contracts(slots: int) -> dict:
|
| 57 |
+
if slots not in (8, 16):
|
| 58 |
+
raise ValueError("Packing requires 8 or 16 slots")
|
| 59 |
+
contracts = {
|
| 60 |
+
f"embed_{length}": {"inputs_embeds": (1, length, 512), "attention_mask": (1, length)}
|
| 61 |
+
for length in LENGTHS
|
| 62 |
+
}
|
| 63 |
+
contracts["pack_256"] = {
|
| 64 |
+
"inputs_embeds": (1, 256, 512), "attention_bias": (1, 1, 256, 256),
|
| 65 |
+
"positions": (256, 1), "pool": (slots, 256),
|
| 66 |
+
}
|
| 67 |
+
return contracts
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def checkpoint_files(source: Path) -> list[Path]:
|
| 71 |
+
index = source / "model.safetensors.index.json"
|
| 72 |
+
if index.is_file():
|
| 73 |
+
mapping = json.loads(index.read_text())["weight_map"]
|
| 74 |
+
names = sorted({name for key, name in mapping.items() if key.startswith("language_model.")})
|
| 75 |
+
else:
|
| 76 |
+
names = ["model.safetensors"]
|
| 77 |
+
if not names:
|
| 78 |
+
raise ValueError("No text encoder safetensors found")
|
| 79 |
+
files = []
|
| 80 |
+
for name in names:
|
| 81 |
+
if Path(name).name != name or not name.endswith(".safetensors"):
|
| 82 |
+
raise ValueError("Checkpoint shards must be safetensors files in the source directory")
|
| 83 |
+
path = source / name
|
| 84 |
+
if not path.is_file():
|
| 85 |
+
raise ValueError(f"Missing checkpoint shard: {path}")
|
| 86 |
+
files.append(path)
|
| 87 |
+
return files
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def sha256(path: Path) -> str:
|
| 91 |
+
digest = hashlib.sha256()
|
| 92 |
+
with path.open("rb") as stream:
|
| 93 |
+
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
| 94 |
+
digest.update(block)
|
| 95 |
+
return digest.hexdigest()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def validate_functions(description, contracts: dict, slots: int, dtype: int, raw_dtype: int) -> None:
|
| 99 |
+
functions = {function.name: function for function in description.functions}
|
| 100 |
+
if set(functions) != set(contracts):
|
| 101 |
+
raise ValueError("Exported functions do not match the adapter contract")
|
| 102 |
+
for name, inputs in contracts.items():
|
| 103 |
+
function = functions[name]
|
| 104 |
+
if {feature.name for feature in function.input} != set(inputs):
|
| 105 |
+
raise ValueError(f"Unexpected exported inputs for {name}")
|
| 106 |
+
for feature in function.input:
|
| 107 |
+
array = feature.type.multiArrayType
|
| 108 |
+
if tuple(array.shape) != inputs[feature.name] or array.dataType != dtype:
|
| 109 |
+
raise ValueError(f"Unexpected exported shape or type for {name}.{feature.name}")
|
| 110 |
+
if len(function.output) != 2 or {feature.name for feature in function.output} != {"embedding", "embedding_raw"}:
|
| 111 |
+
raise ValueError(f"Unexpected exported outputs for {name}")
|
| 112 |
+
for feature in function.output:
|
| 113 |
+
array = feature.type.multiArrayType
|
| 114 |
+
expected_dtype = raw_dtype if feature.name == "embedding_raw" else dtype
|
| 115 |
+
if tuple(array.shape) != (slots if name == "pack_256" else 1, 768) or array.dataType != expected_dtype:
|
| 116 |
+
raise ValueError(f"Unexpected exported embedding shape or type for {name}.{feature.name}")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def load_encoder(source: Path, destination: Path, text: dict):
|
| 120 |
+
import torch
|
| 121 |
+
from safetensors import safe_open
|
| 122 |
+
from transformers.models.embedding_gemma2.configuration_embedding_gemma2 import EmbeddingGemma2TextConfig
|
| 123 |
+
from transformers.models.embedding_gemma2.modeling_embedding_gemma2 import (
|
| 124 |
+
EmbeddingGemma2RotaryEmbedding, EmbeddingGemma2TextModel,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
config = EmbeddingGemma2TextConfig(**text)
|
| 128 |
+
config._attn_implementation = "eager"
|
| 129 |
+
# Build without allocating the token table or the unused media encoders.
|
| 130 |
+
with torch.device("meta"):
|
| 131 |
+
model = EmbeddingGemma2TextModel(config)
|
| 132 |
+
setattr(model, "embed_tokens", torch.nn.Identity())
|
| 133 |
+
model.rotary_emb = EmbeddingGemma2RotaryEmbedding(config)
|
| 134 |
+
expected = model.state_dict()
|
| 135 |
+
state = {}
|
| 136 |
+
table_found = False
|
| 137 |
+
provenance = {}
|
| 138 |
+
for path in checkpoint_files(source):
|
| 139 |
+
provenance[path.name] = sha256(path)
|
| 140 |
+
with safe_open(path, framework="pt", device="cpu") as tensors:
|
| 141 |
+
for key in tensors.keys():
|
| 142 |
+
if not key.startswith("language_model."):
|
| 143 |
+
continue
|
| 144 |
+
if key == TOKEN_TABLE:
|
| 145 |
+
if table_found:
|
| 146 |
+
raise ValueError("Duplicate token table")
|
| 147 |
+
table = tensors.get_slice(key)
|
| 148 |
+
if table.get_shape() != [262144, 512] or table.get_dtype() != "BF16":
|
| 149 |
+
raise ValueError("Expected the original 262144 x 512 BF16 token table")
|
| 150 |
+
with (destination / "embeddings.bf16").open("wb") as output:
|
| 151 |
+
for start in range(0, 262144, 4096):
|
| 152 |
+
rows = table[start:start + 4096].contiguous()
|
| 153 |
+
output.write(rows.view(torch.int16).numpy().astype("<i2", copy=False).tobytes())
|
| 154 |
+
table_found = True
|
| 155 |
+
continue
|
| 156 |
+
name = key.removeprefix("language_model.")
|
| 157 |
+
if name not in expected or name in state:
|
| 158 |
+
raise ValueError(f"Unexpected or duplicate text tensor: {key}")
|
| 159 |
+
tensor = tensors.get_tensor(key)
|
| 160 |
+
if tensor.shape != expected[name].shape or not tensor.is_floating_point():
|
| 161 |
+
raise ValueError(f"Unexpected shape or type for {key}")
|
| 162 |
+
state[name] = tensor.float()
|
| 163 |
+
if not table_found:
|
| 164 |
+
raise ValueError("Missing BF16 token table")
|
| 165 |
+
model.load_state_dict(state, strict=True, assign=True)
|
| 166 |
+
return model.eval(), provenance
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def export_wrapper(model, packed: bool):
|
| 170 |
+
import torch
|
| 171 |
+
from transformers.models.embedding_gemma2.modeling_embedding_gemma2 import EmbeddingGemma2RMSNorm
|
| 172 |
+
|
| 173 |
+
class SafeRMSNorm(torch.nn.Module):
|
| 174 |
+
def __init__(self, original):
|
| 175 |
+
super().__init__()
|
| 176 |
+
self.eps = original.eps
|
| 177 |
+
self.weight = original.weight if original.with_scale else None
|
| 178 |
+
|
| 179 |
+
def forward(self, values):
|
| 180 |
+
result = rms_normalize(values, self.eps)
|
| 181 |
+
return result if self.weight is None else result * self.weight
|
| 182 |
+
|
| 183 |
+
def replace_norms(module):
|
| 184 |
+
for name, child in list(module.named_children()):
|
| 185 |
+
if isinstance(child, EmbeddingGemma2RMSNorm):
|
| 186 |
+
setattr(module, name, SafeRMSNorm(child))
|
| 187 |
+
else:
|
| 188 |
+
replace_norms(child)
|
| 189 |
+
|
| 190 |
+
replace_norms(model)
|
| 191 |
+
|
| 192 |
+
class Encoder(torch.nn.Module):
|
| 193 |
+
def __init__(self):
|
| 194 |
+
super().__init__()
|
| 195 |
+
self.layers = model.layers
|
| 196 |
+
self.ple = model.ple
|
| 197 |
+
self.norm = model.norm
|
| 198 |
+
self.projection = model.embedding_projection
|
| 199 |
+
self.layer_types = model.config.layer_types
|
| 200 |
+
self.packed = packed
|
| 201 |
+
for kind in sorted(set(self.layer_types)):
|
| 202 |
+
cos, sin = model.rotary_emb(torch.empty(1), torch.arange(512).unsqueeze(0), kind)
|
| 203 |
+
self.register_buffer(kind + "_cos", cos.squeeze(0))
|
| 204 |
+
self.register_buffer(kind + "_sin", sin.squeeze(0))
|
| 205 |
+
|
| 206 |
+
def forward(self, inputs_embeds, attention_mask, positions=None, pool=None):
|
| 207 |
+
length = inputs_embeds.shape[1]
|
| 208 |
+
if self.packed:
|
| 209 |
+
assert positions is not None and pool is not None
|
| 210 |
+
bias = attention_mask
|
| 211 |
+
else:
|
| 212 |
+
bias = (1.0 - attention_mask[:, None, None, :]) * -10000.0
|
| 213 |
+
positions = torch.arange(length)
|
| 214 |
+
pool = attention_mask / attention_mask.sum(dim=-1, keepdim=True)
|
| 215 |
+
rotations = {}
|
| 216 |
+
for kind in sorted(set(self.layer_types)):
|
| 217 |
+
cos = getattr(self, kind + "_cos")
|
| 218 |
+
sin = getattr(self, kind + "_sin")
|
| 219 |
+
if self.packed:
|
| 220 |
+
indices = positions.reshape(-1).to(torch.int32)
|
| 221 |
+
cos = torch.nn.functional.embedding(indices, cos)
|
| 222 |
+
sin = torch.nn.functional.embedding(indices, sin)
|
| 223 |
+
else:
|
| 224 |
+
cos, sin = cos[:length], sin[:length]
|
| 225 |
+
rotations[kind] = (cos.unsqueeze(0), sin.unsqueeze(0))
|
| 226 |
+
# The sliding-window radius covers every token at these fixed lengths.
|
| 227 |
+
per_layer = self.ple(inputs_embeds)
|
| 228 |
+
hidden = inputs_embeds
|
| 229 |
+
for i, layer in enumerate(self.layers):
|
| 230 |
+
hidden = layer(hidden, per_layer[:, :, i, :], attention_mask=bias,
|
| 231 |
+
position_embeddings=rotations[self.layer_types[i]])
|
| 232 |
+
hidden = self.projection(self.norm(hidden)).squeeze(0)
|
| 233 |
+
pooled = torch.matmul(pool, hidden)
|
| 234 |
+
return l2_normalize(pooled), pooled
|
| 235 |
+
|
| 236 |
+
return Encoder().eval()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def export(source: Path, destination: Path, slots: int) -> None:
|
| 240 |
+
text = read_config(source)
|
| 241 |
+
contracts = function_contracts(slots)
|
| 242 |
+
checkpoint_files(source)
|
| 243 |
+
if not (source / "tokenizer.json").is_file():
|
| 244 |
+
raise ValueError("Missing tokenizer.json")
|
| 245 |
+
if destination.exists():
|
| 246 |
+
raise ValueError("Destination already exists; refusing to overwrite model assets")
|
| 247 |
+
|
| 248 |
+
import coremltools as ct
|
| 249 |
+
from coremltools.proto.FeatureTypes_pb2 import ArrayFeatureType
|
| 250 |
+
import numpy as np
|
| 251 |
+
import torch
|
| 252 |
+
import transformers
|
| 253 |
+
|
| 254 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 255 |
+
# Publish only a complete export. Failed conversions leave no destination.
|
| 256 |
+
with tempfile.TemporaryDirectory(prefix=".embeddinggemma-export-", dir=destination.parent) as temporary:
|
| 257 |
+
work = Path(temporary)
|
| 258 |
+
assets = work / "assets"
|
| 259 |
+
assets.mkdir()
|
| 260 |
+
model, checkpoints = load_encoder(source, assets, text)
|
| 261 |
+
functions = ct.utils.MultiFunctionDescriptor()
|
| 262 |
+
with torch.inference_mode():
|
| 263 |
+
for name, shapes in contracts.items():
|
| 264 |
+
packed = name == "pack_256"
|
| 265 |
+
wrapper = export_wrapper(model, packed)
|
| 266 |
+
examples = [torch.zeros(shape, dtype=torch.float32) for shape in shapes.values()]
|
| 267 |
+
if packed:
|
| 268 |
+
examples[2][:, 0] = torch.arange(256)
|
| 269 |
+
examples[3][:, :16] = 1.0 / 16
|
| 270 |
+
else:
|
| 271 |
+
examples[1][:] = 1
|
| 272 |
+
print(f"Exporting {name}", flush=True)
|
| 273 |
+
traced = torch.jit.trace(wrapper, tuple(examples), check_trace=False)
|
| 274 |
+
converted = ct.convert(
|
| 275 |
+
traced, convert_to="mlprogram", minimum_deployment_target=ct.target.iOS18,
|
| 276 |
+
compute_precision=ct.precision.FLOAT16, skip_model_load=True,
|
| 277 |
+
inputs=[ct.TensorType(name=key, shape=shape, dtype=np.float16) for key, shape in shapes.items()],
|
| 278 |
+
outputs=[ct.TensorType(name="embedding", dtype=np.float16), ct.TensorType(name="embedding_raw", dtype=np.float32)],
|
| 279 |
+
)
|
| 280 |
+
path = work / (name + ".mlpackage")
|
| 281 |
+
converted.save(str(path))
|
| 282 |
+
functions.add_function(str(path), "main", name)
|
| 283 |
+
functions.default_function_name = "embed_32"
|
| 284 |
+
package = assets / "EmbeddingGemma2Text.mlpackage"
|
| 285 |
+
ct.utils.save_multifunction(functions, str(package))
|
| 286 |
+
validate_functions(ct.utils.load_spec(str(package)).description, contracts, slots,
|
| 287 |
+
getattr(ArrayFeatureType, "FLOAT16"), getattr(ArrayFeatureType, "FLOAT32"))
|
| 288 |
+
shutil.copy2(source / "tokenizer.json", assets / "tokenizer.json")
|
| 289 |
+
shutil.copy2(source / "config.json", assets / "source-config.json")
|
| 290 |
+
manifest = {
|
| 291 |
+
"source_checkpoints_sha256": checkpoints,
|
| 292 |
+
"source_config_sha256": sha256(source / "config.json"),
|
| 293 |
+
"tokenizer_sha256": sha256(assets / "tokenizer.json"),
|
| 294 |
+
"token_table_sha256": sha256(assets / "embeddings.bf16"),
|
| 295 |
+
"model_sha256": sha256(package / "Data/com.apple.CoreML/model.mlmodel"),
|
| 296 |
+
"pack_slots": slots, "functions": contracts,
|
| 297 |
+
"outputs": {"embedding": "float16_l2_normalized", "embedding_raw": "float32_mean_pooled"},
|
| 298 |
+
"torch": torch.__version__, "transformers": transformers.__version__, "coremltools": ct.__version__,
|
| 299 |
+
}
|
| 300 |
+
(assets / "export.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
| 301 |
+
if destination.exists():
|
| 302 |
+
raise ValueError("Destination appeared during export; refusing to overwrite it")
|
| 303 |
+
assets.rename(destination)
|
| 304 |
+
print(f"Exported assets to {destination}", flush=True)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def main() -> None:
|
| 308 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 309 |
+
parser.add_argument("source", type=Path, help="local Hugging Face checkpoint directory")
|
| 310 |
+
parser.add_argument("destination", type=Path, help="new output directory")
|
| 311 |
+
parser.add_argument("--pack-slots", type=int, choices=(8, 16), default=8)
|
| 312 |
+
args = parser.parse_args()
|
| 313 |
+
try:
|
| 314 |
+
export(args.source, args.destination, args.pack_slots)
|
| 315 |
+
except (ValueError, OSError, ImportError) as error:
|
| 316 |
+
parser.exit(1, f"error: {error}\n")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
main()
|
conversion/upstream/qvac/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Keep the validated Core ML export toolchain in its separate environment.
|
| 2 |
+
coremltools==9.0 # check_requirements: ignore "=="
|
| 3 |
+
numpy==2.2.6 # check_requirements: ignore "=="
|
| 4 |
+
safetensors==0.8.0 # check_requirements: ignore "=="
|
| 5 |
+
torch==2.7.0 # check_requirements: ignore "=="
|
| 6 |
+
transformers @ git+https://github.com/huggingface/transformers.git@ab7e5ac33f234b41665fee663fefd441d35ad3d4
|
conversion/upstream/transformers-LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2018- The Hugging Face team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Apache License
|
| 4 |
+
Version 2.0, January 2004
|
| 5 |
+
http://www.apache.org/licenses/
|
| 6 |
+
|
| 7 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 8 |
+
|
| 9 |
+
1. Definitions.
|
| 10 |
+
|
| 11 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 12 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 13 |
+
|
| 14 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 15 |
+
the copyright owner that is granting the License.
|
| 16 |
+
|
| 17 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 18 |
+
other entities that control, are controlled by, or are under common
|
| 19 |
+
control with that entity. For the purposes of this definition,
|
| 20 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 21 |
+
direction or management of such entity, whether by contract or
|
| 22 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 23 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 24 |
+
|
| 25 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 26 |
+
exercising permissions granted by this License.
|
| 27 |
+
|
| 28 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 29 |
+
including but not limited to software source code, documentation
|
| 30 |
+
source, and configuration files.
|
| 31 |
+
|
| 32 |
+
"Object" form shall mean any form resulting from mechanical
|
| 33 |
+
transformation or translation of a Source form, including but
|
| 34 |
+
not limited to compiled object code, generated documentation,
|
| 35 |
+
and conversions to other media types.
|
| 36 |
+
|
| 37 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 38 |
+
Object form, made available under the License, as indicated by a
|
| 39 |
+
copyright notice that is included in or attached to the work
|
| 40 |
+
(an example is provided in the Appendix below).
|
| 41 |
+
|
| 42 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 43 |
+
form, that is based on (or derived from) the Work and for which the
|
| 44 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 45 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 46 |
+
of this License, Derivative Works shall not include works that remain
|
| 47 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 48 |
+
the Work and Derivative Works thereof.
|
| 49 |
+
|
| 50 |
+
"Contribution" shall mean any work of authorship, including
|
| 51 |
+
the original version of the Work and any modifications or additions
|
| 52 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 53 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 54 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 55 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 56 |
+
means any form of electronic, verbal, or written communication sent
|
| 57 |
+
to the Licensor or its representatives, including but not limited to
|
| 58 |
+
communication on electronic mailing lists, source code control systems,
|
| 59 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 60 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 61 |
+
excluding communication that is conspicuously marked or otherwise
|
| 62 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 63 |
+
|
| 64 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 65 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 66 |
+
subsequently incorporated within the Work.
|
| 67 |
+
|
| 68 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 69 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 70 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 71 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 72 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 73 |
+
Work and such Derivative Works in Source or Object form.
|
| 74 |
+
|
| 75 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 76 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 77 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 78 |
+
(except as stated in this section) patent license to make, have made,
|
| 79 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 80 |
+
where such license applies only to those patent claims licensable
|
| 81 |
+
by such Contributor that are necessarily infringed by their
|
| 82 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 83 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 84 |
+
institute patent litigation against any entity (including a
|
| 85 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 86 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 87 |
+
or contributory patent infringement, then any patent licenses
|
| 88 |
+
granted to You under this License for that Work shall terminate
|
| 89 |
+
as of the date such litigation is filed.
|
| 90 |
+
|
| 91 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 92 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 93 |
+
modifications, and in Source or Object form, provided that You
|
| 94 |
+
meet the following conditions:
|
| 95 |
+
|
| 96 |
+
(a) You must give any other recipients of the Work or
|
| 97 |
+
Derivative Works a copy of this License; and
|
| 98 |
+
|
| 99 |
+
(b) You must cause any modified files to carry prominent notices
|
| 100 |
+
stating that You changed the files; and
|
| 101 |
+
|
| 102 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 103 |
+
that You distribute, all copyright, patent, trademark, and
|
| 104 |
+
attribution notices from the Source form of the Work,
|
| 105 |
+
excluding those notices that do not pertain to any part of
|
| 106 |
+
the Derivative Works; and
|
| 107 |
+
|
| 108 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 109 |
+
distribution, then any Derivative Works that You distribute must
|
| 110 |
+
include a readable copy of the attribution notices contained
|
| 111 |
+
within such NOTICE file, excluding those notices that do not
|
| 112 |
+
pertain to any part of the Derivative Works, in at least one
|
| 113 |
+
of the following places: within a NOTICE text file distributed
|
| 114 |
+
as part of the Derivative Works; within the Source form or
|
| 115 |
+
documentation, if provided along with the Derivative Works; or,
|
| 116 |
+
within a display generated by the Derivative Works, if and
|
| 117 |
+
wherever such third-party notices normally appear. The contents
|
| 118 |
+
of the NOTICE file are for informational purposes only and
|
| 119 |
+
do not modify the License. You may add Your own attribution
|
| 120 |
+
notices within Derivative Works that You distribute, alongside
|
| 121 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 122 |
+
that such additional attribution notices cannot be construed
|
| 123 |
+
as modifying the License.
|
| 124 |
+
|
| 125 |
+
You may add Your own copyright statement to Your modifications and
|
| 126 |
+
may provide additional or different license terms and conditions
|
| 127 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 128 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 129 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 130 |
+
the conditions stated in this License.
|
| 131 |
+
|
| 132 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 133 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 134 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 135 |
+
this License, without any additional terms or conditions.
|
| 136 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 137 |
+
the terms of any separate license agreement you may have executed
|
| 138 |
+
with Licensor regarding such Contributions.
|
| 139 |
+
|
| 140 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 141 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 142 |
+
except as required for reasonable and customary use in describing the
|
| 143 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 144 |
+
|
| 145 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 146 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 147 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 148 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 149 |
+
implied, including, without limitation, any warranties or conditions
|
| 150 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 151 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 152 |
+
appropriateness of using or redistributing the Work and assume any
|
| 153 |
+
risks associated with Your exercise of permissions under this License.
|
| 154 |
+
|
| 155 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 156 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 157 |
+
unless required by applicable law (such as deliberate and grossly
|
| 158 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 159 |
+
liable to You for damages, including any direct, indirect, special,
|
| 160 |
+
incidental, or consequential damages of any character arising as a
|
| 161 |
+
result of this License or out of the use or inability to use the
|
| 162 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 163 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 164 |
+
other commercial damages or losses), even if such Contributor
|
| 165 |
+
has been advised of the possibility of such damages.
|
| 166 |
+
|
| 167 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 168 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 169 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 170 |
+
or other liability obligations and/or rights consistent with this
|
| 171 |
+
License. However, in accepting such obligations, You may act only
|
| 172 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 173 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 174 |
+
defend, and hold each Contributor harmless for any liability
|
| 175 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 176 |
+
of your accepting any such warranty or additional liability.
|
| 177 |
+
|
| 178 |
+
END OF TERMS AND CONDITIONS
|
| 179 |
+
|
| 180 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 181 |
+
|
| 182 |
+
To apply the Apache License to your work, attach the following
|
| 183 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 184 |
+
replaced with your own identifying information. (Don't include
|
| 185 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 186 |
+
comment syntax for the file format. We also recommend that a
|
| 187 |
+
file or class name and description of purpose be included on the
|
| 188 |
+
same "printed page" as the copyright notice for easier
|
| 189 |
+
identification within third-party archives.
|
| 190 |
+
|
| 191 |
+
Copyright [yyyy] [name of copyright owner]
|
| 192 |
+
|
| 193 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 194 |
+
you may not use this file except in compliance with the License.
|
| 195 |
+
You may obtain a copy of the License at
|
| 196 |
+
|
| 197 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 198 |
+
|
| 199 |
+
Unless required by applicable law or agreed to in writing, software
|
| 200 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 201 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 202 |
+
See the License for the specific language governing permissions and
|
| 203 |
+
limitations under the License.
|
conversion/validate.swift
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import Foundation
|
| 2 |
+
import CoreML
|
| 3 |
+
|
| 4 |
+
struct TokenRow: Decodable { let text: String; let tokens: [Int32] }
|
| 5 |
+
struct ReferenceRow: Decodable { let `case`: Int; let text: String; let tokens: [Int32]; let length: Int; let vector: [Double] }
|
| 6 |
+
|
| 7 |
+
func write(_ value: Any, _ path: String) throws {
|
| 8 |
+
try JSONSerialization.data(withJSONObject:value,options:[.prettyPrinted,.sortedKeys]).write(to:URL(fileURLWithPath:path),options:.atomic)
|
| 9 |
+
}
|
| 10 |
+
func footprint(_ root:String, _ tag:String) throws {
|
| 11 |
+
let p=Process();p.executableURL=URL(fileURLWithPath:"/usr/bin/footprint")
|
| 12 |
+
p.arguments=["--wired",String(ProcessInfo.processInfo.processIdentifier)]
|
| 13 |
+
let path=root+"/evidence/footprint-"+tag+".txt"
|
| 14 |
+
FileManager.default.createFile(atPath:path,contents:nil)
|
| 15 |
+
let h=try FileHandle(forWritingTo:URL(fileURLWithPath:path));p.standardOutput=h;p.standardError=h
|
| 16 |
+
try p.run();p.waitUntilExit();try h.close()
|
| 17 |
+
}
|
| 18 |
+
func provider(_ ids:[Int32],_ length:Int) throws -> MLFeatureProvider {
|
| 19 |
+
precondition(ids.count<=length)
|
| 20 |
+
let x=try MLMultiArray(shape:[1,NSNumber(value:length)],dataType:.int32)
|
| 21 |
+
let m=try MLMultiArray(shape:[1,NSNumber(value:length)],dataType:.float32)
|
| 22 |
+
for i in 0..<length {x[i]=NSNumber(value:i<ids.count ? ids[i] : 0);m[i]=NSNumber(value:i<ids.count ? 1.0 : 0.0)}
|
| 23 |
+
return try MLDictionaryFeatureProvider(dictionary:["input_ids":x,"attention_mask":m])
|
| 24 |
+
}
|
| 25 |
+
func vector(_ output: MLFeatureProvider) -> [Double] {
|
| 26 |
+
let a=output.featureValue(for:"embedding")!.multiArrayValue!
|
| 27 |
+
return (0..<a.count).map{a[$0].doubleValue}
|
| 28 |
+
}
|
| 29 |
+
func cosine(_ a:[Double],_ b:[Double]) -> Double {
|
| 30 |
+
let dot=zip(a,b).map(*).reduce(0,+)
|
| 31 |
+
return dot/sqrt(a.map{$0*$0}.reduce(0,+)*b.map{$0*$0}.reduce(0,+))
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
@main struct Validate {
|
| 35 |
+
static func main() async throws {
|
| 36 |
+
let args=CommandLine.arguments
|
| 37 |
+
let root=args[1], mode=args[2], multi=args[3]=="multi"
|
| 38 |
+
let lengths=args[4].split(separator:",").map{Int($0)!}
|
| 39 |
+
precondition(!lengths.isEmpty && lengths==Array(Set(lengths)).sorted())
|
| 40 |
+
precondition(Set(lengths).isSubset(of:[128,256,512,1024,2048]))
|
| 41 |
+
if multi {precondition(lengths==[128,256,512,1024,2048],"Validate every delivered function")}
|
| 42 |
+
let maxLength=lengths.last!
|
| 43 |
+
let fm=FileManager.default
|
| 44 |
+
var result:[String:Any]=["mode":mode,"sequenceLengths":lengths,"maxSequenceLength":maxLength,"computeUnits":"cpuAndNeuralEngine","pid":ProcessInfo.processInfo.processIdentifier,"host":ProcessInfo.processInfo.hostName,"os":ProcessInfo.processInfo.operatingSystemVersionString]
|
| 45 |
+
var models:[Int:MLModel]=[:], urls:[Int:URL]=[:], loads:[String:Double]=[:], compiles:[String:Double]=[:], first:[String:Double]=[:]
|
| 46 |
+
try footprint(root,mode+"-start")
|
| 47 |
+
for length in lengths {
|
| 48 |
+
let stem=multi ? "EmbeddingGemma2Owned" : "s\(length)"
|
| 49 |
+
let url=URL(fileURLWithPath:root+"/models/"+stem+".mlmodelc")
|
| 50 |
+
let t=Date()
|
| 51 |
+
if !fm.fileExists(atPath:url.path) {
|
| 52 |
+
let temporary=try await MLModel.compileModel(at:URL(fileURLWithPath:root+"/models/"+stem+".mlpackage"))
|
| 53 |
+
try fm.moveItem(at:temporary,to:url)
|
| 54 |
+
}
|
| 55 |
+
compiles[String(length)]=Date().timeIntervalSince(t)
|
| 56 |
+
let cfg=MLModelConfiguration();cfg.computeUnits = .cpuAndNeuralEngine
|
| 57 |
+
if multi {cfg.functionName="s\(length)"}
|
| 58 |
+
let load=Date();let model=try MLModel(contentsOf:url,configuration:cfg)
|
| 59 |
+
loads[String(length)]=Date().timeIntervalSince(load);models[length]=model;urls[length]=url
|
| 60 |
+
let pred=Date();_ = try await model.prediction(from:provider([2,9259,1],length));first[String(length)]=Date().timeIntervalSince(pred)
|
| 61 |
+
try footprint(root,mode+"-s\(length)")
|
| 62 |
+
print("s\(length) load \(loads[String(length)]!) first \(first[String(length)]!)");fflush(stdout)
|
| 63 |
+
result["compileSeconds"]=compiles;result["loadSeconds"]=loads;result["firstPredictSeconds"]=first;result["phase"]="loaded-s\(length)"
|
| 64 |
+
try write(result,root+"/evidence/"+mode+"-progress.json")
|
| 65 |
+
}
|
| 66 |
+
result["compileSeconds"]=compiles;result["loadSeconds"]=loads;result["firstPredictSeconds"]=first
|
| 67 |
+
for length in lengths {_ = try await models[length]!.prediction(from:provider([2,9259,1],length))}
|
| 68 |
+
try footprint(root,mode+"-all-active")
|
| 69 |
+
if mode=="warm" {
|
| 70 |
+
try write(result,root+"/evidence/"+mode+".json")
|
| 71 |
+
return
|
| 72 |
+
}
|
| 73 |
+
let refs=try JSONDecoder().decode([ReferenceRow].self,from:Data(contentsOf:URL(fileURLWithPath:root+"/evidence/hf-reference.json")))
|
| 74 |
+
var parity:[[String:Any]]=[]
|
| 75 |
+
for row in refs where lengths.contains(row.length) {
|
| 76 |
+
let value=vector(try await models[row.length]!.prediction(from:provider(row.tokens,row.length)))
|
| 77 |
+
guard value.count==768 && row.vector.count==768 else {throw NSError(domain:"Embedding dimension mismatch",code:7)}
|
| 78 |
+
let finite=value.allSatisfy{$0.isFinite}, norm=sqrt(value.map{$0*$0}.reduce(0,+))
|
| 79 |
+
let c=cosine(value,row.vector)
|
| 80 |
+
let maxAbs=zip(value,row.vector).map{abs($0-$1)}.max()!
|
| 81 |
+
guard value.count==768 && finite && abs(norm-1)<=0.001 && c>0.999 && maxAbs<=0.01 else {throw NSError(domain:"CoreML parity failed",code:1,userInfo:["case":row.case,"cosine":c,"norm":norm,"maxAbs":maxAbs])}
|
| 82 |
+
parity.append(["case":row.case,"length":row.length,"tokens":row.tokens.count,"cosine":c,"norm":norm,"finite":finite,"maxAbs":maxAbs,"vector":value])
|
| 83 |
+
}
|
| 84 |
+
result["hfFP32Parity"]=parity
|
| 85 |
+
result["phase"]="fixture-parity-complete"
|
| 86 |
+
try write(result,root+"/evidence/"+mode+"-progress.json")
|
| 87 |
+
print("HF FP32 parity passed for \(parity.count) cases");fflush(stdout)
|
| 88 |
+
if mode=="regression" {
|
| 89 |
+
try write(result,root+"/evidence/"+mode+".json")
|
| 90 |
+
return
|
| 91 |
+
}
|
| 92 |
+
if multi {
|
| 93 |
+
let rows=try JSONDecoder().decode([TokenRow].self,from:Data(contentsOf:URL(fileURLWithPath:root+"/tokens.json")))
|
| 94 |
+
var vectors:[[Double]]=[],indices:[Int]=[],latency:[Double]=[],byBucket:[String:[Double]]=[:]
|
| 95 |
+
var minNorm=Double.infinity,maxNorm=0.0
|
| 96 |
+
var excluded:[[String:Int]]=[]
|
| 97 |
+
for i in 0..<1500 {
|
| 98 |
+
let ids=rows[i*2].tokens
|
| 99 |
+
guard let length=lengths.first(where:{$0>=ids.count}) else {excluded.append(["documentIndex":i,"tokens":ids.count]);continue}
|
| 100 |
+
let t=Date();let value=vector(try await models[length]!.prediction(from:provider(ids,length)))
|
| 101 |
+
let ms=Date().timeIntervalSince(t)*1000
|
| 102 |
+
let norm=sqrt(value.map{$0*$0}.reduce(0,+));minNorm=min(minNorm,norm);maxNorm=max(maxNorm,norm)
|
| 103 |
+
guard value.count==768 && value.allSatisfy({$0.isFinite}) && abs(norm-1)<=0.001 else {throw NSError(domain:"Invalid FiQA embedding",code:3,userInfo:["document":i,"norm":norm])}
|
| 104 |
+
vectors.append(value);indices.append(i);latency.append(ms);byBucket[String(length),default:[]].append(ms)
|
| 105 |
+
}
|
| 106 |
+
let sorted=latency.sorted()
|
| 107 |
+
result["documents"]=indices.count;result["excludedOverMaxLength"]=excluded
|
| 108 |
+
result["corpusNormRange"]=[minNorm,maxNorm]
|
| 109 |
+
result["p50Ms"]=sorted[sorted.count/2];result["p95Ms"]=sorted[Int(Double(sorted.count)*0.95)]
|
| 110 |
+
result["docsPerSecond"]=Double(latency.count)*1000/latency.reduce(0,+)
|
| 111 |
+
result["latenciesByBucketMs"]=byBucket
|
| 112 |
+
try write(["indices":indices,"vectors":vectors,"sequenceLengths":lengths,"maxSequenceLength":maxLength],root+"/evidence/"+mode+"-vectors.json")
|
| 113 |
+
try footprint(root,mode+"-after-corpus")
|
| 114 |
+
}
|
| 115 |
+
result["phase"]="corpus-complete"
|
| 116 |
+
try write(result,root+"/evidence/"+mode+"-progress.json")
|
| 117 |
+
print("Corpus passed: \(result["documents"] ?? 0) documents");fflush(stdout)
|
| 118 |
+
var plans:[String:Any]=[:]
|
| 119 |
+
for length in lengths {
|
| 120 |
+
let cfg=MLModelConfiguration();cfg.computeUnits = .cpuAndNeuralEngine
|
| 121 |
+
if multi {cfg.functionName="s\(length)"}
|
| 122 |
+
let plan=try await MLComputePlan.load(contentsOf:urls[length]!,configuration:cfg)
|
| 123 |
+
if case let .program(program)=plan.modelStructure {
|
| 124 |
+
var ops:[String:Int]=[:],cost:[String:Double]=[:],cpu:[[String:String]]=[]
|
| 125 |
+
func walk(_ b:MLModelStructure.Program.Block) {
|
| 126 |
+
for op in b.operations {
|
| 127 |
+
var device="none"
|
| 128 |
+
if let usage=plan.deviceUsage(for:op) {switch usage.preferred {case .cpu:device="cpu";case .gpu:device="gpu";case .neuralEngine:device="ane";@unknown default:device="other"}}
|
| 129 |
+
if device != "none" || op.blocks.isEmpty {ops[device,default:0]+=1;cost[device,default:0]+=plan.estimatedCost(of:op)?.weight ?? 0}
|
| 130 |
+
if device=="cpu" {cpu.append(["operator":op.operatorName])}
|
| 131 |
+
for child in op.blocks {walk(child)}
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
for (name,function) in program.functions where !multi || name==cfg.functionName {walk(function.block)}
|
| 135 |
+
guard (ops["ane"] ?? 0)>100 else {throw NSError(domain:"CPU-only graph rejected",code:2)}
|
| 136 |
+
guard !cpu.contains(where: { let name=$0["operator"]!;return name.contains("conv") || name.contains("matmul") || name.contains("linear") || name.contains("softmax") }) else {throw NSError(domain:"CPU attention/FFN core rejected",code:4)}
|
| 137 |
+
plans[String(length)]=["ops":ops,"estimatedCost":cost,"cpuOperators":cpu]
|
| 138 |
+
result["plans"]=plans
|
| 139 |
+
try write(result,root+"/evidence/"+mode+"-progress.json")
|
| 140 |
+
print("Compute plan s\(length): \(ops)");fflush(stdout)
|
| 141 |
+
} else {throw NSError(domain:"Missing program compute plan",code:5)}
|
| 142 |
+
}
|
| 143 |
+
guard plans.count==lengths.count else {throw NSError(domain:"Missing requested function plan",code:6)}
|
| 144 |
+
result["plans"]=plans
|
| 145 |
+
try write(result,root+"/evidence/"+mode+"-progress.json")
|
| 146 |
+
result["phase"]="complete"
|
| 147 |
+
try write(result,root+"/evidence/"+mode+".json")
|
| 148 |
+
print("PASS: stock HF parity and non-CPU-only placement; wrote \(mode).json");fflush(stdout)
|
| 149 |
+
models.removeAll()
|
| 150 |
+
}
|
| 151 |
+
}
|
docs/technical-notes.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Measurements and technical notes
|
| 2 |
+
|
| 3 |
+
See the [current report](../validation/2026-11-16-five-bucket/REPORT.txt) and
|
| 4 |
+
[release validation summary](../validation/2026-11-16-five-bucket/release-validation.json).
|
| 5 |
+
|
| 6 |
+
| Measurement | Result |
|
| 7 |
+
|---|---|
|
| 8 |
+
| Rewritten forward vs stock HF FP32, 16 fixtures | Minimum cosine 0.999999999997; max absolute error 2.82e-7 |
|
| 9 |
+
| Native Core ML vs fresh stock HF FP32, 16 fixtures | Minimum cosine 0.99992672; max absolute error 0.00221308 |
|
| 10 |
+
| Long fixtures | 1151-token document, 1630-token multilingual text, exact 2048 tokens, plus short text padded to 2048 |
|
| 11 |
+
| Corpus | 1,499/1,500 FiQA documents; one 2212-token document excluded without truncation |
|
| 12 |
+
| Corpus norms | 0.999999893–1.000000097; finite, nonzero 768-dimensional vectors |
|
| 13 |
+
| Previous owned output overlap | All 1,491 overlapping outputs exactly unchanged |
|
| 14 |
+
| Sequential corpus inference, excluding tokenization | 56.64 documents/s; p50 7.34 ms; p95 35.73 ms |
|
| 15 |
+
| Five-function cold / cached load | 164.93 s / 3.95 s; package compilation separately 2.38 s |
|
| 16 |
+
| Matched long-input calls, 55 measured | ANE mean 300.24 ms; Metal Q8 mean 435.10 ms; aggregate 1.45× |
|
| 17 |
+
| Exact 2048-token median | ANE 299.55 ms; Metal Q8 726.67 ms (2.43×) |
|
| 18 |
+
| Exact 1025-token median | Essentially tied: ANE 299.53 ms; Metal Q8 299.22 ms |
|
| 19 |
+
|
| 20 |
+
The matched benchmark uses identical complete token IDs, two warmup rounds and five measured rounds over 11 inputs. It includes input allocation, prediction and normalized output copying, and excludes tokenization/model loading. Metal uses llama.cpp b11600, yzma 1.30.0, direct `llama_encode`, and Q8_0 weights; ANE uses FP16 weights with FP32 final normalization. These are direct runtime paths with different precision and host APIs, not exact application wrappers. No downstream head projection is applied. The comparison does not show an ANE advantage at every length.
|
| 21 |
+
|
| 22 |
+
Core ML compute plans report preferred placement and estimated cost, not an
|
| 23 |
+
Instruments runtime trace or a guarantee of ANE-only execution on other systems.
|
| 24 |
+
`cpuAndNeuralEngine` permits CPU operations; validation checks the transformer
|
| 25 |
+
core separately. Fresh stock-HF checks are bounded fixtures. Historical results
|
| 26 |
+
are labeled separately. These measure conversion fidelity, not broad retrieval
|
| 27 |
+
quality or suitability for every application.
|
| 28 |
+
|
| 29 |
+
Final FP32 normalization is intentional: the initial all-FP16 output failed a
|
| 30 |
+
strict unit-norm gate on one 413-token document. Keeping only the final L2
|
| 31 |
+
arithmetic in FP32 fixed it; that document remains a regression fixture.
|
| 32 |
+
|
| 33 |
+
## Reproduction and limitations
|
| 34 |
+
|
| 35 |
+
The converter uses Python 3.12.9, Torch 2.7.0, Transformers 5.19.0, Core ML Tools
|
| 36 |
+
9.0, NumPy 2.2.6 and safetensors 0.8.0. Full pins, source hashes, fixtures and
|
| 37 |
+
instructions are in the [included converter](../conversion/README.md).
|
| 38 |
+
This artifact merges the four exports retained from the validated November 12
|
| 39 |
+
build with a new s2048 export from November 16. The forward implementation,
|
| 40 |
+
source weights and dependency pins are unchanged. Individual conversion
|
| 41 |
+
fingerprints are preserved; they are not presented as one identical build.
|
| 42 |
+
The final merged package is validated directly. A fresh s2048 rebuild reproduced
|
| 43 |
+
identical weight-file bytes and an identical parsed model graph; the historical
|
| 44 |
+
s128 rebuild did too. Whole-package byte identity across rebuilds is not claimed:
|
| 45 |
+
UUIDs and protobuf map ordering vary.
|
| 46 |
+
|
| 47 |
+
Adding s2048 increased package size by 16,489,148 bytes (15.73 MiB, 2.96%).
|
| 48 |
+
Merely downloading a function does not load it. Applications should load larger
|
| 49 |
+
functions on demand and explicitly release idle functions; lazy loading without
|
| 50 |
+
eviction eventually retains the full set.
|
| 51 |
+
|
| 52 |
+
On the measured M2/macOS 27.2.1 run, s2048 alone used about **649 MiB wired neural memory**; s128+s2048 used **932 MiB**; all five recently active functions used **2,031 MiB**. These are separate from ordinary process footprint. Explicitly releasing s2048 removed its wired allocation immediately: zero wired when it was alone, or 283 MiB while s128 remained active. About 592 MiB remained reclaimable after releasing s2048; after releasing both functions, zero was wired and about 874 MiB remained reclaimable. Releasing a function therefore does not imply that every cached page disappears immediately. Older macOS 15 tests required explicit release rather than relying on idle reclaimability.
|
| 53 |
+
|
| 54 |
+
Disk weight sharing does not eliminate per-function neural allocations. Full-app
|
| 55 |
+
8 GiB safety with bucket eviction and llama.cpp fallback, and the exact
|
| 56 |
+
specialization-cache invalidation rules, remain unvalidated. First loading can
|
| 57 |
+
take minutes. This repository provides the converted model, not a production
|
| 58 |
+
memory/fallback implementation.
|
| 59 |
+
|
| 60 |
+
The model derives from Google DeepMind's Apache-2.0 checkpoint. The fixed-shape
|
| 61 |
+
forward adapts Transformers v5.19.0; overflow-safe normalization formulas adapt
|
| 62 |
+
the MIT-licensed [QVAC exporter](https://github.com/tetherto/qvac-fabric-llm.cpp/blob/2ed826df0c0eefc7135e9c3acc45aaa277f9b6ff/examples/embedding-coreml/export_coreml.py).
|
| 63 |
+
See `NOTICE`, `LICENSE` and `licenses/`. This is an independent conversion, not
|
| 64 |
+
an official Google release.
|
docs/usage.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Using the Core ML package
|
| 2 |
+
|
| 3 |
+
Use the included stock tokenizer. Prefix queries with
|
| 4 |
+
`task: search result | query: ` and documents with `title: none | text: `,
|
| 5 |
+
replacing `none` with the actual title when available.
|
| 6 |
+
|
| 7 |
+
Add BOS token 2 and EOS token 1 exactly once. Choose the smallest fitting length
|
| 8 |
+
from 128, 256, 512, 1024 and 2048, including the prompt and special tokens.
|
| 9 |
+
Right-pad with token 0. Inputs longer than 2048 require an application policy;
|
| 10 |
+
the package does not truncate them automatically.
|
| 11 |
+
|
| 12 |
+
For function `sL`, the contract is:
|
| 13 |
+
|
| 14 |
+
| Feature | Type and shape |
|
| 15 |
+
|---|---|
|
| 16 |
+
| `input_ids` | int32 `[1,L]` |
|
| 17 |
+
| `attention_mask` | float32 `[1,L]`; real tokens 1, padding 0 |
|
| 18 |
+
| `embedding` | float32 `[1,768]`, L2-normalized |
|
| 19 |
+
|
| 20 |
+
The masked mean includes prompts and special tokens. Output is the raw model
|
| 21 |
+
embedding; application head projection and Matryoshka truncation/renormalization
|
| 22 |
+
are downstream operations.
|
| 23 |
+
|
| 24 |
+
## Python example
|
| 25 |
+
|
| 26 |
+
On Apple Silicon macOS, install `coremltools==9.0`, `numpy` and `tokenizers`
|
| 27 |
+
in a Python 3.12 environment, then run from the parent of the download directory:
|
| 28 |
+
|
| 29 |
+
```python
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
import coremltools as ct
|
| 32 |
+
import numpy as np
|
| 33 |
+
from tokenizers import Tokenizer
|
| 34 |
+
|
| 35 |
+
root = Path("embeddinggemma-2-coreml")
|
| 36 |
+
tokenizer = Tokenizer.from_file(str(root / "tokenizer.json"))
|
| 37 |
+
text = "task: search result | query: How do bond prices respond to interest rates?"
|
| 38 |
+
ids = tokenizer.encode(text).ids
|
| 39 |
+
if not ids or ids[0] != 2:
|
| 40 |
+
ids.insert(0, 2)
|
| 41 |
+
if ids[-1] != 1:
|
| 42 |
+
ids.append(1)
|
| 43 |
+
|
| 44 |
+
length = next((n for n in (128, 256, 512, 1024, 2048) if len(ids) <= n), None)
|
| 45 |
+
if length is None:
|
| 46 |
+
raise ValueError("Input exceeds this package's 2048-token limit")
|
| 47 |
+
input_ids = np.zeros((1, length), dtype=np.int32)
|
| 48 |
+
attention_mask = np.zeros((1, length), dtype=np.float32)
|
| 49 |
+
input_ids[0, :len(ids)] = ids
|
| 50 |
+
attention_mask[0, :len(ids)] = 1
|
| 51 |
+
|
| 52 |
+
model = ct.models.MLModel(
|
| 53 |
+
str(root / "EmbeddingGemma2Owned.mlpackage"),
|
| 54 |
+
function_name=f"s{length}",
|
| 55 |
+
compute_units=ct.ComputeUnit.CPU_AND_NE,
|
| 56 |
+
)
|
| 57 |
+
embedding = model.predict({
|
| 58 |
+
"input_ids": input_ids,
|
| 59 |
+
"attention_mask": attention_mask,
|
| 60 |
+
})["embedding"][0]
|
| 61 |
+
assert embedding.shape == (768,) and np.isfinite(embedding).all()
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
Native inference uses Core ML and does not require Python. See the included
|
| 65 |
+
[Swift validator](../conversion/validate.swift) for a native example.
|
| 66 |
+
|
| 67 |
+
## Loading and memory
|
| 68 |
+
|
| 69 |
+
Compile the package on the deployment device and retain the compiled artifact
|
| 70 |
+
in an application-owned directory. Reuse it only for unchanged package bytes.
|
| 71 |
+
First specialization can take minutes, even though package compilation itself
|
| 72 |
+
is much shorter.
|
| 73 |
+
|
| 74 |
+
Load larger functions lazily and explicitly release unused models. Including a
|
| 75 |
+
function in the download does not load it, but retaining all five can consume
|
| 76 |
+
about 2 GiB of wired neural memory on the measured M2, beyond ordinary process
|
| 77 |
+
footprint. Releasing a model may leave reclaimable cache. Full-app 8 GB safety
|
| 78 |
+
and exact cache-invalidation rules are unmeasured.
|
| 79 |
+
|
| 80 |
+
`cpuAndNeuralEngine` permits CPU operations. The measured compute plans place
|
| 81 |
+
the transformer core on ANE; this is not an ANE-only execution guarantee.
|
| 82 |
+
See [measurements and limitations](technical-notes.md).
|
release-manifest.json
CHANGED
|
@@ -29,7 +29,9 @@
|
|
| 29 |
"converter": {
|
| 30 |
"repository": "anyproto/any",
|
| 31 |
"commit": "6424fab8cb6bd2874ce08e85d9081e24ff96902f",
|
| 32 |
-
"path": "scripts/embedbench/research/eg2_coreml"
|
|
|
|
|
|
|
| 33 |
},
|
| 34 |
"perFunctionConversionProvenance": {
|
| 35 |
"s128": {
|
|
@@ -221,8 +223,8 @@
|
|
| 221 |
"sha256": "75c1febc3806782ec847a8216b43b0dea15a57ee2f7c498523613397ab5b89dd"
|
| 222 |
},
|
| 223 |
"README.md": {
|
| 224 |
-
"bytes":
|
| 225 |
-
"sha256": "
|
| 226 |
},
|
| 227 |
"licenses/QVAC-MIT.txt": {
|
| 228 |
"bytes": 1078,
|
|
@@ -335,6 +337,95 @@
|
|
| 335 |
"validation/2026-11-16-five-bucket/warm.json": {
|
| 336 |
"bytes": 904,
|
| 337 |
"sha256": "f05b09e05e4a8b296f99dffb3b1cb848296e781ef690060be27f020dba4d5b63"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
}
|
| 339 |
-
}
|
|
|
|
| 340 |
}
|
|
|
|
| 29 |
"converter": {
|
| 30 |
"repository": "anyproto/any",
|
| 31 |
"commit": "6424fab8cb6bd2874ce08e85d9081e24ff96902f",
|
| 32 |
+
"path": "scripts/embedbench/research/eg2_coreml",
|
| 33 |
+
"bundledPath": "conversion",
|
| 34 |
+
"snapshotManifest": "conversion/source-snapshot.json"
|
| 35 |
},
|
| 36 |
"perFunctionConversionProvenance": {
|
| 37 |
"s128": {
|
|
|
|
| 223 |
"sha256": "75c1febc3806782ec847a8216b43b0dea15a57ee2f7c498523613397ab5b89dd"
|
| 224 |
},
|
| 225 |
"README.md": {
|
| 226 |
+
"bytes": 1781,
|
| 227 |
+
"sha256": "9f2e50a30d595ce16b13a1c35301df84caa664392af9886da34ba36b5eba83cd"
|
| 228 |
},
|
| 229 |
"licenses/QVAC-MIT.txt": {
|
| 230 |
"bytes": 1078,
|
|
|
|
| 337 |
"validation/2026-11-16-five-bucket/warm.json": {
|
| 338 |
"bytes": 904,
|
| 339 |
"sha256": "f05b09e05e4a8b296f99dffb3b1cb848296e781ef690060be27f020dba4d5b63"
|
| 340 |
+
},
|
| 341 |
+
"conversion/NOTICE": {
|
| 342 |
+
"bytes": 1651,
|
| 343 |
+
"sha256": "f37332d719ec2d4c5f93b1a7ce41c42017a1d7666f533f92d51b08d78f28b4bb"
|
| 344 |
+
},
|
| 345 |
+
"conversion/README.md": {
|
| 346 |
+
"bytes": 3083,
|
| 347 |
+
"sha256": "dd2d3f813fbc87dfe30f9e58c8294870feba95489d5b66138d9e7f18869e38a4"
|
| 348 |
+
},
|
| 349 |
+
"conversion/buckets.py": {
|
| 350 |
+
"bytes": 143,
|
| 351 |
+
"sha256": "ff2261663941716c9b6884bb11a9cbaa75d660d6c41061d03c9ce0a0c473656a"
|
| 352 |
+
},
|
| 353 |
+
"conversion/convert.py": {
|
| 354 |
+
"bytes": 3987,
|
| 355 |
+
"sha256": "432a26fb6bea8e7f943a783592c3f6c8bdecf56bce4d78c465d3f203c05ea5ca"
|
| 356 |
+
},
|
| 357 |
+
"conversion/eg2.py": {
|
| 358 |
+
"bytes": 5898,
|
| 359 |
+
"sha256": "773b5fd8a36388fd484d3113ac09d258c6136f1577141a29bc84c028c7bd8410"
|
| 360 |
+
},
|
| 361 |
+
"conversion/fetch_stock.py": {
|
| 362 |
+
"bytes": 1206,
|
| 363 |
+
"sha256": "cfb7629e2b6e0f3d847b2accf3b9ff56394d73740c5c31258e67ffca93f7b65b"
|
| 364 |
+
},
|
| 365 |
+
"conversion/fixtures/SHA256SUMS": {
|
| 366 |
+
"bytes": 78,
|
| 367 |
+
"sha256": "6ff7b41f33e878630ad7fbab24ae2eb0e8a888b120aca1ca4eb62be1b92945c6"
|
| 368 |
+
},
|
| 369 |
+
"conversion/fixtures/tokens.json.gz": {
|
| 370 |
+
"bytes": 1099170,
|
| 371 |
+
"sha256": "3319a38f4dafccde2ed4c0eec5d3445e7b25716c0befd59f0332e6eefd6a5cb1"
|
| 372 |
+
},
|
| 373 |
+
"conversion/parity.py": {
|
| 374 |
+
"bytes": 5803,
|
| 375 |
+
"sha256": "2c680ea416ddde788df7b68ef08d53a7565264a7224f6b04ba592fdbaa61b27c"
|
| 376 |
+
},
|
| 377 |
+
"conversion/provenance.py": {
|
| 378 |
+
"bytes": 673,
|
| 379 |
+
"sha256": "ab05275c8da35cd35847e14fac38c31aa3142adb2cfa0f351f3fbbebfd693330"
|
| 380 |
+
},
|
| 381 |
+
"conversion/requirements.lock": {
|
| 382 |
+
"bytes": 720,
|
| 383 |
+
"sha256": "448293cf8031689a3a57035f0620e375b6eb18f684b621ef35df556b51b51efd"
|
| 384 |
+
},
|
| 385 |
+
"conversion/source-manifest.json": {
|
| 386 |
+
"bytes": 672,
|
| 387 |
+
"sha256": "1cb8409645fbb2187f61781193a7fd89c53af34b0c2cd9d7d081715b674ce071"
|
| 388 |
+
},
|
| 389 |
+
"conversion/source-snapshot.json": {
|
| 390 |
+
"bytes": 3112,
|
| 391 |
+
"sha256": "cb12bc2fd35c70027b760a6db087b22035bb4cf3a2b18383b40751ad6ffc472f"
|
| 392 |
+
},
|
| 393 |
+
"conversion/upstream/modeling_embedding_gemma2.py": {
|
| 394 |
+
"bytes": 43805,
|
| 395 |
+
"sha256": "132d8714852fa8f0c376af797229e7b48fe94e0cf6cae6f6640681e934062923"
|
| 396 |
+
},
|
| 397 |
+
"conversion/upstream/qvac/LICENSE": {
|
| 398 |
+
"bytes": 1078,
|
| 399 |
+
"sha256": "94f29bbed6a22c35b992c5c6ebf0e7c92f13b836b90f36f461c9cf2f0f1d010d"
|
| 400 |
+
},
|
| 401 |
+
"conversion/upstream/qvac/README.md": {
|
| 402 |
+
"bytes": 14541,
|
| 403 |
+
"sha256": "b87b9d24bb4f27cf644022950d7070930b9fae625d1563cfff3d2838f494828a"
|
| 404 |
+
},
|
| 405 |
+
"conversion/upstream/qvac/export_coreml.py": {
|
| 406 |
+
"bytes": 15278,
|
| 407 |
+
"sha256": "5069938b448ae1469edea758140f4710883c1317b1f889778e24e57d07f0d638"
|
| 408 |
+
},
|
| 409 |
+
"conversion/upstream/qvac/requirements.txt": {
|
| 410 |
+
"bytes": 385,
|
| 411 |
+
"sha256": "b33c80ea0f097c533acb68b9d310d795cce7f262acae78ffd70a07fa71d029b9"
|
| 412 |
+
},
|
| 413 |
+
"conversion/upstream/transformers-LICENSE": {
|
| 414 |
+
"bytes": 11418,
|
| 415 |
+
"sha256": "77fd4710def9ec3c0f6225800e0235f15a425abd4a8b03559127fcd782612049"
|
| 416 |
+
},
|
| 417 |
+
"conversion/validate.swift": {
|
| 418 |
+
"bytes": 10307,
|
| 419 |
+
"sha256": "49c2540dcf1df164a259b820cf09f5adcfc70314984f1a2a8fe7c8b09fc32cad"
|
| 420 |
+
},
|
| 421 |
+
"docs/technical-notes.md": {
|
| 422 |
+
"bytes": 5162,
|
| 423 |
+
"sha256": "7404e73a675163ddf54221a32add5321daf2f4c84ebdab89065abf309413fe59"
|
| 424 |
+
},
|
| 425 |
+
"docs/usage.md": {
|
| 426 |
+
"bytes": 3182,
|
| 427 |
+
"sha256": "9be904fe551a4f2a8316920eb76c92880c59c224c98cfc43a7d40f74060c854f"
|
| 428 |
}
|
| 429 |
+
},
|
| 430 |
+
"documentationUpdated": "2026-11-17"
|
| 431 |
}
|