File size: 10,644 Bytes
c1ca102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# /// script
# requires-python = "==3.13.*"
# dependencies = [
#   "gliner2==2.1.0",
#   "torch==2.15.0",
#   "transformers==4.57.6",
#   "tokenizers==0.22.2",
#   "onnx==1.23.2",
#   "onnxscript==0.7.2",
#   "onnxruntime==1.23.2",
#   "huggingface_hub==0.36.2",
# ]
# ///
# SPDX-License-Identifier: Apache-2.0
"""Rebuild the iris-names ONNX files from the pinned upstream models.

    python build_bundle.py OUT_DIR

Downloads fastino/gliner2.5-base-v1 and the Q4F16 ONNX file of
Xenova/DeBERTa-v3-base-mnli-fever-anli at fixed commits, converts and repackages
them, then compares every file with ../SHA256SUMS. Nothing is trained, and no
weight is changed or quantised here. OUT_DIR must not exist.

The functions prefixed onnx_ are modified from gliner2 2.1.0 (by Fastino AI,
Apache-2.0, https://github.com/fastino-ai/GLiNER2). The changes let the boundary
head export to ONNX and run on sentences of any length:
  1. shift_left_with_bos / shift_right_with_eos: cat/where instead of in-place writes.
  2. BoundaryAttentionBlock: the diagonal mask compares positions, because ONNX
     Runtime has no boolean EyeLike.
  3. select_top_boundaries: right-pads to k before topk, so k is constant.
  4. aten::sort and aten::argsort with stable=True get a TopK symbolic.
"""

import hashlib
import json
import shutil
import sys
import tempfile
from pathlib import Path

import gliner2.models.boundary.encoding as b_enc
import gliner2.models.boundary.pool as b_pool
import gliner2.models.boundary.proposal as b_prop
import onnx
import torch
from gliner2 import AutoExtractor
from gliner2.models.boundary.constants import MASK_LOGIT
from huggingface_hub import snapshot_download
from torch.onnx import register_custom_op_symbolic
from torch.onnx._internal.torchscript_exporter import symbolic_helper

GLINER = ("fastino/gliner2.5-base-v1", "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c")
NLI = ("Xenova/DeBERTa-v3-base-mnli-fever-anli", "72a1ce83a0144efaf828b3c3844320a61197a53d")
TOKENIZER_FILES = ["config.json", "tokenizer.json", "tokenizer_config.json"]


def sort_symbolic(g, self, *args):
    if len(args) == 3:  # (stable, dim, descending)
        args = args[1:]
    dim = symbolic_helper._parse_arg(args[0], "i")
    descending = symbolic_helper._parse_arg(args[1], "i")
    return symbolic_helper._sort_helper(g, self, dim, descending=descending, out=None)


def argsort_symbolic(g, self, *args):
    return sort_symbolic(g, self, *args)[1]


def onnx_shift_left_with_bos(text_states, bos_state):
    b, l, h = text_states.shape
    bos = bos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
    return torch.cat([bos, text_states], dim=1)


def onnx_shift_right_with_eos(text_states, text_lengths, eos_state):
    b, l, h = text_states.shape
    eos = eos_state.to(text_states.dtype).view(1, 1, h).expand(b, 1, h)
    padded = torch.cat([text_states, eos], dim=1)
    idx = torch.arange(l + 1, device=text_states.device).unsqueeze(0)
    is_eos = idx == text_lengths.clamp(max=l).unsqueeze(1)
    return torch.where(is_eos.unsqueeze(-1), eos_state.to(text_states.dtype).view(1, 1, h), padded)


def onnx_attention_forward(self, states, mask):
    b, n, d = states.shape
    qkv = self.qkv_projection(self.norm(states)).view(b, n, 3, self.num_heads, self.head_dim)
    query, key, value = qkv.unbind(2)
    query = query.transpose(1, 2)
    key = key.transpose(1, 2)
    value = value.transpose(1, 2)
    allowed = mask.view(b, 1, 1, n).expand(b, 1, n, n)
    positions = torch.arange(n, device=states.device)
    if self.window > 0:
        local = (positions.view(n, 1) - positions.view(1, n)).abs() <= self.window
        allowed = allowed & local.view(1, 1, n, n)
    diagonal = positions.view(n, 1) == positions.view(1, n)
    allowed = allowed | diagonal.view(1, 1, n, n)
    attended = torch.nn.functional.scaled_dot_product_attention(
        query, key, value, attn_mask=allowed, dropout_p=0.0
    )
    attended = attended.transpose(1, 2).reshape(b, n, d)
    update = self.output_projection(attended)
    return (states + update) * mask.unsqueeze(-1).to(states.dtype)


def onnx_select_top_boundaries(logits, valid_mask, k):
    b, q, n = logits.shape
    floor = MASK_LOGIT
    masked = logits.masked_fill(~valid_mask, floor)
    pad_logits = masked.new_full((b, q, k), floor)
    pad_valid = valid_mask.new_zeros((b, q, k))
    masked_padded = torch.cat([masked, pad_logits], dim=-1)
    valid_padded = torch.cat([valid_mask, pad_valid], dim=-1)
    scores, idx = torch.topk(masked_padded, k=k, dim=-1, largest=True, sorted=True)
    valid = torch.gather(valid_padded, -1, idx)
    scores = torch.where(valid, scores, torch.zeros_like(scores))
    idx = torch.where(valid, idx, torch.zeros_like(idx))
    return scores, idx, valid


class Encoder(torch.nn.Module):
    def __init__(self, enc):
        super().__init__()
        self.enc = enc

    def forward(self, input_ids, attention_mask):
        return self.enc(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state


class BoundaryHead(torch.nn.Module):
    def __init__(self, bh):
        super().__init__()
        self.bh = bh
        self.bh.candidate_encoder = None  # entity spans only: no relations or attributes

    def forward(self, token_states, text_mask, query_states, query_mask):
        out = self.bh(token_states, text_mask, query_states, query_mask, return_candidates=True)
        c = out.candidates
        return c.indices, c.pair_logits, c.valid_mask, out.null_logits


def rewrite_tokenizer(src: Path, dst: Path):
    """Make the tokenizer load in swift-transformers 1.4.0. Token IDs do not change."""
    shutil.copyfile(src / "config.json", dst / "config.json")
    config = json.loads((src / "tokenizer_config.json").read_text(encoding="utf-8"))
    config["tokenizer_class"] = "XLMRobertaTokenizer"
    (dst / "tokenizer_config.json").write_text(json.dumps(config, ensure_ascii=False), encoding="utf-8")
    tokenizer = json.loads((src / "tokenizer.json").read_text(encoding="utf-8"))
    vocab = tokenizer["model"]["vocab"]
    for token in sorted(tokenizer["added_tokens"], key=lambda t: t["id"]):
        if token["id"] < len(vocab):
            if vocab[token["id"]][0] != token["content"]:
                raise SystemExit(f"unexpected added token {token}")
        elif token["id"] == len(vocab):
            vocab.append([token["content"], 0.0])
        else:
            raise SystemExit(f"gap before added token {token}")
    (dst / "tokenizer.json").write_text(json.dumps(tokenizer, ensure_ascii=False), encoding="utf-8")


def save_external(src: Path, out_dir: Path):
    onnx.save_model(
        onnx.load(str(src)), str(out_dir / "model.onnx"), save_as_external_data=True,
        all_tensors_to_one_file=True, location="model.onnx_data", size_threshold=1024,
        convert_attribute=False,
    )


def export_gliner(src: Path, out: Path, tmp: Path):
    register_custom_op_symbolic("aten::sort", sort_symbolic, 11)
    register_custom_op_symbolic("aten::argsort", argsort_symbolic, 11)
    b_enc.shift_left_with_bos = onnx_shift_left_with_bos
    b_enc.shift_right_with_eos = onnx_shift_right_with_eos
    b_enc.BoundaryAttentionBlock.forward = onnx_attention_forward
    b_prop.select_top_boundaries = onnx_select_top_boundaries
    b_pool.select_top_boundaries = onnx_select_top_boundaries

    torch.manual_seed(0)
    model = AutoExtractor.from_pretrained(str(src))
    model.eval()

    torch.manual_seed(0)
    batch, words, queries, hidden = 2, 40, 23, 768  # example input: batch, words and queries stay dynamic
    torch.onnx.export(
        BoundaryHead(model.boundary_head).eval(),
        (torch.randn(batch, words, hidden), torch.ones(batch, words, dtype=torch.bool),
         torch.randn(batch, queries, hidden), torch.ones(batch, queries, dtype=torch.bool)),
        str(out / "boundary_head.onnx"),
        input_names=["token_states", "text_mask", "query_states", "query_mask"],
        output_names=["indices", "pair_logits", "valid_mask", "null_logits"],
        dynamic_axes={
            "token_states": {0: "batch", 1: "words"},
            "text_mask": {0: "batch", 1: "words"},
            "query_states": {0: "batch", 1: "queries"},
            "query_mask": {0: "batch", 1: "queries"},
            "indices": {0: "batch", 1: "queries", 2: "candidates"},
            "pair_logits": {0: "batch", 1: "queries", 2: "candidates"},
            "valid_mask": {0: "batch", 1: "queries", 2: "candidates"},
            "null_logits": {0: "batch", 1: "queries"},
        },
        opset_version=18, dynamo=False,
    )

    torch.manual_seed(0)
    torch.onnx.export(
        Encoder(model.encoder.float()).eval(),
        (torch.randint(1, 1000, (2, 32), dtype=torch.long), torch.ones((2, 32), dtype=torch.long)),
        str(tmp / "encoder.onnx"),
        input_names=["input_ids", "attention_mask"],
        output_names=["last_hidden_state"],
        dynamic_axes={
            "input_ids": {0: "batch", 1: "seq"},
            "attention_mask": {0: "batch", 1: "seq"},
            "last_hidden_state": {0: "batch", 1: "seq"},
        },
        opset_version=18, dynamo=False,
    )
    (out / "encoder").mkdir()
    save_external(tmp / "encoder.onnx", out / "encoder")


def sha256(path: Path) -> str:
    with path.open("rb") as f:
        return hashlib.file_digest(f, "sha256").hexdigest()


def main() -> int:
    if len(sys.argv) != 2:
        raise SystemExit("usage: python build_bundle.py OUT_DIR")
    out = Path(sys.argv[1])
    sums = (Path(__file__).resolve().parent.parent / "SHA256SUMS").read_text().splitlines()
    (out / "gliner25").mkdir(parents=True)
    (out / "deberta-nli").mkdir()
    gliner = Path(snapshot_download(GLINER[0], revision=GLINER[1],
                                    allow_patterns=TOKENIZER_FILES + ["encoder_config/config.json", "model.safetensors"]))
    nli = Path(snapshot_download(NLI[0], revision=NLI[1], allow_patterns=TOKENIZER_FILES + ["onnx/model_q4f16.onnx"]))
    with tempfile.TemporaryDirectory() as tmp:
        export_gliner(gliner, out / "gliner25", Path(tmp))
    save_external(nli / "onnx" / "model_q4f16.onnx", out / "deberta-nli")
    rewrite_tokenizer(gliner, out / "gliner25")
    rewrite_tokenizer(nli, out / "deberta-nli")

    different = 0
    for line in sums:
        want, name = line.split("  ", 1)
        same = sha256(out / name) == want
        different += not same
        print("same     " if same else "DIFFERENT", name)
    print(f"{len(sums) - different} of {len(sums)} files are byte-identical to the published ones")
    return 1 if different else 0


if __name__ == "__main__":
    sys.exit(main())