Re-export model.onnx and model_int8.onnx from model.safetensors; fix onnx_config and tokenizer_config

#3
Files changed (5) hide show
  1. export_onnx.py +386 -0
  2. model.onnx +2 -2
  3. model_int8.onnx +2 -2
  4. onnx_config.json +2 -2
  5. tokenizer_config.json +2 -2
export_onnx.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "pylate==1.6.0",
5
+ # "torch==2.11.0",
6
+ # "transformers==5.3.0",
7
+ # "sentence-transformers==5.3.0",
8
+ # "onnx==1.19.1",
9
+ # "onnxscript==0.7.2",
10
+ # "onnxruntime==1.23.2",
11
+ # "numpy==2.5.3",
12
+ # ]
13
+ # ///
14
+ """Export a PyLate ColBERT checkpoint to ONNX, quantize it to INT8, and validate both.
15
+
16
+ uv run export_onnx.py export --model-id lightonai/mLateOn --out-dir mlateon-onnx
17
+ uv run export_onnx.py quantize --model-id lightonai/mLateOn --out-dir mlateon-onnx
18
+ uv run export_onnx.py check --model-id lightonai/mLateOn --onnx mlateon-onnx/model.onnx
19
+
20
+ inputs : input_ids, attention_mask int64 [batch, sequence], [Q]/[D] prefix already inserted
21
+ output : output float32 [batch, sequence, dim], L2-normalized per token.
22
+ Padding positions are NOT zeroed; mask them with attention_mask.
23
+
24
+ Validation compares ONNX Runtime against PyLate's encode() on the same tokens and checks
25
+ three things, because per-token cosine alone does not catch a wrong checkpoint:
26
+ 1. per-token embeddings (max |diff| and cosine) for queries and documents,
27
+ 2. MaxSim scores on a query x document matrix, plus top-1 ranking agreement,
28
+ 3. sequence lengths from a single unpadded sentence up to the model's maximum, so a
29
+ sliding-window mask traced as a constant would be caught.
30
+ For the INT8 model the fp32 ONNX is also used as a reference, which separates export
31
+ error from quantization error.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import argparse
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+
43
+ # Short multilingual texts used for the embedding and MaxSim checks. The last one
44
+ # repeats a sentence 30 times and is numerically sensitive: float32 runs (PyLate's
45
+ # included) sit about 1e-5 away from float64 on it, versus about 1e-7 elsewhere.
46
+ DOCUMENTS = [
47
+ "Paris is the capital and most populous city of France.",
48
+ "Ein HNSW-Index baut einen hierarchischen Graphen für die schnelle Nachbarsuche auf.",
49
+ "Le Louvre est le musée le plus visité au monde.",
50
+ "El Volga es el río más largo de Europa.",
51
+ "Roma è la capitale d'Italia.",
52
+ "Lisboa é a capital de Portugal.",
53
+ "القاهرة هي عاصمة جمهورية مصر العربية.",
54
+ "def add(a, b):\n return a + b",
55
+ "東京は日本の首都です。",
56
+ "Late interaction models keep one vector per token and score with MaxSim. " * 30,
57
+ ]
58
+
59
+ # One query per document, in matching order, so the expected top-1 is the diagonal.
60
+ QUERIES = [
61
+ "What is the capital of France?",
62
+ "Wie funktioniert ein HNSW-Index?",
63
+ "Quel est le musée le plus visité du monde ?",
64
+ "¿Cuál es el río más largo de Europa?",
65
+ "Qual è la capitale d'Italia?",
66
+ "capital de Portugal",
67
+ "ما هي عاصمة مصر؟",
68
+ "python function that adds two numbers",
69
+ "日本の首都はどこですか",
70
+ "how do late interaction models score documents",
71
+ ]
72
+
73
+ # Word counts for the length sweep. Each is encoded alone (batch of one, no padding).
74
+ LENGTH_SWEEP_WORDS = [8, 100, 400, 1500, 3000, 6000]
75
+
76
+
77
+ # --------------------------------------------------------------------------- helpers
78
+
79
+
80
+ def log(msg: str = "") -> None:
81
+ print(msg, flush=True)
82
+
83
+
84
+ def load_reference(model_id: str, **model_kwargs):
85
+ from pylate import models
86
+
87
+ return models.ColBERT(model_id, device="cpu", model_kwargs=model_kwargs or None)
88
+
89
+
90
+ def load_session(path: Path):
91
+ import onnxruntime as ort
92
+
93
+ return ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
94
+
95
+
96
+ def run_onnx(session, features) -> list[np.ndarray]:
97
+ """Run the graph on PyLate-tokenized features and strip padding, as encode() does."""
98
+ output = session.run(
99
+ None,
100
+ {
101
+ "input_ids": features["input_ids"].numpy(),
102
+ "attention_mask": features["attention_mask"].numpy(),
103
+ },
104
+ )[0]
105
+ mask = features["attention_mask"].numpy().astype(bool)
106
+ return [output[i][mask[i]] for i in range(output.shape[0])]
107
+
108
+
109
+ def maxsim(queries: list[np.ndarray], documents: list[np.ndarray]) -> np.ndarray:
110
+ """ColBERT score matrix: sum over query tokens of the max dot product over doc tokens."""
111
+ scores = np.zeros((len(queries), len(documents)), dtype=np.float64)
112
+ for i, q in enumerate(queries):
113
+ for j, d in enumerate(documents):
114
+ scores[i, j] = (q.astype(np.float64) @ d.astype(np.float64).T).max(axis=1).sum()
115
+ return scores
116
+
117
+
118
+ def long_text(words: int) -> str:
119
+ base = (
120
+ "Late interaction retrieval keeps one embedding per token and scores a query "
121
+ "against a document with the MaxSim operator, which is cheap and robust. "
122
+ ).split()
123
+ return " ".join(base[i % len(base)] for i in range(words))
124
+
125
+
126
+ # --------------------------------------------------------------------------- checks
127
+
128
+
129
+ def compare_embeddings(expected, actual, label: str, tol: float | None):
130
+ """Per-text max |diff| and cosine. Returns (max_diff, mean_cos) over all tokens."""
131
+ all_cos, worst = [], 0.0
132
+ log(f"\n{label}:")
133
+ for i, (e, a) in enumerate(zip(expected, actual)):
134
+ if e.shape != a.shape:
135
+ raise SystemExit(f"shape mismatch on text {i}: {e.shape} vs {a.shape}")
136
+ max_diff = float(np.abs(e - a).max())
137
+ cos = (e * a).sum(-1) # both are unit vectors
138
+ all_cos.append(cos)
139
+ worst = max(worst, max_diff)
140
+ log(f" text {i}: tokens={len(e):5d} max|diff|={max_diff:.2e} cos min={cos.min():.7f} mean={cos.mean():.7f}")
141
+ all_cos = np.concatenate(all_cos)
142
+ log(f" all {len(all_cos)} tokens: max|diff|={worst:.2e} cos min={all_cos.min():.7f} mean={all_cos.mean():.7f}")
143
+ if tol is not None and worst >= tol:
144
+ raise SystemExit(f"FAIL {label}: max|diff| {worst:.2e} >= {tol:.0e}")
145
+ return worst, float(all_cos.mean())
146
+
147
+
148
+ def compare_maxsim(ref_q, ref_d, act_q, act_d, label: str, score_tol: float | None):
149
+ ref = maxsim(ref_q, ref_d)
150
+ act = maxsim(act_q, act_d)
151
+ diff = np.abs(ref - act)
152
+ top1_ref, top1_act = ref.argmax(1), act.argmax(1)
153
+ order_ref, order_act = ref.argsort(1), act.argsort(1)
154
+ log(f"\n{label}: MaxSim {ref.shape[0]}x{ref.shape[1]}")
155
+ log(
156
+ f" score max|diff|={diff.max():.2e} mean|diff|={diff.mean():.2e} score range=[{ref.min():.2f}, {ref.max():.2f}]"
157
+ )
158
+ log(
159
+ f" top-1 agreement: {(top1_ref == top1_act).mean():.0%} full-order agreement: {(order_ref == order_act).all(1).mean():.0%}"
160
+ )
161
+ log(f" reference top-1 hits diagonal: {(top1_ref == np.arange(len(top1_ref))).mean():.0%}")
162
+ if score_tol is not None and diff.max() >= score_tol:
163
+ raise SystemExit(f"FAIL {label}: MaxSim max|diff| {diff.max():.2e} >= {score_tol:.0e}")
164
+ if (top1_ref != top1_act).any():
165
+ raise SystemExit(f"FAIL {label}: top-1 ranking differs from reference")
166
+ return float(diff.max())
167
+
168
+
169
+ def length_sweep(reference, session, cos_tol: float | None, max_words: int):
170
+ """Encode single long documents, one at a time, so there is no padding at all.
171
+
172
+ Gated on cosine rather than absolute difference: past a few thousand tokens the
173
+ float32 reference itself drifts. On mLateOn at 6753 tokens, PyLate float32 is 1.7e-4
174
+ from a float64 run while the ONNX graph is 6e-6 from it, so a 1e-4 absolute gate
175
+ would fail the better of the two.
176
+ """
177
+ log("\nlength sweep (batch of one, no padding, is_query=False):")
178
+ worst = 0.0
179
+ for words in [w for w in LENGTH_SWEEP_WORDS if w <= max_words]:
180
+ text = long_text(words)
181
+ features = reference.tokenize([text], is_query=False)
182
+ n = int(features["attention_mask"].sum())
183
+ t0 = time.time()
184
+ expected = reference.encode([text], is_query=False, show_progress_bar=False)[0]
185
+ actual = run_onnx(session, features)[0]
186
+ max_diff = float(np.abs(expected - actual).max())
187
+ cos_min = float((expected * actual).sum(-1).min())
188
+ worst = max(worst, 1.0 - cos_min)
189
+ log(f" tokens={n:5d} max|diff|={max_diff:.2e} cos min={cos_min:.7f} ({time.time() - t0:.0f}s)")
190
+ if cos_tol is not None and worst >= cos_tol:
191
+ raise SystemExit(f"FAIL length sweep: 1 - cos min = {worst:.2e} >= {cos_tol:.0e}")
192
+ return worst
193
+
194
+
195
+ def check(
196
+ model_id: str,
197
+ onnx_path: Path,
198
+ tol: float | None,
199
+ score_tol: float | None,
200
+ max_words: int,
201
+ fp32_path: Path | None = None,
202
+ cos_tol: float | None = None,
203
+ ) -> dict:
204
+ """Validate onnx_path against PyLate (and optionally against a fp32 ONNX)."""
205
+ reference = load_reference(model_id)
206
+ session = load_session(onnx_path)
207
+ results = {}
208
+
209
+ enc = {}
210
+ for is_query, texts in ((False, DOCUMENTS), (True, QUERIES)):
211
+ kind = "queries" if is_query else "documents"
212
+ expected = reference.encode(texts, is_query=is_query, show_progress_bar=False)
213
+ actual = run_onnx(session, reference.tokenize(texts, is_query=is_query))
214
+ results[f"{kind}_max_diff"], results[f"{kind}_mean_cos"] = compare_embeddings(
215
+ expected, actual, f"{kind} vs PyLate", tol
216
+ )
217
+ enc[kind] = (expected, actual)
218
+
219
+ results["maxsim_max_diff"] = compare_maxsim(
220
+ enc["queries"][0],
221
+ enc["documents"][0],
222
+ enc["queries"][1],
223
+ enc["documents"][1],
224
+ "ONNX vs PyLate",
225
+ score_tol,
226
+ )
227
+ results["length_sweep_one_minus_cos"] = length_sweep(reference, session, cos_tol, max_words)
228
+
229
+ if fp32_path is not None:
230
+ fp32 = load_session(fp32_path)
231
+ for is_query, texts in ((False, DOCUMENTS), (True, QUERIES)):
232
+ kind = "queries" if is_query else "documents"
233
+ features = reference.tokenize(texts, is_query=is_query)
234
+ compare_embeddings(
235
+ run_onnx(fp32, features),
236
+ run_onnx(session, features),
237
+ f"{kind}: {onnx_path.name} vs {fp32_path.name}",
238
+ None,
239
+ )
240
+ return results
241
+
242
+
243
+ # --------------------------------------------------------------------------- export
244
+
245
+
246
+ def export(model_id: str, out: Path, opset: int, ir_version: int) -> None:
247
+ import onnx
248
+ import torch
249
+ from pylate import models
250
+
251
+ class ColBERTForONNX(torch.nn.Module):
252
+ """Transformer -> PyLate Dense layers -> L2 normalization, as in PyLate's encode()."""
253
+
254
+ def __init__(self, colbert: models.ColBERT):
255
+ super().__init__()
256
+ transformer, *dense_layers = colbert
257
+ self.transformer = transformer.auto_model
258
+ # Call the whole Dense modules, not their .linear: Dense.forward adds the
259
+ # residual projection when use_residual is set (layers 1 and 2 of mLateOn).
260
+ self.dense_layers = torch.nn.ModuleList(dense_layers)
261
+
262
+ def forward(self, input_ids, attention_mask):
263
+ hidden = self.transformer(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
264
+ features = {"token_embeddings": hidden}
265
+ for dense in self.dense_layers:
266
+ features = dense(features)
267
+ return torch.nn.functional.normalize(features["token_embeddings"], p=2, dim=-1)
268
+
269
+ # Eager attention exports to plain MatMul/Softmax ops.
270
+ colbert = load_reference(model_id, attn_implementation="eager")
271
+ local_window = getattr(colbert[0].auto_model.config, "local_attention", 0)
272
+
273
+ # Trace with a padded batch longer than the local attention window, so both the
274
+ # padding mask and the sliding-window mask are present in the graph.
275
+ example = colbert.tokenize([long_text(max(local_window, 128) * 2), "A short document."], is_query=False)
276
+ log(f"tracing with input_ids {tuple(example['input_ids'].shape)} (local window {local_window})")
277
+
278
+ out.parent.mkdir(parents=True, exist_ok=True)
279
+ with torch.no_grad():
280
+ torch.onnx.export(
281
+ ColBERTForONNX(colbert).eval(),
282
+ (example["input_ids"], example["attention_mask"]),
283
+ str(out),
284
+ input_names=["input_ids", "attention_mask"],
285
+ output_names=["output"],
286
+ dynamic_shapes=(
287
+ {0: "batch_size", 1: "sequence_length"},
288
+ {0: "batch_size", 1: "sequence_length"},
289
+ ),
290
+ opset_version=opset,
291
+ dynamo=True,
292
+ external_data=False, # single file like the previous model.onnx (protobuf limit is 2 GB)
293
+ optimize=True,
294
+ )
295
+
296
+ # The dynamo exporter stores Python stack traces (with local paths) in node metadata.
297
+ # Strip them, then lower the IR version so older onnxruntime releases can load the
298
+ # file. The full checker fails if anything else in the graph needs a newer IR.
299
+ model = onnx.load(str(out))
300
+ for node in model.graph.node:
301
+ del node.metadata_props[:]
302
+ del model.graph.metadata_props[:]
303
+ model.ir_version = ir_version
304
+ model.producer_name = "pylate-onnx-export"
305
+ onnx.save(model, str(out))
306
+ onnx.checker.check_model(str(out), full_check=True)
307
+ load_session(out) # must load with the pinned onnxruntime
308
+ log(f"saved {out} ({out.stat().st_size / 1e6:.0f} MB, opset {opset}, IR {ir_version})")
309
+
310
+
311
+ def quantize(fp32: Path, int8: Path, per_channel: bool, reduce_range: bool) -> None:
312
+ from onnxruntime.quantization import QuantType, quantize_dynamic
313
+
314
+ # Dynamic quantization: int8 weights, activations quantized per batch at runtime.
315
+ # Only MatMuls with constant weights are converted; attention score MatMuls stay fp32.
316
+ quantize_dynamic(
317
+ str(fp32),
318
+ str(int8),
319
+ weight_type=QuantType.QInt8,
320
+ per_channel=per_channel,
321
+ reduce_range=reduce_range,
322
+ )
323
+ log(f"saved {int8} ({int8.stat().st_size / 1e6:.0f} MB, per_channel={per_channel}, reduce_range={reduce_range})")
324
+
325
+
326
+ # --------------------------------------------------------------------------- cli
327
+
328
+
329
+ def main(argv=None) -> None:
330
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
331
+ common = argparse.ArgumentParser(add_help=False)
332
+ common.add_argument("--model-id", default="lightonai/mLateOn")
333
+ common.add_argument("--out-dir", type=Path, default=Path("mlateon-onnx"))
334
+ common.add_argument(
335
+ "--max-words",
336
+ type=int,
337
+ default=6000,
338
+ help="cap for the length sweep (6000 words is about 8k tokens; lower it for a quick run)",
339
+ )
340
+ sub = p.add_subparsers(dest="cmd", required=True)
341
+
342
+ e = sub.add_parser(
343
+ "export", parents=[common], help="export model.onnx from the safetensors checkpoint and validate it"
344
+ )
345
+ e.add_argument("--opset", type=int, default=18)
346
+ e.add_argument("--ir-version", type=int, default=9)
347
+ e.add_argument("--tol", type=float, default=1e-4, help="max |diff| per token embedding vs PyLate")
348
+ e.add_argument("--score-tol", type=float, default=1e-3, help="max |diff| on MaxSim scores vs PyLate")
349
+ e.add_argument("--cos-tol", type=float, default=1e-5, help="max (1 - cosine) per token in the length sweep")
350
+ e.add_argument("--no-check", action="store_true")
351
+
352
+ q = sub.add_parser("quantize", parents=[common], help="quantize model.onnx to model_int8.onnx and validate it")
353
+ q.add_argument("--per-tensor", action="store_true", help="per-tensor weight scales instead of per-channel")
354
+ q.add_argument(
355
+ "--reduce-range",
356
+ action="store_true",
357
+ help="7-bit weights; avoids saturation on x86 CPUs without VNNI at a small accuracy cost",
358
+ )
359
+ q.add_argument("--no-check", action="store_true")
360
+
361
+ c = sub.add_parser("check", parents=[common], help="validate an existing ONNX file against PyLate")
362
+ c.add_argument("--onnx", type=Path, required=True)
363
+ c.add_argument("--fp32", type=Path, default=None, help="also compare against this fp32 ONNX")
364
+ c.add_argument("--tol", type=float, default=None)
365
+ c.add_argument("--score-tol", type=float, default=None)
366
+ c.add_argument("--cos-tol", type=float, default=None)
367
+
368
+ a = p.parse_args(argv)
369
+ fp32, int8 = a.out_dir / "model.onnx", a.out_dir / "model_int8.onnx"
370
+
371
+ if a.cmd == "export":
372
+ export(a.model_id, fp32, a.opset, a.ir_version)
373
+ if not a.no_check:
374
+ check(a.model_id, fp32, a.tol, a.score_tol, a.max_words, cos_tol=a.cos_tol)
375
+ elif a.cmd == "quantize":
376
+ quantize(fp32, int8, per_channel=not a.per_tensor, reduce_range=a.reduce_range)
377
+ if not a.no_check:
378
+ # INT8 cannot match fp32 to 1e-4; the MaxSim top-1 check is the hard gate.
379
+ check(a.model_id, int8, None, None, a.max_words, fp32_path=fp32)
380
+ else:
381
+ check(a.model_id, a.onnx, a.tol, a.score_tol, a.max_words, fp32_path=a.fp32, cos_tol=a.cos_tol)
382
+ log("\nOK")
383
+
384
+
385
+ if __name__ == "__main__":
386
+ main(sys.argv[1:])
model.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c3c2be391b1b101273bab96c5f241b0b93922e39947d5ac6d3883b05cbcd2e2e
3
- size 1247529629
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ef72047e438bdb17993fd75fe68944bb91d6fd9208881c4ca638f0c337a4ca5
3
+ size 1247204767
model_int8.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:02260bc68c4d942a3a65b1b0624c11e69b71eeb0be1a0c280ee834b39d3d5b27
3
- size 312704983
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:470c17cd1a6bc2fe2553126f23694ba4b9f76c8c811b863c6fbfa65445a70ac3
3
+ size 312794488
onnx_config.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "model_type": "ColBERT",
3
- "model_name": "lightonai/LateOn-multilingual",
4
  "model_class": "ModernBertModel",
5
  "uses_token_type_ids": false,
6
  "query_prefix": "[Q] ",
@@ -16,4 +16,4 @@
16
  "query_prefix_id": 256000,
17
  "document_prefix_id": 256001,
18
  "do_lower_case": false
19
- }
 
1
  {
2
  "model_type": "ColBERT",
3
+ "model_name": "lightonai/mLateOn",
4
  "model_class": "ModernBertModel",
5
  "uses_token_type_ids": false,
6
  "query_prefix": "[Q] ",
 
16
  "query_prefix_id": 256000,
17
  "document_prefix_id": 256001,
18
  "do_lower_case": false
19
+ }
tokenizer_config.json CHANGED
@@ -6,12 +6,12 @@
6
  "eos_token": "<eos>",
7
  "is_local": true,
8
  "mask_token": "<mask>",
9
- "max_length": 299,
10
  "model_input_names": [
11
  "input_ids",
12
  "attention_mask"
13
  ],
14
- "model_max_length": 299,
15
  "pad_to_multiple_of": null,
16
  "pad_token": "<mask>",
17
  "pad_token_type_id": 0,
 
6
  "eos_token": "<eos>",
7
  "is_local": true,
8
  "mask_token": "<mask>",
9
+ "max_length": 8191,
10
  "model_input_names": [
11
  "input_ids",
12
  "attention_mask"
13
  ],
14
+ "model_max_length": 8191,
15
  "pad_to_multiple_of": null,
16
  "pad_token": "<mask>",
17
  "pad_token_type_id": 0,