CardAnvilModels commited on
Commit
7eee2d7
·
verified ·
1 Parent(s): a8c9fe2

SAM 3 text-prompted segmentation for WebGPU: Standard (fp16) and Compact (8-bit weights)

Browse files

Vision, text and detector graphs exported from facebook/sam3 at 3c879f39 (model.safetensors SHA-256 6d06f0a5...), checked against PyTorch on CPU and WebGPU. Distributed under the SAM License (LICENSE).

LICENSE ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SAM License
2
+ Last Updated: November 19, 2025
3
+
4
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein.
5
+
6
+
7
+ “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
8
+
9
+ “Documentation” means the specifications, manuals and documentation accompanying
10
+ SAM Materials distributed by Meta.
11
+
12
+
13
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
14
+
15
+
16
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
17
+
18
+
19
+ “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
20
+
21
+
22
+ “Trade Controls” means any of the following: Sanctions and applicable export and import controls.
23
+
24
+ By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement.
25
+
26
+
27
+ 1. License Rights and Redistribution.
28
+
29
+
30
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials.
31
+
32
+ b. Redistribution and Use.
33
+ i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials.
34
+
35
+
36
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication.
37
+
38
+
39
+ iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
40
+ iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials.
41
+ v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
42
+ 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
43
+
44
+
45
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS.
46
+
47
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
48
+
49
+ 5. Intellectual Property.
50
+
51
+
52
+ a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
53
+
54
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials.
55
+
56
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
57
+
58
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
59
+
60
+
61
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: sam-license
4
+ license_link: LICENSE
5
+ library_name: onnx
6
+ pipeline_tag: mask-generation
7
+ base_model: facebook/sam3
8
+ tags:
9
+ - sam3
10
+ - segment-anything
11
+ - text-prompted-segmentation
12
+ - onnx
13
+ - onnxruntime-web
14
+ - webgpu
15
+ ---
16
+
17
+ # SAM 3 (text prompts) — ONNX for WebGPU
18
+
19
+ ONNX exports of [SAM 3](https://github.com/facebookresearch/sam3) (Meta, 2025) for in-browser
20
+ inference with [ONNX Runtime Web](https://onnxruntime.ai/docs/tutorials/web/) on WebGPU. They
21
+ cover SAM 3's **text-prompted** path, "promptable concept segmentation": a short phrase in, a
22
+ mask for every instance of it out, plus a semantic mask. Used by
23
+ [Card Anvil](https://github.com/Card-Anvil)'s Describe command.
24
+
25
+ **Licence: the [SAM License](LICENSE), not an open-source licence.** These files are a format
26
+ conversion of Meta's `facebook/sam3` weights, distributed under the SAM License as it requires.
27
+ By downloading or using them you accept its terms, including its restrictions on use. The full
28
+ text is in [`LICENSE`](LICENSE).
29
+
30
+ The model is split into three graphs, each at a fixed shape: a 1008 × 1008 image, a 32-token
31
+ phrase, batch 1. Two precisions share one repository.
32
+
33
+ | Variant | Files | Download | For |
34
+ | ------------ | -------------------------------------------------------------- | -------- | --------------------------------------- |
35
+ | **Standard** | `vision_fp16`, `text_fp16`, `detector_fp16` | 1.68 GB | GPUs with plenty of video memory |
36
+ | **Compact** | `vision_q8f16`, `text_q8f16`, `detector_fp16` | 0.94 GB | Integrated GPUs, less video memory |
37
+
38
+ ## Files
39
+
40
+ | File | Graph | Precision | Size |
41
+ | -------------------------- | --------------------------------------------- | ------------------------------------------------------------ | ------ |
42
+ | `onnx/vision_fp16.onnx` | Perception Encoder ViT (32 layers) and neck | fp16 | 915 MB |
43
+ | `onnx/vision_q8f16.onnx` | The same | MatMul weights 8-bit (`MatMulNBits`), fp16 activations | 477 MB |
44
+ | `onnx/text_fp16.onnx` | CLIP text encoder (24 layers) and projection | fp16 | 709 MB |
45
+ | `onnx/text_q8f16.onnx` | The same | MatMul weights 8-bit, fp16 activations | 411 MB |
46
+ | `onnx/detector_fp16.onnx` | DETR encoder and decoder, scoring, masks | fp16 (both variants) | 54 MB |
47
+
48
+ Every graph takes and returns float32 (int64 for token ids and masks); fp16 is internal.
49
+
50
+ The tokenizer (`tokenizer.json`, `vocab.json`, `merges.txt` and their configs) and
51
+ `processor_config.json` are copied unchanged from `facebook/sam3`.
52
+
53
+ ## The graphs
54
+
55
+ | Graph | Inputs | Outputs |
56
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | **vision** | `pixel_values` [1, 3, 1008, 1008] | `features_288` [1, 256, 288, 288], `features_144` [1, 256, 144, 144], `features_72` [1, 256, 72, 72] |
58
+ | **text** | `input_ids` [1, 32], `attention_mask` [1, 32] | `text_features` [1, 32, 256] |
59
+ | **detector** | the three feature levels, `text_features`, `text_mask` [1, 32] (the attention mask) | `pred_logits` [1, 200], `pred_boxes` [1, 200, 4] (x0, y0, x1, y1, 0–1), `presence_logits` [1, 1], `pred_masks` [1, 200, 288, 288], `semantic_seg` [1, 1, 288, 288] |
60
+
61
+ Run **vision** once per image, and **text** then **detector** once per phrase. The feature levels
62
+ can stay on the GPU between the two sessions (`preferredOutputLocation: "gpu-buffer"`).
63
+
64
+ ## Using it
65
+
66
+ **Image.** Resize to exactly 1008 × 1008 (bilinear; SAM 3 stretches, it does not pad), scale to
67
+ 0–1, then normalise with mean 0.5 and standard deviation 0.5 (so −1 to 1), channels first.
68
+
69
+ **Phrase.** SAM 3's CLIP tokenizer: lower-case byte-pair encoding, `<|startoftext|>` (49406)
70
+ first, `<|endoftext|>` (49407) last and as padding, to 32 tokens. `attention_mask` is 1 for real
71
+ tokens. One phrase per run: `"dragon, sword"` is one phrase to the model, so split on commas and
72
+ run each.
73
+
74
+ **Results.**
75
+
76
+ - A detection's score is `sigmoid(pred_logits[q]) × sigmoid(presence_logits)`. Keep those above
77
+ 0.5, the reference threshold.
78
+ - Its mask is `pred_masks[q] > 0` (logits) at 288 × 288, over the whole stretched image. Resize it
79
+ to the original image's size.
80
+ - `semantic_seg > 0` is the phrase's semantic mask. It covers stuff such as sky better than the
81
+ instances do.
82
+
83
+ ## How it was made
84
+
85
+ `export_sam3.py` (here), with the graph split in `sam3_graphs.py`:
86
+
87
+ 1. **Load** `Sam3Model` from `facebook/sam3` at
88
+ [`3c879f39`](https://huggingface.co/facebook/sam3/tree/3c879f39826c281e95690f02c7821c4de09afae7)
89
+ (`model.safetensors` SHA-256 `6d06f0a5f84e435071fe6603e61d0b4cc7b40e0d39d487cfd4d67d8cc11cc14a`),
90
+ with eager attention. Versions: Transformers 5.20.2, PyTorch 2.14.1, on the CPU.
91
+ 2. **Split it** as `Sam3Model.forward` runs a text prompt with no box prompts. The 72² level's
92
+ position encoding depends only on the fixed input size, so the detector holds it as a
93
+ constant.
94
+ 3. **Export** each graph with `torch.onnx.export` (the dynamo exporter), opset 18, fp32.
95
+ 4. **Convert to fp16** with `onnxconverter-common` (`keep_io_types`). The converter retypes a
96
+ `Cast` from bool (the text mask) without changing its target type, so `fix_casts` points it at
97
+ fp16; without that, the detector doesn't load.
98
+ 5. **Quantise** the vision and text graphs' MatMul weights to 8 bits with ONNX Runtime's
99
+ `MatMulNBitsQuantizer` (symmetric, block size 128). The detector stays fp16.
100
+
101
+ **Why weight-only 8-bit.** The usual dynamic "int8" export runs `MatMulInteger` and
102
+ `DynamicQuantizeLinear`, which ONNX Runtime Web's WebGPU backend doesn't implement, so those nodes
103
+ would fall back to the CPU. `MatMulNBits` keeps the weights at 8 bits and runs on WebGPU.
104
+
105
+ ## How it was checked
106
+
107
+ Against PyTorch fp32 (`reference.py`, then `verify_onnx.py`), on six images and ten phrases:
108
+ Hugging Face's SAM car example, and Magic: The Gathering art crops. The art was used locally
109
+ only and isn't included. Each check runs the whole chain (vision, text, detector) from the same
110
+ inputs. It compares which detections pass 0.5, and the IoU, at 288 × 288, of the kept detections'
111
+ union and of the semantic mask.
112
+
113
+ | Run | Same detections | Worst union IoU | Worst semantic IoU |
114
+ | ------------------------------------------- | --------------- | --------------- | ------------------ |
115
+ | The split graphs in PyTorch | 10 / 10 | max \|Δ\| 2e-6 | |
116
+ | fp32 ONNX, ONNX Runtime 1.31 CPU | 10 / 10 | 1.000 | 1.000 |
117
+ | Standard, ONNX Runtime 1.31 CPU | 10 / 10 | 0.999 | 0.999 |
118
+ | Compact, ONNX Runtime 1.31 CPU | 10 / 10 | 0.993 | 0.997 |
119
+ | Standard, ONNX Runtime Web 1.31 WebGPU | 10 / 10 | 0.975 | 0.978 |
120
+ | Compact, ONNX Runtime Web 1.31 WebGPU | 10 / 10 | 0.975 | 0.974 |
121
+
122
+ **Speed on WebGPU,** warm, in Microsoft Edge on an NVIDIA RTX 4070 Ti SUPER with ONNX Runtime Web
123
+ 1.31 (`ort.webgpu`, single-threaded WebAssembly):
124
+
125
+ | Variant | Vision (once per image) | Text (per phrase) | Detector (per phrase) |
126
+ | -------- | ----------------------- | ----------------- | --------------------- |
127
+ | Standard | about 0.8 s | about 20 ms | about 0.25–0.33 s |
128
+ | Compact | about 2.2 s | about 15 ms | about 0.23–0.33 s |
129
+
130
+ Every node that does arithmetic runs on WebGPU in both variants. ONNX Runtime keeps only
131
+ shape-only nodes on the CPU, by design. **Compact is smaller, not faster.** On a fast discrete
132
+ GPU, expanding 8-bit weights costs more than it saves, so Standard is quicker there. Compact is
133
+ for machines short of video memory, where it hasn't been measured yet.
134
+
135
+ ## Licence
136
+
137
+ The [SAM License](LICENSE) (Meta, last updated November 19, 2025). These ONNX files are a
138
+ derivative of the SAM Materials and are distributed under its terms. Section 1.b.i requires that
139
+ redistribution carry the same terms and a copy of the licence. The scripts here
140
+ (`export_sam3.py`, `sam3_graphs.py`, `reference.py`, `verify_onnx.py`) are Card Anvil's own.
141
+ They run Hugging Face Transformers' SAM 3 implementation (Apache-2.0) and copy none of it.
142
+
143
+ ## Citation
144
+
145
+ ```bibtex
146
+ @misc{carion2025sam3segmentconcepts,
147
+ title={SAM 3: Segment Anything with Concepts},
148
+ author={Nicolas Carion and Laura Gustafson and Yuan-Ting Hu and Shoubhik Debnath and Ronghang Hu and Didac Suris and Chaitanya Ryali and Kalyan Vasudev Alwala and Haitham Khedr and Andrew Huang and Jie Lei and Tengyu Ma and Baishan Guo and Arpit Kalla and Markus Marks and Joseph Greer and Meng Wang and Peize Sun and Roman Rädle and Triantafyllos Afouras and Effrosyni Mavroudi and Katherine Xu and Tsung-Han Wu and Yu Zhou and Liliane Momeni and Rishi Hazra and Shuangrui Ding and Sagar Vaze and Francois Porcher and Feng Li and Siyuan Li and Aishwarya Kamath and Ho Kei Cheng and Piotr Dollár and Nikhila Ravi and Kate Saenko and Pengchuan Zhang and Christoph Feichtenhofer},
149
+ year={2025},
150
+ eprint={2511.16719},
151
+ archivePrefix={arXiv},
152
+ primaryClass={cs.CV},
153
+ url={https://arxiv.org/abs/2511.16719},
154
+ }
155
+ ```
export_sam3.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exports SAM 3 (facebook/sam3) to ONNX for in-browser inference with ONNX Runtime Web on WebGPU.
2
+
3
+ Three graphs (see `sam3_graphs.py`): `vision` (once per image), `text` and `detector` (once per
4
+ phrase), each at a fixed shape: a 1008 × 1008 image, a 32-token phrase, batch 1.
5
+
6
+ Files, in `<out>/onnx/`, named by graph and precision:
7
+
8
+ - `*_fp16.onnx`: fp16 weights and activations, inputs and outputs float32. Standard is the three
9
+ of these.
10
+ - `vision_q8f16.onnx`, `text_q8f16.onnx`: as fp16, but every MatMul weight stored at 8 bits
11
+ (`MatMulNBits`, symmetric, block size 128) and expanded on the GPU. Compact is these two and
12
+ `detector_fp16.onnx`, which is small and left at fp16.
13
+
14
+ Weight-only quantisation keeps every node on WebGPU: the usual dynamic "int8" export runs
15
+ `MatMulInteger` and `DynamicQuantizeLinear`, which ONNX Runtime Web's WebGPU backend lacks.
16
+
17
+ Usage:
18
+ python export_sam3.py --weights <facebook/sam3 checkout> --out <dir>
19
+
20
+ Requires torch, transformers (with `Sam3Model`), onnx, onnxscript, onnxconverter-common and
21
+ onnxruntime. Runs on the CPU. The fp32 graphs go to `<out>/fp32/`, with external data, and
22
+ `--skip-fp32` reuses them.
23
+ """
24
+
25
+ import argparse
26
+ from pathlib import Path
27
+
28
+ import onnx
29
+ import torch
30
+ from onnxconverter_common import float16
31
+ from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer
32
+ from transformers import Sam3Model
33
+
34
+ from sam3_graphs import IMAGE_SIZE, TEXT_TOKENS, Sam3Detector, Sam3Text, Sam3Vision, position_encoding_72
35
+
36
+ OPSET = 18
37
+ GRAPHS = ("vision", "text", "detector")
38
+ QUANTISED = ("vision", "text")
39
+
40
+
41
+ def export_fp32(model, out: Path) -> None:
42
+ out.mkdir(parents=True, exist_ok=True)
43
+ pixels = torch.zeros(1, 3, IMAGE_SIZE, IMAGE_SIZE)
44
+ ids = torch.zeros(1, TEXT_TOKENS, dtype=torch.long)
45
+ mask = torch.ones(1, TEXT_TOKENS, dtype=torch.long)
46
+ vision = Sam3Vision(model).eval()
47
+ with torch.no_grad():
48
+ levels = vision(pixels)
49
+ text = Sam3Text(model).eval()
50
+ with torch.no_grad():
51
+ features = text(ids, mask)
52
+ detector = Sam3Detector(model, position_encoding_72(model)).eval()
53
+ jobs = {
54
+ "vision": (vision, (pixels,), ["pixel_values"], ["features_288", "features_144", "features_72"]),
55
+ "text": (text, (ids, mask), ["input_ids", "attention_mask"], ["text_features"]),
56
+ "detector": (
57
+ detector,
58
+ (*levels, features, mask),
59
+ ["features_288", "features_144", "features_72", "text_features", "text_mask"],
60
+ ["pred_logits", "pred_boxes", "presence_logits", "pred_masks", "semantic_seg"],
61
+ ),
62
+ }
63
+ for name, (module, args, inputs, outputs) in jobs.items():
64
+ print(f"exporting {name}")
65
+ with torch.no_grad():
66
+ torch.onnx.export(
67
+ module,
68
+ args,
69
+ str(out / f"{name}.onnx"),
70
+ input_names=inputs,
71
+ output_names=outputs,
72
+ opset_version=OPSET,
73
+ dynamo=True,
74
+ external_data=True,
75
+ optimize=True,
76
+ )
77
+
78
+
79
+ def fix_casts(model: onnx.ModelProto) -> int:
80
+ """Points each Cast to float32 whose output the converter declared float16 at float16.
81
+
82
+ `convert_float_to_float16` retypes a Cast's output but leaves its `to`, so a Cast from a
83
+ non-float source (the text mask, cast from bool for pooling) still says float32 and the
84
+ graph doesn't load. Returns how many it fixed.
85
+ """
86
+ declared = {vi.name: vi.type.tensor_type.elem_type for vi in model.graph.value_info}
87
+ fixed = 0
88
+ for node in model.graph.node:
89
+ if node.op_type != "Cast" or declared.get(node.output[0]) != onnx.TensorProto.FLOAT16:
90
+ continue
91
+ for attribute in node.attribute:
92
+ if attribute.name == "to" and attribute.i == onnx.TensorProto.FLOAT:
93
+ attribute.i = onnx.TensorProto.FLOAT16
94
+ fixed += 1
95
+ return fixed
96
+
97
+
98
+ def to_fp16(src: Path, dst: Path) -> None:
99
+ dst.mkdir(parents=True, exist_ok=True)
100
+ for name in GRAPHS:
101
+ model = onnx.load(str(src / f"{name}.onnx"))
102
+ # Stale annotations from the export would fight the converter's own inference.
103
+ del model.graph.value_info[:]
104
+ half = float16.convert_float_to_float16(model, keep_io_types=True, disable_shape_infer=False)
105
+ print(f"fp16 {name}: {fix_casts(half)} casts fixed")
106
+ onnx.save(half, str(dst / f"{name}_fp16.onnx"))
107
+
108
+
109
+ def to_q8f16(onnx_dir: Path, bits: int, block_size: int) -> None:
110
+ for name in QUANTISED:
111
+ print(f"{bits}-bit {name}")
112
+ quantiser = MatMulNBitsQuantizer(
113
+ onnx.load(str(onnx_dir / f"{name}_fp16.onnx")),
114
+ bits=bits,
115
+ block_size=block_size,
116
+ is_symmetric=True,
117
+ )
118
+ quantiser.process()
119
+ onnx.save(quantiser.model.model, str(onnx_dir / f"{name}_q{bits}f16.onnx"))
120
+
121
+
122
+ def main() -> None:
123
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
124
+ parser.add_argument("--weights", type=Path, required=True)
125
+ parser.add_argument("--out", type=Path, required=True)
126
+ parser.add_argument("--bits", type=int, default=8)
127
+ parser.add_argument("--block-size", type=int, default=128)
128
+ parser.add_argument("--skip-fp32", action="store_true", help="reuse an earlier fp32 export")
129
+ args = parser.parse_args()
130
+
131
+ if not args.skip_fp32:
132
+ model = Sam3Model.from_pretrained(args.weights, attn_implementation="eager").eval()
133
+ export_fp32(model, args.out / "fp32")
134
+ del model
135
+ to_fp16(args.out / "fp32", args.out / "onnx")
136
+ to_q8f16(args.out / "onnx", args.bits, args.block_size)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
onnx/detector_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89991506cc7e54e828227ca12a4ae015f4107b67a4216b9c2906ce7f7e349d17
3
+ size 54124388
onnx/text_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2dfb1755d2c821451657b998d095b00727e8b400e706e95165c59039aca15b3
3
+ size 709242464
onnx/text_q8f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2626b5d0941ad4a63b1eddd1e1d04aa08623df3b4270fcf3516a77558ae4dbc2
3
+ size 411216397
onnx/vision_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02e1573a208a702dfbed03349fcbcf0b9bc228ee1ce24a6809b871f0cb1564fa
3
+ size 914738433
onnx/vision_q8f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:505385b0d30f71af60bde43e75b3e7f35d2d5263a1ee3928c6adcd2efcc401b8
3
+ size 476516937
processor_config.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "crop_size": null,
4
+ "data_format": "channels_first",
5
+ "device": null,
6
+ "disable_grouping": null,
7
+ "do_center_crop": null,
8
+ "do_convert_rgb": true,
9
+ "do_normalize": true,
10
+ "do_pad": null,
11
+ "do_rescale": true,
12
+ "do_resize": true,
13
+ "image_mean": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "image_processor_type": "Sam3ImageProcessorFast",
19
+ "image_seq_length": null,
20
+ "image_std": [
21
+ 0.5,
22
+ 0.5,
23
+ 0.5
24
+ ],
25
+ "input_data_format": null,
26
+ "mask_size": {
27
+ "height": 288,
28
+ "width": 288
29
+ },
30
+ "pad_size": null,
31
+ "processor_class": "Sam3VideoProcessor",
32
+ "resample": 2,
33
+ "rescale_factor": 0.00392156862745098,
34
+ "return_tensors": null,
35
+ "size": {
36
+ "height": 1008,
37
+ "width": 1008
38
+ }
39
+ },
40
+ "processor_class": "Sam3VideoProcessor",
41
+ "target_size": 1008,
42
+ "video_processor": {
43
+ "crop_size": null,
44
+ "data_format": "channels_first",
45
+ "default_to_square": true,
46
+ "device": null,
47
+ "do_center_crop": null,
48
+ "do_convert_rgb": true,
49
+ "do_normalize": true,
50
+ "do_pad": null,
51
+ "do_rescale": true,
52
+ "do_resize": true,
53
+ "do_sample_frames": null,
54
+ "fps": null,
55
+ "image_mean": [
56
+ 0.5,
57
+ 0.5,
58
+ 0.5
59
+ ],
60
+ "image_std": [
61
+ 0.5,
62
+ 0.5,
63
+ 0.5
64
+ ],
65
+ "input_data_format": null,
66
+ "num_frames": null,
67
+ "pad_size": null,
68
+ "processor_class": "Sam3VideoProcessor",
69
+ "resample": 2,
70
+ "rescale_factor": 0.00392156862745098,
71
+ "return_metadata": false,
72
+ "return_tensors": null,
73
+ "size": {
74
+ "height": 1008,
75
+ "width": 1008
76
+ },
77
+ "video_metadata": null,
78
+ "video_processor_type": "Sam2VideoVideoProcessor"
79
+ }
80
+ }
reference.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runs SAM 3 in PyTorch on the test images, whole and as the three split graphs, checks they
2
+ agree, and saves the inputs and the split graphs' outputs as references for the ONNX checks."""
3
+
4
+ import sys
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+ from transformers import Sam3Model, Sam3Processor
12
+
13
+ from sam3_graphs import Sam3Detector, Sam3Text, Sam3Vision, position_encoding_72
14
+
15
+ ROOT = Path(__file__).parent
16
+ WEIGHTS = ROOT / "weights"
17
+ CASES = {
18
+ "car.png": ["car"],
19
+ "shivan_dragon.jpg": ["dragon", "fire"],
20
+ "serra_angel.jpg": ["angel", "wings"],
21
+ "llanowar_elves.jpg": ["elf", "tree"],
22
+ "lightning_bolt.jpg": ["lightning"],
23
+ "island.jpg": ["sky", "water"],
24
+ }
25
+
26
+
27
+ def main() -> None:
28
+ torch.set_grad_enabled(False)
29
+ model = Sam3Model.from_pretrained(WEIGHTS, attn_implementation="eager").eval()
30
+ processor = Sam3Processor.from_pretrained(WEIGHTS)
31
+ vision, text = Sam3Vision(model).eval(), Sam3Text(model).eval()
32
+ detector = Sam3Detector(model, position_encoding_72(model)).eval()
33
+ out_dir = ROOT / "reference"
34
+ out_dir.mkdir(exist_ok=True)
35
+
36
+ for image_name, phrases in CASES.items():
37
+ image = Image.open(ROOT / "images" / image_name).convert("RGB")
38
+ pixels = processor(images=image, return_tensors="pt").pixel_values
39
+ start = time.time()
40
+ levels = vision(pixels)
41
+ print(f"{image_name}: vision {time.time() - start:.1f}s, levels {[tuple(l.shape) for l in levels]}")
42
+ for phrase in phrases:
43
+ tokens = processor(text=phrase, return_tensors="pt")
44
+ ids, mask = tokens.input_ids, tokens.attention_mask
45
+ features = text(ids, mask)
46
+ split = detector(*levels, features, mask)
47
+ whole = model(pixel_values=pixels, input_ids=ids, attention_mask=mask)
48
+ pairs = {
49
+ "pred_logits": (split[0], whole.pred_logits),
50
+ "pred_boxes": (split[1], whole.pred_boxes),
51
+ "presence_logits": (split[2], whole.presence_logits),
52
+ "pred_masks": (split[3], whole.pred_masks),
53
+ "semantic_seg": (split[4], whole.semantic_seg),
54
+ }
55
+ diffs = {k: float((a - b).abs().max()) for k, (a, b) in pairs.items()}
56
+ scores = split[0].sigmoid() * split[2].sigmoid()
57
+ kept = int((scores > 0.5).sum())
58
+ print(f" '{phrase}': ids {tuple(ids.shape)}, kept {kept}, max |split - whole| {diffs}")
59
+ stem = f"{Path(image_name).stem}__{phrase}"
60
+ np.savez_compressed(
61
+ out_dir / f"{stem}.npz",
62
+ pixel_values=pixels.numpy(),
63
+ input_ids=ids.numpy(),
64
+ attention_mask=mask.numpy(),
65
+ features_288=levels[0].numpy(),
66
+ features_144=levels[1].numpy(),
67
+ features_72=levels[2].numpy(),
68
+ text_features=features.numpy(),
69
+ **{k: v[0].numpy() for k, v in pairs.items()},
70
+ )
71
+ sys.stdout.flush()
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
sam3_graphs.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAM 3's text-prompted segmentation, split into the three graphs the browser runs.
2
+
3
+ The split follows `Sam3Model.forward` (Hugging Face Transformers, `models/sam3/modeling_sam3.py`)
4
+ for a text prompt with no box prompts:
5
+
6
+ - **vision**: the Perception Encoder ViT and its neck, run once per image. Its outputs are the
7
+ first three feature levels (288², 144² and 72², 256 channels); `Sam3Model` drops the fourth.
8
+ - **text**: the CLIP text encoder and `text_projection`, run once per phrase.
9
+ - **detector**: the DETR encoder and decoder, the box head, the dot-product scoring and the mask
10
+ decoder, run once per phrase over the vision graph's features.
11
+
12
+ The 72² level's sine position encoding depends only on the input size, which is fixed at
13
+ 1008 × 1008, so the detector carries it as a constant instead of taking it as an input.
14
+ """
15
+
16
+ import torch
17
+ from torch import nn
18
+ from transformers.models.sam3.modeling_sam3 import box_cxcywh_to_xyxy, inverse_sigmoid
19
+
20
+ IMAGE_SIZE = 1008
21
+ TEXT_TOKENS = 32
22
+
23
+
24
+ class Sam3Vision(nn.Module):
25
+ def __init__(self, model):
26
+ super().__init__()
27
+ self.vision_encoder = model.vision_encoder
28
+
29
+ def forward(self, pixel_values: torch.Tensor):
30
+ levels = self.vision_encoder(pixel_values).fpn_hidden_states
31
+ return levels[0], levels[1], levels[2]
32
+
33
+
34
+ class Sam3Text(nn.Module):
35
+ def __init__(self, model):
36
+ super().__init__()
37
+ self.text_encoder = model.text_encoder
38
+ self.text_projection = model.text_projection
39
+
40
+ def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor):
41
+ hidden = self.text_encoder(
42
+ input_ids=input_ids, attention_mask=attention_mask, return_dict=True
43
+ ).last_hidden_state
44
+ return self.text_projection(hidden)
45
+
46
+
47
+ class Sam3Detector(nn.Module):
48
+ def __init__(self, model, position_encoding: torch.Tensor):
49
+ super().__init__()
50
+ self.detr_encoder = model.detr_encoder
51
+ self.detr_decoder = model.detr_decoder
52
+ self.dot_product_scoring = model.dot_product_scoring
53
+ self.mask_decoder = model.mask_decoder
54
+ self.register_buffer("position_encoding", position_encoding)
55
+
56
+ def forward(
57
+ self,
58
+ features_288: torch.Tensor,
59
+ features_144: torch.Tensor,
60
+ features_72: torch.Tensor,
61
+ text_features: torch.Tensor,
62
+ text_mask: torch.Tensor,
63
+ ):
64
+ mask = text_mask.bool()
65
+ encoder = self.detr_encoder(
66
+ vision_features=[features_72],
67
+ text_features=text_features,
68
+ vision_pos_embeds=[self.position_encoding],
69
+ text_mask=mask,
70
+ )
71
+ decoder = self.detr_decoder(
72
+ vision_features=encoder.last_hidden_state,
73
+ text_features=encoder.text_features,
74
+ vision_pos_encoding=encoder.pos_embeds_flattened,
75
+ text_mask=mask,
76
+ spatial_shapes=encoder.spatial_shapes,
77
+ )
78
+ hidden = decoder.intermediate_hidden_states[-1:]
79
+ offsets = self.detr_decoder.box_head(hidden)
80
+ boxes = (inverse_sigmoid(decoder.reference_boxes[-1:]) + offsets).sigmoid()
81
+ logits = self.dot_product_scoring(
82
+ decoder_hidden_states=hidden,
83
+ text_features=encoder.text_features,
84
+ text_mask=mask,
85
+ ).squeeze(-1)
86
+ masks = self.mask_decoder(
87
+ decoder_queries=hidden[0],
88
+ backbone_features=[features_288, features_144, features_72],
89
+ encoder_hidden_states=encoder.last_hidden_state,
90
+ prompt_features=text_features,
91
+ prompt_mask=mask,
92
+ )
93
+ return (
94
+ logits[0],
95
+ box_cxcywh_to_xyxy(boxes)[0],
96
+ decoder.presence_logits[-1],
97
+ masks.pred_masks,
98
+ masks.semantic_seg,
99
+ )
100
+
101
+
102
+ def position_encoding_72(model) -> torch.Tensor:
103
+ """The 72² level's position encoding for a 1008² image, as the vision model computes it."""
104
+ with torch.no_grad():
105
+ dummy = torch.zeros(1, 3, IMAGE_SIZE, IMAGE_SIZE)
106
+ return model.vision_encoder(dummy).fpn_position_encoding[2].clone()
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<|endoftext|>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "49406": {
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "49407": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ }
20
+ },
21
+ "bos_token": "<|startoftext|>",
22
+ "clean_up_tokenization_spaces": false,
23
+ "do_lower_case": true,
24
+ "eos_token": "<|endoftext|>",
25
+ "errors": "replace",
26
+ "extra_special_tokens": {},
27
+ "max_length": 32,
28
+ "model_max_length": 32,
29
+ "pad_token": "<|endoftext|>",
30
+ "processor_class": "Sam3VideoProcessor",
31
+ "tokenizer_class": "CLIPTokenizer",
32
+ "unk_token": "<|endoftext|>"
33
+ }
verify_onnx.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks an exported variant against the PyTorch fp32 references (`reference.py`).
2
+
3
+ Each case runs the whole ONNX chain — vision, text, detector — from the same inputs, then
4
+ compares with PyTorch: the largest raw error per output, whether the same detections pass the
5
+ 0.5 score (query score × presence), and mask IoU at 288 × 288 for each kept detection, their
6
+ union, and the semantic mask.
7
+
8
+ Usage: python verify_onnx.py <out dir> <fp32|standard|compact> [--provider CPUExecutionProvider]
9
+ """
10
+
11
+ import argparse
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import onnxruntime as ort
17
+
18
+ ROOT = Path(__file__).parent
19
+ FILES = {
20
+ "fp32": {"vision": "fp32/vision.onnx", "text": "fp32/text.onnx", "detector": "fp32/detector.onnx"},
21
+ "standard": {
22
+ "vision": "onnx/vision_fp16.onnx",
23
+ "text": "onnx/text_fp16.onnx",
24
+ "detector": "onnx/detector_fp16.onnx",
25
+ },
26
+ "compact": {
27
+ "vision": "onnx/vision_q8f16.onnx",
28
+ "text": "onnx/text_q8f16.onnx",
29
+ "detector": "onnx/detector_fp16.onnx",
30
+ },
31
+ }
32
+
33
+
34
+ def sigmoid(x):
35
+ return 1.0 / (1.0 + np.exp(-x))
36
+
37
+
38
+ def iou(a, b):
39
+ union = np.logical_or(a, b).sum()
40
+ return 1.0 if union == 0 else float(np.logical_and(a, b).sum() / union)
41
+
42
+
43
+ def main() -> None:
44
+ parser = argparse.ArgumentParser()
45
+ parser.add_argument("out", type=Path)
46
+ parser.add_argument("variant", choices=sorted(FILES))
47
+ parser.add_argument("--provider", default="CPUExecutionProvider")
48
+ args = parser.parse_args()
49
+
50
+ options = ort.SessionOptions()
51
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
52
+ sessions = {}
53
+ for name, file in FILES[args.variant].items():
54
+ start = time.time()
55
+ sessions[name] = ort.InferenceSession(str(args.out / file), options, providers=[args.provider])
56
+ print(f"loaded {name} in {time.time() - start:.1f}s")
57
+
58
+ vision_cache = {}
59
+ worst_union, worst_semantic, all_same = 1.0, 1.0, True
60
+ for path in sorted((ROOT / "reference").glob("*.npz")):
61
+ ref = np.load(path)
62
+ image = path.stem.split("__")[0]
63
+ if image not in vision_cache:
64
+ # Cases come sorted by image: keep only the current image's features in memory.
65
+ vision_cache.clear()
66
+ start = time.time()
67
+ vision_cache[image] = sessions["vision"].run(None, {"pixel_values": ref["pixel_values"]})
68
+ vision_ms = (time.time() - start) * 1000
69
+ levels = vision_cache[image]
70
+ errors = [float(np.abs(l - ref[k]).max()) for l, k in zip(levels, ("features_288", "features_144", "features_72"))]
71
+ print(f"{image}: vision {vision_ms:.0f} ms, max |Δ| per level {['%.2e' % e for e in errors]}")
72
+ levels = vision_cache[image]
73
+ (text_features,) = sessions["text"].run(
74
+ None, {"input_ids": ref["input_ids"], "attention_mask": ref["attention_mask"]}
75
+ )
76
+ start = time.time()
77
+ logits, boxes, presence, masks, semantic = sessions["detector"].run(
78
+ None,
79
+ {
80
+ "features_288": levels[0],
81
+ "features_144": levels[1],
82
+ "features_72": levels[2],
83
+ "text_features": text_features,
84
+ "text_mask": ref["attention_mask"],
85
+ },
86
+ )
87
+ detector_ms = (time.time() - start) * 1000
88
+
89
+ def kept(l, p):
90
+ return np.nonzero((sigmoid(l) * sigmoid(p)).reshape(-1) > 0.5)[0]
91
+
92
+ ours, theirs = kept(logits, presence), kept(ref["pred_logits"], ref["presence_logits"])
93
+ same = set(ours.tolist()) == set(theirs.tolist())
94
+ all_same &= same
95
+ # The references keep the batch dimension, as the ONNX outputs do.
96
+ ref_masks = ref["pred_masks"][0]
97
+ per_query = [iou(masks[0, q] > 0, ref_masks[q] > 0) for q in theirs]
98
+ union_ours = np.any(masks[0, ours] > 0, axis=0) if len(ours) else np.zeros((288, 288), bool)
99
+ union_ref = np.any(ref_masks[theirs] > 0, axis=0) if len(theirs) else np.zeros((288, 288), bool)
100
+ union_iou = iou(union_ours, union_ref)
101
+ semantic_iou = iou(semantic[0, 0] > 0, ref["semantic_seg"][0, 0] > 0)
102
+ worst_union = min(worst_union, union_iou)
103
+ worst_semantic = min(worst_semantic, semantic_iou)
104
+ print(
105
+ f" {path.stem.split('__')[1]!r}: text |Δ| {np.abs(text_features - ref['text_features']).max():.2e}, "
106
+ f"logits |Δ| {np.abs(logits - ref['pred_logits']).max():.3f}, kept {len(ours)} vs {len(theirs)}"
107
+ f"{'' if same else ' (DIFFERENT)'}, mask IoU min {min(per_query, default=1):.3f}, "
108
+ f"union {union_iou:.3f}, semantic {semantic_iou:.3f}, detector {detector_ms:.0f} ms"
109
+ )
110
+ print(f"worst union IoU {worst_union:.3f}, worst semantic IoU {worst_semantic:.3f}, same detections everywhere: {all_same}")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
vocab.json ADDED
The diff for this file is too large to render. See raw diff