sunyijie commited on
Commit
a96afcc
·
1 Parent(s): d9673ac
src/export_onnx.py DELETED
@@ -1,336 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Export FG-CLIP 2 Large (HuggingFace remote-code format) to ONNX.
3
-
4
- Produces two standalone graphs:
5
- * image encoder: pixel_values[1,N,768] -> image_features[1,1024]
6
- * text encoder: input_ids[1,L] -> text_features[1,1024]
7
-
8
- Input contract (matches the official processor / tokenizer):
9
- image : Siglip2 patchified input. ``Siglip2ImageProcessor`` returns
10
- ``pixel_values`` of shape [1, num_patches, 3*patch_size*patch_size].
11
- This export fixes a square grid (default 16x16 = 256 patches, i.e. a
12
- 256x256 image), so only ``pixel_values`` is exposed as a graph input.
13
- text : int64 token ids padded to a fixed length. 64 for walk_type
14
- ``short``/``box``, 196 for ``long``. The official tokenizer does not
15
- emit an attention mask, so the graph takes ids only.
16
-
17
- walk_type selects which text head is baked into the graph:
18
- short -> text_model's own projection head (default, retrieval)
19
- long -> longtext_head (long captions)
20
- box -> boxtext_head (dense / region descriptions)
21
-
22
- Usage:
23
- python src/export_onnx.py
24
- python src/export_onnx.py --walk-type long --text-length 196
25
- """
26
-
27
- import argparse
28
- import json
29
- import os
30
- import sys
31
-
32
- import numpy as np
33
- import torch
34
- import torch.nn as nn
35
- from transformers import AutoModelForCausalLM
36
-
37
- DEFAULT_MODEL_DIR = os.path.join(
38
- os.path.dirname(os.path.abspath(__file__)), "..", "fg-clip2-large"
39
- )
40
- DEFAULT_OUTPUT_DIR = os.path.join(
41
- os.path.dirname(os.path.abspath(__file__)), "..", "models"
42
- )
43
-
44
-
45
- class ImageEncoder(nn.Module):
46
- """Vision tower with a fixed grid.
47
-
48
- ``Fgclip2VisionEmbeddings`` resizes its positional table with
49
- ``antialias=True``, which maps to ``aten::_upsample_bilinear2d_aa`` and has
50
- no ONNX symbolic. The resize is an identity when the target grid equals the
51
- table grid (the default 16x16 case), so the table is baked in directly.
52
- For other grids we fall back to bilinear interpolation without antialias;
53
- that differs slightly from the PyTorch default, see export_info.json.
54
- """
55
-
56
- def __init__(self, model, grid_h: int, grid_w: int):
57
- super().__init__()
58
- self.vision_model = model.vision_model
59
- emb = model.vision_model.embeddings
60
- table = emb.position_embedding.weight.reshape(
61
- emb.position_embedding_size, emb.position_embedding_size, -1
62
- )
63
- if (grid_h, grid_w) != (emb.position_embedding_size, emb.position_embedding_size):
64
- import torch.nn.functional as F
65
-
66
- resized = F.interpolate(
67
- table.permute(2, 0, 1).unsqueeze(0),
68
- size=(grid_h, grid_w),
69
- mode="bilinear",
70
- align_corners=False,
71
- antialias=False,
72
- )
73
- table = resized.reshape(table.shape[-1], -1).transpose(0, 1)
74
- self.register_buffer("pos_table", table.reshape(1, -1, table.shape[-1]).clone(), persistent=False)
75
-
76
- def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
77
- vm = self.vision_model
78
- hidden = vm.embeddings.patch_embedding(pixel_values) + self.pos_table
79
- hidden = vm.encoder(inputs_embeds=hidden, attention_mask=None).last_hidden_state
80
- hidden = vm.post_layernorm(hidden)
81
- return vm.head(hidden, attention_mask=None)
82
-
83
-
84
- class TextEncoder(nn.Module):
85
- def __init__(self, model, walk_type: str):
86
- super().__init__()
87
- self.text_model = model.text_model
88
- self.walk_type = walk_type
89
- if walk_type == "long":
90
- self.out_head = model.longtext_head
91
- elif walk_type == "box":
92
- self.out_head = model.boxtext_head
93
- else:
94
- self.out_head = None
95
-
96
- def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
97
- pooled = self.text_model(input_ids=input_ids, walk_type=self.walk_type).pooler_output
98
- if self.out_head is not None:
99
- pooled = self.out_head(pooled)
100
- return pooled
101
-
102
-
103
- def build_model(model_dir: str):
104
- model = AutoModelForCausalLM.from_pretrained(
105
- model_dir,
106
- trust_remote_code=True,
107
- local_files_only=True,
108
- )
109
- model.eval()
110
- model.requires_grad_(False)
111
-
112
- # The remote config only propagates the top-level attention backend, and
113
- # transformers 5 defaults sub-configs to sdpa; force eager everywhere.
114
- model.config._attn_implementation = "eager"
115
- model.config.vision_config._attn_implementation = "eager"
116
- model.config.text_config._attn_implementation = "eager"
117
- model.vision_model.config._attn_implementation = "eager"
118
- model.text_model.config._attn_implementation = "eager"
119
-
120
- # transformers 5 builds non-persistent buffers / plain attributes under a
121
- # meta-device context. position_ids, mask1 and mask2 are never in the
122
- # checkpoint, so rebuild them explicitly (same values as __init__).
123
- emb = model.text_model.embeddings
124
- cfg = model.config.text_config
125
- idx = torch.arange(cfg.longtext_len)
126
- emb.position_ids = idx.unsqueeze(0)
127
- emb.mask1 = (idx.unsqueeze(1) < cfg.keep_len).to(torch.float32)
128
- emb.mask2 = (idx.unsqueeze(1) >= cfg.keep_len).to(torch.float32)
129
-
130
- stale = [n for n, b in model.named_buffers() if b.is_meta]
131
- stale += [n for n, p in model.named_parameters() if p.is_meta]
132
- if stale:
133
- raise RuntimeError(f"unresolved meta tensors after load: {stale[:10]}")
134
- return model
135
-
136
-
137
- def export_graph(module, args, path, input_names, output_names, opset):
138
- print(f"[export] {path}")
139
- with torch.no_grad():
140
- torch.onnx.export(
141
- module,
142
- args,
143
- path,
144
- input_names=input_names,
145
- output_names=output_names,
146
- opset_version=opset,
147
- do_constant_folding=False,
148
- export_params=True,
149
- dynamo=False,
150
- )
151
-
152
-
153
- def consolidate_external_data(onnx_path):
154
- """Merge per-tensor side-car weights into a single <model>.onnx.data file."""
155
- import onnx
156
-
157
- model = onnx.load(onnx_path, load_external_data=False)
158
- locations = set()
159
- for tensor in model.graph.initializer:
160
- if tensor.data_location != onnx.TensorProto.EXTERNAL:
161
- continue
162
- for kv in tensor.external_data:
163
- if kv.key == "location":
164
- locations.add(kv.value)
165
- if not locations:
166
- return None
167
-
168
- base = os.path.dirname(onnx_path)
169
- onnx.external_data_helper.load_external_data_for_model(model, base)
170
-
171
- data_name = os.path.basename(onnx_path) + ".data"
172
- onnx.save_model(
173
- model,
174
- onnx_path,
175
- save_as_external_data=True,
176
- all_tensors_to_one_file=True,
177
- location=data_name,
178
- size_threshold=1024,
179
- )
180
-
181
- for location in locations:
182
- stale = os.path.join(base, location)
183
- if os.path.isfile(stale) and os.path.basename(stale) != data_name:
184
- os.remove(stale)
185
-
186
- return os.path.join(base, data_name)
187
-
188
-
189
- def verify(onnx_path, module, inputs, output_name, atol, rtol):
190
- import onnxruntime as ort
191
-
192
- session = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
193
- feed = {node.name: x.numpy() for node, x in zip(session.get_inputs(), inputs)}
194
- ort_out = session.run([output_name], feed)[0]
195
-
196
- with torch.no_grad():
197
- ref = module(*inputs).numpy()
198
-
199
- abs_err = np.abs(ort_out - ref)
200
- max_abs = float(abs_err.max())
201
- rel = max_abs / max(float(np.abs(ref).max()), 1e-12)
202
- ok = np.allclose(ort_out, ref, atol=atol, rtol=rtol)
203
- print(
204
- f"[verify] {os.path.basename(onnx_path)}: max_abs={max_abs:.3e} "
205
- f"rel={rel:.3e} shape={ort_out.shape} -> {'OK' if ok else 'FAIL'}"
206
- )
207
- return ok
208
-
209
-
210
- def main():
211
- parser = argparse.ArgumentParser(
212
- description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
213
- )
214
- parser.add_argument("--model-dir", default=DEFAULT_MODEL_DIR)
215
- parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
216
- parser.add_argument(
217
- "--image-size",
218
- type=int,
219
- default=256,
220
- help="square input size; must be divisible by patch_size (default 256)",
221
- )
222
- parser.add_argument("--walk-type", choices=["short", "long", "box"], default="short")
223
- parser.add_argument(
224
- "--text-length",
225
- type=int,
226
- default=0,
227
- help="fixed token length (0 = 64 for short/box, 196 for long)",
228
- )
229
- parser.add_argument("--opset", type=int, default=14)
230
- parser.add_argument("--no-verify", action="store_true")
231
- parser.add_argument("--atol", type=float, default=1e-4)
232
- parser.add_argument("--rtol", type=float, default=1e-3)
233
- args = parser.parse_args()
234
-
235
- model_dir = os.path.abspath(args.model_dir)
236
- output_dir = os.path.abspath(args.output_dir)
237
- os.makedirs(output_dir, exist_ok=True)
238
-
239
- print(f"[load] {model_dir}")
240
- model = build_model(model_dir)
241
- vision_cfg = model.config.vision_config
242
- text_cfg = model.config.text_config
243
-
244
- patch_size = vision_cfg.patch_size
245
- if args.image_size % patch_size != 0:
246
- raise SystemExit(f"image size {args.image_size} is not divisible by patch_size {patch_size}")
247
- grid = args.image_size // patch_size
248
- num_patches = grid * grid
249
- if num_patches > vision_cfg.num_patches:
250
- raise SystemExit(
251
- f"grid {grid}x{grid} needs {num_patches} patches, model supports {vision_cfg.num_patches}"
252
- )
253
-
254
- text_length = args.text_length or (text_cfg.longtext_len if args.walk_type == "long" else text_cfg.max_position_embeddings)
255
-
256
- image_encoder = ImageEncoder(model, grid, grid).eval()
257
- text_encoder = TextEncoder(model, args.walk_type).eval()
258
-
259
- image_input = torch.randn(
260
- 1, num_patches, vision_cfg.num_channels * patch_size * patch_size
261
- )
262
- text_input = torch.randint(0, text_cfg.vocab_size, (1, text_length), dtype=torch.int64)
263
-
264
- image_path = os.path.join(output_dir, "fgclip2_large_image_encoder.onnx")
265
- text_path = os.path.join(output_dir, f"fgclip2_large_text_encoder_{args.walk_type}.onnx")
266
-
267
- export_graph(
268
- image_encoder,
269
- (image_input,),
270
- image_path,
271
- ["pixel_values"],
272
- ["image_features"],
273
- args.opset,
274
- )
275
- export_graph(
276
- text_encoder,
277
- (text_input,),
278
- text_path,
279
- ["input_ids"],
280
- ["text_features"],
281
- args.opset,
282
- )
283
-
284
- image_data = consolidate_external_data(image_path)
285
- text_data = consolidate_external_data(text_path)
286
-
287
- feature_dim = text_cfg.projection_size
288
- info = {
289
- "model_dir": model_dir,
290
- "opset": args.opset,
291
- "walk_type": args.walk_type,
292
- "image_encoder": {
293
- "file": os.path.basename(image_path),
294
- "external_data": os.path.basename(image_data) if image_data else None,
295
- "input": {
296
- "name": "pixel_values",
297
- "shape": [1, num_patches, vision_cfg.num_channels * patch_size * patch_size],
298
- },
299
- "output": {"name": "image_features", "shape": [1, feature_dim]},
300
- "preprocess": {
301
- "image_size": args.image_size,
302
- "patch_size": patch_size,
303
- "grid": [grid, grid],
304
- "mean": [0.5, 0.5, 0.5],
305
- "std": [0.5, 0.5, 0.5],
306
- },
307
- },
308
- "text_encoder": {
309
- "file": os.path.basename(text_path),
310
- "external_data": os.path.basename(text_data) if text_data else None,
311
- "input": {"name": "input_ids", "shape": [1, text_length], "dtype": "int64"},
312
- "output": {"name": "text_features", "shape": [1, feature_dim]},
313
- "walk_type": args.walk_type,
314
- },
315
- }
316
- info_path = os.path.join(output_dir, "export_info.json")
317
- with open(info_path, "w", encoding="utf-8") as f:
318
- json.dump(info, f, indent=2)
319
- print(f"[info] {info_path}")
320
-
321
- if not args.no_verify:
322
- ok_image = verify(image_path, image_encoder, [image_input], "image_features", args.atol, args.rtol)
323
- ok_text = verify(text_path, text_encoder, [text_input], "text_features", args.atol, args.rtol)
324
- if not (ok_image and ok_text):
325
- print("[error] verification failed", file=sys.stderr)
326
- return 1
327
-
328
- for path, data in ((image_path, image_data), (text_path, text_data)):
329
- total = os.path.getsize(path) + (os.path.getsize(data) if data else 0)
330
- suffix = f" + {os.path.basename(data)}" if data else ""
331
- print(f"[done] {path}{suffix} ({total / 1024**2:.1f} MiB)")
332
- return 0
333
-
334
-
335
- if __name__ == "__main__":
336
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/gen_image_calibration_data.py DELETED
@@ -1,101 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Generate Pulsar2 "Numpy" calibration data for the FG-CLIP 2 image encoder.
3
-
4
- The image encoder ONNX takes ``pixel_values[1, 256, 768]`` — a patchified
5
- Siglip2 input, not an NCHW image. Pulsar2's ``Image`` calibration path cannot
6
- produce it (its input processors only resize/normalize/layout-convert), so the
7
- samples are preprocessed here and saved as ``.npy`` files.
8
-
9
- Preprocess matches Siglip2ImageProcessor: RGB, BILINEAR resize to a square
10
- ``image_size``, /255, (x-0.5)/0.5, then 16x16 patches in (nh, nw, p, p, C)
11
- order.
12
- """
13
-
14
- import argparse
15
- import os
16
- import zipfile
17
-
18
- import numpy as np
19
- from PIL import Image
20
-
21
- PATCH_SIZE = 16
22
- DEFAULT_IMAGES = os.path.join(
23
- os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
24
- "coco2017val_500",
25
- )
26
- DEFAULT_OUTPUT_DIR = os.path.join(
27
- os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
28
- "fgclip2_image_calibration",
29
- )
30
- IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
31
-
32
-
33
- def list_images(directory, limit):
34
- names = sorted(n for n in os.listdir(directory) if n.lower().endswith(IMAGE_SUFFIXES))
35
- if limit:
36
- names = names[:limit]
37
- if not names:
38
- raise SystemExit(f"no images found in {directory}")
39
- return names
40
-
41
-
42
- def preprocess(path, image_size):
43
- image = Image.open(path).convert("RGB")
44
- resample = getattr(Image, "Resampling", Image).BILINEAR
45
- image = image.resize((image_size, image_size), resample)
46
- x = np.asarray(image, dtype=np.float32) / 255.0
47
- x = (x - 0.5) / 0.5
48
- grid = image_size // PATCH_SIZE
49
- patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
50
- patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
51
- return np.ascontiguousarray(patches)
52
-
53
-
54
- def main():
55
- parser = argparse.ArgumentParser(description=__doc__)
56
- parser.add_argument("--images", default=DEFAULT_IMAGES)
57
- parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
58
- parser.add_argument("--zip", dest="zip_path",
59
- default=os.path.join(os.path.dirname(DEFAULT_OUTPUT_DIR),
60
- "fgclip2_image_calibration.zip"))
61
- parser.add_argument("--image-size", type=int, default=256,
62
- help="must be a multiple of 16 and match the exported grid")
63
- parser.add_argument("--limit", type=int, default=64, help="max images (0 = all)")
64
- parser.add_argument("--no-zip", action="store_true")
65
- args = parser.parse_args()
66
-
67
- images_dir = os.path.abspath(args.images)
68
- output_dir = os.path.abspath(args.output_dir)
69
- zip_path = os.path.abspath(args.zip_path)
70
- if args.image_size % PATCH_SIZE != 0:
71
- raise SystemExit(f"image size {args.image_size} is not divisible by {PATCH_SIZE}")
72
-
73
- names = list_images(images_dir, args.limit)
74
- os.makedirs(output_dir, exist_ok=True)
75
- for idx, name in enumerate(names):
76
- arr = preprocess(os.path.join(images_dir, name), args.image_size)
77
- np.save(os.path.join(output_dir, f"{idx:06d}.npy"), arr)
78
- print(f"[write] {len(names)} npy files -> {output_dir}")
79
-
80
- manifest = output_dir.rstrip(os.sep) + "_manifest.txt"
81
- with open(manifest, "w", encoding="utf-8") as f:
82
- for idx, name in enumerate(names):
83
- f.write(f"{idx:06d}.npy\t{name}\n")
84
- print(f"[write] manifest -> {manifest}")
85
-
86
- if not args.no_zip:
87
- folder = os.path.basename(output_dir.rstrip(os.sep))
88
- os.makedirs(os.path.dirname(zip_path), exist_ok=True)
89
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
90
- for name in sorted(os.listdir(output_dir)):
91
- if name.endswith(".npy"):
92
- zf.write(os.path.join(output_dir, name), f"{folder}/{name}")
93
- print(f"[zip] {zip_path} ({os.path.getsize(zip_path) / 1024 ** 2:.2f} MiB)")
94
-
95
- sample = preprocess(os.path.join(images_dir, names[0]), args.image_size)
96
- print(f"[info] sample shape={sample.shape} dtype={sample.dtype} "
97
- f"min={sample.min():.4f} max={sample.max():.4f}")
98
-
99
-
100
- if __name__ == "__main__":
101
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/gen_text_calibration_data.py DELETED
@@ -1,146 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Generate Pulsar2 "Numpy" calibration data for the FG-CLIP 2 text encoder.
3
-
4
- The text encoder ONNX takes ``input_ids[1, 64]`` int64 token ids (Gemma BPE),
5
- so calibration samples are tokenized captions saved as ``.npy`` files and
6
- packed into a zip archive (``calibration_format: "Numpy"``).
7
-
8
- Do not reuse the Chinese-CLIP calibration zip: it is BertTokenizer output with
9
- shape [1, 52] and will fail with a shape mismatch.
10
-
11
- Default corpus: the human-written raw Chinese captions from coco-cn
12
- (``imageid.human-written-caption.txt``), read directly from the dataset tar.gz.
13
- """
14
-
15
- import argparse
16
- import io
17
- import os
18
- import tarfile
19
- import zipfile
20
-
21
- import numpy as np
22
- from transformers import AutoTokenizer
23
-
24
-
25
- DEFAULT_CAPTIONS = os.path.join(
26
- os.path.dirname(os.path.abspath(__file__)),
27
- "..", "..", "..", "datasets", "coco-cn-version1805v1.1.tar.gz",
28
- )
29
- DEFAULT_MEMBER = "coco-cn-version1805v1.1/imageid.human-written-caption.txt"
30
- DEFAULT_MODEL_DIR = os.path.join(
31
- os.path.dirname(os.path.abspath(__file__)), "..", "fg-clip2-large"
32
- )
33
- DEFAULT_OUTPUT_DIR = os.path.join(
34
- os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
35
- "fgclip2_text_calibration",
36
- )
37
-
38
-
39
- def read_lines(path, member=None):
40
- """Yield text lines from a plain file or a tar/tar.gz member."""
41
- if tarfile.is_tarfile(path):
42
- with tarfile.open(path, "r:*") as tar:
43
- names = [n for n in tar.getnames() if not os.path.basename(n).startswith("._")]
44
- if member is None:
45
- member = next(n for n in names if n.endswith(".txt") and "caption" in n)
46
- if member not in names:
47
- raise SystemExit(f"member not found in {path}: {member}")
48
- f = tar.extractfile(member)
49
- for raw in io.TextIOWrapper(f, encoding="utf-8"):
50
- yield raw.rstrip("\n")
51
- else:
52
- with open(path, encoding="utf-8") as f:
53
- for raw in f:
54
- yield raw.rstrip("\n")
55
-
56
-
57
- def parse_caption(line):
58
- """Split ``COCO_val2014_000000043734#0<tab>两只黑色的狗...`` into (key, text)."""
59
- line = line.strip()
60
- if not line:
61
- return None
62
- if "\t" in line:
63
- key, text = line.split("\t", 1)
64
- else:
65
- parts = line.split(None, 1)
66
- if len(parts) != 2:
67
- return None
68
- key, text = parts
69
- text = text.strip()
70
- return (key, text) if text else None
71
-
72
-
73
- def main():
74
- parser = argparse.ArgumentParser(description=__doc__)
75
- parser.add_argument("--captions", default=DEFAULT_CAPTIONS,
76
- help="plain caption .txt or dataset .tar/.tar.gz")
77
- parser.add_argument("--member", default=DEFAULT_MEMBER,
78
- help="member path inside the archive")
79
- parser.add_argument("--model-dir", default=DEFAULT_MODEL_DIR,
80
- help="directory holding tokenizer.json")
81
- parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
82
- parser.add_argument("--zip", dest="zip_path",
83
- default=os.path.join(os.path.dirname(DEFAULT_OUTPUT_DIR),
84
- "fgclip2_text_calibration.zip"))
85
- parser.add_argument("--text-length", type=int, default=64)
86
- parser.add_argument("--limit", type=int, default=512,
87
- help="max samples to write, 0 means all")
88
- parser.add_argument("--no-zip", action="store_true")
89
- args = parser.parse_args()
90
-
91
- captions_path = os.path.abspath(args.captions)
92
- model_dir = os.path.abspath(args.model_dir)
93
- output_dir = os.path.abspath(args.output_dir)
94
- zip_path = os.path.abspath(args.zip_path)
95
-
96
- tokenizer = AutoTokenizer.from_pretrained(model_dir, local_files_only=True)
97
-
98
- records = []
99
- for line in read_lines(captions_path, args.member):
100
- item = parse_caption(line)
101
- if item is not None:
102
- records.append(item)
103
- if args.limit and len(records) >= args.limit:
104
- break
105
- if not records:
106
- raise SystemExit(f"no captions parsed from {captions_path}")
107
- print(f"[read] {len(records)} captions from {captions_path}")
108
-
109
- os.makedirs(output_dir, exist_ok=True)
110
- _, texts = zip(*records)
111
- enc = tokenizer(
112
- list(texts),
113
- padding="max_length",
114
- max_length=args.text_length,
115
- truncation=True,
116
- return_tensors="np",
117
- )
118
- input_ids = enc["input_ids"]
119
- assert input_ids.shape == (len(records), args.text_length), input_ids.shape
120
-
121
- for idx in range(len(records)):
122
- arr = input_ids[idx:idx + 1].astype(np.int64)
123
- np.save(os.path.join(output_dir, f"{idx:06d}.npy"), arr)
124
-
125
- manifest = output_dir.rstrip(os.sep) + "_manifest.txt"
126
- with open(manifest, "w", encoding="utf-8") as f:
127
- for idx, (key, text) in enumerate(records):
128
- f.write(f"{idx:06d}.npy\t{key}\t{text}\n")
129
- print(f"[write] {len(records)} npy files -> {output_dir}")
130
- print(f"[write] manifest -> {manifest}")
131
-
132
- if not args.no_zip:
133
- folder = os.path.basename(output_dir.rstrip(os.sep))
134
- os.makedirs(os.path.dirname(zip_path), exist_ok=True)
135
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
136
- for name in sorted(os.listdir(output_dir)):
137
- if name.endswith(".npy"):
138
- zf.write(os.path.join(output_dir, name), f"{folder}/{name}")
139
- print(f"[zip] {zip_path} ({os.path.getsize(zip_path) / 1024 ** 2:.2f} MiB)")
140
-
141
- print(f"[info] sample shape={input_ids[0:1].shape} dtype=int64 "
142
- f"ids[:8]={input_ids[0][:8].tolist()}")
143
-
144
-
145
- if __name__ == "__main__":
146
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/infer/fgclip2_infer_axmodel.py DELETED
@@ -1,403 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Run the FG-CLIP 2 Large encoders on AX650 (axmodel).
3
-
4
- This script is meant for the BOARD. It only needs axengine + numpy + Pillow;
5
- it never imports onnxruntime, torch or transformers.
6
-
7
- Two modes:
8
-
9
- single --image PATH --texts ... quick sanity check, prints similarity
10
- dataset --dataset DIR batch inference, writes raw features
11
-
12
- Dataset layout:
13
- <dataset>/images/*.jpg
14
- <dataset>/pairs.jsonl # one JSON object per line: {"image": "...", "text": "..."}
15
-
16
- Input contract (verified against the compiled graph):
17
- image : patchified Siglip2 input [1, num_patches, 3*patch*patch].
18
- resize(RGB, BILINEAR) to image-size -> /255 -> (x-0.5)/0.5 -> 16x16 patches.
19
- text : int64 token ids [1,L] (L=64 for walk_type "short"). Input dtype is
20
- read from the runtime, i.e. it may become int32 after pulsar2
21
- rewrites the ONNX int64 input.
22
-
23
- Usage:
24
- # single image
25
- python fgclip2_infer_axmodel.py \
26
- --image-model fgclip2_large_image_encoder.axmodel \
27
- --text-model fgclip2_large_text_encoder_short.axmodel \
28
- --tokenizer tokenizer.json --image bedroom.jpg \
29
- --texts 一个简约风格的卧室角落 一张铺着白色床单的床
30
-
31
- # dataset
32
- python fgclip2_infer_axmodel.py \
33
- --image-model fgclip2_large_image_encoder.axmodel \
34
- --text-model fgclip2_large_text_encoder_short.axmodel \
35
- --tokenizer tokenizer.json \
36
- --dataset fgclip_eval_64 --output results/axmodel.npz
37
- """
38
-
39
- import argparse
40
- import json
41
- import os
42
- import sys
43
- import time
44
-
45
- import numpy as np
46
- from PIL import Image
47
-
48
- try:
49
- from tqdm import tqdm
50
- except ImportError: # board image may not ship tqdm
51
- tqdm = None
52
-
53
-
54
- PATCH_SIZE = 16
55
- IMAGE_MEAN = 0.5
56
- IMAGE_STD = 0.5
57
- DEFAULT_TEXTS = ["一个简约风格的卧室角落,黑色金属衣架上挂着衣物。", "一只猫在窗台上晒太阳。"]
58
- BACKEND = "axmodel"
59
-
60
-
61
- # ---------------------------------------------------------------------------
62
- # Gemma BPE tokenizer (reads tokenizer.json; mirrors the HF fast tokenizer)
63
- # ---------------------------------------------------------------------------
64
-
65
- class GemmaBpeTokenizer:
66
- def __init__(self, tokenizer_file, pad_id=0, eos_id=1, unk_id=3):
67
- with open(tokenizer_file, encoding="utf-8") as f:
68
- data = json.load(f)
69
- self.vocab = data["model"]["vocab"]
70
- self.rank = {}
71
- for rank, pair in enumerate(data["model"]["merges"]):
72
- self.rank[(pair[0], pair[1])] = rank
73
- added = [(a["content"], a["id"]) for a in data.get("added_tokens", [])]
74
- added.sort(key=lambda x: -len(x[0]))
75
- self.added = added
76
- self.pad_id = pad_id
77
- self.eos_id = eos_id
78
- self.unk_id = unk_id
79
-
80
- def _byte_fallback(self, ch):
81
- out = []
82
- for b in ch.encode("utf-8"):
83
- token = f"<0x{b:02X}>"
84
- out.append(token if token in self.vocab else None)
85
- return out
86
-
87
- def _bpe(self, segment):
88
- symbols = []
89
- for ch in segment:
90
- if ch in self.vocab:
91
- symbols.append(ch)
92
- else:
93
- for token in self._byte_fallback(ch):
94
- symbols.append(token if token is not None else "<unk>")
95
-
96
- while len(symbols) > 1:
97
- best_rank, best_i = None, -1
98
- for i in range(len(symbols) - 1):
99
- rank = self.rank.get((symbols[i], symbols[i + 1]))
100
- if rank is not None and (best_rank is None or rank < best_rank):
101
- best_rank, best_i = rank, i
102
- if best_rank is None:
103
- break
104
-
105
- pair = (symbols[best_i], symbols[best_i + 1])
106
- merged, i = [], 0
107
- while i < len(symbols):
108
- if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
109
- merged.append(symbols[i] + symbols[i + 1])
110
- i += 2
111
- else:
112
- merged.append(symbols[i])
113
- i += 1
114
- symbols = merged
115
- return symbols
116
-
117
- def encode(self, text, max_length, dtype=np.int64):
118
- text = text.replace(" ", "▁")
119
- ids, buf, i = [], "", 0
120
- while i < len(text):
121
- hit = None
122
- for content, token_id in self.added:
123
- if text.startswith(content, i):
124
- hit = (content, token_id)
125
- break
126
- if hit is not None:
127
- if buf:
128
- ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
129
- buf = ""
130
- ids.append(hit[1])
131
- i += len(hit[0])
132
- else:
133
- buf += text[i]
134
- i += 1
135
- if buf:
136
- ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
137
-
138
- ids = (ids + [self.eos_id])[:max_length]
139
- ids += [self.pad_id] * (max_length - len(ids))
140
- return np.asarray(ids, dtype=dtype).reshape(1, max_length)
141
-
142
-
143
- # ---------------------------------------------------------------------------
144
- # Runtime helpers
145
- # ---------------------------------------------------------------------------
146
-
147
- def create_session(path):
148
- import axengine
149
- return axengine.InferenceSession(path)
150
-
151
-
152
- def input_name_and_dtype(sess):
153
- node = sess.get_inputs()[0]
154
- dtype = getattr(node, "dtype", None)
155
- if not isinstance(dtype, np.dtype):
156
- text = str(getattr(node, "type", ""))
157
- name = text.split("(")[-1].rstrip(")")
158
- dtype = np.dtype({
159
- "float": np.float32, "double": np.float64, "float16": np.float16,
160
- "int8": np.int8, "uint8": np.uint8, "int16": np.int16,
161
- "uint16": np.uint16, "int32": np.int32, "uint32": np.uint32,
162
- "int64": np.int64,
163
- }.get(name, name))
164
- return node.name, dtype
165
-
166
-
167
- def run_feature(sess, x):
168
- name, dtype = input_name_and_dtype(sess)
169
- x = np.ascontiguousarray(x, dtype=dtype)
170
- start = time.perf_counter()
171
- out = sess.run(None, {name: x})[0]
172
- elapsed = (time.perf_counter() - start) * 1000.0
173
- return np.asarray(out, dtype=np.float32).reshape(-1), elapsed
174
-
175
-
176
- def preprocess_image(path, image_size):
177
- image = Image.open(path).convert("RGB")
178
- resample = getattr(Image, "Resampling", Image).BILINEAR
179
- image = image.resize((image_size, image_size), resample)
180
- x = np.asarray(image, dtype=np.float32) / 255.0
181
- x = (x - IMAGE_MEAN) / IMAGE_STD
182
- grid = image_size // PATCH_SIZE
183
- patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
184
- patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
185
- return np.ascontiguousarray(patches)
186
-
187
-
188
- def normalize(x):
189
- return x / (np.linalg.norm(x, axis=-1, keepdims=True) + 1e-12)
190
-
191
-
192
- def softmax(x):
193
- x = x - np.max(x)
194
- e = np.exp(x)
195
- return e / np.sum(e)
196
-
197
-
198
- # ---------------------------------------------------------------------------
199
- # Dataset
200
- # ---------------------------------------------------------------------------
201
-
202
- def load_pairs(dataset_dir, pairs_file, limit):
203
- pairs_path = pairs_file or os.path.join(dataset_dir, "pairs.jsonl")
204
- if not os.path.isfile(pairs_path):
205
- raise SystemExit(f"pairs file not found: {pairs_path}")
206
- pairs = []
207
- with open(pairs_path, encoding="utf-8") as f:
208
- for line in f:
209
- line = line.strip()
210
- if not line:
211
- continue
212
- item = json.loads(line)
213
- pairs.append((item["image"], item["text"]))
214
- if limit and len(pairs) >= limit:
215
- break
216
- if not pairs:
217
- raise SystemExit(f"no pairs in {pairs_path}")
218
- return pairs
219
-
220
-
221
- def group_pairs(pairs):
222
- """Deduplicate images, keep the first-seen order, map each text to an image."""
223
- image_names = []
224
- image_index = {}
225
- text_captions = []
226
- text_image_index = []
227
- for image_name, text in pairs:
228
- if image_name not in image_index:
229
- image_index[image_name] = len(image_names)
230
- image_names.append(image_name)
231
- text_captions.append(text)
232
- text_image_index.append(image_index[image_name])
233
- return image_names, text_captions, np.asarray(text_image_index, dtype=np.int32)
234
-
235
-
236
- def save_dump(path, backend, image_model, text_model, image_names, text_captions,
237
- text_image_index, image_features, text_features,
238
- image_ms, text_ms, image_pre_ms, text_pre_ms):
239
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
240
- np.savez(
241
- path,
242
- backend=np.asarray(backend),
243
- image_model=np.asarray(os.path.basename(image_model)),
244
- text_model=np.asarray(os.path.basename(text_model)),
245
- image_names=np.asarray(image_names),
246
- text_captions=np.asarray(text_captions),
247
- text_image_index=np.asarray(text_image_index, dtype=np.int32),
248
- image_features=image_features,
249
- text_features=text_features,
250
- image_ms=np.asarray(image_ms, dtype=np.float32),
251
- text_ms=np.asarray(text_ms, dtype=np.float32),
252
- image_preprocess_ms=np.asarray(image_pre_ms, dtype=np.float32),
253
- text_tokenize_ms=np.asarray(text_pre_ms, dtype=np.float32),
254
- )
255
- print(f"[save] {path}")
256
-
257
-
258
- # ---------------------------------------------------------------------------
259
- # Modes
260
- # ---------------------------------------------------------------------------
261
-
262
- def run_single(args, tokenizer, image_sess, text_sess):
263
- start = time.perf_counter()
264
- pre_start = time.perf_counter()
265
- x = preprocess_image(args.image, args.image_size)
266
- pre_ms = (time.perf_counter() - pre_start) * 1000.0
267
- image_feature, image_ms = run_feature(image_sess, x)
268
-
269
- text_features = []
270
- text_ms = []
271
- for text in args.texts:
272
- tok_start = time.perf_counter()
273
- ids = tokenizer.encode(text, args.text_length)
274
- tok_ms = (time.perf_counter() - tok_start) * 1000.0
275
- feat, ms = run_feature(text_sess, ids)
276
- text_features.append(feat)
277
- text_ms.append(ms)
278
- if args.verbose:
279
- print(f"[time] text tokenize={tok_ms:.2f}ms infer={ms:.2f}ms")
280
- text_features = np.stack(text_features)
281
- total_ms = (time.perf_counter() - start) * 1000.0
282
-
283
- print(f"[time] preprocess={pre_ms:.2f}ms image_infer={image_ms:.2f}ms "
284
- f"text_infer(avg)={np.mean(text_ms):.2f}ms total={total_ms:.2f}ms")
285
-
286
- sim = normalize(image_feature[None])[0] @ normalize(text_features).T
287
- probs = softmax(sim * 100.0)
288
- best = int(np.argmax(probs))
289
- print("similarity matrix (cosine):")
290
- for i, text in enumerate(args.texts):
291
- print(f" {text:<40} sim={sim[i]:.4f} prob={probs[i]:.4f}")
292
- print(f"[result] top-1: {args.texts[best]} (prob={probs[best]:.4f})")
293
-
294
- if args.output:
295
- save_dump(
296
- args.output, BACKEND, args.image_model, args.text_model,
297
- [os.path.basename(args.image)], args.texts, np.zeros(len(args.texts)),
298
- image_feature[None], text_features,
299
- [image_ms], text_ms, [pre_ms], [0.0] * len(args.texts),
300
- )
301
-
302
-
303
- def run_dataset(args, tokenizer, image_sess, text_sess):
304
- dataset_dir = os.path.abspath(args.dataset)
305
- pairs = load_pairs(dataset_dir, args.pairs, args.limit)
306
- image_names, text_captions, text_image_index = group_pairs(pairs)
307
- print(f"[data] {len(image_names)} images, {len(text_captions)} captions")
308
-
309
- image_iter = tqdm(image_names, desc="image") if tqdm else image_names
310
- image_features = None
311
- image_ms = []
312
- image_pre_ms = []
313
- for i, name in enumerate(image_iter):
314
- pre_start = time.perf_counter()
315
- x = preprocess_image(os.path.join(dataset_dir, "images", name), args.image_size)
316
- image_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
317
- feat, ms = run_feature(image_sess, x)
318
- if image_features is None:
319
- image_features = np.zeros((len(image_names), feat.shape[0]), dtype=np.float32)
320
- image_features[i] = feat
321
- image_ms.append(ms)
322
-
323
- text_iter = tqdm(text_captions, desc="text") if tqdm else text_captions
324
- text_features = np.zeros((len(text_captions), image_features.shape[1]), dtype=np.float32)
325
- text_ms = []
326
- text_pre_ms = []
327
- for i, caption in enumerate(text_iter):
328
- pre_start = time.perf_counter()
329
- ids = tokenizer.encode(caption, args.text_length)
330
- text_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
331
- feat, ms = run_feature(text_sess, ids)
332
- if feat.shape[0] != text_features.shape[1]:
333
- raise SystemExit(f"feature size mismatch: "
334
- f"image={text_features.shape[1]} text={feat.shape[0]}")
335
- text_features[i] = feat
336
- text_ms.append(ms)
337
-
338
- print(f"[time] image preprocess={np.mean(image_pre_ms):.2f}ms "
339
- f"infer={np.mean(image_ms):.2f}ms/img; "
340
- f"text tokenize={np.mean(text_pre_ms):.2f}ms "
341
- f"infer={np.mean(text_ms):.2f}ms/text")
342
- print(f"[time] image p50={np.percentile(image_ms, 50):.2f}ms "
343
- f"p90={np.percentile(image_ms, 90):.2f}ms "
344
- f"p99={np.percentile(image_ms, 99):.2f}ms")
345
- total_ms = float(np.sum(image_pre_ms) + np.sum(image_ms) + np.sum(text_pre_ms) + np.sum(text_ms))
346
- print(f"[time] total={total_ms:.2f}ms fps={len(text_captions) / (total_ms / 1000.0):.2f}/s")
347
-
348
- save_dump(
349
- args.output, BACKEND, args.image_model, args.text_model,
350
- image_names, text_captions, text_image_index,
351
- image_features, text_features,
352
- image_ms, text_ms, image_pre_ms, text_pre_ms,
353
- )
354
-
355
-
356
- # ---------------------------------------------------------------------------
357
- # Main
358
- # ---------------------------------------------------------------------------
359
-
360
- def main():
361
- parser = argparse.ArgumentParser(
362
- description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
363
- allow_abbrev=False)
364
- parser.add_argument("--image-model", required=True, help="image encoder .axmodel")
365
- parser.add_argument("--text-model", required=True, help="text encoder .axmodel")
366
- parser.add_argument("--tokenizer", required=True, help="tokenizer.json path")
367
- parser.add_argument("--image", default=None, help="single image path (single mode)")
368
- parser.add_argument("--texts", nargs="+", default=None,
369
- help=f"candidate texts for single mode (default: {DEFAULT_TEXTS})")
370
- parser.add_argument("--dataset", default=None, help="dataset directory (dataset mode)")
371
- parser.add_argument("--pairs", default=None,
372
- help="pairs.jsonl (default: <dataset>/pairs.jsonl)")
373
- parser.add_argument("--output", default=None,
374
- help="output .npz (required in dataset mode, optional in single mode)")
375
- parser.add_argument("--image-size", type=int, default=256,
376
- help="square input size, must be a multiple of 16 (default 256)")
377
- parser.add_argument("--text-length", type=int, default=64,
378
- help="fixed token length (64 for short/box, 196 for long)")
379
- parser.add_argument("--limit", type=int, default=0,
380
- help="only use the first N pairs (dataset mode, 0 = all)")
381
- parser.add_argument("--verbose", action="store_true",
382
- help="print tokenize/infer time per text in single mode")
383
- args = parser.parse_args()
384
-
385
- if bool(args.image) == bool(args.dataset):
386
- parser.error("exactly one of --image (single mode) / --dataset (dataset mode) is required")
387
- if args.dataset and not args.output:
388
- parser.error("--output is required in dataset mode")
389
- if args.image and not args.texts:
390
- args.texts = DEFAULT_TEXTS
391
-
392
- tokenizer = GemmaBpeTokenizer(args.tokenizer)
393
- image_sess = create_session(args.image_model)
394
- text_sess = create_session(args.text_model)
395
-
396
- if args.image:
397
- run_single(args, tokenizer, image_sess, text_sess)
398
- else:
399
- run_dataset(args, tokenizer, image_sess, text_sess)
400
-
401
-
402
- if __name__ == "__main__":
403
- sys.exit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/infer/fgclip2_infer_onnx.py DELETED
@@ -1,398 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Run the FG-CLIP 2 Large encoders in FP32 ONNX.
3
-
4
- This script is meant for the DEVELOPMENT HOST. It uses onnxruntime and writes
5
- the same .npz schema as ``fgclip2_infer_axmodel.py`` so one evaluator can
6
- compare the two backends.
7
-
8
- Two modes:
9
-
10
- single --image PATH --texts ... quick sanity check, prints similarity
11
- dataset --dataset DIR batch inference, writes raw features
12
-
13
- Dataset layout:
14
- <dataset>/images/*.jpg
15
- <dataset>/pairs.jsonl # one JSON object per line: {"image": "...", "text": "..."}
16
-
17
- Input contract:
18
- image : patchified Siglip2 input [1, num_patches, 3*patch*patch].
19
- resize(RGB, BILINEAR) to image-size -> /255 -> (x-0.5)/0.5 -> 16x16 patches.
20
- text : int64 token ids [1,L] (L=64 for walk_type "short"). Tokenizer is a
21
- pure-Python Gemma BPE reader (tokenizer.json); it matches the
22
- HuggingFace tokenizer and needs no transformers on the board.
23
-
24
- Usage:
25
- # single image
26
- python src/infer/fgclip2_infer_onnx.py \
27
- --image-model models/fgclip2_large_image_encoder.onnx \
28
- --text-model models/fgclip2_large_text_encoder_short.onnx \
29
- --tokenizer fg-clip2-large/tokenizer.json --image bedroom.jpg \
30
- --texts 一个简约风格的卧室角落 一张铺着白色床单的床
31
-
32
- # dataset
33
- python src/infer/fgclip2_infer_onnx.py \
34
- --image-model models/fgclip2_large_image_encoder.onnx \
35
- --text-model models/fgclip2_large_text_encoder_short.onnx \
36
- --tokenizer fg-clip2-large/tokenizer.json \
37
- --dataset fgclip_eval_64 --output results/onnx.npz
38
- """
39
-
40
- import argparse
41
- import json
42
- import os
43
- import sys
44
- import time
45
-
46
- import numpy as np
47
- from PIL import Image
48
-
49
- try:
50
- from tqdm import tqdm
51
- except ImportError: # board image may not ship tqdm
52
- tqdm = None
53
-
54
-
55
- PATCH_SIZE = 16
56
- IMAGE_MEAN = 0.5
57
- IMAGE_STD = 0.5
58
- DEFAULT_TEXTS = ["一个简约风格的卧室角落,黑色金属衣架上挂着衣物。", "一只猫在窗台上晒太阳。"]
59
- BACKEND = "onnx"
60
-
61
-
62
- # ---------------------------------------------------------------------------
63
- # Gemma BPE tokenizer (reads tokenizer.json; mirrors the HF fast tokenizer)
64
- # ---------------------------------------------------------------------------
65
-
66
- class GemmaBpeTokenizer:
67
- def __init__(self, tokenizer_file, pad_id=0, eos_id=1, unk_id=3):
68
- with open(tokenizer_file, encoding="utf-8") as f:
69
- data = json.load(f)
70
- self.vocab = data["model"]["vocab"]
71
- self.rank = {}
72
- for rank, pair in enumerate(data["model"]["merges"]):
73
- self.rank[(pair[0], pair[1])] = rank
74
- added = [(a["content"], a["id"]) for a in data.get("added_tokens", [])]
75
- added.sort(key=lambda x: -len(x[0]))
76
- self.added = added
77
- self.pad_id = pad_id
78
- self.eos_id = eos_id
79
- self.unk_id = unk_id
80
-
81
- def _byte_fallback(self, ch):
82
- out = []
83
- for b in ch.encode("utf-8"):
84
- token = f"<0x{b:02X}>"
85
- out.append(token if token in self.vocab else None)
86
- return out
87
-
88
- def _bpe(self, segment):
89
- symbols = []
90
- for ch in segment:
91
- if ch in self.vocab:
92
- symbols.append(ch)
93
- else:
94
- for token in self._byte_fallback(ch):
95
- symbols.append(token if token is not None else "<unk>")
96
-
97
- while len(symbols) > 1:
98
- best_rank, best_i = None, -1
99
- for i in range(len(symbols) - 1):
100
- rank = self.rank.get((symbols[i], symbols[i + 1]))
101
- if rank is not None and (best_rank is None or rank < best_rank):
102
- best_rank, best_i = rank, i
103
- if best_rank is None:
104
- break
105
-
106
- pair = (symbols[best_i], symbols[best_i + 1])
107
- merged, i = [], 0
108
- while i < len(symbols):
109
- if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
110
- merged.append(symbols[i] + symbols[i + 1])
111
- i += 2
112
- else:
113
- merged.append(symbols[i])
114
- i += 1
115
- symbols = merged
116
- return symbols
117
-
118
- def encode(self, text, max_length, dtype=np.int64):
119
- text = text.replace(" ", "▁")
120
- ids, buf, i = [], "", 0
121
- while i < len(text):
122
- hit = None
123
- for content, token_id in self.added:
124
- if text.startswith(content, i):
125
- hit = (content, token_id)
126
- break
127
- if hit is not None:
128
- if buf:
129
- ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
130
- buf = ""
131
- ids.append(hit[1])
132
- i += len(hit[0])
133
- else:
134
- buf += text[i]
135
- i += 1
136
- if buf:
137
- ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
138
-
139
- ids = (ids + [self.eos_id])[:max_length]
140
- ids += [self.pad_id] * (max_length - len(ids))
141
- return np.asarray(ids, dtype=dtype).reshape(1, max_length)
142
-
143
-
144
- # ---------------------------------------------------------------------------
145
- # Runtime helpers
146
- # ---------------------------------------------------------------------------
147
-
148
- def create_session(path):
149
- import onnxruntime as ort
150
- return ort.InferenceSession(path, providers=["CPUExecutionProvider"])
151
-
152
-
153
- def input_name_and_dtype(sess):
154
- node = sess.get_inputs()[0]
155
- dtype = getattr(node, "dtype", None)
156
- if not isinstance(dtype, np.dtype):
157
- text = str(getattr(node, "type", ""))
158
- name = text.split("(")[-1].rstrip(")")
159
- dtype = np.dtype({
160
- "float": np.float32, "double": np.float64, "float16": np.float16,
161
- "int8": np.int8, "uint8": np.uint8, "int16": np.int16,
162
- "uint16": np.uint16, "int32": np.int32, "uint32": np.uint32,
163
- "int64": np.int64,
164
- }.get(name, name))
165
- return node.name, dtype
166
-
167
-
168
- def run_feature(sess, x):
169
- name, dtype = input_name_and_dtype(sess)
170
- x = np.ascontiguousarray(x, dtype=dtype)
171
- start = time.perf_counter()
172
- out = sess.run(None, {name: x})[0]
173
- elapsed = (time.perf_counter() - start) * 1000.0
174
- return np.asarray(out, dtype=np.float32).reshape(-1), elapsed
175
-
176
-
177
- def preprocess_image(path, image_size):
178
- image = Image.open(path).convert("RGB")
179
- resample = getattr(Image, "Resampling", Image).BILINEAR
180
- image = image.resize((image_size, image_size), resample)
181
- x = np.asarray(image, dtype=np.float32) / 255.0
182
- x = (x - IMAGE_MEAN) / IMAGE_STD
183
- grid = image_size // PATCH_SIZE
184
- patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
185
- patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
186
- return np.ascontiguousarray(patches)
187
-
188
-
189
- def normalize(x):
190
- return x / (np.linalg.norm(x, axis=-1, keepdims=True) + 1e-12)
191
-
192
-
193
- def softmax(x):
194
- x = x - np.max(x)
195
- e = np.exp(x)
196
- return e / np.sum(e)
197
-
198
-
199
- # ---------------------------------------------------------------------------
200
- # Dataset
201
- # ---------------------------------------------------------------------------
202
-
203
- def load_pairs(dataset_dir, pairs_file, limit):
204
- pairs_path = pairs_file or os.path.join(dataset_dir, "pairs.jsonl")
205
- if not os.path.isfile(pairs_path):
206
- raise SystemExit(f"pairs file not found: {pairs_path}")
207
- pairs = []
208
- with open(pairs_path, encoding="utf-8") as f:
209
- for line in f:
210
- line = line.strip()
211
- if not line:
212
- continue
213
- item = json.loads(line)
214
- pairs.append((item["image"], item["text"]))
215
- if limit and len(pairs) >= limit:
216
- break
217
- if not pairs:
218
- raise SystemExit(f"no pairs in {pairs_path}")
219
- return pairs
220
-
221
-
222
- def group_pairs(pairs):
223
- """Deduplicate images, keep the first-seen order, map each text to an image."""
224
- image_names = []
225
- image_index = {}
226
- text_captions = []
227
- text_image_index = []
228
- for image_name, text in pairs:
229
- if image_name not in image_index:
230
- image_index[image_name] = len(image_names)
231
- image_names.append(image_name)
232
- text_captions.append(text)
233
- text_image_index.append(image_index[image_name])
234
- return image_names, text_captions, np.asarray(text_image_index, dtype=np.int32)
235
-
236
-
237
- def save_dump(path, backend, image_model, text_model, image_names, text_captions,
238
- text_image_index, image_features, text_features,
239
- image_ms, text_ms, image_pre_ms, text_pre_ms):
240
- os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
241
- np.savez(
242
- path,
243
- backend=np.asarray(backend),
244
- image_model=np.asarray(os.path.basename(image_model)),
245
- text_model=np.asarray(os.path.basename(text_model)),
246
- image_names=np.asarray(image_names),
247
- text_captions=np.asarray(text_captions),
248
- text_image_index=np.asarray(text_image_index, dtype=np.int32),
249
- image_features=image_features,
250
- text_features=text_features,
251
- image_ms=np.asarray(image_ms, dtype=np.float32),
252
- text_ms=np.asarray(text_ms, dtype=np.float32),
253
- image_preprocess_ms=np.asarray(image_pre_ms, dtype=np.float32),
254
- text_tokenize_ms=np.asarray(text_pre_ms, dtype=np.float32),
255
- )
256
- print(f"[save] {path}")
257
-
258
-
259
- # ---------------------------------------------------------------------------
260
- # Modes
261
- # ---------------------------------------------------------------------------
262
-
263
- def run_single(args, tokenizer, image_sess, text_sess):
264
- start = time.perf_counter()
265
- pre_start = time.perf_counter()
266
- x = preprocess_image(args.image, args.image_size)
267
- pre_ms = (time.perf_counter() - pre_start) * 1000.0
268
- image_feature, image_ms = run_feature(image_sess, x)
269
-
270
- text_features = []
271
- text_ms = []
272
- for text in args.texts:
273
- ids = tokenizer.encode(text, args.text_length)
274
- feat, ms = run_feature(text_sess, ids)
275
- text_features.append(feat)
276
- text_ms.append(ms)
277
- text_features = np.stack(text_features)
278
- total_ms = (time.perf_counter() - start) * 1000.0
279
-
280
- print(f"[time] preprocess={pre_ms:.2f}ms image_infer={image_ms:.2f}ms "
281
- f"text_infer(avg)={np.mean(text_ms):.2f}ms total={total_ms:.2f}ms")
282
-
283
- sim = normalize(image_feature[None])[0] @ normalize(text_features).T
284
- probs = softmax(sim * 100.0)
285
- best = int(np.argmax(probs))
286
- print("similarity matrix (cosine):")
287
- for i, text in enumerate(args.texts):
288
- print(f" {text:<40} sim={sim[i]:.4f} prob={probs[i]:.4f}")
289
- print(f"[result] top-1: {args.texts[best]} (prob={probs[best]:.4f})")
290
-
291
- if args.output:
292
- save_dump(
293
- args.output, BACKEND, args.image_model, args.text_model,
294
- [os.path.basename(args.image)], args.texts, np.zeros(len(args.texts)),
295
- image_feature[None], text_features,
296
- [image_ms], text_ms, [pre_ms], [0.0] * len(args.texts),
297
- )
298
-
299
-
300
- def run_dataset(args, tokenizer, image_sess, text_sess):
301
- dataset_dir = os.path.abspath(args.dataset)
302
- pairs = load_pairs(dataset_dir, args.pairs, args.limit)
303
- image_names, text_captions, text_image_index = group_pairs(pairs)
304
- print(f"[data] {len(image_names)} images, {len(text_captions)} captions")
305
-
306
- image_iter = tqdm(image_names, desc="image") if tqdm else image_names
307
- image_features = None
308
- image_ms = []
309
- image_pre_ms = []
310
- for i, name in enumerate(image_iter):
311
- pre_start = time.perf_counter()
312
- x = preprocess_image(os.path.join(dataset_dir, "images", name), args.image_size)
313
- image_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
314
- feat, ms = run_feature(image_sess, x)
315
- if image_features is None:
316
- image_features = np.zeros((len(image_names), feat.shape[0]), dtype=np.float32)
317
- image_features[i] = feat
318
- image_ms.append(ms)
319
-
320
- text_iter = tqdm(text_captions, desc="text") if tqdm else text_captions
321
- text_features = np.zeros((len(text_captions), image_features.shape[1]), dtype=np.float32)
322
- text_ms = []
323
- text_pre_ms = []
324
- for i, caption in enumerate(text_iter):
325
- pre_start = time.perf_counter()
326
- ids = tokenizer.encode(caption, args.text_length)
327
- text_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
328
- feat, ms = run_feature(text_sess, ids)
329
- if feat.shape[0] != text_features.shape[1]:
330
- raise SystemExit(f"feature size mismatch: "
331
- f"image={text_features.shape[1]} text={feat.shape[0]}")
332
- text_features[i] = feat
333
- text_ms.append(ms)
334
-
335
- print(f"[time] image preprocess={np.mean(image_pre_ms):.2f}ms "
336
- f"infer={np.mean(image_ms):.2f}ms/img; "
337
- f"text tokenize={np.mean(text_pre_ms):.2f}ms "
338
- f"infer={np.mean(text_ms):.2f}ms/text")
339
- print(f"[time] image p50={np.percentile(image_ms, 50):.2f}ms "
340
- f"p90={np.percentile(image_ms, 90):.2f}ms "
341
- f"p99={np.percentile(image_ms, 99):.2f}ms")
342
- total_ms = float(np.sum(image_pre_ms) + np.sum(image_ms) + np.sum(text_pre_ms) + np.sum(text_ms))
343
- print(f"[time] total={total_ms:.2f}ms fps={len(text_captions) / (total_ms / 1000.0):.2f}/s")
344
-
345
- save_dump(
346
- args.output, BACKEND, args.image_model, args.text_model,
347
- image_names, text_captions, text_image_index,
348
- image_features, text_features,
349
- image_ms, text_ms, image_pre_ms, text_pre_ms,
350
- )
351
-
352
-
353
- # ---------------------------------------------------------------------------
354
- # Main
355
- # ---------------------------------------------------------------------------
356
-
357
- def main():
358
- parser = argparse.ArgumentParser(
359
- description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
360
- allow_abbrev=False)
361
- parser.add_argument("--image-model", required=True, help="image encoder .onnx")
362
- parser.add_argument("--text-model", required=True, help="text encoder .onnx")
363
- parser.add_argument("--tokenizer", required=True, help="tokenizer.json path")
364
- parser.add_argument("--image", default=None, help="single image path (single mode)")
365
- parser.add_argument("--texts", nargs="+", default=None,
366
- help=f"candidate texts for single mode (default: {DEFAULT_TEXTS})")
367
- parser.add_argument("--dataset", default=None, help="dataset directory (dataset mode)")
368
- parser.add_argument("--pairs", default=None,
369
- help="pairs.jsonl (default: <dataset>/pairs.jsonl)")
370
- parser.add_argument("--output", default=None,
371
- help="output .npz (required in dataset mode, optional in single mode)")
372
- parser.add_argument("--image-size", type=int, default=256,
373
- help="square input size, must be a multiple of 16 (default 256)")
374
- parser.add_argument("--text-length", type=int, default=64,
375
- help="fixed token length (64 for short/box, 196 for long)")
376
- parser.add_argument("--limit", type=int, default=0,
377
- help="only use the first N pairs (dataset mode, 0 = all)")
378
- args = parser.parse_args()
379
-
380
- if bool(args.image) == bool(args.dataset):
381
- parser.error("exactly one of --image (single mode) / --dataset (dataset mode) is required")
382
- if args.dataset and not args.output:
383
- parser.error("--output is required in dataset mode")
384
- if args.image and not args.texts:
385
- args.texts = DEFAULT_TEXTS
386
-
387
- tokenizer = GemmaBpeTokenizer(args.tokenizer)
388
- image_sess = create_session(args.image_model)
389
- text_sess = create_session(args.text_model)
390
-
391
- if args.image:
392
- run_single(args, tokenizer, image_sess, text_sess)
393
- else:
394
- run_dataset(args, tokenizer, image_sess, text_sess)
395
-
396
-
397
- if __name__ == "__main__":
398
- sys.exit(main())