nicolasembleton commited on
Commit
a4f5713
·
verified ·
1 Parent(s): 5e55e26

replace v1 export script with v2 exporter (pair reranker in graph)

Browse files
Files changed (1) hide show
  1. export_script.py +415 -344
export_script.py CHANGED
@@ -1,181 +1,303 @@
1
  #!/usr/bin/env python3
2
- """Export GLiNER 2.5 BoundaryExtractor to ONNX for onnxruntime-web / WebGPU.
3
 
4
- The graph is encoder + word/query gather + boundary start/end logits.
5
- Schema packing and span decode stay in the host (JS/Python), matching how
6
- GLiNER.js runs the original span models.
7
 
8
- ═══════════════════════════════════════════════════════════════════════════
9
- TWO MODES: LOCAL (direct) and MODAL (remote CPU)
10
- ═══════════════════════════════════════════════════════════════════════════
 
 
 
11
 
12
- ── LOCAL (no Modal, runs on your machine) ──────────────────────────────
 
13
 
14
- Requires Python 3.11+ and these packages:
15
- pip install "torch==2.5.1" "transformers>=4.46.0" "huggingface_hub[hf_transfer]" \
16
- onnx onnxruntime safetensors sentencepiece tokenizers "gliner2[local]"
17
 
18
- Set your HF token if uploading:
19
- export HF_TOKEN=hf_xxx # or `hf auth login`
 
20
 
21
- Run:
22
- python convert_gliner25_onnx.py --model-id fastino/gliner2.5-small-v1
23
- python convert_gliner25_onnx.py --model-id fastino/gliner2.5-base-v1 --upload --upload-prefix nicolasembleton
24
- python convert_gliner25_onnx.py --model-id fastino/gliner2.5-multi-v1 --seq-len 256 --n-queries 8
25
-
26
- Output appears at ./output/{slug}-onnx/ with:
27
- onnx/model.onnx — the graph
28
- tokenizer.json + config — for host-side schema packing
29
- export_config.json — input/output contract
30
- README.md — Hub model card with YAML
31
-
32
- ── MODAL (remote CPU, no local torch install) ──────────────────────────
33
-
34
- Requires the `modal` CLI authenticated (`modal token new`).
35
- Also requires a Modal Secret named `huggingface-token` with key `HF_TOKEN`
36
- (your Hub write token). Create it once:
37
- modal secret create huggingface-token HF_TOKEN=hf_xxx
38
-
39
- The Modal image installs the same packages as above inside a Debian-slim
40
- container (python 3.11). 4 CPU / 16 GB RAM is enough for all GLiNER 2.5
41
- checkpoints (74M–287M params). A Modal Volume (`gliner25-onnx`) caches
42
- outputs between runs but is deleted after upload to stop storage cost.
43
-
44
- Run:
45
- modal run convert_gliner25_onnx.py --model-id fastino/gliner2.5-small-v1 \
46
- --upload --upload-prefix nicolasembleton
47
-
48
- When run via `modal run`, the `@app.local_entrypoint` fires, which calls
49
- `export_one.remote(...)` — the function executes inside the Modal container.
50
- When run via `python convert_gliner25_onnx.py`, the `__main__` block calls
51
- `export_one(...)` directly in the current process.
52
-
53
- ── KEY IMPLEMENTATION NOTES (read before modifying) ────────────────────
54
-
55
- 1. EyeLike fix: BoundaryAttentionBlock.forward uses torch.eye() + SDPA
56
- which exports to ONNX as an EyeLike op that onnxruntime-web does not
57
- implement. We monkey-patch each attention block's forward with a
58
- matmul/softmax version that produces identical outputs but uses only
59
- standard ONNX ops. This is the single most important patch in the file.
60
-
61
- 2. export_mode="vectorized": sets the boundary proposer to materialize a
62
- single full-width block instead of a Python block loop. Needed for
63
- graph export; does not change the logits head.
64
-
65
- 3. The Wrapper class only wraps encoder + boundary_encoder +
66
- boundary_query_head. It does NOT wrap the proposer/scorer/pool —
67
- those are Python-side post-processing. The ONNX graph outputs raw
68
- start_logits and end_logits. The host (JS/Python) does top-k
69
- selection and span pairing from those logits.
70
-
71
- 4. Dynamic axes on batch, tokens, words, and queries so the graph
72
- handles arbitrary input lengths at inference time.
73
-
74
- 5. Opset 17 is the minimum that supports all ops used here. WebGPU
75
- via onnxruntime-web supports opset 17+.
76
-
77
- 6. ORT validation: we catch ORT exceptions and re-raise as RuntimeError
78
- because Modal can't deserialize onnxruntime-specific exception types
79
- in the local environment. The RMSE check confirms the ONNX graph
80
- matches torch output to ~1e-6.
81
-
82
- ═══════════════════════════════════════════════════════════════════════════
83
  """
84
-
85
  from __future__ import annotations
86
 
87
  import argparse
88
  import json
89
- import os
90
  import shutil
 
91
  from pathlib import Path
92
 
93
- # ── Modal setup (imported lazily so local mode works without modal) ──────
94
- try:
95
- import modal
96
- _HAS_MODAL = True
97
- except ImportError:
98
- modal = None
99
- _HAS_MODAL = False
100
-
101
- VOLUME_NAME = "gliner25-onnx"
102
- # Inside Modal, outputs go to a mounted Volume. Locally, to ./output/.
103
- _MODAL_OUT_DIR = "/data/output"
104
- _LOCAL_OUT_DIR = str(Path(__file__).resolve().parent / "output")
105
-
106
- # ── Modal image + app (only built if modal is imported) ──────────────────
107
- if _HAS_MODAL:
108
- image = (
109
- modal.Image.debian_slim(python_version="3.11")
110
- .pip_install(
111
- "torch==2.5.1",
112
- "transformers>=4.46.0",
113
- "huggingface_hub[hf_transfer]",
114
- "onnx",
115
- "onnxruntime",
116
- "safetensors",
117
- "sentencepiece",
118
- "tokenizers",
119
- "gliner2[local]",
120
- )
121
- .env({"HF_HUB_ENABLE_HF_TRANSFER": "1", "TOKENIZERS_PARALLELISM": "false"})
122
- )
123
- app = modal.App("gliner25-onnx")
124
- vol = modal.Volume.from_name(VOLUME_NAME, create_if_missing=True)
125
- else:
126
- image = None
127
- app = None
128
- vol = None
129
-
130
-
131
- def export_one(
132
- model_id: str,
133
- upload_prefix: str = "",
134
- seq_len: int = 128,
135
- n_queries: int = 4,
136
- n_words: int = 48,
137
- out_dir: str | None = None,
138
- upload: bool = False,
139
- ):
140
- """Export a single GLiNER 2.5 model to ONNX.
141
-
142
- Args:
143
- model_id: HuggingFace model ID (e.g. fastino/gliner2.5-small-v1)
144
- upload_prefix: HF namespace to upload to (e.g. nicolasembleton). Empty = skip upload.
145
- seq_len: dummy sequence length for the ONNX trace (dynamic at runtime)
146
- n_queries: dummy number of entity-type queries (dynamic at runtime)
147
- n_words: dummy number of word positions (dynamic at runtime)
148
- out_dir: output directory. Defaults to ./output/ locally, /data/output/ on Modal.
149
- upload: if True and upload_prefix is set, upload to HF Hub (requires HF_TOKEN)
150
-
151
- Returns:
152
- dict with repo URL, ONNX file size in MB, and RMSE vs torch
153
  """
154
- import torch
155
- import torch.nn as nn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- if out_dir is None:
158
- out_dir = _MODAL_OUT_DIR if _HAS_MODAL and modal.App.current() else _LOCAL_OUT_DIR
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- from gliner2 import AutoExtractor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
- print(f"Loading {model_id} ...")
163
- model = AutoExtractor.from_pretrained(model_id, map_location="cpu")
164
- model.eval()
165
 
166
- # Graph-friendly proposer (no Python block loop). Does not change logits head.
 
 
 
 
 
167
  try:
168
- model.boundary_head.boundary_proposer.settings.export_mode = "vectorized"
169
- except Exception as e:
170
- print(f" [warn] could not set export_mode: {e}")
 
 
 
 
 
171
 
172
  encoder = model.encoder
173
  encoder.eval()
174
- hidden = encoder.config.hidden_size
 
175
 
176
- # ── EyeLike fix: replace torch.eye + SDPA with matmul attention ───────
177
  def _exportable_attn_forward(block, states, mask):
178
- """matmul/softmax attention — avoids EyeLike op unsupported by ORT-web."""
179
  b, n, d = states.shape
180
  qkv = block.qkv_projection(block.norm(states)).view(b, n, 3, block.num_heads, block.head_dim)
181
  query, key, value = qkv.permute(2, 0, 3, 1, 4)
@@ -196,14 +318,13 @@ def export_one(
196
  return (states + update) * mask.unsqueeze(-1).to(states.dtype)
197
 
198
  class Wrapper(nn.Module):
199
- """Encoder + boundary start/end logits. No proposer/scorer (host-side)."""
200
 
201
  def __init__(self, extractor):
202
  super().__init__()
203
  self.encoder = extractor.encoder
204
- self.boundary_encoder = extractor.boundary_head.boundary_encoder
205
- self.boundary_query_head = extractor.boundary_head.boundary_query_head
206
- for block in self.boundary_encoder.attention_blocks:
207
  block.forward = lambda states, mask, _b=block: _exportable_attn_forward(_b, states, mask)
208
 
209
  def _gather(self, hidden_states, indices, mask):
@@ -212,25 +333,54 @@ def export_one(
212
  states = hidden_states.gather(1, safe.unsqueeze(-1).expand(-1, -1, h))
213
  return states * mask.unsqueeze(-1).to(states.dtype)
214
 
215
- def forward(self, input_ids, attention_mask, text_word_indices, text_word_mask, query_marker_indices, query_marker_mask):
 
216
  hidden_states = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
217
  text_states = self._gather(hidden_states, text_word_indices, text_word_mask)
218
  query_states = self._gather(hidden_states, query_marker_indices, query_marker_mask)
219
- encoding = self.boundary_encoder(text_states, text_word_mask.bool())
220
- marginals = self.boundary_query_head(
221
- encoding.states,
222
- encoding.mask,
223
- text_states,
224
- text_word_mask.bool(),
225
- query_states,
226
- query_marker_mask.bool(),
227
  )
228
- return marginals.start_logits, marginals.end_logits
 
 
 
 
 
 
 
 
 
 
 
229
 
230
- wrapper = Wrapper(model).eval()
231
 
232
- # ── Dummy inputs for tracing ─────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  b, t, l, q = 1, seq_len, n_words, n_queries
 
 
 
 
 
 
 
234
  dummy = {
235
  "input_ids": torch.ones(b, t, dtype=torch.long),
236
  "attention_mask": torch.ones(b, t, dtype=torch.long),
@@ -241,227 +391,148 @@ def export_one(
241
  }
242
 
243
  with torch.no_grad():
244
- s, e = wrapper(*dummy.values())
245
- print(f" dummy start {tuple(s.shape)} end {tuple(e.shape)}")
246
 
247
- # ── Export ────────────────────────────────────────────────────────────
248
  slug = model_id.split("/")[-1]
249
  out = Path(out_dir) / f"{slug}-onnx"
250
  if out.exists():
251
  shutil.rmtree(out)
252
  onnx_dir = out / "onnx"
253
  onnx_dir.mkdir(parents=True)
254
- onnx_path = onnx_dir / "model.onnx"
255
 
256
  input_names = list(dummy.keys())
 
257
  dynamic_axes = {
258
- "input_ids": {0: "batch", 1: "tokens"},
259
- "attention_mask": {0: "batch", 1: "tokens"},
260
- "text_word_indices": {0: "batch", 1: "words"},
261
- "text_word_mask": {0: "batch", 1: "words"},
262
- "query_marker_indices": {0: "batch", 1: "queries"},
263
- "query_marker_mask": {0: "batch", 1: "queries"},
264
  "start_logits": {0: "batch", 1: "queries", 2: "boundaries"},
265
  "end_logits": {0: "batch", 1: "queries", 2: "boundaries"},
 
 
 
266
  }
267
 
268
  print(" torch.onnx.export ...")
269
  torch.onnx.export(
270
  wrapper,
271
  tuple(dummy[k] for k in input_names),
272
- str(onnx_path),
273
  input_names=input_names,
274
- output_names=["start_logits", "end_logits"],
275
  dynamic_axes=dynamic_axes,
276
  opset_version=17,
277
  do_constant_folding=True,
278
  )
279
- size_mb = onnx_path.stat().st_size / 1e6
280
- print(f" wrote {onnx_path} ({size_mb:.1f} MB)")
281
 
282
- # ── Validate with onnxruntime ────────────────────────────────────────
283
  import onnx
284
  import onnxruntime as ort
285
 
286
- onnx.checker.check_model(str(onnx_path))
287
- try:
288
- sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
289
- feeds = {k: v.numpy() for k, v in dummy.items()}
290
- outs = sess.run(None, feeds)
291
- print(f" ort start {outs[0].shape} end {outs[1].shape}")
292
- err = float(((outs[0] - s.numpy()) ** 2).mean() ** 0.5)
293
- print(f" start-logit RMSE vs torch: {err:.6f}")
294
- except Exception as e:
295
- # Re-raise as RuntimeError: Modal can't deserialize ORT exception types locally
296
- raise RuntimeError(f"ORT load/run failed: {type(e).__name__}: {e}") from None
297
-
298
- # ── Save tokenizer + config for host-side packing ────────────────────
299
- tok = model.processor.tokenizer
300
- tok.save_pretrained(str(out))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  cfg = {
302
  "architecture": "boundary",
 
303
  "base_model": model_id,
304
- "hidden_size": hidden,
 
305
  "opset": 17,
306
  "inputs": input_names,
307
- "outputs": ["start_logits", "end_logits"],
308
- "notes": "Host must pack schema markers into input_ids and pass word/query gather indices. Decode spans from start/end logits in JS.",
309
  }
310
  (out / "export_config.json").write_text(json.dumps(cfg, indent=2))
 
 
311
 
312
- readme = f"""---
313
- library_name: onnx
314
- license: apache-2.0
315
- pipeline_tag: token-classification
316
- base_model: {model_id}
317
- tags:
318
- - onnx
319
- - gliner2
320
- - boundary
321
- - webgpu
322
- - token-classification
323
- ---
324
-
325
- # {slug}-onnx
326
 
327
- ONNX export of [{model_id}](https://huggingface.co/{model_id}) (GLiNER 2.5 `BoundaryExtractor`) for onnxruntime / WebGPU.
328
-
329
- This is **not** a drop-in `AutoExtractor` graph. The ONNX file runs:
330
-
331
- 1. DeBERTa encoder on packed `input_ids`
332
- 2. Gather of word states and query-marker states
333
- 3. Boundary start/end logits `[batch, queries, words+1]`
334
-
335
- Schema packing (entity-type markers) and span decode stay on the host, same split as GLiNER.js.
336
-
337
- ## Inputs
338
-
339
- | Name | Shape | Dtype |
340
- |------|-------|-------|
341
- | input_ids | [B, T] | int64 |
342
- | attention_mask | [B, T] | int64 |
343
- | text_word_indices | [B, L] | int64 |
344
- | text_word_mask | [B, L] | float32 |
345
- | query_marker_indices | [B, Q] | int64 |
346
- | query_marker_mask | [B, Q] | float32 |
347
-
348
- ## Outputs
349
-
350
- | Name | Shape |
351
- |------|-------|
352
- | start_logits | [B, Q, L+1] |
353
- | end_logits | [B, Q, L+1] |
354
-
355
- ## Python check
356
-
357
- ```python
358
- import onnxruntime as ort
359
- sess = ort.InferenceSession("onnx/model.onnx")
360
- ```
361
-
362
- WebGPU: load `onnx/model.onnx` with `onnxruntime-web` `webgpu` execution provider. Int64 inputs are required; some browsers need the WASM backend as fallback.
363
- """
364
- (out / "README.md").write_text(readme)
365
-
366
- # ── Commit volume if on Modal ────────────────────────────────────────
367
- if _HAS_MODAL and vol is not None:
368
- vol.commit()
369
-
370
- # ── Upload to HuggingFace Hub ────────────────────────────────────────
371
- if upload and upload_prefix:
372
- from huggingface_hub import HfApi
373
-
374
- repo = f"{upload_prefix}/{slug}-onnx"
375
- token = os.environ.get("HF_TOKEN")
376
- if not token:
377
- raise RuntimeError("HF_TOKEN missing — set it or pass --no-upload")
378
- api = HfApi(token=token)
379
- api.create_repo(repo_id=repo, repo_type="model", exist_ok=True)
380
- print(f" uploading → {repo}")
381
- api.upload_folder(folder_path=str(out), repo_id=repo, repo_type="model")
382
- print(f" done https://huggingface.co/{repo}")
383
- return {"repo": repo, "onnx_mb": size_mb, "rmse": err}
384
- else:
385
- print(f" output at {out} (no upload)")
386
- return {"repo": None, "onnx_mb": size_mb, "rmse": err}
387
-
388
-
389
- # ═══ Modal entrypoint ═════════════════════════════════════════════════════
390
- if _HAS_MODAL:
391
- @app.function(
392
- image=image,
393
- volumes={"/data": vol},
394
- secrets=[modal.Secret.from_name("huggingface-token")],
395
- cpu=4,
396
- memory=16384,
397
- timeout=3600,
398
- )
399
- def _export_remote(model_id, upload_prefix, seq_len, n_queries, n_words):
400
- return export_one(
401
- model_id=model_id,
402
- upload_prefix=upload_prefix,
403
- seq_len=seq_len,
404
- n_queries=n_queries,
405
- n_words=n_words,
406
- out_dir=_MODAL_OUT_DIR,
407
- upload=True,
408
- )
409
-
410
- @app.local_entrypoint()
411
- def main(
412
- model_id: str = "fastino/gliner2.5-small-v1",
413
- upload_prefix: str = "nicolasembleton",
414
- seq_len: int = 128,
415
- n_queries: int = 4,
416
- n_words: int = 48,
417
- ):
418
- """Modal entrypoint: `modal run convert_gliner25_onnx.py --model-id ...`"""
419
- result = _export_remote.remote(
420
- model_id=model_id,
421
- upload_prefix=upload_prefix,
422
- seq_len=seq_len,
423
- n_queries=n_queries,
424
- n_words=n_words,
425
- )
426
- print(result)
427
-
428
-
429
- # ═══ Local CLI entrypoint ════════════════════════════════════════════════
430
- # Works whether or not modal is installed. When modal is installed, the
431
- # @app.local_entrypoint above handles `modal run ...`. For local execution
432
- # use: `python convert_gliner25_onnx.py --model-id ... --local`
433
- # The --local flag forces the local codepath even when modal is present.
434
- def _local_cli():
435
- parser = argparse.ArgumentParser(description="Export GLiNER 2.5 to ONNX (local mode)")
436
- parser.add_argument("--model-id", required=True, help="HuggingFace model ID")
437
- parser.add_argument("--upload-prefix", default="", help="HF namespace to upload to")
438
- parser.add_argument("--upload", action="store_true", help="Upload to HF Hub")
439
  parser.add_argument("--seq-len", type=int, default=128)
440
  parser.add_argument("--n-queries", type=int, default=4)
441
  parser.add_argument("--n-words", type=int, default=48)
442
- parser.add_argument("--out-dir", default=None, help="Output directory (default: ./output/)")
443
  args = parser.parse_args()
444
- result = export_one(
445
  model_id=args.model_id,
446
- upload_prefix=args.upload_prefix,
447
  seq_len=args.seq_len,
448
  n_queries=args.n_queries,
449
  n_words=args.n_words,
450
- out_dir=args.out_dir,
451
- upload=args.upload,
452
  )
453
- print(result)
454
 
455
 
456
  if __name__ == "__main__":
457
- # If --local is in argv, strip it and run locally regardless of modal.
458
- import sys
459
- if "--local" in sys.argv:
460
- sys.argv.remove("--local")
461
- _local_cli()
462
- elif _HAS_MODAL:
463
- # modal run will pick up @app.local_entrypoint; if python was used
464
- # directly without --local, fall back to local CLI too.
465
- _local_cli()
466
- else:
467
- _local_cli()
 
1
  #!/usr/bin/env python3
2
+ """Export GLiNER 2.5 BoundaryExtractor to ONNX WITH the pair reranker (v2).
3
 
4
+ Same six inputs as the v1 export. The graph now includes the sparse
5
+ proposer + pair scorer (vectorized mode), so outputs are:
 
6
 
7
+ start_logits [B, Q, L+1] boundary marginals (same as v1)
8
+ end_logits [B, Q, L+1]
9
+ pair_indices [B, Q, C, 2] half-open word-boundary candidate spans
10
+ pair_logits [B, Q, C] reranked span scores (apply sigmoid +
11
+ pair_temperature in the host)
12
+ pair_valid [B, Q, C] bool (exported as uint8 for ONNX)
13
 
14
+ C = candidate budget from the checkpoint's BoundaryHeadSettings
15
+ (default 64; fixed at export time, padded dynamically at runtime).
16
 
17
+ Requires local venv: .venv-export (torch 2.5.1, gliner2[local], onnx).
 
 
18
 
19
+ Usage:
20
+ .venv-export/bin/python export_v2_pairs.py --model-id fastino/gliner2.5-small-v1 \
21
+ --out-dir ./output-v2 [--upload --upload-prefix nicolasembleton --repo-suffix "-onnx-v2"]
22
 
23
+ Validation baked in: ORT outputs vs torch wrapper outputs (RMSE per tensor),
24
+ plus a decode-parity check against AutoExtractor.extract_entities on the
25
+ model-card sentence when --parity is passed (requires the packed inputs to be
26
+ reproduced exactly; we reuse the model's own processor for that).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  """
 
28
  from __future__ import annotations
29
 
30
  import argparse
31
  import json
 
32
  import shutil
33
+ import sys
34
  from pathlib import Path
35
 
36
+ import torch
37
+ import torch.nn as nn
38
+
39
+
40
+ def _patch_proposer_for_export():
41
+ """Replace sort/argsort/scatter_reduce proposer internals with ONNX-safe topk versions.
42
+
43
+ torch.sort(stable=True) has no ONNX symbolic ("Sort, Out parameter is not
44
+ supported") and assemble_candidates uses scatter_reduce (opset>=18). We
45
+ substitute topk everywhere. Consequences, both benign for inference:
46
+ - tie order may differ from the Python path (affects only which duplicate
47
+ copy survives), and
48
+ - duplicate (start,end) pairs can occupy multiple candidate slots; the
49
+ host dedupes by (start,end) when iterating candidates.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  """
51
+ from gliner2.models.boundary import proposal as P
52
+
53
+ def select_top_boundaries(logits, valid_mask, k):
54
+ # Pad with k invalid sentinel slots before topk: the traced graph has
55
+ # a CONSTANT k, but runtime inputs can have fewer boundaries than k
56
+ # (ORT TopK errors when k > axis dim). Fake slots select last and are
57
+ # zeroed via valid=False — same semantics as upstream invalid slots.
58
+ pad_shape = list(logits.shape)
59
+ pad_shape[-1] = k
60
+ pad_logits = logits.new_full(pad_shape, -1.0e4)
61
+ pad_valid = torch.zeros(pad_shape, dtype=valid_mask.dtype, device=valid_mask.device)
62
+ masked = logits.masked_fill(~valid_mask, -1.0e4)
63
+ padded = torch.cat([masked, pad_logits], dim=-1)
64
+ padded_valid = torch.cat([valid_mask, pad_valid], dim=-1)
65
+ scores, idx = torch.topk(padded, k, dim=-1)
66
+ valid = torch.gather(padded_valid, -1, idx)
67
+ scores = torch.where(valid, scores, torch.zeros_like(scores))
68
+ idx = torch.where(valid, idx, torch.zeros_like(idx))
69
+ return scores, idx, valid
70
+
71
+ def merge_running_topk(current_scores, current_indices, block_scores, block_indices, k):
72
+ scores = torch.cat([current_scores, block_scores], dim=-1)
73
+ indices = torch.cat([current_indices, block_indices], dim=-1)
74
+ take = min(k, scores.shape[-1])
75
+ top_scores, order = torch.topk(scores, take, dim=-1)
76
+ top_indices = torch.gather(indices, -1, order)
77
+ return top_scores, top_indices
78
+
79
+ def assemble_candidates(pair_starts, pair_ends, pair_scores, pair_valid, query_mask, *,
80
+ capacity, n_boundaries, gold_pairs=None, gold_mask=None,
81
+ gold_injection_prob=1.0, generator=None):
82
+ pre_valid = pair_valid & query_mask.unsqueeze(-1)
83
+ floor = -1.0e4
84
+ scores = torch.where(pre_valid, pair_scores, torch.full_like(pair_scores, floor))
85
+ take = min(capacity, scores.shape[-1])
86
+ _, order = torch.topk(scores, take, dim=-1)
87
+ starts = torch.gather(pair_starts, -1, order)
88
+ ends = torch.gather(pair_ends, -1, order)
89
+ selected_valid = torch.gather(pre_valid, -1, order)
90
+ indices = torch.stack((starts, ends), dim=-1)
91
+ indices = torch.where(selected_valid.unsqueeze(-1), indices, torch.zeros_like(indices))
92
+ if take < capacity:
93
+ pad = capacity - take
94
+ indices = torch.nn.functional.pad(indices, (0, 0, 0, pad))
95
+ selected_valid = torch.nn.functional.pad(selected_valid, (0, pad), value=False)
96
+ pre_keys = pair_starts * n_boundaries + pair_ends
97
+ return indices, selected_valid, torch.zeros_like(selected_valid), pre_keys, pre_valid
98
+
99
+ P.select_top_boundaries = select_top_boundaries
100
+ P.merge_running_topk = merge_running_topk
101
+ P.assemble_candidates = assemble_candidates
102
+ # pool.py binds select_top_boundaries at import time (from ... import),
103
+ # so it needs the patched name in its own namespace as well.
104
+ from gliner2.models.boundary import pool as Pool
105
+
106
+ Pool.select_top_boundaries = select_top_boundaries
107
+ Pool.merge_running_topk = merge_running_topk
108
+
109
+ # _deduplicate_pool: replace stable-sort dedup with topk selection.
110
+ # Duplicates may occupy extra slots; identical (start,end) keys produce
111
+ # identical pair_logits, so the decoded span set is unchanged (the host
112
+ # dedupes by (start,end) when consuming candidates).
113
+ def _deduplicate_pool_export(keys, scores, valid, capacity, n_boundaries):
114
+ # Same constant-k padding trick: pad scores/keys/valid by `capacity`
115
+ # sentinel slots so topk(capacity) never exceeds the axis dim and the
116
+ # output is always exactly `capacity` wide (fixed C for the host).
117
+ floor = -1.0e4
118
+ scores = torch.where(valid, scores, torch.full_like(scores, floor))
119
+ pad_shape = list(scores.shape)
120
+ pad_shape[-1] = capacity
121
+ pad_scores = scores.new_full(pad_shape, floor)
122
+ pad_keys = keys.new_zeros(pad_shape)
123
+ pad_valid = torch.zeros(pad_shape, dtype=valid.dtype, device=valid.device)
124
+ scores_p = torch.cat([scores, pad_scores], -1)
125
+ keys_p = torch.cat([keys, pad_keys], -1)
126
+ valid_p = torch.cat([valid, pad_valid], -1)
127
+ _, order = torch.topk(scores_p, capacity, dim=-1)
128
+ selected_keys = keys_p.gather(-1, order)
129
+ selected_valid = valid_p.gather(-1, order)
130
+ return selected_keys, selected_valid
131
+
132
+ Pool._deduplicate_pool = _deduplicate_pool_export
133
+
134
+ # DocumentCandidatePool.forward: the per-query quota ranking uses
135
+ # torch.argsort inline. Replace forward with the inference-only copy
136
+ # that uses topk (identical selection up to exact ties).
137
+ import math as _math
138
+ from gliner2.models.boundary.indexing import gather_rows as _gather_rows
139
+ from gliner2.models.boundary.constants import MASK_LOGIT as _MASK
140
+ from gliner2.models.boundary.proposal import ( # patched topk versions
141
+ select_top_boundaries as _select_top,
142
+ )
143
 
144
+ def _pool_forward_export(
145
+ self,
146
+ boundary_states, # [B,N,D]
147
+ boundary_mask, # [B,N]
148
+ query_mask, # [B,Q]
149
+ start_logits, # [B,Q,N]
150
+ end_logits, # [B,Q,N]
151
+ *,
152
+ gold_pairs=None,
153
+ gold_mask=None,
154
+ gold_injection_prob=1.0,
155
+ return_stats=False,
156
+ generator=None,
157
+ ):
158
+ if gold_pairs is not None or return_stats:
159
+ raise RuntimeError("export pool forward supports inference only")
160
+ from gliner2.models.boundary.pool import PooledCandidates
161
+
162
+ b, n, d = boundary_states.shape
163
+ q = query_mask.shape[1]
164
+ floor = torch.full_like(start_logits, _MASK)
165
+ q_boundary = boundary_mask.unsqueeze(1) & query_mask.unsqueeze(-1)
166
+ union_start = torch.where(q_boundary, start_logits, floor).amax(1)
167
+ union_end = torch.where(q_boundary, end_logits, floor).amax(1)
168
+ union_valid = boundary_mask & query_mask.any(-1, keepdim=True)
169
+
170
+ _, starts, starts_valid = _select_top(
171
+ union_start.unsqueeze(1), union_valid.unsqueeze(1), self.pool_boundary_top_k,
172
+ )
173
+ _, ends, ends_valid = _select_top(
174
+ union_end.unsqueeze(1), union_valid.unsqueeze(1), self.pool_boundary_top_k,
175
+ )
176
+ starts = starts[:, 0]
177
+ ends = ends[:, 0]
178
+ starts_valid = starts_valid[:, 0]
179
+ ends_valid = ends_valid[:, 0]
180
+ ks, ke = starts.shape[1], ends.shape[1]
181
+ pair_s = starts.unsqueeze(-1).expand(b, ks, ke).reshape(b, -1)
182
+ pair_e = ends.unsqueeze(1).expand(b, ks, ke).reshape(b, -1)
183
+ pair_valid = (
184
+ starts_valid.unsqueeze(-1)
185
+ & ends_valid.unsqueeze(1)
186
+ & (ends.unsqueeze(1) > starts.unsqueeze(-1))
187
+ ).reshape(b, -1)
188
+
189
+ start_all = self.start_projection(boundary_states)
190
+ end_all = self.end_projection(boundary_states)
191
+ selected_start = _gather_rows(start_all, pair_s)
192
+ selected_end = _gather_rows(end_all, pair_e)
193
+ compat = (selected_start * selected_end).sum(-1) / _math.sqrt(d)
194
+ union_pair_score = (
195
+ compat
196
+ + union_start.gather(1, pair_s.clamp(0, n - 1))
197
+ + union_end.gather(1, pair_e.clamp(0, n - 1))
198
+ )
199
 
200
+ quota = min(self.min_pool_per_query, pair_s.shape[-1])
201
+ if quota:
202
+ s_idx = pair_s.clamp(0, start_logits.shape[2] - 1).unsqueeze(1).expand(b, q, -1)
203
+ e_idx = pair_e.clamp(0, end_logits.shape[2] - 1).unsqueeze(1).expand(b, q, -1)
204
+ per_query = (
205
+ start_logits.gather(2, s_idx)
206
+ + end_logits.gather(2, e_idx)
207
+ + compat.unsqueeze(1)
208
+ )
209
+ per_query_valid = pair_valid.unsqueeze(1) & query_mask.unsqueeze(-1)
210
+ # topk instead of argsort (export-safe; same selection up to ties).
211
+ # Pad with quota invalid sentinels first: quota may exceed the
212
+ # number of pairs at runtime (constant-k graph).
213
+ pq = per_query.masked_fill(~per_query_valid, _MASK)
214
+ pad_pq = pq.new_full(list(pq.shape)[:-1] + [quota], _MASK)
215
+ pad_v = torch.zeros_like(pad_pq, dtype=per_query_valid.dtype)
216
+ ranked = torch.topk(torch.cat([pq, pad_pq], -1), quota, dim=-1).indices.clamp(max=per_query_valid.shape[-1] - 1)
217
+ quota_valid_pre = torch.cat([per_query_valid, pad_v], -1).gather(-1, ranked)
218
+ quota_s = s_idx.gather(-1, ranked)
219
+ quota_e = e_idx.gather(-1, ranked)
220
+ quota_valid = quota_valid_pre.reshape(b, -1)
221
+ quota_keys = (quota_s * n + quota_e).reshape(b, -1)
222
+ rank_bonus = torch.arange(
223
+ quota, 0, -1, device=boundary_states.device,
224
+ dtype=union_pair_score.dtype,
225
+ )
226
+ quota_scores = (
227
+ union_pair_score.new_full((b, q, quota), -_MASK * 0.5)
228
+ + rank_bonus.view(1, 1, quota)
229
+ ).reshape(b, -1)
230
+ else:
231
+ quota_keys = pair_s.new_zeros((b, 0))
232
+ quota_scores = union_pair_score.new_zeros((b, 0))
233
+ quota_valid = pair_valid.new_zeros((b, 0))
234
+
235
+ global_keys = pair_s * n + pair_e
236
+ all_keys = torch.cat((quota_keys, global_keys), -1)
237
+ all_scores = torch.cat((quota_scores, union_pair_score.detach()), -1)
238
+ all_valid = torch.cat((quota_valid, pair_valid), -1)
239
+
240
+ with torch.no_grad():
241
+ selected_keys, selected_valid = Pool._deduplicate_pool(
242
+ all_keys, all_scores, all_valid, self.pool_size, n
243
+ )
244
+ selected_keys = torch.where(
245
+ selected_valid, selected_keys, torch.zeros_like(selected_keys)
246
+ )
247
+ selected_s = torch.div(selected_keys, n, rounding_mode="floor")
248
+ selected_e = selected_keys - selected_s * n
249
+ indices = torch.stack((selected_s, selected_e), -1)
250
+ indices = torch.where(
251
+ selected_valid.unsqueeze(-1), indices, torch.zeros_like(indices)
252
+ )
253
+ gs = _gather_rows(start_all, selected_s)
254
+ ge = _gather_rows(end_all, selected_e)
255
+ selected_compat = (gs * ge).sum(-1) / _math.sqrt(d)
256
+ selected_score = (
257
+ selected_compat
258
+ + union_start.gather(1, selected_s.clamp(0, n - 1))
259
+ + union_end.gather(1, selected_e.clamp(0, n - 1))
260
+ )
261
+ selected_score = selected_score.masked_fill(~selected_valid, _MASK)
262
+ selected_compat = torch.where(
263
+ selected_valid, selected_compat, torch.zeros_like(selected_compat)
264
+ )
265
+ return PooledCandidates(
266
+ indices=indices,
267
+ mask=selected_valid,
268
+ proposal_logits=selected_score,
269
+ gold_mask=None,
270
+ compat_logits=selected_compat,
271
+ stats=None,
272
+ )
273
+
274
+ Pool.DocumentCandidatePool.forward = _pool_forward_export
275
+ print(" [patch] pool internals replaced with topk versions (ONNX-safe)")
276
 
 
 
 
277
 
278
+ def build_wrapper(model):
279
+ """Wrap encoder + full boundary head (proposer + pair scorer included)."""
280
+ from gliner2 import AutoExtractor # noqa: F401 (type hint only)
281
+
282
+ # Vectorized proposer: no Python block loop, graph-exportable, and
283
+ # documented upstream as producing identical results.
284
  try:
285
+ model.boundary_head.boundary_proposer.settings = (
286
+ model.boundary_head.boundary_proposer.settings.__class__(
287
+ **{**model.boundary_head.boundary_proposer.settings.__dict__,
288
+ "export_mode": "vectorized"}
289
+ )
290
+ )
291
+ except Exception as e: # pragma: no cover
292
+ print(f" [warn] could not set vectorized export_mode: {e}")
293
 
294
  encoder = model.encoder
295
  encoder.eval()
296
+ head = model.boundary_head
297
+ head.eval()
298
 
299
+ # EyeLike fix (same as v1): matmul/softmax attention, no torch.eye/SDPA.
300
  def _exportable_attn_forward(block, states, mask):
 
301
  b, n, d = states.shape
302
  qkv = block.qkv_projection(block.norm(states)).view(b, n, 3, block.num_heads, block.head_dim)
303
  query, key, value = qkv.permute(2, 0, 3, 1, 4)
 
318
  return (states + update) * mask.unsqueeze(-1).to(states.dtype)
319
 
320
  class Wrapper(nn.Module):
321
+ """Encoder + gathers + full boundary head with candidate outputs."""
322
 
323
  def __init__(self, extractor):
324
  super().__init__()
325
  self.encoder = extractor.encoder
326
+ self.boundary_head = extractor.boundary_head
327
+ for block in self.boundary_head.boundary_encoder.attention_blocks:
 
328
  block.forward = lambda states, mask, _b=block: _exportable_attn_forward(_b, states, mask)
329
 
330
  def _gather(self, hidden_states, indices, mask):
 
333
  states = hidden_states.gather(1, safe.unsqueeze(-1).expand(-1, -1, h))
334
  return states * mask.unsqueeze(-1).to(states.dtype)
335
 
336
+ def forward(self, input_ids, attention_mask, text_word_indices, text_word_mask,
337
+ query_marker_indices, query_marker_mask):
338
  hidden_states = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
339
  text_states = self._gather(hidden_states, text_word_indices, text_word_mask)
340
  query_states = self._gather(hidden_states, query_marker_indices, query_marker_mask)
341
+ out = self.boundary_head(
342
+ text_states, text_word_mask.bool(),
343
+ query_states, query_marker_mask.bool(),
344
+ return_candidates=True,
 
 
 
 
345
  )
346
+ cands = out.candidates
347
+ # pair_valid as uint8 for ONNX friendliness
348
+ valid_u8 = cands.valid_mask.to(torch.uint8)
349
+ return (
350
+ out.start_logits, # [B, Q, L+1]
351
+ out.end_logits, # [B, Q, L+1]
352
+ cands.indices.to(torch.int64), # [B, Q, C, 2]
353
+ cands.pair_logits, # [B, Q, C]
354
+ valid_u8, # [B, Q, C]
355
+ )
356
+
357
+ return Wrapper(model).eval()
358
 
 
359
 
360
+ def export_one(model_id: str, out_dir: str, seq_len: int = 128, n_queries: int = 4,
361
+ n_words: int = 48, parity: bool = True):
362
+ from gliner2 import AutoExtractor
363
+
364
+ print(f"Loading {model_id} ...")
365
+ model = AutoExtractor.from_pretrained(model_id, map_location="cpu")
366
+ model.eval()
367
+
368
+ _patch_proposer_for_export()
369
+ wrapper = build_wrapper(model)
370
+
371
+ candidate_budget = (
372
+ model.boundary_head.boundary_proposer.settings.candidate_budget
373
+ )
374
+ print(f" candidate budget C = {candidate_budget}")
375
+
376
  b, t, l, q = 1, seq_len, n_words, n_queries
377
+ # Pair temperature lives on the checkpoint settings; try the head first.
378
+ try:
379
+ pair_temperature = float(model.boundary_head.settings.pair_temperature)
380
+ except AttributeError:
381
+ pair_temperature = float(model.boundary_settings.pair_temperature)
382
+ print(f" pair_temperature = {pair_temperature}")
383
+
384
  dummy = {
385
  "input_ids": torch.ones(b, t, dtype=torch.long),
386
  "attention_mask": torch.ones(b, t, dtype=torch.long),
 
391
  }
392
 
393
  with torch.no_grad():
394
+ ref = wrapper(*dummy.values())
395
+ print(" torch shapes:", [tuple(r.shape) for r in ref])
396
 
 
397
  slug = model_id.split("/")[-1]
398
  out = Path(out_dir) / f"{slug}-onnx"
399
  if out.exists():
400
  shutil.rmtree(out)
401
  onnx_dir = out / "onnx"
402
  onnx_dir.mkdir(parents=True)
 
403
 
404
  input_names = list(dummy.keys())
405
+ output_names = ["start_logits", "end_logits", "pair_indices", "pair_logits", "pair_valid"]
406
  dynamic_axes = {
407
+ **{k: {0: "batch", 1: ax} for k, ax in [
408
+ ("input_ids", "tokens"), ("attention_mask", "tokens"),
409
+ ("text_word_indices", "words"), ("text_word_mask", "words"),
410
+ ("query_marker_indices", "queries"), ("query_marker_mask", "queries"),
411
+ ]},
 
412
  "start_logits": {0: "batch", 1: "queries", 2: "boundaries"},
413
  "end_logits": {0: "batch", 1: "queries", 2: "boundaries"},
414
+ "pair_indices": {0: "batch", 1: "queries", 2: "candidates"},
415
+ "pair_logits": {0: "batch", 1: "queries", 2: "candidates"},
416
+ "pair_valid": {0: "batch", 1: "queries", 2: "candidates"},
417
  }
418
 
419
  print(" torch.onnx.export ...")
420
  torch.onnx.export(
421
  wrapper,
422
  tuple(dummy[k] for k in input_names),
423
+ str(onnx_dir / "model.onnx"),
424
  input_names=input_names,
425
+ output_names=output_names,
426
  dynamic_axes=dynamic_axes,
427
  opset_version=17,
428
  do_constant_folding=True,
429
  )
430
+ size_mb = (onnx_dir / "model.onnx").stat().st_size / 1e6
431
+ print(f" wrote model.onnx ({size_mb:.1f} MB)")
432
 
433
+ # ── Validate: ORT vs torch ────────────────────────────────────────
434
  import onnx
435
  import onnxruntime as ort
436
 
437
+ onnx.checker.check_model(str(onnx_dir / "model.onnx"))
438
+ sess = ort.InferenceSession(str(onnx_dir / "model.onnx"), providers=["CPUExecutionProvider"])
439
+ feeds = {k: v.numpy() for k, v in dummy.items()}
440
+ outs = sess.run(None, feeds)
441
+ names = [o.name for o in sess.get_outputs()]
442
+ print(" ort outputs:", list(zip(names, [o.shape for o in outs])))
443
+ for i, name in enumerate(names):
444
+ if name in ("start_logits", "end_logits"):
445
+ err = float(((outs[i] - ref[i].numpy()) ** 2).mean() ** 0.5)
446
+ print(f" RMSE {name}: {err:.6f}")
447
+ # Candidate slots are score-ordered; topk tie order can differ between
448
+ # eager torch and the traced graph. Compare as SETS keyed by (query,
449
+ # start, end): that is what decode consumes.
450
+ ort_idx, ort_logit, ort_valid = outs[2], outs[3], outs[4]
451
+ t_idx, t_logit, t_valid = ref[2].numpy(), ref[3].numpy(), ref[4].numpy()
452
+ max_diff, matched, unmatched = 0.0, 0, 0
453
+ for b in range(ort_idx.shape[0]):
454
+ for q in range(ort_idx.shape[1]):
455
+ t_map = {}
456
+ for c in range(t_idx.shape[2]):
457
+ if t_valid[b, q, c]:
458
+ key = (int(t_idx[b, q, c, 0]), int(t_idx[b, q, c, 1]))
459
+ t_map[key] = float(t_logit[b, q, c])
460
+ for c in range(ort_idx.shape[2]):
461
+ if ort_valid[b, q, c]:
462
+ key = (int(ort_idx[b, q, c, 0]), int(ort_idx[b, q, c, 1]))
463
+ if key in t_map:
464
+ matched += 1
465
+ max_diff = max(max_diff, abs(t_map[key] - float(ort_logit[b, q, c])))
466
+ else:
467
+ unmatched += 1
468
+ print(f" candidate set check: matched={matched} unmatched(ORT-only)={unmatched} "
469
+ f"max|Δlogit|={max_diff:.6f}")
470
+
471
+ # ── Decode parity vs AutoExtractor (optional, strongest check) ─────
472
+ if parity:
473
+ print(" decode parity vs AutoExtractor ...")
474
+ text = "Apple CEO Tim Cook announced iPhone 15 in Cupertino yesterday."
475
+ labels = ["company", "person", "product", "location"]
476
+ # Reference: the full pipeline
477
+ ref_result = model.extract_entities(text, labels, include_confidence=True, include_spans=True)
478
+ # Our path: pack with the model's own processor, run wrapper, decode pairs
479
+ batch = model.processor.collate_fn_inference([(text, {"entities": {k: [] for k in labels}})], architecture="boundary")
480
+ with torch.no_grad():
481
+ pout = wrapper(
482
+ batch.input_ids, batch.attention_mask,
483
+ batch.text_word_indices, batch.text_word_mask,
484
+ batch.query_marker_indices, batch.query_marker_mask,
485
+ )
486
+ start_logits, end_logits, pair_indices, pair_logits, pair_valid = pout
487
+ probs = torch.sigmoid(pair_logits / pair_temperature)
488
+ # candidates above 0.5 for query 0 (company) — print top spans per query
489
+ q_names = [spec for spec in labels]
490
+ n_q = pair_indices.shape[1]
491
+ print(f" pair_temperature = {pair_temperature}")
492
+ for qi in range(min(n_q, len(q_names))):
493
+ valid = pair_valid[0, qi].bool()
494
+ top = probs[0, qi][valid].topk(min(3, int(valid.sum())))
495
+ for score, ci in zip(top.values.tolist(), top.indices.tolist()):
496
+ s, e = pair_indices[0, qi, ci].tolist()
497
+ print(f" q={q_names[qi]!r} span=({s},{e}) p={score:.3f}")
498
+ print(f" AutoExtractor reference: {json.dumps(ref_result)[:400]}")
499
+
500
+ # ── Save tokenizer + configs ────────────────────────────────────────
501
+ model.processor.tokenizer.save_pretrained(str(out))
502
  cfg = {
503
  "architecture": "boundary",
504
+ "export_version": 2,
505
  "base_model": model_id,
506
+ "candidate_budget": int(candidate_budget),
507
+ "pair_temperature": float(pair_temperature),
508
  "opset": 17,
509
  "inputs": input_names,
510
+ "outputs": output_names,
511
+ "notes": "Graph includes proposer + pair reranker (vectorized). Host: keep spans with sigmoid(pair_logits / pair_temperature) >= threshold, resolve overlaps per label, map boundaries to chars (boundary i = before word i; pair (s,e) covers words s..e-1).",
512
  }
513
  (out / "export_config.json").write_text(json.dumps(cfg, indent=2))
514
+ print(f" output at {out}")
515
+ return {"onnx_mb": size_mb, "candidate_budget": candidate_budget}
516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
+ def main():
519
+ parser = argparse.ArgumentParser()
520
+ parser.add_argument("--model-id", required=True)
521
+ processor = parser.add_argument("--out-dir", default="./output-v2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  parser.add_argument("--seq-len", type=int, default=128)
523
  parser.add_argument("--n-queries", type=int, default=4)
524
  parser.add_argument("--n-words", type=int, default=48)
525
+ parser.add_argument("--no-parity", action="store_true")
526
  args = parser.parse_args()
527
+ export_one(
528
  model_id=args.model_id,
529
+ out_dir=args.out_dir,
530
  seq_len=args.seq_len,
531
  n_queries=args.n_queries,
532
  n_words=args.n_words,
533
+ parity=not args.no_parity,
 
534
  )
 
535
 
536
 
537
  if __name__ == "__main__":
538
+ main()