CardAnvilModels commited on
Commit
73f79ab
·
verified ·
1 Parent(s): e1d67dd

Grounding DINO tiny, fp16, with a text mask for any number of phrases

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers.js
4
+ base_model: IDEA-Research/grounding-dino-tiny
5
+ pipeline_tag: zero-shot-object-detection
6
+ tags:
7
+ - onnx
8
+ - grounding-dino
9
+ - open-vocabulary-detection
10
+ - transformers.js
11
+ - onnxruntime-web
12
+ - webgpu
13
+ ---
14
+
15
+ # Grounding DINO Tiny (ONNX, fp16), multi-phrase
16
+
17
+ Grounding DINO Tiny as ONNX for [Transformers.js](https://github.com/huggingface/transformers.js),
18
+ fp16. Give it an image and a prompt of one or more phrases (`goat. city. sky.`), and it returns
19
+ boxes, each with the phrase it matched. [Card Anvil](https://github.com/Card-Anvil)'s Describe
20
+ command uses it in the browser, on WebGPU or WebAssembly, to find what to select in card art.
21
+
22
+ **Why another export.** [`onnx-community/grounding-dino-tiny-ONNX`](https://huggingface.co/onnx-community/grounding-dino-tiny-ONNX)
23
+ scores only the **first** phrase of a prompt. Every phrase after it comes out near zero (0.02–0.05
24
+ where PyTorch gives 0.5–0.8), so `goat. city. sky.` finds only goats. That export was made with
25
+ transformers 4.48, which builds each phrase's text attention mask in a Python loop over the
26
+ prompt's special tokens. Tracing unrolled the loop for a one-phrase example prompt.
27
+
28
+ This export rebuilds that function from tensor comparisons and min/max. Before each export it is
29
+ checked against Transformers' own on 140 prompts of 0–6 phrases, so the graph handles any number
30
+ of phrases, up to the model's 256 tokens.
31
+
32
+ It is a drop-in replacement: the same inputs, outputs and file name as onnx-community's, so
33
+ Transformers.js loads it the same way.
34
+
35
+ ## Files
36
+
37
+ | File | What | Size |
38
+ | ------------------------ | ------------------------------------------------------------------------------------------------------- | ------ |
39
+ | `onnx/model_fp16.onnx` | The whole model, fp16 weights, float32 inputs and outputs | 364 MB |
40
+ | `config.json`, `preprocessor_config.json`, tokenizer files | Copied unchanged from onnx-community's repo at [`ff690b0a`](https://huggingface.co/onnx-community/grounding-dino-tiny-ONNX/tree/ff690b0a8050566c290287545bd059350f3e9096) | |
41
+ | `export_grounding_dino.py` | The script that made it | |
42
+
43
+ | Inputs | Outputs |
44
+ | ----------------------------------------------------------------------- | ------------------------------------------------------------- |
45
+ | `pixel_values` [1, 3, 800, 800], `pixel_mask` [1, 800, 800] | `logits` [1, 900, 256]: each query's score for each token |
46
+ | `input_ids`, `token_type_ids`, `attention_mask` [1, n], n from 4 to 256 | `pred_boxes` [1, 900, 4]: centre x, centre y, width, height, 0–1 |
47
+
48
+ The processor stretches the image to 800 × 800, with no padding.
49
+
50
+ ## Usage
51
+
52
+ ```js
53
+ import {
54
+ AutoProcessor,
55
+ GroundingDinoForObjectDetection,
56
+ RawImage,
57
+ } from "@huggingface/transformers";
58
+
59
+ const id = "CardAnvilModels/grounding-dino-tiny-ONNX";
60
+ const model = await GroundingDinoForObjectDetection.from_pretrained(id, {
61
+ dtype: "fp16",
62
+ device: "webgpu", // or "wasm"
63
+ });
64
+ const processor = await AutoProcessor.from_pretrained(id);
65
+
66
+ const image = await RawImage.fromURL("https://example.com/art.jpg");
67
+ // Lower-case phrases, each ended with a full stop.
68
+ const inputs = await processor(image, "goat. city. sky.");
69
+ const outputs = await model(inputs);
70
+ const [result] = processor.post_process_grounded_object_detection(
71
+ outputs,
72
+ inputs.input_ids,
73
+ {
74
+ box_threshold: 0.35,
75
+ text_threshold: 0.25,
76
+ target_sizes: [[image.height, image.width]],
77
+ },
78
+ );
79
+ // result.boxes: [x0, y0, x1, y1] in pixels; result.labels: the phrase each matched.
80
+ ```
81
+
82
+ In one pass, the phrases compete for boxes, as they do in the original model. Something found on
83
+ its own can lose to another phrase that claims the same region.
84
+
85
+ ## How it was checked
86
+
87
+ With onnxruntime 1.31 on the CPU, against PyTorch (transformers 5.20, fp32) on the same inputs:
88
+
89
+ - **fp32 export:** within 0.01 of PyTorch, on single phrases and on prompts of three and four
90
+ phrases.
91
+ - **This fp16 file:** within 0.01 of PyTorch on single phrases, and close on joint prompts. The
92
+ largest gap seen was about 0.1, on one three-phrase prompt.
93
+
94
+ In Microsoft Edge, with ONNX Runtime Web 1.31, on 24 images and 98 prompts:
95
+
96
+ | Measure | onnx-community's | This export |
97
+ | ------------------------------------------- | ---------------- | -------------------------------- |
98
+ | WebGPU, a pass (RTX 4070 Ti SUPER) | 327 ms | 347 ms |
99
+ | WebAssembly, a pass (one thread) | 13.4 s | 14.7 s |
100
+ | Single-phrase boxes | — | the same: median IoU 0.995 |
101
+ | Phrases found alone that a joint pass loses | 45 of 68 | 14 of 66, as in PyTorch |
102
+
103
+ All 48 `GridSample` nodes (the deformable attention) run on WebGPU.
104
+
105
+ ## How it was made
106
+
107
+ `export_grounding_dino.py`, with torch 2.14.1, transformers 5.20.2, onnx 1.23.2, onnxscript 0.7.2
108
+ and onnxconverter-common 1.16.0:
109
+
110
+ 1. **fp32 export** from [`IDEA-Research/grounding-dino-tiny`](https://huggingface.co/IDEA-Research/grounding-dino-tiny)
111
+ at `a2bb814d`, with the dynamo exporter, opset 18, and a dynamic sequence length. Two changes
112
+ make it export:
113
+ - the text-mask function rebuilt as above (Transformers' uses `torch.isin`, which exports as
114
+ `searchsorted`, which ONNX lacks);
115
+ - `TRANSFORMERS_DISABLE_TORCH_CHECK=1`, since its shape checks export as `_is_all_true`, which
116
+ ONNX also lacks.
117
+ 2. **fp16 conversion** with `onnxconverter_common`, inputs and outputs kept float32. The converter
118
+ leaves 23 `Cast` nodes aimed at float32; the script retypes them.
119
+
120
+ ## Credits and licence
121
+
122
+ - Model: [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) by IDEA Research, from
123
+ _Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection_ (2023),
124
+ through [`IDEA-Research/grounding-dino-tiny`](https://huggingface.co/IDEA-Research/grounding-dino-tiny).
125
+ - Config and tokenizer files: [ONNX Community](https://huggingface.co/onnx-community).
126
+
127
+ Licensed under the Apache License 2.0, as the original model is. See [`LICENSE`](LICENSE).
config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "IDEA-Research/grounding-dino-tiny",
3
+ "activation_dropout": 0.0,
4
+ "activation_function": "relu",
5
+ "architectures": [
6
+ "GroundingDinoForObjectDetection"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auxiliary_loss": false,
10
+ "backbone": null,
11
+ "backbone_config": {
12
+ "model_type": "swin",
13
+ "out_features": [
14
+ "stage2",
15
+ "stage3",
16
+ "stage4"
17
+ ],
18
+ "out_indices": [
19
+ 2,
20
+ 3,
21
+ 4
22
+ ]
23
+ },
24
+ "backbone_kwargs": null,
25
+ "bbox_cost": 5.0,
26
+ "bbox_loss_coefficient": 5.0,
27
+ "class_cost": 1.0,
28
+ "d_model": 256,
29
+ "decoder_attention_heads": 8,
30
+ "decoder_bbox_embed_share": true,
31
+ "decoder_ffn_dim": 2048,
32
+ "decoder_layers": 6,
33
+ "decoder_n_points": 4,
34
+ "disable_custom_kernels": false,
35
+ "dropout": 0.1,
36
+ "embedding_init_target": true,
37
+ "encoder_attention_heads": 8,
38
+ "encoder_ffn_dim": 2048,
39
+ "encoder_layers": 6,
40
+ "encoder_n_points": 4,
41
+ "focal_alpha": 0.25,
42
+ "fusion_dropout": 0.0,
43
+ "fusion_droppath": 0.1,
44
+ "giou_cost": 2.0,
45
+ "giou_loss_coefficient": 2.0,
46
+ "init_std": 0.02,
47
+ "is_encoder_decoder": true,
48
+ "layer_norm_eps": 1e-05,
49
+ "max_text_len": 256,
50
+ "model_type": "grounding-dino",
51
+ "num_feature_levels": 4,
52
+ "num_queries": 900,
53
+ "position_embedding_type": "sine",
54
+ "positional_embedding_temperature": 20,
55
+ "query_dim": 4,
56
+ "text_config": {
57
+ "model_type": "bert"
58
+ },
59
+ "text_enhancer_dropout": 0.0,
60
+ "torch_dtype": "float32",
61
+ "transformers_version": "4.48.0.dev0",
62
+ "two_stage": true,
63
+ "two_stage_bbox_embed_share": false,
64
+ "use_pretrained_backbone": false,
65
+ "use_timm_backbone": false
66
+ }
export_grounding_dino.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grounding DINO tiny as ONNX, with a text mask that works for any number of phrases.
2
+
3
+ onnx-community/grounding-dino-tiny-ONNX was exported with transformers 4.48, whose
4
+ `generate_masks_with_special_tokens_and_transfer_map` loops in Python over the prompt's special
5
+ tokens. Tracing unrolled that loop for its example prompt, so the export scores only a prompt's
6
+ first phrase. Transformers 5 builds the mask from tensor operations, which export as they are.
7
+
8
+ Same inputs and outputs as onnx-community's, so Transformers.js loads it unchanged:
9
+ pixel_values, input_ids, token_type_ids, attention_mask, pixel_mask -> logits, pred_boxes.
10
+
11
+ Usage, from this folder, with tools/sam3-export's .venv:
12
+ ../sam3-export/.venv/Scripts/python.exe -I export_grounding_dino.py --weights <dir> --out onnx
13
+ """
14
+
15
+ import argparse
16
+ import os
17
+ from pathlib import Path
18
+
19
+ import onnx
20
+ import torch
21
+ import transformers.models.grounding_dino.modeling_grounding_dino as grounding_dino
22
+ from onnxconverter_common import float16
23
+ from transformers import GroundingDinoForObjectDetection
24
+
25
+ OPSET = 18
26
+ IMAGE_SIZE = 800 # the export's processor stretches the art to 800 x 800
27
+ INPUTS = ["pixel_values", "input_ids", "token_type_ids", "attention_mask", "pixel_mask"]
28
+ OUTPUTS = ["logits", "pred_boxes"]
29
+
30
+
31
+ def phrase_masks(input_ids: torch.LongTensor) -> tuple[torch.Tensor, torch.Tensor]:
32
+ """`generate_masks_with_special_tokens_and_transfer_map`, in operations ONNX has.
33
+
34
+ Transformers' version uses `torch.isin` (exported as `searchsorted`, which ONNX lacks) and
35
+ `cummax`/`cummin`. This finds each token's previous and next special token with a masked
36
+ min/max over a sequence x sequence grid instead: at most 256 x 256, so cheap. Same result;
37
+ `check_phrase_masks` compares the two.
38
+ """
39
+ batch_size, seq_len = input_ids.shape
40
+ device = input_ids.device
41
+ special = torch.zeros_like(input_ids, dtype=torch.bool)
42
+ for token in grounding_dino.SPECIAL_TOKENS:
43
+ special = special | (input_ids == token)
44
+ indices = torch.arange(seq_len, device=device)
45
+ row = indices.view(1, seq_len, 1) # each token i
46
+ col = indices.view(1, 1, seq_len) # each candidate special token j
47
+ is_special = special.unsqueeze(1) # (B, 1, N)
48
+ prev_special = torch.where(is_special & (col <= row), col, -1).amax(dim=2)
49
+ next_special = torch.where(is_special & (col >= row), col, seq_len).amin(dim=2)
50
+ valid_block = (next_special != 0) & (next_special != seq_len - 1) & (next_special != seq_len)
51
+ attention_mask = (next_special.unsqueeze(2) == next_special.unsqueeze(1)) & valid_block.unsqueeze(1)
52
+ identity = (row == col).expand(batch_size, -1, -1)
53
+ attention_mask = identity | attention_mask
54
+ position_ids = indices.unsqueeze(0) - prev_special - 1
55
+ position_ids = torch.where(valid_block, position_ids, torch.zeros_like(position_ids))
56
+ position_ids = torch.clamp(position_ids, min=0).to(torch.long)
57
+ return attention_mask, position_ids
58
+
59
+
60
+ def check_phrase_masks() -> None:
61
+ """`phrase_masks` against Transformers' own on prompts of 0–6 phrases, with padding."""
62
+ original = grounding_dino.generate_masks_with_special_tokens_and_transfer_map
63
+ generator = torch.Generator().manual_seed(0)
64
+ for phrases in range(7):
65
+ for _ in range(20):
66
+ ids = [101]
67
+ for _ in range(phrases):
68
+ words = int(torch.randint(1, 4, (1,), generator=generator))
69
+ ids += torch.randint(2000, 3000, (words,), generator=generator).tolist() + [1012]
70
+ ids += [102] + [0] * int(torch.randint(0, 3, (1,), generator=generator))
71
+ input_ids = torch.tensor([ids])
72
+ want, got = original(input_ids), phrase_masks(input_ids)
73
+ assert all(torch.equal(a, b) for a, b in zip(want, got)), ids
74
+ print("phrase_masks matches Transformers on 140 prompts")
75
+
76
+
77
+ class Detector(torch.nn.Module):
78
+ def __init__(self, model):
79
+ super().__init__()
80
+ self.model = model
81
+
82
+ def forward(self, pixel_values, input_ids, token_type_ids, attention_mask, pixel_mask):
83
+ out = self.model(
84
+ pixel_values=pixel_values,
85
+ input_ids=input_ids,
86
+ token_type_ids=token_type_ids,
87
+ attention_mask=attention_mask,
88
+ pixel_mask=pixel_mask,
89
+ )
90
+ return out.logits, out.pred_boxes
91
+
92
+
93
+ def example(tokens: int):
94
+ """Inputs for tracing: three phrases' worth of special tokens, so nothing assumes one."""
95
+ # [CLS] dragon . sword . fire . [SEP], padded with filler words to `tokens`.
96
+ ids = [101, 1000, 1012, 1001, 1012, 1002, 1012] + [1003] * (tokens - 8) + [102]
97
+ return (
98
+ torch.zeros(1, 3, IMAGE_SIZE, IMAGE_SIZE),
99
+ torch.tensor([ids], dtype=torch.long),
100
+ torch.zeros(1, tokens, dtype=torch.long),
101
+ torch.ones(1, tokens, dtype=torch.long),
102
+ torch.ones(1, IMAGE_SIZE, IMAGE_SIZE, dtype=torch.long),
103
+ )
104
+
105
+
106
+ def export_fp32(weights: Path, out: Path) -> Path:
107
+ out.mkdir(parents=True, exist_ok=True)
108
+ check_phrase_masks()
109
+ # The model's forward calls the module-level function, so this swaps it for the export.
110
+ grounding_dino.generate_masks_with_special_tokens_and_transfer_map = phrase_masks
111
+ # Its shape asserts export as `_is_all_true`, which ONNX lacks; they're hints, not logic.
112
+ os.environ["TRANSFORMERS_DISABLE_TORCH_CHECK"] = "1"
113
+ model = Detector(GroundingDinoForObjectDetection.from_pretrained(weights).eval()).eval()
114
+ seq = torch.export.Dim("sequence", min=4, max=256)
115
+ path = out / "model.onnx"
116
+ with torch.no_grad():
117
+ torch.onnx.export(
118
+ model,
119
+ example(12),
120
+ str(path),
121
+ input_names=INPUTS,
122
+ output_names=OUTPUTS,
123
+ opset_version=OPSET,
124
+ dynamo=True,
125
+ dynamic_shapes=(None, {1: seq}, {1: seq}, {1: seq}, None),
126
+ external_data=True,
127
+ optimize=True,
128
+ )
129
+ return path
130
+
131
+
132
+ def fix_casts(model: onnx.ModelProto) -> int:
133
+ """As in tools/sam3-export: retype each Cast the fp16 converter left aimed at float32."""
134
+ declared = {vi.name: vi.type.tensor_type.elem_type for vi in model.graph.value_info}
135
+ fixed = 0
136
+ for node in model.graph.node:
137
+ if node.op_type != "Cast" or declared.get(node.output[0]) != onnx.TensorProto.FLOAT16:
138
+ continue
139
+ for attribute in node.attribute:
140
+ if attribute.name == "to" and attribute.i == onnx.TensorProto.FLOAT:
141
+ attribute.i = onnx.TensorProto.FLOAT16
142
+ fixed += 1
143
+ return fixed
144
+
145
+
146
+ def to_fp16(src: Path, dst: Path) -> None:
147
+ model = onnx.load(str(src))
148
+ del model.graph.value_info[:]
149
+ half = float16.convert_float_to_float16(model, keep_io_types=True, disable_shape_infer=False)
150
+ print(f"fp16: {fix_casts(half)} casts fixed")
151
+ onnx.save(half, str(dst))
152
+
153
+
154
+ def main() -> None:
155
+ parser = argparse.ArgumentParser()
156
+ parser.add_argument("--weights", type=Path, required=True)
157
+ parser.add_argument("--out", type=Path, default=Path("onnx"))
158
+ parser.add_argument("--skip-fp32", action="store_true")
159
+ args = parser.parse_args()
160
+ fp32 = args.out / "fp32" / "model.onnx"
161
+ if not args.skip_fp32:
162
+ fp32 = export_fp32(args.weights, args.out / "fp32")
163
+ to_fp16(fp32, args.out / "model_fp16.onnx")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
onnx/model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88a353167c3aa952f73ff7b0e380e155b25c7500e1c07c4d2898bb0ee42c2e89
3
+ size 363683399
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_annotations": true,
3
+ "do_normalize": true,
4
+ "do_pad": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "format": "coco_detection",
8
+ "image_mean": [
9
+ 0.485,
10
+ 0.456,
11
+ 0.406
12
+ ],
13
+ "image_processor_type": "GroundingDinoImageProcessor",
14
+ "image_std": [
15
+ 0.229,
16
+ 0.224,
17
+ 0.225
18
+ ],
19
+ "pad_size": null,
20
+ "processor_class": "GroundingDinoProcessor",
21
+ "resample": 2,
22
+ "rescale_factor": 0.00392156862745098,
23
+ "size": {
24
+ "width": 800,
25
+ "height": 800
26
+ }
27
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "extra_special_tokens": {},
48
+ "mask_token": "[MASK]",
49
+ "model_max_length": 512,
50
+ "pad_token": "[PAD]",
51
+ "processor_class": "GroundingDinoProcessor",
52
+ "sep_token": "[SEP]",
53
+ "strip_accents": null,
54
+ "tokenize_chinese_chars": true,
55
+ "tokenizer_class": "BertTokenizer",
56
+ "unk_token": "[UNK]"
57
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff