HanningChen commited on
Commit
f2f112a
·
1 Parent(s): 816d148

Initial HF Space: FastAPI + HTML (no weights yet)

Browse files
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # weights / artifacts
2
+ *.pt
3
+ *.pth
4
+ *.ckpt
5
+ *.onnx
6
+ *.engine
7
+
8
+ .checkpoints/
9
+ test_model/
10
+ webui/uploads/
11
+ webui/results/
12
+ __pycache__/
13
+ *.pyc
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # System deps commonly needed by PIL/opencv/ultralytics
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ git \
8
+ ffmpeg \
9
+ libgl1 \
10
+ libglib2.0-0 \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Copy & install python deps
14
+ COPY requirements.txt /app/requirements.txt
15
+ RUN pip install --no-cache-dir -r /app/requirements.txt
16
+
17
+ # Copy project
18
+ COPY . /app
19
+
20
+ # HF Spaces expects your web server on 7860
21
+ EXPOSE 7860
22
+
23
+ # Start FastAPI
24
+ CMD ["uvicorn", "webui.app:app", "--host", "0.0.0.0", "--port", "7860"]
ImageBind/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ **__pycache__
2
+ .vscode
3
+ .idea/
4
+ .python-version
5
+ build/
6
+ imagebind.egg-info
7
+ .DS_Store
8
+ venv/
ImageBind/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@fb.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
ImageBind/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ImageBind
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Meta's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to Omnivore, you agree that your contributions will be licensed
31
+ under the [LICENSE](LICENSE) file in the root directory of this source tree.
ImageBind/LICENSE ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial-ShareAlike 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58
+ Public License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial-ShareAlike 4.0 International Public License
63
+ ("Public License"). To the extent this Public License may be
64
+ interpreted as a contract, You are granted the Licensed Rights in
65
+ consideration of Your acceptance of these terms and conditions, and the
66
+ Licensor grants You such rights in consideration of benefits the
67
+ Licensor receives from making the Licensed Material available under
68
+ these terms and conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. BY-NC-SA Compatible License means a license listed at
88
+ creativecommons.org/compatiblelicenses, approved by Creative
89
+ Commons as essentially the equivalent of this Public License.
90
+
91
+ d. Copyright and Similar Rights means copyright and/or similar rights
92
+ closely related to copyright including, without limitation,
93
+ performance, broadcast, sound recording, and Sui Generis Database
94
+ Rights, without regard to how the rights are labeled or
95
+ categorized. For purposes of this Public License, the rights
96
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
97
+ Rights.
98
+
99
+ e. Effective Technological Measures means those measures that, in the
100
+ absence of proper authority, may not be circumvented under laws
101
+ fulfilling obligations under Article 11 of the WIPO Copyright
102
+ Treaty adopted on December 20, 1996, and/or similar international
103
+ agreements.
104
+
105
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
106
+ any other exception or limitation to Copyright and Similar Rights
107
+ that applies to Your use of the Licensed Material.
108
+
109
+ g. License Elements means the license attributes listed in the name
110
+ of a Creative Commons Public License. The License Elements of this
111
+ Public License are Attribution, NonCommercial, and ShareAlike.
112
+
113
+ h. Licensed Material means the artistic or literary work, database,
114
+ or other material to which the Licensor applied this Public
115
+ License.
116
+
117
+ i. Licensed Rights means the rights granted to You subject to the
118
+ terms and conditions of this Public License, which are limited to
119
+ all Copyright and Similar Rights that apply to Your use of the
120
+ Licensed Material and that the Licensor has authority to license.
121
+
122
+ j. Licensor means the individual(s) or entity(ies) granting rights
123
+ under this Public License.
124
+
125
+ k. NonCommercial means not primarily intended for or directed towards
126
+ commercial advantage or monetary compensation. For purposes of
127
+ this Public License, the exchange of the Licensed Material for
128
+ other material subject to Copyright and Similar Rights by digital
129
+ file-sharing or similar means is NonCommercial provided there is
130
+ no payment of monetary compensation in connection with the
131
+ exchange.
132
+
133
+ l. Share means to provide material to the public by any means or
134
+ process that requires permission under the Licensed Rights, such
135
+ as reproduction, public display, public performance, distribution,
136
+ dissemination, communication, or importation, and to make material
137
+ available to the public including in ways that members of the
138
+ public may access the material from a place and at a time
139
+ individually chosen by them.
140
+
141
+ m. Sui Generis Database Rights means rights other than copyright
142
+ resulting from Directive 96/9/EC of the European Parliament and of
143
+ the Council of 11 March 1996 on the legal protection of databases,
144
+ as amended and/or succeeded, as well as other essentially
145
+ equivalent rights anywhere in the world.
146
+
147
+ n. You means the individual or entity exercising the Licensed Rights
148
+ under this Public License. Your has a corresponding meaning.
149
+
150
+
151
+ Section 2 -- Scope.
152
+
153
+ a. License grant.
154
+
155
+ 1. Subject to the terms and conditions of this Public License,
156
+ the Licensor hereby grants You a worldwide, royalty-free,
157
+ non-sublicensable, non-exclusive, irrevocable license to
158
+ exercise the Licensed Rights in the Licensed Material to:
159
+
160
+ a. reproduce and Share the Licensed Material, in whole or
161
+ in part, for NonCommercial purposes only; and
162
+
163
+ b. produce, reproduce, and Share Adapted Material for
164
+ NonCommercial purposes only.
165
+
166
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
167
+ Exceptions and Limitations apply to Your use, this Public
168
+ License does not apply, and You do not need to comply with
169
+ its terms and conditions.
170
+
171
+ 3. Term. The term of this Public License is specified in Section
172
+ 6(a).
173
+
174
+ 4. Media and formats; technical modifications allowed. The
175
+ Licensor authorizes You to exercise the Licensed Rights in
176
+ all media and formats whether now known or hereafter created,
177
+ and to make technical modifications necessary to do so. The
178
+ Licensor waives and/or agrees not to assert any right or
179
+ authority to forbid You from making technical modifications
180
+ necessary to exercise the Licensed Rights, including
181
+ technical modifications necessary to circumvent Effective
182
+ Technological Measures. For purposes of this Public License,
183
+ simply making modifications authorized by this Section 2(a)
184
+ (4) never produces Adapted Material.
185
+
186
+ 5. Downstream recipients.
187
+
188
+ a. Offer from the Licensor -- Licensed Material. Every
189
+ recipient of the Licensed Material automatically
190
+ receives an offer from the Licensor to exercise the
191
+ Licensed Rights under the terms and conditions of this
192
+ Public License.
193
+
194
+ b. Additional offer from the Licensor -- Adapted Material.
195
+ Every recipient of Adapted Material from You
196
+ automatically receives an offer from the Licensor to
197
+ exercise the Licensed Rights in the Adapted Material
198
+ under the conditions of the Adapter's License You apply.
199
+
200
+ c. No downstream restrictions. You may not offer or impose
201
+ any additional or different terms or conditions on, or
202
+ apply any Effective Technological Measures to, the
203
+ Licensed Material if doing so restricts exercise of the
204
+ Licensed Rights by any recipient of the Licensed
205
+ Material.
206
+
207
+ 6. No endorsement. Nothing in this Public License constitutes or
208
+ may be construed as permission to assert or imply that You
209
+ are, or that Your use of the Licensed Material is, connected
210
+ with, or sponsored, endorsed, or granted official status by,
211
+ the Licensor or others designated to receive attribution as
212
+ provided in Section 3(a)(1)(A)(i).
213
+
214
+ b. Other rights.
215
+
216
+ 1. Moral rights, such as the right of integrity, are not
217
+ licensed under this Public License, nor are publicity,
218
+ privacy, and/or other similar personality rights; however, to
219
+ the extent possible, the Licensor waives and/or agrees not to
220
+ assert any such rights held by the Licensor to the limited
221
+ extent necessary to allow You to exercise the Licensed
222
+ Rights, but not otherwise.
223
+
224
+ 2. Patent and trademark rights are not licensed under this
225
+ Public License.
226
+
227
+ 3. To the extent possible, the Licensor waives any right to
228
+ collect royalties from You for the exercise of the Licensed
229
+ Rights, whether directly or through a collecting society
230
+ under any voluntary or waivable statutory or compulsory
231
+ licensing scheme. In all other cases the Licensor expressly
232
+ reserves any right to collect such royalties, including when
233
+ the Licensed Material is used other than for NonCommercial
234
+ purposes.
235
+
236
+
237
+ Section 3 -- License Conditions.
238
+
239
+ Your exercise of the Licensed Rights is expressly made subject to the
240
+ following conditions.
241
+
242
+ a. Attribution.
243
+
244
+ 1. If You Share the Licensed Material (including in modified
245
+ form), You must:
246
+
247
+ a. retain the following if it is supplied by the Licensor
248
+ with the Licensed Material:
249
+
250
+ i. identification of the creator(s) of the Licensed
251
+ Material and any others designated to receive
252
+ attribution, in any reasonable manner requested by
253
+ the Licensor (including by pseudonym if
254
+ designated);
255
+
256
+ ii. a copyright notice;
257
+
258
+ iii. a notice that refers to this Public License;
259
+
260
+ iv. a notice that refers to the disclaimer of
261
+ warranties;
262
+
263
+ v. a URI or hyperlink to the Licensed Material to the
264
+ extent reasonably practicable;
265
+
266
+ b. indicate if You modified the Licensed Material and
267
+ retain an indication of any previous modifications; and
268
+
269
+ c. indicate the Licensed Material is licensed under this
270
+ Public License, and include the text of, or the URI or
271
+ hyperlink to, this Public License.
272
+
273
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
274
+ reasonable manner based on the medium, means, and context in
275
+ which You Share the Licensed Material. For example, it may be
276
+ reasonable to satisfy the conditions by providing a URI or
277
+ hyperlink to a resource that includes the required
278
+ information.
279
+ 3. If requested by the Licensor, You must remove any of the
280
+ information required by Section 3(a)(1)(A) to the extent
281
+ reasonably practicable.
282
+
283
+ b. ShareAlike.
284
+
285
+ In addition to the conditions in Section 3(a), if You Share
286
+ Adapted Material You produce, the following conditions also apply.
287
+
288
+ 1. The Adapter's License You apply must be a Creative Commons
289
+ license with the same License Elements, this version or
290
+ later, or a BY-NC-SA Compatible License.
291
+
292
+ 2. You must include the text of, or the URI or hyperlink to, the
293
+ Adapter's License You apply. You may satisfy this condition
294
+ in any reasonable manner based on the medium, means, and
295
+ context in which You Share Adapted Material.
296
+
297
+ 3. You may not offer or impose any additional or different terms
298
+ or conditions on, or apply any Effective Technological
299
+ Measures to, Adapted Material that restrict exercise of the
300
+ rights granted under the Adapter's License You apply.
301
+
302
+
303
+ Section 4 -- Sui Generis Database Rights.
304
+
305
+ Where the Licensed Rights include Sui Generis Database Rights that
306
+ apply to Your use of the Licensed Material:
307
+
308
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309
+ to extract, reuse, reproduce, and Share all or a substantial
310
+ portion of the contents of the database for NonCommercial purposes
311
+ only;
312
+
313
+ b. if You include all or a substantial portion of the database
314
+ contents in a database in which You have Sui Generis Database
315
+ Rights, then the database in which You have Sui Generis Database
316
+ Rights (but not its individual contents) is Adapted Material,
317
+ including for purposes of Section 3(b); and
318
+
319
+ c. You must comply with the conditions in Section 3(a) if You Share
320
+ all or a substantial portion of the contents of the database.
321
+
322
+ For the avoidance of doubt, this Section 4 supplements and does not
323
+ replace Your obligations under this Public License where the Licensed
324
+ Rights include other Copyright and Similar Rights.
325
+
326
+
327
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328
+
329
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339
+
340
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349
+
350
+ c. The disclaimer of warranties and limitation of liability provided
351
+ above shall be interpreted in a manner that, to the extent
352
+ possible, most closely approximates an absolute disclaimer and
353
+ waiver of all liability.
354
+
355
+
356
+ Section 6 -- Term and Termination.
357
+
358
+ a. This Public License applies for the term of the Copyright and
359
+ Similar Rights licensed here. However, if You fail to comply with
360
+ this Public License, then Your rights under this Public License
361
+ terminate automatically.
362
+
363
+ b. Where Your right to use the Licensed Material has terminated under
364
+ Section 6(a), it reinstates:
365
+
366
+ 1. automatically as of the date the violation is cured, provided
367
+ it is cured within 30 days of Your discovery of the
368
+ violation; or
369
+
370
+ 2. upon express reinstatement by the Licensor.
371
+
372
+ For the avoidance of doubt, this Section 6(b) does not affect any
373
+ right the Licensor may have to seek remedies for Your violations
374
+ of this Public License.
375
+
376
+ c. For the avoidance of doubt, the Licensor may also offer the
377
+ Licensed Material under separate terms or conditions or stop
378
+ distributing the Licensed Material at any time; however, doing so
379
+ will not terminate this Public License.
380
+
381
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382
+ License.
383
+
384
+
385
+ Section 7 -- Other Terms and Conditions.
386
+
387
+ a. The Licensor shall not be bound by any additional or different
388
+ terms or conditions communicated by You unless expressly agreed.
389
+
390
+ b. Any arrangements, understandings, or agreements regarding the
391
+ Licensed Material not stated herein are separate from and
392
+ independent of the terms and conditions of this Public License.
393
+
394
+
395
+ Section 8 -- Interpretation.
396
+
397
+ a. For the avoidance of doubt, this Public License does not, and
398
+ shall not be interpreted to, reduce, limit, restrict, or impose
399
+ conditions on any use of the Licensed Material that could lawfully
400
+ be made without permission under this Public License.
401
+
402
+ b. To the extent possible, if any provision of this Public License is
403
+ deemed unenforceable, it shall be automatically reformed to the
404
+ minimum extent necessary to make it enforceable. If the provision
405
+ cannot be reformed, it shall be severed from this Public License
406
+ without affecting the enforceability of the remaining terms and
407
+ conditions.
408
+
409
+ c. No term or condition of this Public License will be waived and no
410
+ failure to comply consented to unless expressly agreed to by the
411
+ Licensor.
412
+
413
+ d. Nothing in this Public License constitutes or may be interpreted
414
+ as a limitation upon, or waiver of, any privileges and immunities
415
+ that apply to the Licensor or You, including from the legal
416
+ processes of any jurisdiction or authority.
417
+
418
+ =======================================================================
419
+
420
+ Creative Commons is not a party to its public
421
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
422
+ its public licenses to material it publishes and in those instances
423
+ will be considered the “Licensor.” The text of the Creative Commons
424
+ public licenses is dedicated to the public domain under the CC0 Public
425
+ Domain Dedication. Except for the limited purpose of indicating that
426
+ material is shared under a Creative Commons public license or as
427
+ otherwise permitted by the Creative Commons policies published at
428
+ creativecommons.org/policies, Creative Commons does not authorize the
429
+ use of the trademark "Creative Commons" or any other trademark or logo
430
+ of Creative Commons without its prior written consent including,
431
+ without limitation, in connection with any unauthorized modifications
432
+ to any of its public licenses or any other arrangements,
433
+ understandings, or agreements concerning use of licensed material. For
434
+ the avoidance of doubt, this paragraph does not form part of the
435
+ public licenses.
436
+
437
+ Creative Commons may be contacted at creativecommons.org.
ImageBind/README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ImageBind: One Embedding Space To Bind Them All
2
+
3
+ **[FAIR, Meta AI](https://ai.facebook.com/research/)**
4
+
5
+ Rohit Girdhar*,
6
+ Alaaeldin El-Nouby*,
7
+ Zhuang Liu,
8
+ Mannat Singh,
9
+ Kalyan Vasudev Alwala,
10
+ Armand Joulin,
11
+ Ishan Misra*
12
+
13
+ To appear at CVPR 2023 (*Highlighted paper*)
14
+
15
+ [[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)]
16
+
17
+ PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
18
+
19
+ ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
20
+
21
+
22
+
23
+ ![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)
24
+
25
+ ## ImageBind model
26
+
27
+ Emergent zero-shot classification performance.
28
+
29
+ <table style="margin: auto">
30
+ <tr>
31
+ <th>Model</th>
32
+ <th><span style="color:blue">IN1k</span></th>
33
+ <th><span style="color:purple">K400</span></th>
34
+ <th><span style="color:green">NYU-D</span></th>
35
+ <th><span style="color:LightBlue">ESC</span></th>
36
+ <th><span style="color:orange">LLVIP</span></th>
37
+ <th><span style="color:purple">Ego4D</span></th>
38
+ <th>download</th>
39
+ </tr>
40
+ <tr>
41
+ <td>imagebind_huge</td>
42
+ <td align="right">77.7</td>
43
+ <td align="right">50.0</td>
44
+ <td align="right">54.0</td>
45
+ <td align="right">66.9</td>
46
+ <td align="right">63.4</td>
47
+ <td align="right">25.0</td>
48
+ <td><a href="https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth">checkpoint</a></td>
49
+ </tr>
50
+
51
+ </table>
52
+
53
+ ## Usage
54
+
55
+ Install pytorch 2.0+ and other 3rd party dependencies.
56
+
57
+ ```shell
58
+ conda create --name imagebind python=3.10 -y
59
+ conda activate imagebind
60
+
61
+ pip install .
62
+ ```
63
+
64
+ For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
65
+
66
+ ```
67
+ pip install soundfile
68
+ ```
69
+
70
+
71
+ Extract and compare features across modalities (e.g. Image, Text and Audio).
72
+
73
+ ```python
74
+ from imagebind import data
75
+ import torch
76
+ from imagebind.models import imagebind_model
77
+ from imagebind.models.imagebind_model import ModalityType
78
+
79
+ text_list=["A dog.", "A car", "A bird"]
80
+ image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
81
+ audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
82
+
83
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
84
+
85
+ # Instantiate model
86
+ model = imagebind_model.imagebind_huge(pretrained=True)
87
+ model.eval()
88
+ model.to(device)
89
+
90
+ # Load data
91
+ inputs = {
92
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
93
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
94
+ ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
95
+ }
96
+
97
+ with torch.no_grad():
98
+ embeddings = model(inputs)
99
+
100
+ print(
101
+ "Vision x Text: ",
102
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
103
+ )
104
+ print(
105
+ "Audio x Text: ",
106
+ torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
107
+ )
108
+ print(
109
+ "Vision x Audio: ",
110
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
111
+ )
112
+
113
+ # Expected output:
114
+ #
115
+ # Vision x Text:
116
+ # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
117
+ # [3.3836e-05, 9.9994e-01, 2.4118e-05],
118
+ # [4.7997e-05, 1.3496e-02, 9.8646e-01]])
119
+ #
120
+ # Audio x Text:
121
+ # tensor([[1., 0., 0.],
122
+ # [0., 1., 0.],
123
+ # [0., 0., 1.]])
124
+ #
125
+ # Vision x Audio:
126
+ # tensor([[0.8070, 0.1088, 0.0842],
127
+ # [0.1036, 0.7884, 0.1079],
128
+ # [0.0018, 0.0022, 0.9960]])
129
+
130
+ ```
131
+
132
+ ## Model card
133
+ Please see the [model card](model_card.md) for details.
134
+
135
+ ## License
136
+
137
+ ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
138
+
139
+ ## Contributing
140
+
141
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
142
+
143
+ ## Citing ImageBind
144
+
145
+ If you find this repository useful, please consider giving a star :star: and citation
146
+
147
+ ```
148
+ @inproceedings{girdhar2023imagebind,
149
+ title={ImageBind: One Embedding Space To Bind Them All},
150
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
151
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
152
+ booktitle={CVPR},
153
+ year={2023}
154
+ }
155
+ ```
ImageBind/imagebind/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from imagebind import data
2
+ from imagebind.models import imagebind_model
3
+ from imagebind.models.imagebind_model import ModalityType
ImageBind/imagebind/bpe/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
ImageBind/imagebind/data.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import math
10
+ import pkg_resources
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torchaudio
15
+ from PIL import Image
16
+ from pytorchvideo import transforms as pv_transforms
17
+ from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
18
+ from pytorchvideo.data.encoded_video import EncodedVideo
19
+ from torchvision import transforms
20
+
21
+ from imagebind.models.multimodal_preprocessors import SimpleTokenizer
22
+
23
+ DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
24
+
25
+
26
+ def return_bpe_path():
27
+ return pkg_resources.resource_filename(
28
+ "imagebind", "bpe/bpe_simple_vocab_16e6.txt.gz"
29
+ )
30
+
31
+
32
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
33
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
34
+ waveform -= waveform.mean()
35
+ fbank = torchaudio.compliance.kaldi.fbank(
36
+ waveform,
37
+ htk_compat=True,
38
+ sample_frequency=sample_rate,
39
+ use_energy=False,
40
+ window_type="hanning",
41
+ num_mel_bins=num_mel_bins,
42
+ dither=0.0,
43
+ frame_length=25,
44
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
45
+ )
46
+ # Convert to [mel_bins, num_frames] shape
47
+ fbank = fbank.transpose(0, 1)
48
+ # Pad to target_length
49
+ n_frames = fbank.size(1)
50
+ p = target_length - n_frames
51
+ # if p is too large (say >20%), flash a warning
52
+ if abs(p) / n_frames > 0.2:
53
+ logging.warning(
54
+ "Large gap between audio n_frames(%d) and "
55
+ "target_length (%d). Is the audio_target_length "
56
+ "setting correct?",
57
+ n_frames,
58
+ target_length,
59
+ )
60
+ # cut and pad
61
+ if p > 0:
62
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
63
+ elif p < 0:
64
+ fbank = fbank[:, 0:target_length]
65
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
66
+ # channel image
67
+ fbank = fbank.unsqueeze(0)
68
+ return fbank
69
+
70
+
71
+ def get_clip_timepoints(clip_sampler, duration):
72
+ # Read out all clips in this video
73
+ all_clips_timepoints = []
74
+ is_last_clip = False
75
+ end = 0.0
76
+ while not is_last_clip:
77
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
78
+ all_clips_timepoints.append((start, end))
79
+ return all_clips_timepoints
80
+
81
+
82
+ def load_and_transform_vision_data(image_paths, device):
83
+ if image_paths is None:
84
+ return None
85
+
86
+ image_outputs = []
87
+
88
+ data_transform = transforms.Compose(
89
+ [
90
+ transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
91
+ transforms.CenterCrop(224),
92
+ transforms.ToTensor(),
93
+ transforms.Normalize(
94
+ mean=(0.48145466, 0.4578275, 0.40821073),
95
+ std=(0.26862954, 0.26130258, 0.27577711),
96
+ ),
97
+ ]
98
+ )
99
+
100
+ for image_path in image_paths:
101
+ with open(image_path, "rb") as fopen:
102
+ image = Image.open(fopen).convert("RGB")
103
+
104
+ image = data_transform(image).to(device)
105
+ image_outputs.append(image)
106
+ return torch.stack(image_outputs, dim=0)
107
+
108
+
109
+ def load_and_transform_text(text, device):
110
+ if text is None:
111
+ return None
112
+ tokenizer = SimpleTokenizer(bpe_path=return_bpe_path())
113
+ tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
114
+ tokens = torch.cat(tokens, dim=0)
115
+ return tokens
116
+
117
+
118
+ def load_and_transform_audio_data(
119
+ audio_paths,
120
+ device,
121
+ num_mel_bins=128,
122
+ target_length=204,
123
+ sample_rate=16000,
124
+ clip_duration=2,
125
+ clips_per_video=3,
126
+ mean=-4.268,
127
+ std=9.138,
128
+ ):
129
+ if audio_paths is None:
130
+ return None
131
+
132
+ audio_outputs = []
133
+ clip_sampler = ConstantClipsPerVideoSampler(
134
+ clip_duration=clip_duration, clips_per_video=clips_per_video
135
+ )
136
+
137
+ for audio_path in audio_paths:
138
+ waveform, sr = torchaudio.load(audio_path)
139
+ if sample_rate != sr:
140
+ waveform = torchaudio.functional.resample(
141
+ waveform, orig_freq=sr, new_freq=sample_rate
142
+ )
143
+ all_clips_timepoints = get_clip_timepoints(
144
+ clip_sampler, waveform.size(1) / sample_rate
145
+ )
146
+ all_clips = []
147
+ for clip_timepoints in all_clips_timepoints:
148
+ waveform_clip = waveform[
149
+ :,
150
+ int(clip_timepoints[0] * sample_rate) : int(
151
+ clip_timepoints[1] * sample_rate
152
+ ),
153
+ ]
154
+ waveform_melspec = waveform2melspec(
155
+ waveform_clip, sample_rate, num_mel_bins, target_length
156
+ )
157
+ all_clips.append(waveform_melspec)
158
+
159
+ normalize = transforms.Normalize(mean=mean, std=std)
160
+ all_clips = [normalize(ac).to(device) for ac in all_clips]
161
+
162
+ all_clips = torch.stack(all_clips, dim=0)
163
+ audio_outputs.append(all_clips)
164
+
165
+ return torch.stack(audio_outputs, dim=0)
166
+
167
+
168
+ def crop_boxes(boxes, x_offset, y_offset):
169
+ """
170
+ Perform crop on the bounding boxes given the offsets.
171
+ Args:
172
+ boxes (ndarray or None): bounding boxes to perform crop. The dimension
173
+ is `num boxes` x 4.
174
+ x_offset (int): cropping offset in the x axis.
175
+ y_offset (int): cropping offset in the y axis.
176
+ Returns:
177
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
178
+ `num boxes` x 4.
179
+ """
180
+ cropped_boxes = boxes.copy()
181
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
182
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
183
+
184
+ return cropped_boxes
185
+
186
+
187
+ def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
188
+ """
189
+ Perform uniform spatial sampling on the images and corresponding boxes.
190
+ Args:
191
+ images (tensor): images to perform uniform crop. The dimension is
192
+ `num frames` x `channel` x `height` x `width`.
193
+ size (int): size of height and weight to crop the images.
194
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
195
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
196
+ crop if height is larger than width.
197
+ boxes (ndarray or None): optional. Corresponding boxes to images.
198
+ Dimension is `num boxes` x 4.
199
+ scale_size (int): optinal. If not None, resize the images to scale_size before
200
+ performing any crop.
201
+ Returns:
202
+ cropped (tensor): images with dimension of
203
+ `num frames` x `channel` x `size` x `size`.
204
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
205
+ `num boxes` x 4.
206
+ """
207
+ assert spatial_idx in [0, 1, 2]
208
+ ndim = len(images.shape)
209
+ if ndim == 3:
210
+ images = images.unsqueeze(0)
211
+ height = images.shape[2]
212
+ width = images.shape[3]
213
+
214
+ if scale_size is not None:
215
+ if width <= height:
216
+ width, height = scale_size, int(height / width * scale_size)
217
+ else:
218
+ width, height = int(width / height * scale_size), scale_size
219
+ images = torch.nn.functional.interpolate(
220
+ images,
221
+ size=(height, width),
222
+ mode="bilinear",
223
+ align_corners=False,
224
+ )
225
+
226
+ y_offset = int(math.ceil((height - size) / 2))
227
+ x_offset = int(math.ceil((width - size) / 2))
228
+
229
+ if height > width:
230
+ if spatial_idx == 0:
231
+ y_offset = 0
232
+ elif spatial_idx == 2:
233
+ y_offset = height - size
234
+ else:
235
+ if spatial_idx == 0:
236
+ x_offset = 0
237
+ elif spatial_idx == 2:
238
+ x_offset = width - size
239
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
240
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
241
+ if ndim == 3:
242
+ cropped = cropped.squeeze(0)
243
+ return cropped, cropped_boxes
244
+
245
+
246
+ class SpatialCrop(nn.Module):
247
+ """
248
+ Convert the video into 3 smaller clips spatially. Must be used after the
249
+ temporal crops to get spatial crops, and should be used with
250
+ -2 in the spatial crop at the slowfast augmentation stage (so full
251
+ frames are passed in here). Will return a larger list with the
252
+ 3x spatial crops as well.
253
+ """
254
+
255
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
256
+ super().__init__()
257
+ self.crop_size = crop_size
258
+ if num_crops == 3:
259
+ self.crops_to_ext = [0, 1, 2]
260
+ self.flipped_crops_to_ext = []
261
+ elif num_crops == 1:
262
+ self.crops_to_ext = [1]
263
+ self.flipped_crops_to_ext = []
264
+ else:
265
+ raise NotImplementedError("Nothing else supported yet")
266
+
267
+ def forward(self, videos):
268
+ """
269
+ Args:
270
+ videos: A list of C, T, H, W videos.
271
+ Returns:
272
+ videos: A list with 3x the number of elements. Each video converted
273
+ to C, T, H', W' by spatial cropping.
274
+ """
275
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
276
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
277
+ res = []
278
+ for video in videos:
279
+ for spatial_idx in self.crops_to_ext:
280
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
281
+ if not self.flipped_crops_to_ext:
282
+ continue
283
+ flipped_video = transforms.functional.hflip(video)
284
+ for spatial_idx in self.flipped_crops_to_ext:
285
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
286
+ return res
287
+
288
+
289
+ class NormalizeVideo:
290
+ def __init__(self, mean, std, inplace=False):
291
+ self.mean = mean
292
+ self.std = std
293
+ self.inplace = inplace
294
+
295
+ def __call__(self, clip):
296
+ if not self.inplace:
297
+ clip = clip.clone()
298
+ mean = torch.as_tensor(self.mean, dtype=clip.dtype, device=clip.device)
299
+ std = torch.as_tensor(self.std, dtype=clip.dtype, device=clip.device)
300
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
301
+ return clip
302
+
303
+
304
+ def load_and_transform_video_data(
305
+ video_paths,
306
+ device,
307
+ clip_duration=2,
308
+ clips_per_video=5,
309
+ sample_rate=16000,
310
+ ):
311
+ if video_paths is None:
312
+ return None
313
+
314
+ video_outputs = []
315
+ video_transform = transforms.Compose(
316
+ [
317
+ pv_transforms.ShortSideScale(224),
318
+ NormalizeVideo(
319
+ mean=(0.48145466, 0.4578275, 0.40821073),
320
+ std=(0.26862954, 0.26130258, 0.27577711),
321
+ ),
322
+ ]
323
+ )
324
+
325
+ clip_sampler = ConstantClipsPerVideoSampler(
326
+ clip_duration=clip_duration, clips_per_video=clips_per_video
327
+ )
328
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
329
+
330
+ for video_path in video_paths:
331
+ video = EncodedVideo.from_path(
332
+ video_path,
333
+ decoder="decord",
334
+ decode_audio=False,
335
+ **{"sample_rate": sample_rate},
336
+ )
337
+
338
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
339
+
340
+ all_video = []
341
+ for clip_timepoints in all_clips_timepoints:
342
+ # Read the clip, get frames
343
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
344
+ if clip is None:
345
+ raise ValueError("No clip found")
346
+ video_clip = frame_sampler(clip["video"])
347
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
348
+
349
+ all_video.append(video_clip)
350
+
351
+ all_video = [video_transform(clip) for clip in all_video]
352
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
353
+
354
+ all_video = torch.stack(all_video, dim=0)
355
+ video_outputs.append(all_video)
356
+
357
+ return torch.stack(video_outputs, dim=0).to(device)
358
+
359
+ #NOTE: Hanning add for TaskCLIP
360
+ def read_and_transform_vision_data(image_list, device):
361
+ if image_list is None:
362
+ return None
363
+
364
+ image_outputs = []
365
+
366
+ data_transform = transforms.Compose(
367
+ [
368
+ transforms.Resize(
369
+ 224, interpolation=transforms.InterpolationMode.BICUBIC
370
+ ),
371
+ transforms.CenterCrop(224),
372
+ transforms.ToTensor(),
373
+ transforms.Normalize(
374
+ mean=(0.48145466, 0.4578275, 0.40821073),
375
+ std=(0.26862954, 0.26130258, 0.27577711),
376
+ ),
377
+ ]
378
+ )
379
+
380
+ for image in image_list:
381
+ image = data_transform(image).to(device)
382
+ image_outputs.append(image)
383
+ return torch.stack(image_outputs, dim=0)
ImageBind/imagebind/models/__init__.py ADDED
File without changes
ImageBind/imagebind/models/helpers.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+
9
+ import einops
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+
14
+
15
+ class Normalize(nn.Module):
16
+ def __init__(self, dim: int) -> None:
17
+ super().__init__()
18
+ self.dim = dim
19
+
20
+ def forward(self, x):
21
+ return torch.nn.functional.normalize(x, dim=self.dim, p=2)
22
+
23
+
24
+ class LearnableLogitScaling(nn.Module):
25
+ def __init__(
26
+ self,
27
+ logit_scale_init: float = 1 / 0.07,
28
+ learnable: bool = True,
29
+ max_logit_scale: float = 100,
30
+ ) -> None:
31
+ super().__init__()
32
+ self.max_logit_scale = max_logit_scale
33
+ self.logit_scale_init = logit_scale_init
34
+ self.learnable = learnable
35
+ log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
36
+ if learnable:
37
+ self.log_logit_scale = nn.Parameter(log_logit_scale)
38
+ else:
39
+ self.register_buffer("log_logit_scale", log_logit_scale)
40
+
41
+ def forward(self, x):
42
+ return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
43
+
44
+ def extra_repr(self):
45
+ st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \
46
+ f" max_logit_scale={self.max_logit_scale}"
47
+ return st
48
+
49
+
50
+ class EinOpsRearrange(nn.Module):
51
+ def __init__(self, rearrange_expr: str, **kwargs) -> None:
52
+ super().__init__()
53
+ self.rearrange_expr = rearrange_expr
54
+ self.kwargs = kwargs
55
+
56
+ def forward(self, x):
57
+ assert isinstance(x, torch.Tensor)
58
+ return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
59
+
60
+
61
+ class VerboseNNModule(nn.Module):
62
+ """
63
+ Wrapper around nn.Module that prints registered buffers and parameter names.
64
+ """
65
+
66
+ @staticmethod
67
+ def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
68
+ st = (
69
+ "("
70
+ + name
71
+ + "): "
72
+ + "tensor("
73
+ + str(tuple(tensor[1].shape))
74
+ + ", requires_grad="
75
+ + str(tensor[1].requires_grad)
76
+ + ")\n"
77
+ )
78
+ return st
79
+
80
+ def extra_repr(self) -> str:
81
+ named_modules = set()
82
+ for p in self.named_modules():
83
+ named_modules.update([p[0]])
84
+ named_modules = list(named_modules)
85
+
86
+ string_repr = ""
87
+ for p in self.named_parameters():
88
+ name = p[0].split(".")[0]
89
+ if name not in named_modules:
90
+ string_repr += self.get_readable_tensor_repr(name, p)
91
+
92
+ for p in self.named_buffers():
93
+ name = p[0].split(".")[0]
94
+ string_repr += self.get_readable_tensor_repr(name, p)
95
+
96
+ return string_repr
97
+
98
+
99
+ def cast_if_src_dtype(
100
+ tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
101
+ ):
102
+ updated = False
103
+ if tensor.dtype == src_dtype:
104
+ tensor = tensor.to(dtype=tgt_dtype)
105
+ updated = True
106
+ return tensor, updated
107
+
108
+
109
+ class QuickGELU(nn.Module):
110
+ # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
111
+ def forward(self, x: torch.Tensor):
112
+ return x * torch.sigmoid(1.702 * x)
113
+
114
+
115
+ class SelectElement(nn.Module):
116
+ def __init__(self, index) -> None:
117
+ super().__init__()
118
+ self.index = index
119
+
120
+ def forward(self, x):
121
+ assert x.ndim >= 3
122
+ return x[:, self.index, ...]
123
+
124
+
125
+ class SelectEOSAndProject(nn.Module):
126
+ """
127
+ Text Pooling used in OpenCLIP
128
+ """
129
+
130
+ def __init__(self, proj: nn.Module) -> None:
131
+ super().__init__()
132
+ self.proj = proj
133
+
134
+ def forward(self, x, seq_len):
135
+ assert x.ndim == 3
136
+ # x is of shape B x L x D
137
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
138
+ x = x[torch.arange(x.shape[0]), seq_len]
139
+ x = self.proj(x)
140
+ return x
ImageBind/imagebind/models/imagebind_model.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+
9
+ import os
10
+ from functools import partial
11
+ from types import SimpleNamespace
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+
16
+ from imagebind.models.helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize,
17
+ SelectElement, SelectEOSAndProject)
18
+ from imagebind.models.multimodal_preprocessors import (AudioPreprocessor,
19
+ IMUPreprocessor, PadIm2Video,
20
+ PatchEmbedGeneric,
21
+ RGBDTPreprocessor,
22
+ SpatioTemporalPosEmbeddingHelper,
23
+ TextPreprocessor,
24
+ ThermalPreprocessor)
25
+ from imagebind.models.transformer import MultiheadAttention, SimpleTransformer
26
+
27
+ ModalityType = SimpleNamespace(
28
+ VISION="vision",
29
+ TEXT="text",
30
+ AUDIO="audio",
31
+ THERMAL="thermal",
32
+ DEPTH="depth",
33
+ IMU="imu",
34
+ )
35
+
36
+
37
+ class ImageBindModel(nn.Module):
38
+ def __init__(
39
+ self,
40
+ video_frames=2,
41
+ kernel_size=(2, 14, 14),
42
+ audio_kernel_size=16,
43
+ audio_stride=10,
44
+ out_embed_dim=768,
45
+ vision_embed_dim=1024,
46
+ vision_num_blocks=24,
47
+ vision_num_heads=16,
48
+ audio_embed_dim=768,
49
+ audio_num_blocks=12,
50
+ audio_num_heads=12,
51
+ audio_num_mel_bins=128,
52
+ audio_target_len=204,
53
+ audio_drop_path=0.1,
54
+ text_embed_dim=768,
55
+ text_num_blocks=12,
56
+ text_num_heads=12,
57
+ depth_embed_dim=384,
58
+ depth_kernel_size=16,
59
+ depth_num_blocks=12,
60
+ depth_num_heads=8,
61
+ depth_drop_path=0.0,
62
+ thermal_embed_dim=768,
63
+ thermal_kernel_size=16,
64
+ thermal_num_blocks=12,
65
+ thermal_num_heads=12,
66
+ thermal_drop_path=0.0,
67
+ imu_embed_dim=512,
68
+ imu_kernel_size=8,
69
+ imu_num_blocks=6,
70
+ imu_num_heads=8,
71
+ imu_drop_path=0.7,
72
+ ):
73
+ super().__init__()
74
+
75
+ self.modality_preprocessors = self._create_modality_preprocessors(
76
+ video_frames,
77
+ vision_embed_dim,
78
+ kernel_size,
79
+ text_embed_dim,
80
+ audio_embed_dim,
81
+ audio_kernel_size,
82
+ audio_stride,
83
+ audio_num_mel_bins,
84
+ audio_target_len,
85
+ depth_embed_dim,
86
+ depth_kernel_size,
87
+ thermal_embed_dim,
88
+ thermal_kernel_size,
89
+ imu_embed_dim,
90
+ )
91
+
92
+ self.modality_trunks = self._create_modality_trunks(
93
+ vision_embed_dim,
94
+ vision_num_blocks,
95
+ vision_num_heads,
96
+ text_embed_dim,
97
+ text_num_blocks,
98
+ text_num_heads,
99
+ audio_embed_dim,
100
+ audio_num_blocks,
101
+ audio_num_heads,
102
+ audio_drop_path,
103
+ depth_embed_dim,
104
+ depth_num_blocks,
105
+ depth_num_heads,
106
+ depth_drop_path,
107
+ thermal_embed_dim,
108
+ thermal_num_blocks,
109
+ thermal_num_heads,
110
+ thermal_drop_path,
111
+ imu_embed_dim,
112
+ imu_num_blocks,
113
+ imu_num_heads,
114
+ imu_drop_path,
115
+ )
116
+
117
+ self.modality_heads = self._create_modality_heads(
118
+ out_embed_dim,
119
+ vision_embed_dim,
120
+ text_embed_dim,
121
+ audio_embed_dim,
122
+ depth_embed_dim,
123
+ thermal_embed_dim,
124
+ imu_embed_dim,
125
+ )
126
+
127
+ self.modality_postprocessors = self._create_modality_postprocessors(
128
+ out_embed_dim
129
+ )
130
+
131
+ def _create_modality_preprocessors(
132
+ self,
133
+ video_frames=2,
134
+ vision_embed_dim=1024,
135
+ kernel_size=(2, 14, 14),
136
+ text_embed_dim=768,
137
+ audio_embed_dim=768,
138
+ audio_kernel_size=16,
139
+ audio_stride=10,
140
+ audio_num_mel_bins=128,
141
+ audio_target_len=204,
142
+ depth_embed_dim=768,
143
+ depth_kernel_size=16,
144
+ thermal_embed_dim=768,
145
+ thermal_kernel_size=16,
146
+ imu_embed_dim=512,
147
+ ):
148
+ rgbt_stem = PatchEmbedGeneric(
149
+ proj_stem=[
150
+ PadIm2Video(pad_type="repeat", ntimes=2),
151
+ nn.Conv3d(
152
+ in_channels=3,
153
+ kernel_size=kernel_size,
154
+ out_channels=vision_embed_dim,
155
+ stride=kernel_size,
156
+ bias=False,
157
+ ),
158
+ ]
159
+ )
160
+ rgbt_preprocessor = RGBDTPreprocessor(
161
+ img_size=[3, video_frames, 224, 224],
162
+ num_cls_tokens=1,
163
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
164
+ rgbt_stem=rgbt_stem,
165
+ depth_stem=None,
166
+ )
167
+
168
+ text_preprocessor = TextPreprocessor(
169
+ context_length=77,
170
+ vocab_size=49408,
171
+ embed_dim=text_embed_dim,
172
+ causal_masking=True,
173
+ )
174
+
175
+ audio_stem = PatchEmbedGeneric(
176
+ proj_stem=[
177
+ nn.Conv2d(
178
+ in_channels=1,
179
+ kernel_size=audio_kernel_size,
180
+ stride=audio_stride,
181
+ out_channels=audio_embed_dim,
182
+ bias=False,
183
+ ),
184
+ ],
185
+ norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
186
+ )
187
+ audio_preprocessor = AudioPreprocessor(
188
+ img_size=[1, audio_num_mel_bins, audio_target_len],
189
+ num_cls_tokens=1,
190
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
191
+ audio_stem=audio_stem,
192
+ )
193
+
194
+ depth_stem = PatchEmbedGeneric(
195
+ [
196
+ nn.Conv2d(
197
+ kernel_size=depth_kernel_size,
198
+ in_channels=1,
199
+ out_channels=depth_embed_dim,
200
+ stride=depth_kernel_size,
201
+ bias=False,
202
+ ),
203
+ ],
204
+ norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
205
+ )
206
+
207
+ depth_preprocessor = RGBDTPreprocessor(
208
+ img_size=[1, 224, 224],
209
+ num_cls_tokens=1,
210
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
211
+ rgbt_stem=None,
212
+ depth_stem=depth_stem,
213
+ )
214
+
215
+ thermal_stem = PatchEmbedGeneric(
216
+ [
217
+ nn.Conv2d(
218
+ kernel_size=thermal_kernel_size,
219
+ in_channels=1,
220
+ out_channels=thermal_embed_dim,
221
+ stride=thermal_kernel_size,
222
+ bias=False,
223
+ ),
224
+ ],
225
+ norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
226
+ )
227
+ thermal_preprocessor = ThermalPreprocessor(
228
+ img_size=[1, 224, 224],
229
+ num_cls_tokens=1,
230
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
231
+ thermal_stem=thermal_stem,
232
+ )
233
+
234
+ imu_stem = PatchEmbedGeneric(
235
+ [
236
+ nn.Linear(
237
+ in_features=48,
238
+ out_features=imu_embed_dim,
239
+ bias=False,
240
+ ),
241
+ ],
242
+ norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
243
+ )
244
+
245
+ imu_preprocessor = IMUPreprocessor(
246
+ img_size=[6, 2000],
247
+ num_cls_tokens=1,
248
+ kernel_size=8,
249
+ embed_dim=imu_embed_dim,
250
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
251
+ imu_stem=imu_stem,
252
+ )
253
+
254
+ modality_preprocessors = {
255
+ ModalityType.VISION: rgbt_preprocessor,
256
+ ModalityType.TEXT: text_preprocessor,
257
+ ModalityType.AUDIO: audio_preprocessor,
258
+ ModalityType.DEPTH: depth_preprocessor,
259
+ ModalityType.THERMAL: thermal_preprocessor,
260
+ ModalityType.IMU: imu_preprocessor,
261
+ }
262
+
263
+ return nn.ModuleDict(modality_preprocessors)
264
+
265
+ def _create_modality_trunks(
266
+ self,
267
+ vision_embed_dim=1024,
268
+ vision_num_blocks=24,
269
+ vision_num_heads=16,
270
+ text_embed_dim=768,
271
+ text_num_blocks=12,
272
+ text_num_heads=12,
273
+ audio_embed_dim=768,
274
+ audio_num_blocks=12,
275
+ audio_num_heads=12,
276
+ audio_drop_path=0.0,
277
+ depth_embed_dim=768,
278
+ depth_num_blocks=12,
279
+ depth_num_heads=12,
280
+ depth_drop_path=0.0,
281
+ thermal_embed_dim=768,
282
+ thermal_num_blocks=12,
283
+ thermal_num_heads=12,
284
+ thermal_drop_path=0.0,
285
+ imu_embed_dim=512,
286
+ imu_num_blocks=6,
287
+ imu_num_heads=8,
288
+ imu_drop_path=0.7,
289
+ ):
290
+ def instantiate_trunk(
291
+ embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
292
+ ):
293
+ return SimpleTransformer(
294
+ embed_dim=embed_dim,
295
+ num_blocks=num_blocks,
296
+ ffn_dropout_rate=0.0,
297
+ drop_path_rate=drop_path,
298
+ attn_target=partial(
299
+ MultiheadAttention,
300
+ embed_dim=embed_dim,
301
+ num_heads=num_heads,
302
+ bias=True,
303
+ add_bias_kv=add_bias_kv,
304
+ ),
305
+ pre_transformer_layer=nn.Sequential(
306
+ nn.LayerNorm(embed_dim, eps=1e-6)
307
+ if pre_transformer_ln
308
+ else nn.Identity(),
309
+ EinOpsRearrange("b l d -> l b d"),
310
+ ),
311
+ post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
312
+ )
313
+
314
+ modality_trunks = {}
315
+ modality_trunks[ModalityType.VISION] = instantiate_trunk(
316
+ vision_embed_dim,
317
+ vision_num_blocks,
318
+ vision_num_heads,
319
+ pre_transformer_ln=True,
320
+ add_bias_kv=False,
321
+ drop_path=0.0,
322
+ )
323
+ modality_trunks[ModalityType.TEXT] = instantiate_trunk(
324
+ text_embed_dim,
325
+ text_num_blocks,
326
+ text_num_heads,
327
+ pre_transformer_ln=False,
328
+ add_bias_kv=False,
329
+ drop_path=0.0,
330
+ )
331
+ modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
332
+ audio_embed_dim,
333
+ audio_num_blocks,
334
+ audio_num_heads,
335
+ pre_transformer_ln=False,
336
+ add_bias_kv=True,
337
+ drop_path=audio_drop_path,
338
+ )
339
+ modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
340
+ depth_embed_dim,
341
+ depth_num_blocks,
342
+ depth_num_heads,
343
+ pre_transformer_ln=False,
344
+ add_bias_kv=True,
345
+ drop_path=depth_drop_path,
346
+ )
347
+ modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
348
+ thermal_embed_dim,
349
+ thermal_num_blocks,
350
+ thermal_num_heads,
351
+ pre_transformer_ln=False,
352
+ add_bias_kv=True,
353
+ drop_path=thermal_drop_path,
354
+ )
355
+ modality_trunks[ModalityType.IMU] = instantiate_trunk(
356
+ imu_embed_dim,
357
+ imu_num_blocks,
358
+ imu_num_heads,
359
+ pre_transformer_ln=False,
360
+ add_bias_kv=True,
361
+ drop_path=imu_drop_path,
362
+ )
363
+
364
+ return nn.ModuleDict(modality_trunks)
365
+
366
+ def _create_modality_heads(
367
+ self,
368
+ out_embed_dim,
369
+ vision_embed_dim,
370
+ text_embed_dim,
371
+ audio_embed_dim,
372
+ depth_embed_dim,
373
+ thermal_embed_dim,
374
+ imu_embed_dim,
375
+ ):
376
+ modality_heads = {}
377
+
378
+ modality_heads[ModalityType.VISION] = nn.Sequential(
379
+ nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
380
+ SelectElement(index=0),
381
+ nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
382
+ )
383
+
384
+ modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
385
+ proj=nn.Sequential(
386
+ nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
387
+ nn.Linear(text_embed_dim, out_embed_dim, bias=False),
388
+ )
389
+ )
390
+
391
+ modality_heads[ModalityType.AUDIO] = nn.Sequential(
392
+ nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
393
+ SelectElement(index=0),
394
+ nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
395
+ )
396
+
397
+ modality_heads[ModalityType.DEPTH] = nn.Sequential(
398
+ nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
399
+ SelectElement(index=0),
400
+ nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
401
+ )
402
+
403
+ modality_heads[ModalityType.THERMAL] = nn.Sequential(
404
+ nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
405
+ SelectElement(index=0),
406
+ nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
407
+ )
408
+
409
+ modality_heads[ModalityType.IMU] = nn.Sequential(
410
+ nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
411
+ SelectElement(index=0),
412
+ nn.Dropout(p=0.5),
413
+ nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
414
+ )
415
+
416
+ return nn.ModuleDict(modality_heads)
417
+
418
+ def _create_modality_postprocessors(self, out_embed_dim):
419
+ modality_postprocessors = {}
420
+
421
+ modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
422
+ modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
423
+ Normalize(dim=-1), LearnableLogitScaling(learnable=True)
424
+ )
425
+ modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
426
+ Normalize(dim=-1),
427
+ LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
428
+ )
429
+ modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
430
+ Normalize(dim=-1),
431
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
432
+ )
433
+ modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
434
+ Normalize(dim=-1),
435
+ LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
436
+ )
437
+ modality_postprocessors[ModalityType.IMU] = nn.Sequential(
438
+ Normalize(dim=-1),
439
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
440
+ )
441
+
442
+ return nn.ModuleDict(modality_postprocessors)
443
+
444
+ def forward(self, inputs):
445
+ outputs = {}
446
+ for modality_key, modality_value in inputs.items():
447
+ reduce_list = (
448
+ modality_value.ndim >= 5
449
+ ) # Audio and Video inputs consist of multiple clips
450
+ if reduce_list:
451
+ B, S = modality_value.shape[:2]
452
+ modality_value = modality_value.reshape(
453
+ B * S, *modality_value.shape[2:]
454
+ )
455
+
456
+ if modality_value is not None:
457
+ modality_value = self.modality_preprocessors[modality_key](
458
+ **{modality_key: modality_value}
459
+ )
460
+ trunk_inputs = modality_value["trunk"]
461
+ head_inputs = modality_value["head"]
462
+ modality_value = self.modality_trunks[modality_key](**trunk_inputs)
463
+ modality_value = self.modality_heads[modality_key](
464
+ modality_value, **head_inputs
465
+ )
466
+ modality_value = self.modality_postprocessors[modality_key](
467
+ modality_value
468
+ )
469
+
470
+ if reduce_list:
471
+ modality_value = modality_value.reshape(B, S, -1)
472
+ modality_value = modality_value.mean(dim=1)
473
+
474
+ outputs[modality_key] = modality_value
475
+
476
+ return outputs
477
+
478
+
479
+ def imagebind_huge(pretrained=False):
480
+ model = ImageBindModel(
481
+ vision_embed_dim=1280,
482
+ vision_num_blocks=32,
483
+ vision_num_heads=16,
484
+ text_embed_dim=1024,
485
+ text_num_blocks=24,
486
+ text_num_heads=16,
487
+ out_embed_dim=1024,
488
+ audio_drop_path=0.1,
489
+ imu_drop_path=0.7,
490
+ )
491
+
492
+ if pretrained:
493
+ if not os.path.exists(".checkpoints/imagebind_huge.pth"):
494
+ print(
495
+ "Downloading imagebind weights to .checkpoints/imagebind_huge.pth ..."
496
+ )
497
+ os.makedirs(".checkpoints", exist_ok=True)
498
+ torch.hub.download_url_to_file(
499
+ "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth",
500
+ ".checkpoints/imagebind_huge.pth",
501
+ progress=True,
502
+ )
503
+
504
+ model.load_state_dict(torch.load(".checkpoints/imagebind_huge.pth", weights_only=True))
505
+
506
+ return model
ImageBind/imagebind/models/multimodal_preprocessors.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import gzip
9
+ import html
10
+ import io
11
+ import math
12
+ from functools import lru_cache
13
+ from typing import Callable, List, Optional, Tuple
14
+
15
+ import ftfy
16
+ import numpy as np
17
+ import regex as re
18
+ import torch
19
+ import torch.nn as nn
20
+ from iopath.common.file_io import g_pathmgr
21
+ from timm.layers import trunc_normal_
22
+
23
+ from imagebind.models.helpers import VerboseNNModule, cast_if_src_dtype
24
+
25
+
26
+ def get_sinusoid_encoding_table(n_position, d_hid):
27
+ """Sinusoid position encoding table"""
28
+
29
+ # TODO: make it with torch instead of numpy
30
+ def get_position_angle_vec(position):
31
+ return [
32
+ position / np.power(10000, 2 * (hid_j // 2) / d_hid)
33
+ for hid_j in range(d_hid)
34
+ ]
35
+
36
+ sinusoid_table = np.array(
37
+ [get_position_angle_vec(pos_i) for pos_i in range(n_position)]
38
+ )
39
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
40
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
41
+
42
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
43
+
44
+
45
+ def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
46
+ N = pos_embed.shape[1]
47
+ if N == target_spatial_size:
48
+ return pos_embed
49
+ dim = pos_embed.shape[-1]
50
+ # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
51
+ pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
52
+ pos_embed = nn.functional.interpolate(
53
+ pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
54
+ 0, 3, 1, 2
55
+ ),
56
+ scale_factor=math.sqrt(target_spatial_size / N),
57
+ mode="bicubic",
58
+ )
59
+ if updated:
60
+ pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
61
+ pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
62
+ return pos_embed
63
+
64
+
65
+ def interpolate_pos_encoding(
66
+ npatch_per_img,
67
+ pos_embed,
68
+ patches_layout,
69
+ input_shape=None,
70
+ first_patch_idx=1,
71
+ ):
72
+ assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
73
+ N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
74
+ if npatch_per_img == N:
75
+ return pos_embed
76
+
77
+ assert (
78
+ patches_layout[-1] == patches_layout[-2]
79
+ ), "Interpolation of pos embed not supported for non-square layouts"
80
+
81
+ class_emb = pos_embed[:, :first_patch_idx]
82
+ pos_embed = pos_embed[:, first_patch_idx:]
83
+
84
+ if input_shape is None or patches_layout[0] == 1:
85
+ # simple 2D pos embedding, no temporal component
86
+ pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
87
+ elif patches_layout[0] > 1:
88
+ # pos embed has a temporal component
89
+ assert len(input_shape) == 4, "temporal interpolation not supported"
90
+ # we only support 2D interpolation in this case
91
+ num_frames = patches_layout[0]
92
+ num_spatial_tokens = patches_layout[1] * patches_layout[2]
93
+ pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
94
+ # interpolate embedding for zeroth frame
95
+ pos_embed = interpolate_pos_encoding_2d(
96
+ npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
97
+ )
98
+ else:
99
+ raise ValueError("This type of interpolation isn't implemented")
100
+
101
+ return torch.cat((class_emb, pos_embed), dim=1)
102
+
103
+
104
+ def _get_pos_embedding(
105
+ npatch_per_img,
106
+ pos_embed,
107
+ patches_layout,
108
+ input_shape,
109
+ first_patch_idx=1,
110
+ ):
111
+ pos_embed = interpolate_pos_encoding(
112
+ npatch_per_img,
113
+ pos_embed,
114
+ patches_layout,
115
+ input_shape=input_shape,
116
+ first_patch_idx=first_patch_idx,
117
+ )
118
+ return pos_embed
119
+
120
+
121
+ class PatchEmbedGeneric(nn.Module):
122
+ """
123
+ PatchEmbed from Hydra
124
+ """
125
+
126
+ def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
127
+ super().__init__()
128
+
129
+ if len(proj_stem) > 1:
130
+ self.proj = nn.Sequential(*proj_stem)
131
+ else:
132
+ # Special case to be able to load pre-trained models that were
133
+ # trained with a standard stem
134
+ self.proj = proj_stem[0]
135
+ self.norm_layer = norm_layer
136
+
137
+ def get_patch_layout(self, img_size):
138
+ with torch.no_grad():
139
+ dummy_img = torch.zeros(
140
+ [
141
+ 1,
142
+ ]
143
+ + img_size
144
+ )
145
+ dummy_out = self.proj(dummy_img)
146
+ embed_dim = dummy_out.shape[1]
147
+ patches_layout = tuple(dummy_out.shape[2:])
148
+ num_patches = np.prod(patches_layout)
149
+ return patches_layout, num_patches, embed_dim
150
+
151
+ def forward(self, x):
152
+ x = self.proj(x)
153
+ # B C (T) H W -> B (T)HW C
154
+ x = x.flatten(2).transpose(1, 2)
155
+ if self.norm_layer is not None:
156
+ x = self.norm_layer(x)
157
+ return x
158
+
159
+
160
+ class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
161
+ def __init__(
162
+ self,
163
+ patches_layout: List,
164
+ num_patches: int,
165
+ num_cls_tokens: int,
166
+ embed_dim: int,
167
+ learnable: bool,
168
+ ) -> None:
169
+ super().__init__()
170
+ self.num_cls_tokens = num_cls_tokens
171
+ self.patches_layout = patches_layout
172
+ self.num_patches = num_patches
173
+ self.num_tokens = num_cls_tokens + num_patches
174
+ self.learnable = learnable
175
+ if self.learnable:
176
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
177
+ trunc_normal_(self.pos_embed, std=0.02)
178
+ else:
179
+ self.register_buffer(
180
+ "pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
181
+ )
182
+
183
+ def get_pos_embedding(self, vision_input, all_vision_tokens):
184
+ input_shape = vision_input.shape
185
+ pos_embed = _get_pos_embedding(
186
+ all_vision_tokens.size(1) - self.num_cls_tokens,
187
+ pos_embed=self.pos_embed,
188
+ patches_layout=self.patches_layout,
189
+ input_shape=input_shape,
190
+ first_patch_idx=self.num_cls_tokens,
191
+ )
192
+ return pos_embed
193
+
194
+
195
+ class RGBDTPreprocessor(VerboseNNModule):
196
+ def __init__(
197
+ self,
198
+ rgbt_stem: PatchEmbedGeneric,
199
+ depth_stem: Optional[PatchEmbedGeneric],
200
+ img_size: Tuple = (3, 224, 224),
201
+ num_cls_tokens: int = 1,
202
+ pos_embed_fn: Optional[Callable] = None,
203
+ use_type_embed: bool = False,
204
+ init_param_style: str = "openclip",
205
+ ) -> None:
206
+ super().__init__()
207
+ stem = rgbt_stem if rgbt_stem is not None else depth_stem
208
+ (
209
+ self.patches_layout,
210
+ self.num_patches,
211
+ self.embed_dim,
212
+ ) = stem.get_patch_layout(img_size)
213
+ self.rgbt_stem = rgbt_stem
214
+ self.depth_stem = depth_stem
215
+ self.use_pos_embed = pos_embed_fn is not None
216
+ self.use_type_embed = use_type_embed
217
+ self.num_cls_tokens = num_cls_tokens
218
+
219
+ if self.use_pos_embed:
220
+ self.pos_embedding_helper = pos_embed_fn(
221
+ patches_layout=self.patches_layout,
222
+ num_cls_tokens=num_cls_tokens,
223
+ num_patches=self.num_patches,
224
+ embed_dim=self.embed_dim,
225
+ )
226
+ if self.num_cls_tokens > 0:
227
+ self.cls_token = nn.Parameter(
228
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
229
+ )
230
+ if self.use_type_embed:
231
+ self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
232
+
233
+ self.init_parameters(init_param_style)
234
+
235
+ @torch.no_grad()
236
+ def init_parameters(self, init_param_style):
237
+ if init_param_style == "openclip":
238
+ # OpenCLIP style initialization
239
+ scale = self.embed_dim**-0.5
240
+ if self.use_pos_embed:
241
+ nn.init.normal_(self.pos_embedding_helper.pos_embed)
242
+ self.pos_embedding_helper.pos_embed *= scale
243
+
244
+ if self.num_cls_tokens > 0:
245
+ nn.init.normal_(self.cls_token)
246
+ self.cls_token *= scale
247
+ elif init_param_style == "vit":
248
+ self.cls_token.data.fill_(0)
249
+ else:
250
+ raise ValueError(f"Unknown init {init_param_style}")
251
+
252
+ if self.use_type_embed:
253
+ nn.init.normal_(self.type_embed)
254
+
255
+ def tokenize_input_and_cls_pos(self, input, stem, mask):
256
+ # tokens is of shape B x L x D
257
+ tokens = stem(input)
258
+ assert tokens.ndim == 3
259
+ assert tokens.shape[2] == self.embed_dim
260
+ B = tokens.shape[0]
261
+ if self.num_cls_tokens > 0:
262
+ class_tokens = self.cls_token.expand(
263
+ B, -1, -1
264
+ ) # stole class_tokens impl from Phil Wang, thanks
265
+ tokens = torch.cat((class_tokens, tokens), dim=1)
266
+ if self.use_pos_embed:
267
+ pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
268
+ tokens = tokens + pos_embed
269
+ if self.use_type_embed:
270
+ tokens = tokens + self.type_embed.expand(B, -1, -1)
271
+ return tokens
272
+
273
+ def forward(self, vision=None, depth=None, patch_mask=None):
274
+ if patch_mask is not None:
275
+ raise NotImplementedError()
276
+
277
+ if vision is not None:
278
+ vision_tokens = self.tokenize_input_and_cls_pos(
279
+ vision, self.rgbt_stem, patch_mask
280
+ )
281
+
282
+ if depth is not None:
283
+ depth_tokens = self.tokenize_input_and_cls_pos(
284
+ depth, self.depth_stem, patch_mask
285
+ )
286
+
287
+ # aggregate tokens
288
+ if vision is not None and depth is not None:
289
+ final_tokens = vision_tokens + depth_tokens
290
+ else:
291
+ final_tokens = vision_tokens if vision is not None else depth_tokens
292
+ return_dict = {
293
+ "trunk": {
294
+ "tokens": final_tokens,
295
+ },
296
+ "head": {},
297
+ }
298
+ return return_dict
299
+
300
+
301
+ class AudioPreprocessor(RGBDTPreprocessor):
302
+ def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
303
+ super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
304
+
305
+ def forward(self, audio=None):
306
+ return super().forward(vision=audio)
307
+
308
+
309
+ class ThermalPreprocessor(RGBDTPreprocessor):
310
+ def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
311
+ super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
312
+
313
+ def forward(self, thermal=None):
314
+ return super().forward(vision=thermal)
315
+
316
+
317
+ def build_causal_attention_mask(context_length):
318
+ # lazily create causal attention mask, with full attention between the vision tokens
319
+ # pytorch uses additive attention mask; fill with -inf
320
+ mask = torch.empty(context_length, context_length, requires_grad=False)
321
+ mask.fill_(float("-inf"))
322
+ mask.triu_(1) # zero out the lower diagonal
323
+ return mask
324
+
325
+
326
+ class TextPreprocessor(VerboseNNModule):
327
+ def __init__(
328
+ self,
329
+ vocab_size: int,
330
+ context_length: int,
331
+ embed_dim: int,
332
+ causal_masking: bool,
333
+ supply_seq_len_to_head: bool = True,
334
+ num_cls_tokens: int = 0,
335
+ init_param_style: str = "openclip",
336
+ ) -> None:
337
+ super().__init__()
338
+ self.vocab_size = vocab_size
339
+ self.context_length = context_length
340
+ self.token_embedding = nn.Embedding(vocab_size, embed_dim)
341
+ self.pos_embed = nn.Parameter(
342
+ torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
343
+ )
344
+ self.causal_masking = causal_masking
345
+ if self.causal_masking:
346
+ mask = build_causal_attention_mask(self.context_length)
347
+ # register the mask as a buffer so it can be moved to the right device
348
+ self.register_buffer("mask", mask)
349
+
350
+ self.supply_seq_len_to_head = supply_seq_len_to_head
351
+ self.num_cls_tokens = num_cls_tokens
352
+ self.embed_dim = embed_dim
353
+ if num_cls_tokens > 0:
354
+ assert self.causal_masking is False, "Masking + CLS token isn't implemented"
355
+ self.cls_token = nn.Parameter(
356
+ torch.zeros(1, self.num_cls_tokens, embed_dim)
357
+ )
358
+
359
+ self.init_parameters(init_param_style)
360
+
361
+ @torch.no_grad()
362
+ def init_parameters(self, init_param_style="openclip"):
363
+ # OpenCLIP style initialization
364
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
365
+ nn.init.normal_(self.pos_embed, std=0.01)
366
+
367
+ if init_param_style == "openclip":
368
+ # OpenCLIP style initialization
369
+ scale = self.embed_dim**-0.5
370
+ if self.num_cls_tokens > 0:
371
+ nn.init.normal_(self.cls_token)
372
+ self.cls_token *= scale
373
+ elif init_param_style == "vit":
374
+ self.cls_token.data.fill_(0)
375
+ else:
376
+ raise ValueError(f"Unknown init {init_param_style}")
377
+
378
+ def forward(self, text):
379
+ # text tokens are of shape B x L x D
380
+ text_tokens = self.token_embedding(text)
381
+ # concat CLS tokens if any
382
+ if self.num_cls_tokens > 0:
383
+ B = text_tokens.shape[0]
384
+ class_tokens = self.cls_token.expand(
385
+ B, -1, -1
386
+ ) # stole class_tokens impl from Phil Wang, thanks
387
+ text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
388
+ text_tokens = text_tokens + self.pos_embed
389
+ return_dict = {
390
+ "trunk": {
391
+ "tokens": text_tokens,
392
+ },
393
+ "head": {},
394
+ }
395
+ # Compute sequence length after adding CLS tokens
396
+ if self.supply_seq_len_to_head:
397
+ text_lengths = text.argmax(dim=-1)
398
+ return_dict["head"] = {
399
+ "seq_len": text_lengths,
400
+ }
401
+ if self.causal_masking:
402
+ return_dict["trunk"].update({"attn_mask": self.mask})
403
+ return return_dict
404
+
405
+
406
+ class Im2Video(nn.Module):
407
+ """Convert an image into a trivial video."""
408
+
409
+ def __init__(self, time_dim=2):
410
+ super().__init__()
411
+ self.time_dim = time_dim
412
+
413
+ def forward(self, x):
414
+ if x.ndim == 4:
415
+ # B, C, H, W -> B, C, T, H, W
416
+ return x.unsqueeze(self.time_dim)
417
+ elif x.ndim == 5:
418
+ return x
419
+ else:
420
+ raise ValueError(f"Dimension incorrect {x.shape}")
421
+
422
+
423
+ class PadIm2Video(Im2Video):
424
+ def __init__(self, ntimes, pad_type, time_dim=2):
425
+ super().__init__(time_dim=time_dim)
426
+ assert ntimes > 0
427
+ assert pad_type in ["zero", "repeat"]
428
+ self.ntimes = ntimes
429
+ self.pad_type = pad_type
430
+
431
+ def forward(self, x):
432
+ x = super().forward(x)
433
+ if x.shape[self.time_dim] == 1:
434
+ if self.pad_type == "repeat":
435
+ new_shape = [1] * len(x.shape)
436
+ new_shape[self.time_dim] = self.ntimes
437
+ x = x.repeat(new_shape)
438
+ elif self.pad_type == "zero":
439
+ padarg = [0, 0] * len(x.shape)
440
+ padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
441
+ x = nn.functional.pad(x, padarg)
442
+ return x
443
+
444
+
445
+ # Modified from github.com/openai/CLIP
446
+ @lru_cache()
447
+ def bytes_to_unicode():
448
+ """
449
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
450
+ The reversible bpe codes work on unicode strings.
451
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
452
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
453
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
454
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
455
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
456
+ """
457
+ bs = (
458
+ list(range(ord("!"), ord("~") + 1))
459
+ + list(range(ord("¡"), ord("¬") + 1))
460
+ + list(range(ord("®"), ord("ÿ") + 1))
461
+ )
462
+ cs = bs[:]
463
+ n = 0
464
+ for b in range(2**8):
465
+ if b not in bs:
466
+ bs.append(b)
467
+ cs.append(2**8 + n)
468
+ n += 1
469
+ cs = [chr(n) for n in cs]
470
+ return dict(zip(bs, cs))
471
+
472
+
473
+ def get_pairs(word):
474
+ """Return set of symbol pairs in a word.
475
+ Word is represented as tuple of symbols (symbols being variable-length strings).
476
+ """
477
+ pairs = set()
478
+ prev_char = word[0]
479
+ for char in word[1:]:
480
+ pairs.add((prev_char, char))
481
+ prev_char = char
482
+ return pairs
483
+
484
+
485
+ def basic_clean(text):
486
+ text = ftfy.fix_text(text)
487
+ text = html.unescape(html.unescape(text))
488
+ return text.strip()
489
+
490
+
491
+ def whitespace_clean(text):
492
+ text = re.sub(r"\s+", " ", text)
493
+ text = text.strip()
494
+ return text
495
+
496
+
497
+ class SimpleTokenizer(object):
498
+ def __init__(self, bpe_path: str, context_length=77):
499
+ self.byte_encoder = bytes_to_unicode()
500
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
501
+
502
+ with g_pathmgr.open(bpe_path, "rb") as fh:
503
+ bpe_bytes = io.BytesIO(fh.read())
504
+ merges: List[str] = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
505
+ merges = merges[1 : 49152 - 256 - 2 + 1]
506
+ merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges]
507
+ vocab = list(bytes_to_unicode().values())
508
+ vocab = vocab + [v + "</w>" for v in vocab]
509
+ for merge in merges:
510
+ vocab.append("".join(merge))
511
+ vocab.extend(["<|startoftext|>", "<|endoftext|>"])
512
+ self.encoder = dict(zip(vocab, range(len(vocab))))
513
+ self.decoder = {v: k for k, v in self.encoder.items()}
514
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
515
+ self.cache = {
516
+ "<|startoftext|>": "<|startoftext|>",
517
+ "<|endoftext|>": "<|endoftext|>",
518
+ }
519
+ self.pat = re.compile(
520
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
521
+ re.IGNORECASE,
522
+ )
523
+ self.context_length = context_length
524
+
525
+ def bpe(self, token):
526
+ if token in self.cache:
527
+ return self.cache[token]
528
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
529
+ pairs = get_pairs(word)
530
+
531
+ if not pairs:
532
+ return token + "</w>"
533
+
534
+ while True:
535
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
536
+ if bigram not in self.bpe_ranks:
537
+ break
538
+ first, second = bigram
539
+ new_word = []
540
+ i = 0
541
+ while i < len(word):
542
+ try:
543
+ j = word.index(first, i)
544
+ new_word.extend(word[i:j])
545
+ i = j
546
+ except:
547
+ new_word.extend(word[i:])
548
+ break
549
+
550
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
551
+ new_word.append(first + second)
552
+ i += 2
553
+ else:
554
+ new_word.append(word[i])
555
+ i += 1
556
+ new_word = tuple(new_word)
557
+ word = new_word
558
+ if len(word) == 1:
559
+ break
560
+ else:
561
+ pairs = get_pairs(word)
562
+ word = " ".join(word)
563
+ self.cache[token] = word
564
+ return word
565
+
566
+ def encode(self, text):
567
+ bpe_tokens = []
568
+ text = whitespace_clean(basic_clean(text)).lower()
569
+ for token in re.findall(self.pat, text):
570
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
571
+ bpe_tokens.extend(
572
+ self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
573
+ )
574
+ return bpe_tokens
575
+
576
+ def decode(self, tokens):
577
+ text = "".join([self.decoder[token] for token in tokens])
578
+ text = (
579
+ bytearray([self.byte_decoder[c] for c in text])
580
+ .decode("utf-8", errors="replace")
581
+ .replace("</w>", " ")
582
+ )
583
+ return text
584
+
585
+ def __call__(self, texts, context_length=None):
586
+ if not context_length:
587
+ context_length = self.context_length
588
+
589
+ if isinstance(texts, str):
590
+ texts = [texts]
591
+
592
+ sot_token = self.encoder["<|startoftext|>"]
593
+ eot_token = self.encoder["<|endoftext|>"]
594
+ all_tokens = [[sot_token] + self.encode(text) for text in texts]
595
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
596
+
597
+ for i, tokens in enumerate(all_tokens):
598
+ tokens = tokens[:context_length - 1] + [eot_token]
599
+ result[i, : len(tokens)] = torch.tensor(tokens)
600
+
601
+ if len(result) == 1:
602
+ return result[0]
603
+ return result
604
+
605
+
606
+ class IMUPreprocessor(VerboseNNModule):
607
+ def __init__(
608
+ self,
609
+ kernel_size: int,
610
+ imu_stem: PatchEmbedGeneric,
611
+ embed_dim: int,
612
+ img_size: Tuple = (6, 2000),
613
+ num_cls_tokens: int = 1,
614
+ pos_embed_fn: Optional[Callable] = None,
615
+ init_param_style: str = "openclip",
616
+ ) -> None:
617
+ super().__init__()
618
+ self.imu_stem = imu_stem
619
+ self.embed_dim = embed_dim
620
+ self.use_pos_embed = pos_embed_fn is not None
621
+ self.num_cls_tokens = num_cls_tokens
622
+ self.kernel_size = kernel_size
623
+ self.pos_embed = nn.Parameter(
624
+ torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
625
+ )
626
+
627
+ if self.num_cls_tokens > 0:
628
+ self.cls_token = nn.Parameter(
629
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
630
+ )
631
+
632
+ self.init_parameters(init_param_style)
633
+
634
+ @torch.no_grad()
635
+ def init_parameters(self, init_param_style):
636
+ nn.init.normal_(self.pos_embed, std=0.01)
637
+
638
+ if init_param_style == "openclip":
639
+ # OpenCLIP style initialization
640
+ scale = self.embed_dim**-0.5
641
+
642
+ if self.num_cls_tokens > 0:
643
+ nn.init.normal_(self.cls_token)
644
+ self.cls_token *= scale
645
+ elif init_param_style == "vit":
646
+ self.cls_token.data.fill_(0)
647
+ else:
648
+ raise ValueError(f"Unknown init {init_param_style}")
649
+
650
+ def tokenize_input_and_cls_pos(self, input, stem):
651
+ # tokens is of shape B x L x D
652
+ tokens = stem.norm_layer(stem.proj(input))
653
+ assert tokens.ndim == 3
654
+ assert tokens.shape[2] == self.embed_dim
655
+ B = tokens.shape[0]
656
+ if self.num_cls_tokens > 0:
657
+ class_tokens = self.cls_token.expand(
658
+ B, -1, -1
659
+ ) # stole class_tokens impl from Phil Wang, thanks
660
+ tokens = torch.cat((class_tokens, tokens), dim=1)
661
+ if self.use_pos_embed:
662
+ tokens = tokens + self.pos_embed
663
+ return tokens
664
+
665
+ def forward(self, imu):
666
+ # Patchify
667
+ imu = imu.unfold(
668
+ -1,
669
+ self.kernel_size,
670
+ self.kernel_size,
671
+ ).permute(0, 2, 1, 3)
672
+ imu = imu.reshape(imu.size(0), imu.size(1), -1)
673
+
674
+ imu_tokens = self.tokenize_input_and_cls_pos(
675
+ imu,
676
+ self.imu_stem,
677
+ )
678
+
679
+ return_dict = {
680
+ "trunk": {
681
+ "tokens": imu_tokens,
682
+ },
683
+ "head": {},
684
+ }
685
+ return return_dict
ImageBind/imagebind/models/transformer.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ # Code modified from
9
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
10
+ # https://github.com/facebookresearch/deit/blob/main/models.py
11
+ # and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
12
+
13
+
14
+ from functools import partial
15
+ from typing import Callable, List, Optional
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint as checkpoint
20
+ from timm.layers import DropPath, trunc_normal_
21
+
22
+
23
+ class Attention(nn.Module):
24
+ def __init__(
25
+ self,
26
+ dim,
27
+ num_heads=8,
28
+ qkv_bias=False,
29
+ qk_scale=None,
30
+ attn_drop=0.0,
31
+ proj_drop=0.0,
32
+ ):
33
+ super().__init__()
34
+ self.num_heads = num_heads
35
+ head_dim = dim // num_heads
36
+ # NOTE scale factor was wrong in my original version,
37
+ # can set manually to be compat with prev weights
38
+ self.scale = qk_scale or head_dim**-0.5
39
+
40
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
41
+ self.attn_drop = nn.Dropout(attn_drop)
42
+ self.proj = nn.Linear(dim, dim)
43
+ self.proj_drop = nn.Dropout(proj_drop)
44
+
45
+ def forward(self, x):
46
+ B, N, C = x.shape
47
+ qkv = (
48
+ self.qkv(x)
49
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
50
+ .permute(2, 0, 3, 1, 4)
51
+ )
52
+ q, k, v = (
53
+ qkv[0],
54
+ qkv[1],
55
+ qkv[2],
56
+ ) # make torchscript happy (cannot use tensor as tuple)
57
+
58
+ attn = (q @ k.transpose(-2, -1)) * self.scale
59
+ attn = attn.softmax(dim=-1)
60
+ attn = self.attn_drop(attn)
61
+
62
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
63
+ x = self.proj(x)
64
+ x = self.proj_drop(x)
65
+ return x
66
+
67
+
68
+ class Mlp(nn.Module):
69
+ def __init__(
70
+ self,
71
+ in_features,
72
+ hidden_features=None,
73
+ out_features=None,
74
+ act_layer=nn.GELU,
75
+ drop=0.0,
76
+ ):
77
+ super().__init__()
78
+ out_features = out_features or in_features
79
+ hidden_features = hidden_features or in_features
80
+ self.fc1 = nn.Linear(in_features, hidden_features)
81
+ self.act = act_layer()
82
+ self.fc2 = nn.Linear(hidden_features, out_features)
83
+ self.drop = nn.Dropout(drop)
84
+
85
+ def forward(self, x):
86
+ x = self.fc1(x)
87
+ x = self.act(x)
88
+ x = self.drop(x)
89
+ x = self.fc2(x)
90
+ x = self.drop(x)
91
+ return x
92
+
93
+
94
+ class MultiheadAttention(nn.MultiheadAttention):
95
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
96
+ return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
97
+
98
+
99
+ class ViTAttention(Attention):
100
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
101
+ assert attn_mask is None
102
+ return super().forward(x)
103
+
104
+
105
+ class BlockWithMasking(nn.Module):
106
+ def __init__(
107
+ self,
108
+ dim: int,
109
+ attn_target: Callable,
110
+ mlp_ratio: int = 4,
111
+ act_layer: Callable = nn.GELU,
112
+ norm_layer: Callable = nn.LayerNorm,
113
+ ffn_dropout_rate: float = 0.0,
114
+ drop_path: float = 0.0,
115
+ layer_scale_type: Optional[str] = None,
116
+ layer_scale_init_value: float = 1e-4,
117
+ ):
118
+ super().__init__()
119
+
120
+ assert not isinstance(
121
+ attn_target, nn.Module
122
+ ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
123
+ self.attn = attn_target()
124
+ if drop_path > 0.0:
125
+ self.drop_path = DropPath(drop_path)
126
+ else:
127
+ self.drop_path = nn.Identity()
128
+ self.norm_1 = norm_layer(dim)
129
+ mlp_hidden_dim = int(mlp_ratio * dim)
130
+ self.mlp = Mlp(
131
+ in_features=dim,
132
+ hidden_features=mlp_hidden_dim,
133
+ act_layer=act_layer,
134
+ drop=ffn_dropout_rate,
135
+ )
136
+ self.norm_2 = norm_layer(dim)
137
+ self.layer_scale_type = layer_scale_type
138
+ if self.layer_scale_type is not None:
139
+ assert self.layer_scale_type in [
140
+ "per_channel",
141
+ "scalar",
142
+ ], f"Found Layer scale type {self.layer_scale_type}"
143
+ if self.layer_scale_type == "per_channel":
144
+ # one gamma value per channel
145
+ gamma_shape = [1, 1, dim]
146
+ elif self.layer_scale_type == "scalar":
147
+ # single gamma value for all channels
148
+ gamma_shape = [1, 1, 1]
149
+ # two gammas: for each part of the fwd in the encoder
150
+ self.layer_scale_gamma1 = nn.Parameter(
151
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
152
+ requires_grad=True,
153
+ )
154
+ self.layer_scale_gamma2 = nn.Parameter(
155
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
156
+ requires_grad=True,
157
+ )
158
+
159
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
160
+ if self.layer_scale_type is None:
161
+ x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
162
+ x = x + self.drop_path(self.mlp(self.norm_2(x)))
163
+ else:
164
+ x = (
165
+ x
166
+ + self.drop_path(self.attn(self.norm_1(x), attn_mask))
167
+ * self.layer_scale_gamma1
168
+ )
169
+ x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
170
+ return x
171
+
172
+
173
+ _LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
174
+
175
+
176
+ class SimpleTransformer(nn.Module):
177
+ def __init__(
178
+ self,
179
+ attn_target: Callable,
180
+ embed_dim: int,
181
+ num_blocks: int,
182
+ block: Callable = BlockWithMasking,
183
+ pre_transformer_layer: Optional[Callable] = None,
184
+ post_transformer_layer: Optional[Callable] = None,
185
+ drop_path_rate: float = 0.0,
186
+ drop_path_type: str = "progressive",
187
+ norm_layer: Callable = _LAYER_NORM,
188
+ mlp_ratio: int = 4,
189
+ ffn_dropout_rate: float = 0.0,
190
+ layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar"
191
+ layer_scale_init_value: float = 1e-4, # from cait; float
192
+ weight_init_style: str = "jax", # possible values jax or pytorch
193
+ ):
194
+ """
195
+ Simple Transformer with the following features
196
+ 1. Supports masked attention
197
+ 2. Supports DropPath
198
+ 3. Supports LayerScale
199
+ 4. Supports Dropout in Attention and FFN
200
+ 5. Makes few assumptions about the input except that it is a Tensor
201
+ """
202
+ super().__init__()
203
+ self.pre_transformer_layer = pre_transformer_layer
204
+ if drop_path_type == "progressive":
205
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
206
+ elif drop_path_type == "uniform":
207
+ dpr = [drop_path_rate for i in range(num_blocks)]
208
+ else:
209
+ raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
210
+
211
+ self.blocks = nn.Sequential(
212
+ *[
213
+ block(
214
+ dim=embed_dim,
215
+ attn_target=attn_target,
216
+ mlp_ratio=mlp_ratio,
217
+ ffn_dropout_rate=ffn_dropout_rate,
218
+ drop_path=dpr[i],
219
+ norm_layer=norm_layer,
220
+ layer_scale_type=layer_scale_type,
221
+ layer_scale_init_value=layer_scale_init_value,
222
+ )
223
+ for i in range(num_blocks)
224
+ ]
225
+ )
226
+ self.post_transformer_layer = post_transformer_layer
227
+ self.weight_init_style = weight_init_style
228
+ self.apply(self._init_weights)
229
+
230
+ def _init_weights(self, m):
231
+ if isinstance(m, nn.Linear):
232
+ if self.weight_init_style == "jax":
233
+ # Based on MAE and official Jax ViT implementation
234
+ torch.nn.init.xavier_uniform_(m.weight)
235
+ elif self.weight_init_style == "pytorch":
236
+ # PyTorch ViT uses trunc_normal_
237
+ trunc_normal_(m.weight, std=0.02)
238
+
239
+ if m.bias is not None:
240
+ nn.init.constant_(m.bias, 0)
241
+ elif isinstance(m, (nn.LayerNorm)):
242
+ nn.init.constant_(m.bias, 0)
243
+ nn.init.constant_(m.weight, 1.0)
244
+
245
+ def forward(
246
+ self,
247
+ tokens: torch.Tensor,
248
+ attn_mask: torch.Tensor = None,
249
+ use_checkpoint: bool = False,
250
+ checkpoint_every_n: int = 1,
251
+ checkpoint_blk_ids: Optional[List[int]] = None,
252
+ ):
253
+ """
254
+ Inputs
255
+ - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
256
+ - attn: mask of shape L x L
257
+
258
+ Output
259
+ - x: data of shape N x L x D (or L x N x D depending on the attention implementation)
260
+ """
261
+ if self.pre_transformer_layer:
262
+ tokens = self.pre_transformer_layer(tokens)
263
+ if use_checkpoint and checkpoint_blk_ids is None:
264
+ checkpoint_blk_ids = [
265
+ blk_id
266
+ for blk_id in range(len(self.blocks))
267
+ if blk_id % checkpoint_every_n == 0
268
+ ]
269
+ if checkpoint_blk_ids:
270
+ checkpoint_blk_ids = set(checkpoint_blk_ids)
271
+ for blk_id, blk in enumerate(self.blocks):
272
+ if use_checkpoint and blk_id in checkpoint_blk_ids:
273
+ tokens = checkpoint.checkpoint(
274
+ blk, tokens, attn_mask, use_reentrant=False
275
+ )
276
+ else:
277
+ tokens = blk(tokens, attn_mask=attn_mask)
278
+ if self.post_transformer_layer:
279
+ tokens = self.post_transformer_layer(tokens)
280
+ return tokens
ImageBind/model_card.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card for ImageBind
2
+
3
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.
4
+ Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.
5
+
6
+ # Model Details
7
+
8
+ ## Model Description
9
+
10
+ <!-- Provide a longer summary of what this model is/does. -->
11
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images
12
+
13
+ - **Developed by:** Meta AI
14
+ - **Model type:** Multimodal model
15
+ - **Language(s) (NLP):** en
16
+ - **License:** CC BY-NC-SA 4.0
17
+ - **Resources for more information:**
18
+ - [GitHub Repo](https://github.com/facebookresearch/ImageBind)
19
+
20
+
21
+ # Uses
22
+
23
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
24
+ This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images.
25
+ We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities.
26
+
27
+ ## Out-of-Scope Use
28
+
29
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
30
+ <!-- If the user enters content, print that. If not, but they enter a task in the list, use that. If neither, say "more info needed." -->
31
+
32
+ This model is *NOT* intended to be used in any real world application -- commercial or otherwise.
33
+ It may produce harmful associations with different inputs.
34
+ The model needs to be investigated and likely re-trained on specific data for any such application.
35
+ The model is expected to work better on web-based visual data since it was trained on such data.
36
+ The text encoder is likely to work only on English language text because of the underlying training datasets.
37
+
38
+ # Bias, Risks, and Limitations
39
+
40
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
41
+ Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness).
42
+ Since our model uses such models as initialization, it will exhibit such biases too.
43
+ Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes.
44
+
45
+
46
+
47
+ # Training Details
48
+
49
+ ## Training Data
50
+
51
+ <!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
52
+
53
+ ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.
54
+ In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.
55
+ We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset.
56
+ We provide the exact training data details in the paper.
57
+
58
+
59
+ ## Training Procedure
60
+
61
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
62
+ Please refer to the research paper and github repo for exact details on this.
63
+
64
+ # Evaluation
65
+
66
+ ## Testing Data, Factors & Metrics
67
+
68
+ We evaluate the model on a variety of different classification benchmarks for each modality.
69
+ The evaluation details are presented in the paper.
70
+ The models performance is measured using standard classification metrics such as accuracy and mAP.
71
+
72
+ # Citation
73
+
74
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
75
+
76
+ **BibTeX:**
77
+ ```
78
+ @inproceedings{girdhar2023imagebind,
79
+ title={ImageBind: One Embedding Space To Bind Them All},
80
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
81
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
82
+ booktitle={CVPR},
83
+ year={2023}
84
+ }
85
+ ```
86
+
87
+
88
+ # Model Card Contact
89
+
90
+ Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com
91
+
92
+ # How to Get Started with the Model
93
+
94
+ Our github repo provides a simple example to extract embeddings from images, audio etc.
ImageBind/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # torch>=2.0.0
2
+ # torchvision
3
+ # torchaudio
4
+ pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@6cdc929315aab1b5674b6dcf73b16ec99147735f
5
+ timm
6
+ ftfy
7
+ regex
8
+ einops
9
+ iopath
10
+ numpy>=1.19
11
+ types-regex
ImageBind/setup.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ with open('requirements.txt') as f:
4
+ required = f.read().splitlines()
5
+
6
+ setup(
7
+ name='imagebind',
8
+ version='0.1.0',
9
+ packages=find_packages(),
10
+ package_data={
11
+ 'imagebind': ['bpe/bpe_simple_vocab_16e6.txt.gz'],
12
+ },
13
+ description='A brief description of the package',
14
+ long_description=open('README.md', encoding='utf-8').read(),
15
+ long_description_content_type="text/markdown",
16
+ url='https://github.com/facebookresearch/ImageBind',
17
+ classifiers=[
18
+ 'Programming Language :: Python :: 3',
19
+ 'License :: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
20
+ ],
21
+ install_requires=required,
22
+ dependency_links=['https://download.pytorch.org/whl/cu113'],
23
+ )
README.md CHANGED
@@ -1,11 +1,9 @@
1
  ---
2
- title: TaskCLIP
3
- emoji: 🔥
4
- colorFrom: blue
5
- colorTo: green
6
  sdk: docker
7
- pinned: false
8
- short_description: TaskCLIP demo version
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
+ title: TaskCLIP Demo
 
 
 
3
  sdk: docker
4
+ app_port: 7860
 
5
  ---
6
 
7
+ # TaskCLIP Demo
8
+
9
+ FastAPI + custom HTML UI for TaskCLIP (YOLO → VLM → TaskCLIP selection).
asic.c ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <math.h>
2
+ #include <stddef.h>
3
+
4
+ // --------- activations ----------
5
+ static inline float relu_f(float x) {
6
+ return (x > 0.0f) ? x : 0.0f;
7
+ }
8
+
9
+ // Numerically-stable sigmoid
10
+ static inline float sigmoid_f(float x) {
11
+ if (x >= 0.0f) {
12
+ float z = expf(-x);
13
+ return 1.0f / (1.0f + z);
14
+ } else {
15
+ float z = expf(x);
16
+ return z / (1.0f + z);
17
+ }
18
+ }
19
+
20
+ // --------- linear layer ----------
21
+ // y[n, out_dim] = sum_i x[n, in_dim] * W[out_dim, in_dim] + b[out_dim]
22
+ static void linear_forward(
23
+ const float *x, // [N, in_dim]
24
+ float *y, // [N, out_dim]
25
+ const float *W, // [out_dim, in_dim] row-major: W[o*in_dim + i]
26
+ const float *b, // [out_dim]
27
+ int N,
28
+ int in_dim,
29
+ int out_dim
30
+ ) {
31
+ for (int n = 0; n < N; ++n) {
32
+ const float *xn = x + (size_t)n * (size_t)in_dim;
33
+ float *yn = y + (size_t)n * (size_t)out_dim;
34
+
35
+ for (int o = 0; o < out_dim; ++o) {
36
+ const float *Wo = W + (size_t)o * (size_t)in_dim;
37
+ float acc = b ? b[o] : 0.0f;
38
+
39
+ // dot(xn, Wo)
40
+ for (int i = 0; i < in_dim; ++i) {
41
+ acc += xn[i] * Wo[i];
42
+ }
43
+ yn[o] = acc;
44
+ }
45
+ }
46
+ }
47
+
48
+ // In-place ReLU on a [N, dim] tensor
49
+ static void relu_inplace(float *x, int N, int dim) {
50
+ size_t total = (size_t)N * (size_t)dim;
51
+ for (size_t idx = 0; idx < total; ++idx) {
52
+ x[idx] = relu_f(x[idx]);
53
+ }
54
+ }
55
+
56
+ // In-place Sigmoid on a [N, dim] tensor
57
+ static void sigmoid_inplace(float *x, int N, int dim) {
58
+ size_t total = (size_t)N * (size_t)dim;
59
+ for (size_t idx = 0; idx < total; ++idx) {
60
+ x[idx] = sigmoid_f(x[idx]);
61
+ }
62
+ }
63
+
64
+ // --------- the requested block ----------
65
+ //
66
+ // input/output buffer "out" starts as [N, D] and ends as [N, 1].
67
+ //
68
+ // You must provide temporary buffers:
69
+ // tmp1: [N, D/2]
70
+ // tmp2: [N, D/8]
71
+ //
72
+ void score_tail_forward(
73
+ float *out, // IN: [N, D], OUT: [N, 1]
74
+ int N,
75
+ int D, // must be divisible by 8
76
+ // Linear2 params: (D -> D/2)
77
+ const float *W2, // [D/2, D]
78
+ const float *b2, // [D/2]
79
+ // Linear3 params: (D/2 -> D/8)
80
+ const float *W3, // [D/8, D/2]
81
+ const float *b3, // [D/8]
82
+ // Linear4 params: (D/8 -> 1)
83
+ const float *W4, // [1, D/8] (or just [D/8])
84
+ const float *b4, // [1] (optional; PyTorch Linear has bias)
85
+ float bias_scalar, // your Parameter(torch.zeros(1))
86
+ // workspaces
87
+ float *tmp1, // [N, D/2]
88
+ float *tmp2 // [N, D/8]
89
+ ) {
90
+ const int D2 = D / 2;
91
+ const int D8 = D / 8;
92
+
93
+ // output = Linear2(output)
94
+ linear_forward(out, tmp1, W2, b2, N, D, D2);
95
+
96
+ // output = ReLU(output)
97
+ relu_inplace(tmp1, N, D2);
98
+
99
+ // output = Linear3(output)
100
+ linear_forward(tmp1, tmp2, W3, b3, N, D2, D8);
101
+
102
+ // output = ReLU(output)
103
+ relu_inplace(tmp2, N, D8);
104
+
105
+ // output = Linear4(output) + bias
106
+ // Linear4 produces [N, 1]
107
+ // Treat W4 as [1, D8] row-major => W4[i] for i in [0..D8-1]
108
+ for (int n = 0; n < N; ++n) {
109
+ const float *xn = tmp2 + (size_t)n * (size_t)D8;
110
+ float acc = 0.0f;
111
+
112
+ // Linear4 bias term (if present)
113
+ if (b4) acc += b4[0];
114
+
115
+ // dot(xn, W4[0, :])
116
+ for (int i = 0; i < D8; ++i) {
117
+ acc += xn[i] * W4[i];
118
+ }
119
+
120
+ // add scalar bias parameter
121
+ acc += bias_scalar;
122
+
123
+ // write back into out as [N,1]
124
+ out[n] = acc;
125
+ }
126
+
127
+ // output = Sigmoid(output)
128
+ sigmoid_inplace(out, N, 1);
129
+ }
coco_task_descriptions.txt ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Shock-absorbing
2
+ Sharp-blade
3
+ Elegant
4
+ Non-reactive
5
+ Plush
6
+ Heightened
7
+ Firm
8
+ Relaxing
9
+ Flexible
10
+ Adjustable-flow
11
+ Flexible-blade
12
+ Comfortable
13
+ Non-slip
14
+ Smooth-edge
15
+ Clear-container
16
+ Arrangement
17
+ Easy-to-use
18
+ Balanced
19
+ Corkscrew
20
+ Even-pounding
21
+ Non-stick
22
+ Stable
23
+ Tooth-grip
24
+ Fire-safe
25
+ Aesthetic
26
+ Sharp-edge
27
+ Cozy
28
+ Water-holding
29
+ Firm-grip
30
+ Leverage-point
31
+ Heavy-duty
32
+ Safety-lock
33
+ Vase
34
+ Wear-resistant
35
+ Pour-spout
36
+ Sophisticated
37
+ Posture-friendly
38
+ Long-stem
39
+ Slotted
40
+ Simple-mechanism
41
+ Comfortable-grip
42
+ Fire-resistant
43
+ Comfortable-handle
44
+ Compact
45
+ Long-handled
46
+ Anti-fatigue
47
+ Sprinkling
48
+ Soil-breaking
49
+ Breathable
50
+ Sugar-dispenser
51
+ Additional-leverage
52
+ Handheld
53
+ Smooth-rim
54
+ Padded
55
+ Traction-enhanced
56
+ Decanter
57
+ Soft
58
+ Sturdy
59
+ Reclining
60
+ Controlled-pour
61
+ Ergonomic-handle
62
+ Pour-control
63
+ Heat-resistant
64
+ Robust
65
+ Soft-butter
66
+ Transparent
67
+ Lightweight
68
+ Fireproof
69
+ Sturdy-handle
70
+ Clear
71
+ Controlled-flow
72
+ Sharp
73
+ Spacious
74
+ Weather-resistant
75
+ Centerpiece
76
+ Convenient
77
+ Reliable
78
+ Metal-construction
79
+ Adjustable
80
+ Cushioned
81
+ Slip-resistant
82
+ Versatile
83
+ Stylish
84
+ Ergonomic
85
+ Crystal
86
+ Curved-tip
87
+ Wine-glass
88
+ Watering-can
89
+ Lumbar-support
90
+ Insulated
91
+ Nozzle
92
+ Effective
93
+ Long-reach
94
+ Sturdy-base
95
+ Even-distribution
96
+ Handy
97
+ Even-flow
98
+ Easy-fill
99
+ Fragrant
100
+ Contoured
101
+ Safe
102
+ Resistant
103
+ Secure
104
+ Efficient
105
+ Supportive
106
+ Even-spread
107
+ Fresh
108
+ Precise
109
+ Ergonomic-design
110
+ Easy-grip
111
+ Fire-extinguisher
112
+ Hose
113
+ Durable
114
+ Reinforced
115
+ Spout
116
+ Textured
117
+ Flat-surface
118
+ Decorative
119
+ Lever-mechanism
120
+ Refined
121
+ Foot-friendly
122
+ Aerator
123
+ Secure-lid
124
+ Protective
125
+ Quick-release
126
+ Stable-base
127
+ Pouring
128
+ Effective-spray
129
+ Gentle
demo.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from ImageBind.imagebind import data
4
+ from ImageBind.imagebind.models import imagebind_model
5
+ from ImageBind.imagebind.models.imagebind_model import ModalityType
6
+ from collections import OrderedDict
7
+ import torch
8
+ import argparse
9
+ from utils import crop_image, draw_bboxes, save_image, find_same_class, open_image_follow_symlink
10
+ from ultralytics import YOLO
11
+ from PIL import Image
12
+ import numpy as np
13
+ from models.TaskCLIP import TaskCLIP
14
+
15
+ id2task_name_file = './id2task_name.json'
16
+ task2prompt_file = './task20.json'
17
+
18
+ if __name__ == "__main__":
19
+ parser = argparse.ArgumentParser()
20
+ parser.add_argument('-vlm_model', default='imagebind', help='Set front CLIP model')
21
+ parser.add_argument('-od_model', default='yolox', help='Set object detection model')
22
+ parser.add_argument('-device', default='cuda:0', help='Set running environment')
23
+ parser.add_argument('-task_id', type=int, default=1, help='Set task id')
24
+ parser.add_argument('-image_path', type=str, default='./images/demo_image_1.jpg', help='Set input image path')
25
+ parser.add_argument('-activation', type=str, default='relu')
26
+ parser.add_argument('-ratio_text', type=float, default=0.3)
27
+ parser.add_argument('-ratio_image', type=float, default=0.3)
28
+ parser.add_argument('-ratio_glob', type=float, default=0.3)
29
+ parser.add_argument('-norm_before', action='store_true', default=False)
30
+ parser.add_argument('-norm_after', action='store_true', default=False)
31
+ parser.add_argument('-norm_range',type=str, default='10|30')
32
+ parser.add_argument('-cross_attention',action='store_true', default=False)
33
+ parser.add_argument('-eval_model_path',default='./test_model/decoder_epoch19.pt', help='set path for loading trained TaskCLIP model')
34
+ parser.add_argument('-threshold', type=float, default=0.01, help='Set threshold for positive detection')
35
+ parser.add_argument('-forward', action='store_true', default=True)
36
+ parser.add_argument('-cluster', action='store_true', default=True)
37
+ parser.add_argument('-forward_thre', type=float, default=0.1, help='Set threshold for positive detection during forward optimization')
38
+ args = parser.parse_args()
39
+ device = args.device
40
+ threshold = args.threshold
41
+
42
+ # prepare task name and key words
43
+ with open(id2task_name_file, 'r') as f:
44
+ id2task_name = json.load(f)
45
+ task_id = str(args.task_id)
46
+ task_name = id2task_name[task_id]
47
+
48
+ # prepare input image
49
+ image_path = args.image_path
50
+ image_name = args.image_path.split('/')[-1].split('.')[0]
51
+ image = open_image_follow_symlink(image_path).convert('RGB')
52
+
53
+ # load vision-language model
54
+ vlm_model_name = args.vlm_model
55
+ if vlm_model_name == 'imagebind':
56
+ vlm_model = imagebind_model.imagebind_huge(pretrained=True).to(device)
57
+ vlm_model.eval()
58
+
59
+ # load object detection model
60
+ if args.od_model == 'yolox':
61
+ od_model = YOLO('./.checkpoints/yolo12x.pt')
62
+ elif args.od_model == 'yolol':
63
+ od_model = YOLO('./.checkpoints/tolo12l.pt')
64
+ elif args.od_model == 'yolom':
65
+ od_model = YOLO('./.checkpoints/tolo12m.pt')
66
+ elif args.od_model == 'yolos':
67
+ od_model = YOLO('./.checkpoints/tolo12s.pt')
68
+ elif args.od_model == 'yolon':
69
+ od_model = YOLO('./.checkpoints/tolo12n.pt')
70
+
71
+ # get key words prompt
72
+ with open(task2prompt_file, 'r') as f:
73
+ prompt = json.load(f)
74
+ prompt_use = []
75
+ for x in range(len(prompt[task_name])):
76
+ prompt_use.append('The item is ' + prompt[task_name][x])
77
+
78
+ # get bbox image
79
+ outputs = od_model(image_path)
80
+ img = np.array(image)
81
+ ocvimg = img[:, :, ::-1].copy()
82
+ bbox_list = outputs[0].boxes.xyxy.tolist()
83
+ classes = outputs[0].boxes.cls.tolist()
84
+ names = outputs[0].names
85
+ confidences = outputs[0].boxes.conf.tolist()
86
+ predict_res = []
87
+ json_entry = {}
88
+ json_entry['bbox'] = []
89
+ json_entry['class'] = classes
90
+ json_entry['confidences'] = confidences
91
+ json_entry['bbox'] = bbox_list
92
+
93
+ # crop bbox images
94
+ seg_dic = crop_image(ocvimg, bbox_list)
95
+ seg_list = []
96
+ for id in seg_dic.keys():
97
+ seg_list.append(seg_dic[id])
98
+ if (len(seg_list) == 0):
99
+ print("*"*100)
100
+ print("Didn't detect any object in the image.")
101
+ print("*"*100)
102
+ N_seg = len(seg_list)
103
+
104
+ # NOTE: test without reasoning model
105
+ img_with_bbox = draw_bboxes(ocvimg, bbox_list, (0, 255, 0))
106
+ save_image(img_with_bbox, f'./res/{task_id}/{image_name}_no_reasoning.jpg')
107
+
108
+
109
+ # encode bbox image and prompt keywords
110
+ with torch.no_grad():
111
+ if vlm_model_name == 'imagebind':
112
+ input = {
113
+ ModalityType.TEXT: data.load_and_transform_text(prompt_use, device),
114
+ ModalityType.VISION: data.read_and_transform_vision_data(seg_list, device),
115
+ }
116
+ embeddings = vlm_model(input)
117
+ text_embeddings = embeddings[ModalityType.TEXT]
118
+ bbox_embeddings = embeddings[ModalityType.VISION]
119
+ input = {
120
+ ModalityType.VISION: data.read_and_transform_vision_data([image], device),
121
+ }
122
+ embeddings = vlm_model(input)
123
+ image_embedding = embeddings[ModalityType.VISION].squeeze(dim=0)
124
+
125
+ # prepare TaskCLIP model
126
+ num_layers = 8
127
+ nhead = 4
128
+ model_config = {}
129
+ model_config['num_layers'] = num_layers
130
+ model_config['norm'] = None
131
+ model_config['return_intermediate'] = False
132
+ model_config['d_model'] = image_embedding.shape[-1]
133
+ model_config['nhead'] = nhead
134
+ model_config['dim_feedforward'] = 2048
135
+ model_config['dropout'] = 0.1
136
+ model_config['N_words'] = text_embeddings.shape[0]
137
+ model_config['activation'] = args.activation
138
+ model_config['normalize_before'] = False
139
+ model_config['device'] = device
140
+ model_config['ratio_text'] = args.ratio_text
141
+ model_config['ratio_image'] = args.ratio_image
142
+ model_config['ratio_glob'] = args.ratio_glob
143
+ model_config['norm_before'] = args.norm_before
144
+ model_config['norm_after'] = args.norm_after
145
+ model_config['MIN_VAL'] = float(args.norm_range.split('|')[0])
146
+ model_config['MAX_VAL'] = float(args.norm_range.split('|')[1])
147
+ model_config['cross_attention'] = args.cross_attention
148
+
149
+ task_clip_model = TaskCLIP(model_config, normalize_before=model_config['normalize_before'], device = model_config['device'])
150
+ task_clip_model.load_state_dict(torch.load(args.eval_model_path))
151
+ task_clip_model.to(device)
152
+
153
+ # feed text, bbox, and image embeddings into HDC model
154
+ with torch.no_grad():
155
+ task_clip_model.eval()
156
+ tgt = bbox_embeddings
157
+ memory = text_embeddings
158
+ image_embedding = image_embedding.view(1,-1)
159
+ tgt_new, memory_new, score_res, score_raw = task_clip_model(tgt, memory,image_embedding)
160
+ score = score_res.view(-1)
161
+
162
+ score = score.cpu().squeeze().detach().numpy().tolist()
163
+ # post-processing and optimization
164
+ predict_res = []
165
+ for i in range(len(bbox_list)):
166
+ predict_res.append({})
167
+ predict_res[i]["category_id"] = -1
168
+ predict_res[i]["score"] = -1
169
+ predict_res[i]["class"] = int(json_entry['class'][i])
170
+
171
+ # same class forward optimization
172
+ if isinstance(score, list):
173
+ visited = [0]*len(score)
174
+ for i, x in enumerate(score):
175
+ if visited[i] == 1:
176
+ continue
177
+ if x > threshold:
178
+ visited[i] = 1
179
+ predict_res[i]["category_id"] = 1
180
+ predict_res[i]["score"] = float(x)
181
+ if args.forward:
182
+ find_same_class(predict_res, score, visited, i, json_entry['class'], json_entry['confidences'], args.forward_thre)
183
+ else:
184
+ predict_res[i]["category_id"] = 0
185
+ predict_res[i]["score"] = 1 - float(x)
186
+ else:
187
+ if score > threshold:
188
+ predict_res[0]["category_id"] = 1
189
+ predict_res[0]["score"] = float(score)
190
+ else:
191
+ predict_res[0]["category_id"] = 0
192
+ predict_res[0]["score"] = 1 - float(score)
193
+
194
+ # cluster bbox optimization
195
+ if args.cluster and args.forward and N_seg > 1:
196
+ cluster = {}
197
+ for p in predict_res:
198
+ if int(p["category_id"]) == 1:
199
+ if p["class"] in cluster.keys():
200
+ cluster[p["class"]].append(p["score"])
201
+ else:
202
+ cluster[p["class"]] = [p["score"]]
203
+
204
+ # choose one cluster
205
+ if len(cluster.keys()) > 1:
206
+ cluster_ave = {}
207
+ for c in cluster.keys():
208
+ cluster_ave[c] = np.sum(cluster[c])/len(cluster[c])
209
+ select_class = max(cluster_ave, key=lambda k: cluster_ave[k])
210
+
211
+ # remove lower score class
212
+ for p in predict_res:
213
+ if p["category_id"] == 1 and p["class"] != select_class:
214
+ p["category_id"] = 0
215
+
216
+ score_final = [x["category_id"] for x in predict_res]
217
+ # mask = score > threshold
218
+ mask = np.array(score_final) == 1
219
+ bbox_arr = np.asarray(bbox_list)
220
+ bbox_select = bbox_arr[mask]
221
+ img_with_bbox = draw_bboxes(ocvimg, bbox_select, (255, 0, 0))
222
+ save_image(img_with_bbox, f'./res/{task_id}/{image_name}_reasoning.jpg')
demo.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ python demo.py \
2
+ -norm_before \
3
+ -activation gelu \
4
+ -eval_model_path './test_model/decoder_epoch19.pt' \
5
+ -cross_attention \
6
+ -image_path './images/21/COCO_train2014_000000196611.jpg' \
7
+ -task_id 21
id2task_name.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "0": "step on",
3
+ "1": "sit comfortably",
4
+ "2": "place flowers",
5
+ "3": "get potatoes out of fire",
6
+ "4": "water plant",
7
+ "5": "get lemon out of tea",
8
+ "6": "dig hole",
9
+ "7": "open bottle of beer",
10
+ "8": "open parcel",
11
+ "9": "serve wine",
12
+ "10": "pour sugar",
13
+ "11": "smear butter",
14
+ "12": "extinguish fire",
15
+ "13": "pound carpet",
16
+ "14": "Gain elevated observation point",
17
+ "15": "Cross a small gap or obstacle",
18
+ "16": "Provide temporary seating for an injured person",
19
+ "17": "Send a visual signal (light)",
20
+ "18": "Protect from rain",
21
+ "19": "Carry supplies over distance",
22
+ "20": "Protect fragile items during transport",
23
+ "21": "Illuminate a dark area for inspection"
24
+ }
models/Adapter.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path as osp
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.nn import functional as F
6
+
7
+ class Adapter(nn.Module):
8
+ def __init__(self, c_in, reduction=4):
9
+ super(Adapter, self).__init__()
10
+ self.fc = nn.Sequential(
11
+ nn.Linear(c_in, c_in // reduction, bias=False),
12
+ nn.ReLU(inplace=True),
13
+ nn.Linear(c_in // reduction, c_in, bias=False),
14
+ nn.ReLU(inplace=True)
15
+ )
16
+
17
+ def forward(self, x):
18
+ x = self.fc(x)
19
+ return x
models/CoCoTask_Model.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .Transformer import TransformerDecoderLayer
3
+ from .Transformer import TransformerDecoder
4
+ from .ScoreFunction import ScoreFunction
5
+
6
+ class CoCoTask_Model(torch.nn.Module):
7
+ def __init__(self,
8
+ num_layers=3,
9
+ norm=None,
10
+ return_intermediate=False,
11
+ d_model = 1024,
12
+ nhead = 8,
13
+ dim_feedforward=2048,
14
+ dropout=0.1,
15
+ N_words=10,
16
+ activation="relu",
17
+ normalize_before=False,
18
+ device = "cuda:0") -> None:
19
+ super().__init__()
20
+ self.decoder_norm = torch.nn.LayerNorm(d_model)
21
+ self.decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
22
+ self.decoder = TransformerDecoder(self.decoder_layer, num_layers, self.decoder_norm, return_intermediate=return_intermediate)
23
+ self.ScoreFunction = ScoreFunction(N_words=N_words)
24
+
25
+ self.threshold = 0.35
26
+
27
+ def forward(self, tgt, memory, norm=False):
28
+ tgt_new, memory_new = self.decoder(tgt,memory,None)
29
+ score_raw = torch.mm(tgt_new,memory_new.T)
30
+ #NOTE: TODO check later to see if imagebind need softmax
31
+ if norm:
32
+ score_raw = torch.softmax(score_raw)
33
+ #score_res = self.MLP(score_raw)
34
+ score_res = self.ScoreFunction(score_raw)
35
+ return tgt_new, memory_new, score_res
models/ScoreFunction.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import copy
4
+ import torch.nn.functional as F
5
+ from torch.nn import Parameter
6
+
7
+ class ScoreFunction(torch.nn.Module):
8
+ def __init__(self, N_words=10) -> None:
9
+ super().__init__()
10
+ self.d_model = 256
11
+ self.n_head = 4
12
+ #self.dropout = torch.nn.Dropout(0.1)
13
+ self.norm = torch.nn.LayerNorm(self.d_model)
14
+ self.Attention = torch.nn.MultiheadAttention(self.d_model, self.n_head, dropout=0)
15
+ self.Linear1 = torch.nn.Linear(N_words,256)
16
+ self.Linear2 = torch.nn.Linear(256,128)
17
+ self.Linear3 = torch.nn.Linear(128,32)
18
+ self.Linear4 = torch.nn.Linear(32,1)
19
+ self.Activation1 = torch.nn.ReLU()
20
+ self.Activation2 = torch.nn.Sigmoid()
21
+ self.register_parameter('bias',Parameter(torch.zeros(1)))
22
+
23
+ def forward(self, input):
24
+ #NOTE: input has shape NxN_word
25
+ output = self.Linear1(input)
26
+ output0 = self.Attention(output, output, value=output, attn_mask=None, key_padding_mask=None)[0]
27
+ output = output0*0.2 + output*0.8
28
+ output = self.norm(output)
29
+ output = self.Activation1(output)
30
+ output = self.Linear2(output)
31
+ output = self.Activation1(output)
32
+ output = self.Linear3(output)
33
+ output = self.Activation1(output)
34
+ output = self.Linear4(output) + self.bias
35
+ output = self.Activation2(output)
36
+ return output
models/ScoreFunction_Conv.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import copy
4
+ import torch.nn.functional as F
5
+
6
+ class ScoreFunctionConv(torch.nn.Module):
7
+ def __init__(self) -> None:
8
+ super().__init__()
9
+ self.d_model = 64
10
+ self.n_head = 4
11
+ self.norm = torch.nn.LayerNorm(self.d_model)
12
+ self.Attention = torch.nn.MultiheadAttention(self.d_model, self.n_head, dropout=0)
13
+ self.conv1 = torch.nn.Conv1d(10, self.d_model, 1, stride=1)
14
+ self.Linear1 = torch.nn.Linear(10,64)
15
+ self.Linear2 = torch.nn.Linear(64,32)
16
+ self.Linear3 = torch.nn.Linear(32,16)
17
+ self.Linear4 = torch.nn.Linear(16,1)
18
+ self.Linear5 = torch.nn.Linear(64,1)
19
+ self.Linear6 = torch.nn.Linear(10,1)
20
+ self.Norm = torch.nn.BatchNorm1d(self.d_model)
21
+ self.Activation1 = torch.nn.ReLU()
22
+ self.Activation2 = torch.nn.Sigmoid()
23
+
24
+ def forward(self, input):
25
+ output = self.conv1(input.unsqueeze(dim=2)).squeeze(dim=2)
26
+ if output.shape[0] > 1:
27
+ output = self.Norm(output)
28
+ output = self.Activation1(output)
29
+ output = self.Linear5(output)
30
+ output = self.Activation2(output)
31
+ return output
models/ScoreFunction_HDC.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import copy
4
+ import torch.nn.functional as F
5
+ from torch.nn import Parameter
6
+
7
+ class HDReason(torch.nn.Module):
8
+ def __init__(self, d=10, D=256):
9
+ super().__init__()
10
+ self.d = d
11
+ self.D = D
12
+ self.vertex_d = 64
13
+ self.q_proj = torch.nn.Linear(self.d, self.vertex_d)
14
+ self.k_proj = torch.nn.Linear(self.d, self.vertex_d)
15
+ self.v_proj = torch.nn.Linear(self.d, self.vertex_d)
16
+ self.HDC_encoder = torch.nn.Linear(self.vertex_d, self.D)
17
+ self.HDC_encoder.requires_grad = False
18
+ self.Linear = torch.nn.Linear(d, self.vertex_d)
19
+ self.scale = self.D ** -0.5
20
+ #TODO: May need to chaneg
21
+ self.activation0 = torch.nn.ReLU()
22
+ self.activation1 = torch.nn.ReLU()
23
+
24
+ def forward(self, x):
25
+ #NOTE: build adjacency graph
26
+ q = self.activation1(self.HDC_encoder(self.activation0(self.q_proj(x))))
27
+ k = self.activation1(self.HDC_encoder(self.activation0(self.k_proj(x))))
28
+ q = q * self.scale
29
+ adj = q @ k.transpose(-2, -1)
30
+ adj = adj.softmax(dim=-1)
31
+ #NOTE: vertex hypervector
32
+ v = self.activation1(self.HDC_encoder(self.activation0(self.v_proj(x))))
33
+ #NOTE: GrapHD memorization
34
+ out = adj @ v
35
+ out = out*0.3 + 0.7*self.HDC_encoder(self.activation0(self.Linear(x)))
36
+ return out
37
+
38
+
39
+ class ScoreFunctionHDC(torch.nn.Module):
40
+ def __init__(self, N_words=20, HDV_D=512) -> None:
41
+ super().__init__()
42
+ self.D = HDV_D
43
+ self.N_words = N_words
44
+ self.norm = torch.nn.LayerNorm(self.D)
45
+ self.HDReason = HDReason(d=self.N_words, D=self.D)
46
+ self.Linear2 = torch.nn.Linear(self.D, self.D // 2)
47
+ self.Linear3 = torch.nn.Linear(self.D // 2, self.D // 8)
48
+ self.Linear4 = torch.nn.Linear(self.D // 8, 1)
49
+ self.Activation1 = torch.nn.ReLU()
50
+ self.Activation2 = torch.nn.Sigmoid()
51
+ self.register_parameter('bias',Parameter(torch.zeros(1)))
52
+
53
+ def forward(self, x):
54
+ #NOTE: input has shape NxN_word
55
+ #NOTE: N_bbox x N_word
56
+ output = self.HDReason(x)
57
+ output = self.norm(output)
58
+ output = self.Activation1(output)
59
+ output = self.Linear2(output)
60
+ output = self.Activation1(output)
61
+ output = self.Linear3(output)
62
+ output = self.Activation1(output)
63
+ output = self.Linear4(output) + self.bias
64
+ output = self.Activation2(output)
65
+ return output
models/TaskCLIP.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .Transformer import TransformerDecoderLayer
3
+ from .Transformer import TransformerCrossDecoderLayer
4
+ from .Transformer import TransformerDecoder
5
+ from .ScoreFunction import ScoreFunction
6
+ from .Adapter import Adapter
7
+ from .ScoreFunction_HDC import ScoreFunctionHDC
8
+
9
+ class TaskCLIP(torch.nn.Module):
10
+ def __init__(self,
11
+ model_config,
12
+ normalize_before=False,
13
+ device = "cuda:1") -> None:
14
+ super().__init__()
15
+ self.num_layers = model_config['num_layers']
16
+ self.return_intermediate = model_config['return_intermediate']
17
+ self.d_model = model_config['d_model']
18
+ self.nhead = model_config['nhead']
19
+ self.dim_feedforward = model_config['dim_feedforward']
20
+ self.dropout = model_config['dropout']
21
+ self.N_words = model_config['N_words']
22
+ self.activation = model_config['activation']
23
+ self.ratio_text = model_config['ratio_text']
24
+ self.ratio_image = model_config['ratio_image']
25
+ self.ratio_glob = model_config['ratio_glob']
26
+ self.norm_before = model_config['norm_before']
27
+ self.norm_after = model_config['norm_after']
28
+ self.MAX_Val = model_config['MAX_VAL']
29
+ self.MIN_Val = model_config['MIN_VAL']
30
+ self.normalize_before = normalize_before
31
+ self.device = device
32
+
33
+ self.decoder_norm = torch.nn.LayerNorm(self.d_model)
34
+ if model_config['cross_attention']:
35
+ self.decoder_layer = TransformerCrossDecoderLayer(self.d_model,
36
+ self.nhead,
37
+ self.dim_feedforward,
38
+ self.dropout,
39
+ self.activation,
40
+ self.normalize_before)
41
+ else:
42
+ self.decoder_layer = TransformerDecoderLayer(self.d_model,
43
+ self.nhead,
44
+ self.dim_feedforward,
45
+ self.dropout,
46
+ self.activation,
47
+ self.normalize_before)
48
+
49
+ self.decoder = TransformerDecoder(self.decoder_layer,
50
+ self.num_layers,
51
+ self.decoder_norm,
52
+ return_intermediate=self.return_intermediate)
53
+ self.vision_adapter = Adapter(self.d_model)
54
+ self.text_adapter = Adapter(self.d_model)
55
+ self.glob_adapter = torch.nn.MultiheadAttention(self.d_model,
56
+ self.nhead,
57
+ dropout=self.dropout)
58
+ if model_config['score_function'] != 'HDC':
59
+ self.ScoreFunction = ScoreFunction(N_words=self.N_words)
60
+ else:
61
+ self.ScoreFunction = ScoreFunctionHDC(N_words=self.N_words, HDV_D=int(model_config['HDV_D']))
62
+ self.threshold = 0.1
63
+
64
+ def forward(self, tgt, memory, image_embedding,norm=False):
65
+ if self.norm_before:
66
+ tgt /= tgt.norm(dim=-1, keepdim=True)
67
+ memory /= memory.norm(dim=-1, keepdim=True)
68
+ x = self.vision_adapter(tgt)
69
+ tgt = self.ratio_image * x + (1 - self.ratio_image) * tgt
70
+ x0 = self.vision_adapter(image_embedding)
71
+ image_embedding_temp = self.ratio_image * x0 + (1 - self.ratio_image) * image_embedding
72
+ y = self.text_adapter(memory)[0]
73
+ memory = self.ratio_text*y + (1 - self.ratio_text) * memory
74
+ tgt = self.ratio_glob*self.glob_adapter(tgt, image_embedding_temp, image_embedding_temp)[0] + (1 - self.ratio_glob)*tgt
75
+ tgt_new, memory_new = self.decoder(tgt,memory,None)
76
+ score_raw = torch.mm(tgt_new,memory_new.T)
77
+ if self.norm_after:
78
+ score_raw = self.Norm(score_raw)
79
+ score_res = self.ScoreFunction(score_raw)
80
+ return tgt_new, memory_new, score_res, score_raw
81
+
82
+ def Norm(self, score):
83
+ min_val = score.min()
84
+ max_val = score.max()
85
+ res = self.MIN_Val + ((score - min_val) * (self.MAX_Val - self.MIN_Val)) / (max_val - min_val)
86
+ return res
models/TextTransformer.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #NOTE: Hanning, Transformer Decoder
2
+
3
+ import torch
4
+ import numpy as np
5
+ import copy
6
+ import torch.nn.functional as F
7
+
8
+ def _get_clones(module, N):
9
+ return torch.nn.ModuleList([copy.deepcopy(module) for i in range(N)])
10
+
11
+ def _get_activation_fn(activation):
12
+ if activation == "relu":
13
+ return F.relu
14
+ if activation == "gelu":
15
+ return F.gelu
16
+ if activation == "glu":
17
+ return F.glu
18
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
19
+
20
+ class TransformerDecoder(torch.nn.Module):
21
+ def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
22
+ super().__init__()
23
+ self.layers = _get_clones(decoder_layer, num_layers)
24
+ self.num_layers = num_layers
25
+ self.norm = norm
26
+ self.return_intermediate = return_intermediate
27
+
28
+ def forward(
29
+ self,
30
+ tgt,
31
+ memory,
32
+ text_memory,
33
+ tgt_mask = None,
34
+ memory_mask = None,
35
+ text_memory_key_padding_mask = None,
36
+ tgt_key_padding_mask = None,
37
+ memory_key_padding_mask = None,
38
+ pos = None,
39
+ query_pos = None,
40
+ ):
41
+ output = tgt
42
+
43
+ intermediate = []
44
+
45
+ for layer in self.layers:
46
+ output, memory = layer(
47
+ output,
48
+ memory,
49
+ text_memory=text_memory,
50
+ tgt_mask=tgt_mask,
51
+ memory_mask=memory_mask,
52
+ text_memory_key_padding_mask=text_memory_key_padding_mask,
53
+ tgt_key_padding_mask=tgt_key_padding_mask,
54
+ memory_key_padding_mask=memory_key_padding_mask,
55
+ pos=pos,
56
+ query_pos=query_pos,
57
+ )
58
+
59
+ if self.return_intermediate:
60
+ intermediate.append(self.norm(output))
61
+
62
+ if self.norm is not None:
63
+ output = self.norm(output)
64
+ memory = self.norm(memory)
65
+ if self.return_intermediate:
66
+ intermediate.pop()
67
+ intermediate.append(output)
68
+
69
+ if self.return_intermediate:
70
+ return torch.stack(intermediate)
71
+
72
+ return output, memory
73
+
74
+
75
+ class TransformerDecoderLayer(torch.nn.Module):
76
+ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False):
77
+ super().__init__()
78
+ self.self_attn_text = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
79
+ self.cross_attn_text = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
80
+
81
+ # Implementation of Feedforward model
82
+ self.linear1 = torch.nn.Linear(d_model, dim_feedforward)
83
+ self.dropout = torch.nn.Dropout(dropout)
84
+ self.linear2 = torch.nn.Linear(dim_feedforward, d_model)
85
+
86
+ self.norm1 = torch.nn.LayerNorm(d_model)
87
+ # self.norm2 = nn.LayerNorm(d_model)
88
+ self.norm3 = torch.nn.LayerNorm(d_model)
89
+ self.norm4 = torch.nn.LayerNorm(d_model)
90
+ self.dropout1 = torch.nn.Dropout(dropout)
91
+ # self.dropout2 = nn.Dropout(dropout)
92
+ self.dropout3 = torch.nn.Dropout(dropout)
93
+ self.dropout4 = torch.nn.Dropout(dropout)
94
+
95
+ self.activation = _get_activation_fn(activation)
96
+ self.normalize_before = normalize_before
97
+
98
+ def with_pos_embed(self, tensor, pos):
99
+ return tensor if pos is None else tensor + pos
100
+
101
+ # For now, trying one version where its self attn -> cross attn text -> cross attn image -> FFN
102
+ def forward_post(
103
+ self,
104
+ tgt,
105
+ memory,
106
+ text_memory,
107
+ tgt_mask = None,
108
+ memory_mask = None,
109
+ text_memory_key_padding_mask = None,
110
+ tgt_key_padding_mask = None,
111
+ memory_key_padding_mask = None,
112
+ pos = None,
113
+ query_pos = None,
114
+ ):
115
+
116
+ #NOTE: memory 2 is None, need to figure out
117
+ q_text = self.with_pos_embed(memory,query_pos)
118
+ k_text = self.with_pos_embed(memory,query_pos)
119
+
120
+ memory2 = self.self_attn_text(q_text,k_text,value=memory,attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
121
+ memory = memory + self.dropout1(memory2)
122
+ memory = self.norm1(memory)
123
+
124
+ # Cross attention to image
125
+ memory2 = self.cross_attn_text(
126
+ query=self.with_pos_embed(memory, query_pos),
127
+ key=self.with_pos_embed(tgt, pos),
128
+ value=tgt,
129
+ attn_mask=memory_mask,
130
+ key_padding_mask=memory_key_padding_mask,
131
+ )[0]
132
+
133
+ memory = memory + self.dropout3(memory2)
134
+ memory = self.norm3(memory)
135
+
136
+ # FFN
137
+ memory2 = self.linear2(self.dropout(self.activation(self.linear1(memory))))
138
+ memory = memory + self.dropout4(memory2)
139
+ memory = self.norm4(memory)
140
+ return tgt, memory
141
+
142
+ def forward(
143
+ self,
144
+ tgt,
145
+ memory,
146
+ text_memory,
147
+ tgt_mask = None,
148
+ memory_mask = None,
149
+ text_memory_key_padding_mask = None,
150
+ tgt_key_padding_mask = None,
151
+ memory_key_padding_mask = None,
152
+ pos = None,
153
+ query_pos = None,
154
+ ):
155
+ return self.forward_post(
156
+ tgt,
157
+ memory,
158
+ text_memory,
159
+ tgt_mask,
160
+ memory_mask,
161
+ text_memory_key_padding_mask,
162
+ tgt_key_padding_mask,
163
+ memory_key_padding_mask,
164
+ pos,
165
+ query_pos,
166
+ )
models/Transformer.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #NOTE: Hanning, Transformer Decoder
2
+
3
+ import torch
4
+ import numpy as np
5
+ import copy
6
+ import torch.nn.functional as F
7
+
8
+ def _get_clones(module, N):
9
+ return torch.nn.ModuleList([copy.deepcopy(module) for i in range(N)])
10
+
11
+ def _get_activation_fn(activation):
12
+ if activation == "relu":
13
+ return F.relu
14
+ if activation == "gelu":
15
+ return F.gelu
16
+ if activation == "glu":
17
+ return F.glu
18
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
19
+
20
+ class TransformerDecoder(torch.nn.Module):
21
+ def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
22
+ super().__init__()
23
+ self.layers = _get_clones(decoder_layer, num_layers)
24
+ self.num_layers = num_layers
25
+ self.norm = norm
26
+ self.return_intermediate = return_intermediate
27
+
28
+ def forward(
29
+ self,
30
+ tgt,
31
+ memory,
32
+ text_memory,
33
+ tgt_mask = None,
34
+ memory_mask = None,
35
+ text_memory_key_padding_mask = None,
36
+ tgt_key_padding_mask = None,
37
+ memory_key_padding_mask = None,
38
+ pos = None,
39
+ query_pos = None,
40
+ ):
41
+ output = tgt
42
+
43
+ intermediate = []
44
+
45
+ for layer in self.layers:
46
+ output, memory = layer(
47
+ output,
48
+ memory,
49
+ text_memory=text_memory,
50
+ tgt_mask=tgt_mask,
51
+ memory_mask=memory_mask,
52
+ text_memory_key_padding_mask=text_memory_key_padding_mask,
53
+ tgt_key_padding_mask=tgt_key_padding_mask,
54
+ memory_key_padding_mask=memory_key_padding_mask,
55
+ pos=pos,
56
+ query_pos=query_pos,
57
+ )
58
+
59
+ if self.return_intermediate:
60
+ intermediate.append(self.norm(output))
61
+
62
+ if self.norm is not None:
63
+ output = self.norm(output)
64
+ memory = self.norm(memory)
65
+ if self.return_intermediate:
66
+ intermediate.pop()
67
+ intermediate.append(output)
68
+
69
+ if self.return_intermediate:
70
+ return torch.stack(intermediate)
71
+
72
+ return output, memory
73
+
74
+
75
+ class TransformerDecoderLayer(torch.nn.Module):
76
+ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False):
77
+ super().__init__()
78
+ self.self_attn_text = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
79
+ self.self_attn_image = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
80
+ self.cross_attn_image = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
81
+
82
+ # Implementation of Feedforward model
83
+ self.linear1 = torch.nn.Linear(d_model, dim_feedforward)
84
+ self.dropout = torch.nn.Dropout(dropout)
85
+ self.linear2 = torch.nn.Linear(dim_feedforward, d_model)
86
+
87
+ self.norm1 = torch.nn.LayerNorm(d_model)
88
+ # self.norm2 = nn.LayerNorm(d_model)
89
+ self.norm3 = torch.nn.LayerNorm(d_model)
90
+ self.norm4 = torch.nn.LayerNorm(d_model)
91
+ self.dropout1 = torch.nn.Dropout(dropout)
92
+ # self.dropout2 = nn.Dropout(dropout)
93
+ self.dropout3 = torch.nn.Dropout(dropout)
94
+ self.dropout4 = torch.nn.Dropout(dropout)
95
+
96
+ self.activation = _get_activation_fn(activation)
97
+ self.normalize_before = normalize_before
98
+
99
+ def with_pos_embed(self, tensor, pos):
100
+ return tensor if pos is None else tensor + pos
101
+
102
+ # For now, trying one version where its self attn -> cross attn text -> cross attn image -> FFN
103
+ def forward_post(
104
+ self,
105
+ tgt,
106
+ memory,
107
+ text_memory,
108
+ tgt_mask = None,
109
+ memory_mask = None,
110
+ text_memory_key_padding_mask = None,
111
+ tgt_key_padding_mask = None,
112
+ memory_key_padding_mask = None,
113
+ pos = None,
114
+ query_pos = None,
115
+ ):
116
+
117
+ #NOTE: tgt is vision and memory is text
118
+ q_vision = self.with_pos_embed(tgt, query_pos)
119
+ k_vision = self.with_pos_embed(tgt, query_pos)
120
+ tgt2 = self.self_attn_image(q_vision, k_vision, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
121
+ tgt = tgt + self.dropout1(tgt2)
122
+ tgt = self.norm1(tgt)
123
+
124
+ #NOTE: memory 2 is None, need to figure out
125
+ q_text = self.with_pos_embed(memory,query_pos)
126
+ k_text = self.with_pos_embed(memory,query_pos)
127
+
128
+ memory2 = self.self_attn_text(q_text,k_text,value=memory,attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
129
+ memory = memory + self.dropout1(memory2)
130
+ memory = self.norm1(memory)
131
+
132
+ # Cross attention to image
133
+ tgt2 = self.cross_attn_image(
134
+ query=self.with_pos_embed(tgt, query_pos),
135
+ key=self.with_pos_embed(memory, pos),
136
+ value=memory,
137
+ attn_mask=memory_mask,
138
+ key_padding_mask=memory_key_padding_mask,
139
+ )[0]
140
+
141
+ tgt = tgt + self.dropout3(tgt2)
142
+ tgt = self.norm3(tgt)
143
+
144
+ # FFN
145
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
146
+ tgt = tgt + self.dropout4(tgt2)
147
+ tgt = self.norm4(tgt)
148
+ return tgt, memory
149
+
150
+ def forward(
151
+ self,
152
+ tgt,
153
+ memory,
154
+ text_memory,
155
+ tgt_mask = None,
156
+ memory_mask = None,
157
+ text_memory_key_padding_mask = None,
158
+ tgt_key_padding_mask = None,
159
+ memory_key_padding_mask = None,
160
+ pos = None,
161
+ query_pos = None,
162
+ ):
163
+ return self.forward_post(
164
+ tgt,
165
+ memory,
166
+ text_memory,
167
+ tgt_mask,
168
+ memory_mask,
169
+ text_memory_key_padding_mask,
170
+ tgt_key_padding_mask,
171
+ memory_key_padding_mask,
172
+ pos,
173
+ query_pos,
174
+ )
175
+
176
+ class TransformerCrossDecoderLayer(torch.nn.Module):
177
+ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False):
178
+ super().__init__()
179
+ self.self_attn_text = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
180
+ self.self_attn_image = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
181
+ self.cross_attn_image = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
182
+ self.cross_attn_text = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
183
+
184
+ # Implementation of Feedforward model
185
+ self.linear1 = torch.nn.Linear(d_model, dim_feedforward)
186
+ self.linear2 = torch.nn.Linear(dim_feedforward, d_model)
187
+
188
+ self.linear3 = torch.nn.Linear(d_model, dim_feedforward)
189
+ self.linear4 = torch.nn.Linear(dim_feedforward, d_model)
190
+
191
+ self.norm0 = torch.nn.LayerNorm(d_model)
192
+ self.norm1 = torch.nn.LayerNorm(d_model)
193
+ self.norm2 = torch.nn.LayerNorm(d_model)
194
+ self.norm3 = torch.nn.LayerNorm(d_model)
195
+ self.norm4 = torch.nn.LayerNorm(d_model)
196
+ self.norm5 = torch.nn.LayerNorm(d_model)
197
+
198
+ self.dropout0 = torch.nn.Dropout(dropout)
199
+ self.dropout1 = torch.nn.Dropout(dropout)
200
+ self.dropout2 = torch.nn.Dropout(dropout)
201
+ self.dropout3 = torch.nn.Dropout(dropout)
202
+ self.dropout4 = torch.nn.Dropout(dropout)
203
+ self.dropout5 = torch.nn.Dropout(dropout)
204
+
205
+ self.activation = _get_activation_fn(activation)
206
+ self.normalize_before = normalize_before
207
+
208
+ def with_pos_embed(self, tensor, pos):
209
+ return tensor if pos is None else tensor + pos
210
+
211
+ # For now, trying one version where its self attn -> cross attn text -> cross attn image -> FFN
212
+ def forward_post(
213
+ self,
214
+ tgt,
215
+ memory,
216
+ text_memory,
217
+ tgt_mask = None,
218
+ memory_mask = None,
219
+ text_memory_key_padding_mask = None,
220
+ tgt_key_padding_mask = None,
221
+ memory_key_padding_mask = None,
222
+ pos = None,
223
+ query_pos = None,
224
+ ):
225
+
226
+ #NOTE: tgt is vision and memory is text
227
+ q_vision = self.with_pos_embed(tgt, query_pos)
228
+ k_vision = self.with_pos_embed(tgt, query_pos)
229
+ tgt2 = self.self_attn_image(q_vision, k_vision, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
230
+ tgt = tgt + self.dropout0(tgt2)
231
+ tgt = self.norm0(tgt)
232
+
233
+ #NOTE: memory 2 is None, need to figure out
234
+ q_text = self.with_pos_embed(memory,query_pos)
235
+ k_text = self.with_pos_embed(memory,query_pos)
236
+
237
+ memory2 = self.self_attn_text(q_text,k_text,value=memory,attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
238
+ memory = memory + self.dropout1(memory2)
239
+ memory = self.norm1(memory)
240
+
241
+ # Cross attention to image
242
+ tgt2 = self.cross_attn_image(
243
+ query=self.with_pos_embed(tgt, query_pos),
244
+ key=self.with_pos_embed(memory, pos),
245
+ value=memory,
246
+ attn_mask=memory_mask,
247
+ key_padding_mask=memory_key_padding_mask,
248
+ )[0]
249
+
250
+ tgt = tgt + self.dropout2(tgt2)
251
+ tgt = self.norm2(tgt)
252
+
253
+ # Cross attention to text
254
+ memory2 = self.cross_attn_image(
255
+ query=self.with_pos_embed(memory, query_pos),
256
+ key=self.with_pos_embed(tgt, pos),
257
+ value=tgt,
258
+ attn_mask=memory_mask,
259
+ key_padding_mask=memory_key_padding_mask,
260
+ )[0]
261
+
262
+ memory = memory + self.dropout3(memory2)
263
+ memory = self.norm3(memory)
264
+
265
+ # FFN
266
+ tgt2 = self.linear2(self.dropout4(self.activation(self.linear1(tgt))))
267
+ tgt = tgt + self.dropout4(tgt2)
268
+ tgt = self.norm4(tgt)
269
+
270
+ memory2 = self.linear4(self.dropout5(self.activation(self.linear3(memory))))
271
+ memory = memory + self.dropout5(memory2)
272
+ memory = self.norm5(memory)
273
+
274
+ return tgt, memory
275
+
276
+ def forward(
277
+ self,
278
+ tgt,
279
+ memory,
280
+ text_memory,
281
+ tgt_mask = None,
282
+ memory_mask = None,
283
+ text_memory_key_padding_mask = None,
284
+ tgt_key_padding_mask = None,
285
+ memory_key_padding_mask = None,
286
+ pos = None,
287
+ query_pos = None,
288
+ ):
289
+ return self.forward_post(
290
+ tgt,
291
+ memory,
292
+ text_memory,
293
+ tgt_mask,
294
+ memory_mask,
295
+ text_memory_key_padding_mask,
296
+ tgt_key_padding_mask,
297
+ memory_key_padding_mask,
298
+ pos,
299
+ query_pos,
300
+ )
models/ablation_model.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .Transformer import TransformerDecoderLayer
3
+ from .Transformer import TransformerDecoder
4
+ from .ScoreFunction import ScoreFunction
5
+
6
+ class CoCoTask_Model(torch.nn.Module):
7
+ def __init__(self,
8
+ num_layers=3,
9
+ norm=None,
10
+ return_intermediate=False,
11
+ d_model = 1024,
12
+ nhead = 8,
13
+ dim_feedforward=2048,
14
+ dropout=0.1,
15
+ activation="relu",
16
+ normalize_before=False,
17
+ device = "cuda:1") -> None:
18
+ super().__init__()
19
+ self.decoder_norm = torch.nn.LayerNorm(d_model)
20
+ self.decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
21
+ self.decoder = TransformerDecoder(self.decoder_layer, num_layers, self.decoder_norm, return_intermediate=return_intermediate)
22
+ self.MAX_Val = 30
23
+ self.MIN_Val = 10
24
+
25
+ # self.MLP = torch.nn.Sequential(torch.nn.Linear(10,64),
26
+ # torch.nn.ReLU(),
27
+ # torch.nn.Linear(64,1),
28
+ # torch.nn.Sigmoid())
29
+
30
+ self.ScoreFunction = ScoreFunction()
31
+
32
+ self.threshold = 0.2
33
+
34
+ def forward(self, tgt, memory):
35
+ #tgt_new, memory_new = self.decoder(tgt,memory,None)
36
+ tgt_new, memory_new = tgt, memory
37
+ score_raw = torch.mm(tgt_new,memory_new.T)
38
+ score_raw = self.Norm(score_raw)
39
+ score_res = self.ScoreFunction(score_raw)
40
+ return tgt_new, memory_new, score_res, score_raw
41
+
42
+ def Norm(self, score):
43
+ min_val = score.min()
44
+ max_val = score.max()
45
+ res = self.MIN_Val + ((score - min_val) * (self.MAX_Val - self.MIN_Val)) / (max_val - min_val)
46
+ return res
models/models.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import detectron2
3
+ import cv2
4
+ import numpy as np
5
+ import glob
6
+ import os
7
+ import json
8
+ from PIL import Image
9
+ from detectron2 import model_zoo
10
+ from detectron2.engine import DefaultPredictor
11
+ from detectron2.config import get_cfg
12
+ from detectron2.utils.visualizer import Visualizer
13
+
14
+ from ImageBind.imagebind import data
15
+ from ImageBind.imagebind.models import imagebind_model
16
+ from ImageBind.imagebind.models.imagebind_model import ModalityType
17
+
18
+ #from .CoCoTask_Model import CoCoTask_Model
19
+ from .test_model2 import CoCoTask_Model
20
+
21
+ class TriStageModel(torch.nn.Module):
22
+ def __init__(self,model_path) -> None:
23
+ super().__init__()
24
+ self.fast_rcnn_path = "COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x.yaml"
25
+ #self.fast_rcnn_path = "Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x.yaml"
26
+ cfg = get_cfg()
27
+ cfg.merge_from_file(model_zoo.get_config_file(self.fast_rcnn_path))
28
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
29
+ cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(self.fast_rcnn_path)
30
+ self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
31
+ self.num_layers = 4
32
+ self.d_model = 1024
33
+ self.nhead = 4
34
+ self.dim_feedforward=2048
35
+ self.dropout=0.1
36
+ self.activation="relu"
37
+ self.normalize_before=False
38
+ self.return_intermediate = False
39
+
40
+ self.FrontEnd = DefaultPredictor(cfg)
41
+ self.MiddleEnd = imagebind_model.imagebind_huge(pretrained=True)
42
+
43
+
44
+ self.BackEnd = self.Construct_BackEnd(self.num_layers,
45
+ self.d_model,
46
+ self.nhead,
47
+ self.dim_feedforward,
48
+ self.dropout,
49
+ self.activation,
50
+ self.device,
51
+ self.normalize_before,
52
+ self.return_intermediate)
53
+ self.BackEnd.load_state_dict(torch.load('/home/hanningchen/IJCAI24/models/saved_models/decoder_score_task1_epoch14.pt'))
54
+
55
+ def Construct_BackEnd(self,
56
+ num_layers,
57
+ d_model,
58
+ nhead,
59
+ dim_feedforward,
60
+ dropout,
61
+ activation,
62
+ device,
63
+ normalize_before=False,
64
+ return_intermediate=False):
65
+ return CoCoTask_Model(num_layers=num_layers,
66
+ norm=None,
67
+ return_intermediate=return_intermediate,
68
+ d_model = d_model,
69
+ nhead = nhead,
70
+ dim_feedforward=dim_feedforward,
71
+ dropout=dropout,
72
+ activation=activation,
73
+ normalize_before=normalize_before,
74
+ device = device)
75
+
76
+ def crop_image(self,input_image,bbx_list,results,img_id):
77
+ seg_list = []
78
+ for i in range(len(bbx_list)):
79
+ bbx_id = i
80
+ bbx_tensor = bbx_list[i].tensor.squeeze()
81
+ x0 = int(bbx_tensor[0])
82
+ y0 = int(bbx_tensor[1])
83
+ x1 = int(bbx_tensor[2])
84
+ y1 = int(bbx_tensor[3])
85
+
86
+ if x0 >= 0 and x1 <= input_image.shape[1] and y0 >= 0 and y1 <= input_image.shape[0]:
87
+ pil_image = Image.fromarray(cv2.cvtColor(input_image[y0:y1,x0:x1,:], cv2.COLOR_BGR2RGB))
88
+ seg_list.append(pil_image)
89
+
90
+ x = float(bbx_tensor[0])
91
+ y = float(bbx_tensor[1])
92
+ w = float(bbx_tensor[2]) - float(bbx_tensor[0])
93
+ h = float(bbx_tensor[3]) - float(bbx_tensor[1])
94
+ results.append({"image_id":img_id,
95
+ "bbox":[x,y,w,h],
96
+ "score":-1,
97
+ "category_id": -1})
98
+ else:
99
+ print("************************")
100
+ print("The bbx exceed the image")
101
+ print("************************")
102
+ if x0 < 0:
103
+ x0 = 0
104
+ if x1 > input_image.shape[1]:
105
+ x1 = int(input_image.shape[1])
106
+ if y0 < 0:
107
+ y0 = 0
108
+ if y1 > input_image.shape[0]:
109
+ y1 = int(input_image.shape[0])
110
+ pil_image = Image.fromarray(cv2.cvtColor(input_image[y0:y1,x0:x1,:], cv2.COLOR_BGR2RGB))
111
+ seg_list.append(pil_image)
112
+
113
+ x = float(bbx_tensor[0])
114
+ y = float(bbx_tensor[1])
115
+ w = float(bbx_tensor[2]) - float(bbx_tensor[0])
116
+ h = float(bbx_tensor[3]) - float(bbx_tensor[1])
117
+ results.append({"image_id":img_id,
118
+ "bbox":[x,y,w,h],
119
+ "score":-1,
120
+ "category_id": -1})
121
+ return seg_list
122
+
123
+ def forward(self,inputs,img_id,reason_path):
124
+ predict_res = []
125
+ self.MiddleEnd.eval()
126
+ self.MiddleEnd.to(self.device)
127
+ self.BackEnd.eval()
128
+ self.BackEnd.to(self.device)
129
+ img = np.array(inputs)
130
+ ocvimg = img[:, :, ::-1].copy()
131
+ outputs = self.FrontEnd(ocvimg)
132
+ List_bbx = outputs["instances"].pred_boxes
133
+ List_class = outputs["instances"].pred_classes.cpu().tolist()
134
+ List_score = outputs["instances"].scores.cpu().tolist()
135
+ seg_list = self.crop_image(ocvimg,List_bbx,predict_res,img_id)
136
+ if len(seg_list) == 0:
137
+ print("*******************")
138
+ print("Detecron didn't find object in image {}".format(img_id))
139
+ print("*******************")
140
+ return []
141
+ #NOTE: Prepare reason list
142
+ #prompt_file = glob.glob(os.path.join(reason_path,"*.json"))
143
+ prompt_file = reason_path
144
+ reason_list = []
145
+ with open(prompt_file) as f:
146
+ prompt = json.load(f)['visual_features']
147
+
148
+ for x in range(len(prompt)):
149
+ prompt[x] = 'The item is ' + prompt[x]
150
+
151
+ for i in range(10):
152
+ reason_list.append(prompt[i])
153
+ """
154
+ for json_file in prompt_file:
155
+ with open(json_file,'r') as f:
156
+ prompt = json.load(f)
157
+ for object_ent in prompt['reasons']:
158
+ reason_list.append(object_ent['description'])
159
+ """
160
+
161
+ #NOTE: Here data.read_and_transform_vision_data is modified by Hanning
162
+ middle_input = {
163
+ ModalityType.TEXT: data.load_and_transform_text(reason_list, self.device),
164
+ ModalityType.VISION: data.read_and_transform_vision_data(seg_list, self.device),
165
+ }
166
+ with torch.no_grad():
167
+ embeddings = self.MiddleEnd(middle_input)
168
+ tgt = embeddings[ModalityType.VISION]
169
+ memory = embeddings[ModalityType.TEXT]
170
+ _, _, score, _ = self.BackEnd(tgt, memory)
171
+
172
+ score = score.cpu().squeeze().detach().numpy().tolist()
173
+ if isinstance(score,list):
174
+ visited = [0]*len(score)
175
+ for i, x in enumerate(score):
176
+ if visited[i] == 1:
177
+ continue
178
+ if x >= self.BackEnd.threshold:
179
+ visited[i] = 1
180
+ predict_res[i]["category_id"] = 1
181
+ predict_res[i]["score"] = float(x)
182
+ #NOTE: Chek the same class
183
+ # self.find_same_class(predict_res,score,visited,i, List_class,List_score)
184
+ else:
185
+ predict_res[i]["category_id"] = 0
186
+ predict_res[i]["score"] = float(1- x)
187
+ else:
188
+ if score >= self.BackEnd.threshold:
189
+ predict_res[0]["category_id"] = 1
190
+ predict_res[0]["score"] = float(score)
191
+ else:
192
+ predict_res[0]["category_id"] = 0
193
+ predict_res[0]["score"] = float(1- score)
194
+ return predict_res
models/test_model1.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .TextTransformer import TransformerDecoderLayer
3
+ from .TextTransformer import TransformerDecoder
4
+ from .ScoreFunction import ScoreFunction
5
+
6
+ class CoCoTask_Model(torch.nn.Module):
7
+ def __init__(self,
8
+ num_layers=3,
9
+ norm=None,
10
+ return_intermediate=False,
11
+ d_model = 1024,
12
+ nhead = 8,
13
+ dim_feedforward=2048,
14
+ dropout=0.1,
15
+ activation="relu",
16
+ normalize_before=False,
17
+ device = "cuda:1") -> None:
18
+ super().__init__()
19
+ self.decoder_norm = torch.nn.LayerNorm(d_model)
20
+ self.decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
21
+ self.decoder = TransformerDecoder(self.decoder_layer, num_layers, self.decoder_norm, return_intermediate=return_intermediate)
22
+ self.MAX_Val = 30
23
+ self.MIN_Val = 10
24
+
25
+ # self.MLP = torch.nn.Sequential(torch.nn.Linear(10,64),
26
+ # torch.nn.ReLU(),
27
+ # torch.nn.Linear(64,1),
28
+ # torch.nn.Sigmoid())
29
+
30
+ self.ScoreFunction = ScoreFunction()
31
+
32
+ self.threshold = 0.4
33
+
34
+ def forward(self, tgt, memory):
35
+ tgt_new, memory_new = self.decoder(tgt,memory,None)
36
+ score_raw = torch.mm(tgt_new,memory_new.T)
37
+ score_raw = self.Norm(score_raw)
38
+ #score_res = self.MLP(score_raw)
39
+ score_res = self.ScoreFunction(score_raw)
40
+ return tgt_new, memory_new, score_res, score_raw
41
+
42
+ def Norm(self, score):
43
+ min_val = score.min()
44
+ max_val = score.max()
45
+ res = self.MIN_Val + ((score - min_val) * (self.MAX_Val - self.MIN_Val)) / (max_val - min_val)
46
+ return res
models/test_model2.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .Transformer import TransformerDecoderLayer
3
+ from .Transformer import TransformerDecoder
4
+ from .ScoreFunction import ScoreFunction
5
+ from .Adapter import Adapter
6
+
7
+ class TaskCLIP(torch.nn.Module):
8
+ def __init__(self,
9
+ model_config,
10
+ normalize_before=False,
11
+ device = "cuda:1") -> None:
12
+ super().__init__()
13
+ self.num_layers = model_config['num_layers']
14
+ self.return_intermediate = model_config['return_intermediate']
15
+ self.d_model = model_config['d_model']
16
+ self.nhead = model_config['nhead']
17
+ self.dim_feedforward = model_config['dim_feedforward']
18
+ self.dropout = model_config['dropout']
19
+ self.N_words = model_config['N_words']
20
+ self.activation = model_config['activation']
21
+ self.ratio_text = model_config['ratio_text']
22
+ self.ratio_image = model_config['ratio_image']
23
+ self.ratio_glob = model_config['ratio_glob']
24
+ self.norm_before = model_config['norm_before']
25
+ self.norm_after = model_config['norm_after']
26
+ self.MAX_Val = model_config['MAX_VAL']
27
+ self.MIN_Val = model_config['MIN_VAL']
28
+ self.normalize_before = normalize_before
29
+ self.device = device
30
+
31
+ self.decoder_norm = torch.nn.LayerNorm(self.d_model)
32
+ self.decoder_layer = TransformerDecoderLayer(self.d_model,
33
+ self.nhead,
34
+ self.dim_feedforward,
35
+ self.dropout,
36
+ self.activation,
37
+ self.normalize_before)
38
+ self.decoder = TransformerDecoder(self.decoder_layer,
39
+ self.num_layers,
40
+ self.decoder_norm,
41
+ return_intermediate=self.return_intermediate)
42
+ #self.adapter_norm = torch.nn.LayerNorm(self.d_model)
43
+ self.vision_adapter = Adapter(self.d_model)
44
+ self.text_adapter = Adapter(self.d_model)
45
+ self.glob_adapter = torch.nn.MultiheadAttention(self.d_model,
46
+ self.nhead,
47
+ dropout=self.dropout)
48
+ self.ScoreFunction = ScoreFunction(N_words=self.N_words)
49
+ self.threshold = 0.1
50
+
51
+ def forward(self, tgt, memory, image_embedding,norm=False):
52
+ if self.norm_before:
53
+ tgt /= tgt.norm(dim=-1, keepdim=True)
54
+ memory /= memory.norm(dim=-1, keepdim=True)
55
+ x = self.vision_adapter(tgt)
56
+ tgt = self.ratio_image * x + (1 - self.ratio_image) * tgt
57
+ x0 = self.vision_adapter(image_embedding)
58
+ image_embedding_temp = self.ratio_image * x0 + (1 - self.ratio_image) * image_embedding
59
+ y = self.text_adapter(memory)[0]
60
+ memory = self.ratio_text*y + (1 - self.ratio_text) * memory
61
+ tgt = self.ratio_glob*self.glob_adapter(tgt, image_embedding_temp, image_embedding_temp)[0] + (1 - self.ratio_glob)*tgt
62
+ tgt_new, memory_new = self.decoder(tgt,memory,None)
63
+ score_raw = torch.mm(tgt_new,memory_new.T)
64
+ if self.norm_after:
65
+ score_raw = self.Norm(score_raw)
66
+ score_res = self.ScoreFunction(score_raw)
67
+ return tgt_new, memory_new, score_res, score_raw
68
+
69
+ def Norm(self, score):
70
+ min_val = score.min()
71
+ max_val = score.max()
72
+ res = self.MIN_Val + ((score - min_val) * (self.MAX_Val - self.MIN_Val)) / (max_val - min_val)
73
+ return res
requirements.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # requirements.txt
2
+
3
+ # --- PyTorch CUDA 11.8 wheels ---
4
+ --extra-index-url https://download.pytorch.org/whl/cu118
5
+ torch==2.0.0+cu118
6
+ torchvision==0.15.1+cu118
7
+ torchaudio==2.0.1+cu118
8
+
9
+ # --- Web backend ---
10
+ fastapi==0.111.0
11
+ uvicorn==0.30.1
12
+ jinja2==3.1.4
13
+ python-multipart==0.0.9
14
+ pydantic==2.7.4
15
+ starlette==0.37.2
16
+ anyio==4.4.0
17
+
18
+ # --- Core ---
19
+ numpy==1.26.4
20
+ pillow==10.3.0
21
+ opencv-python-headless==4.10.0.84
22
+
23
+ # --- Models / inference ---
24
+ ultralytics==8.4.3
25
+ open-clip-torch==2.24.0
26
+
27
+ # --- Local ImageBind package ---
28
+ -e ./ImageBind
task20.json ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "step on": [
3
+ "Slip-resistant",
4
+ "Stable",
5
+ "Durable",
6
+ "Firm",
7
+ "Secure",
8
+ "Anti-fatigue",
9
+ "Comfortable",
10
+ "Padded",
11
+ "Textured",
12
+ "Shock-absorbing",
13
+ "Weather-resistant",
14
+ "Sturdy",
15
+ "Traction-enhanced",
16
+ "Heavy-duty",
17
+ "Reinforced",
18
+ "Safe",
19
+ "Reliable",
20
+ "Foot-friendly",
21
+ "Wear-resistant",
22
+ "Supportive"
23
+ ],
24
+ "sit comfortably": [
25
+ "Ergonomic",
26
+ "Cushioned",
27
+ "Supportive",
28
+ "Adjustable",
29
+ "Reclining",
30
+ "Padded",
31
+ "Breathable",
32
+ "Contoured",
33
+ "Soft",
34
+ "Relaxing",
35
+ "Lumbar-support",
36
+ "Comfortable",
37
+ "Sturdy",
38
+ "Spacious",
39
+ "Posture-friendly",
40
+ "Flexible",
41
+ "Plush",
42
+ "Durable",
43
+ "Cozy",
44
+ "Firm"
45
+ ],
46
+ "place flowers": [
47
+ "Decorative",
48
+ "Elegant",
49
+ "Stable",
50
+ "Clear",
51
+ "Vase",
52
+ "Arrangement",
53
+ "Stylish",
54
+ "Water-holding",
55
+ "Supportive",
56
+ "Spacious",
57
+ "Fresh",
58
+ "Fragrant",
59
+ "Secure",
60
+ "Versatile",
61
+ "Balanced",
62
+ "Aesthetic",
63
+ "Heightened",
64
+ "Centerpiece",
65
+ "Robust",
66
+ "Transparent"
67
+ ],
68
+ "get potatoes out of fire": [
69
+ "Heat-resistant",
70
+ "Long-handled",
71
+ "Safe",
72
+ "Fireproof",
73
+ "Protective",
74
+ "Insulated",
75
+ "Durable",
76
+ "Easy-grip",
77
+ "Sturdy",
78
+ "Non-stick",
79
+ "Secure",
80
+ "Handy",
81
+ "Reliable",
82
+ "Comfortable",
83
+ "Fire-safe",
84
+ "Resistant",
85
+ "Heavy-duty",
86
+ "Stable",
87
+ "Efficient",
88
+ "Convenient"
89
+ ],
90
+ "water plant": [
91
+ "Gentle",
92
+ "Even-distribution",
93
+ "Watering-can",
94
+ "Spout",
95
+ "Long-reach",
96
+ "Controlled-flow",
97
+ "Lightweight",
98
+ "Easy-fill",
99
+ "Ergonomic-handle",
100
+ "Pouring",
101
+ "Durable",
102
+ "Efficient",
103
+ "Precise",
104
+ "Convenient",
105
+ "Adjustable-flow",
106
+ "Handy",
107
+ "Compact",
108
+ "Reliable",
109
+ "Sprinkling",
110
+ "Flexible"
111
+ ],
112
+ "get lemon out of tea": [
113
+ "Slotted",
114
+ "Non-slip",
115
+ "Heat-resistant",
116
+ "Easy-grip",
117
+ "Durable",
118
+ "Precise",
119
+ "Comfortable",
120
+ "Sturdy",
121
+ "Handy",
122
+ "Reliable",
123
+ "Efficient",
124
+ "Convenient",
125
+ "Stable",
126
+ "Compact",
127
+ "Lightweight",
128
+ "Safe",
129
+ "Long-handled",
130
+ "Effective",
131
+ "Versatile",
132
+ "Non-reactive"
133
+ ],
134
+ "dig hole": [
135
+ "Sharp",
136
+ "Durable",
137
+ "Ergonomic-handle",
138
+ "Long-handled",
139
+ "Heavy-duty",
140
+ "Efficient",
141
+ "Reliable",
142
+ "Compact",
143
+ "Lightweight",
144
+ "Comfortable",
145
+ "Easy-grip",
146
+ "Sturdy",
147
+ "Stable",
148
+ "Secure",
149
+ "Robust",
150
+ "Effective",
151
+ "Safe",
152
+ "Convenient",
153
+ "Weather-resistant",
154
+ "Soil-breaking"
155
+ ],
156
+ "open bottle of beer": [
157
+ "Easy-to-use",
158
+ "Secure",
159
+ "Leverage-point",
160
+ "Comfortable",
161
+ "Metal-construction",
162
+ "Firm-grip",
163
+ "Sharp-edge",
164
+ "Ergonomic",
165
+ "Sturdy",
166
+ "Curved-tip",
167
+ "Lever-mechanism",
168
+ "Compact",
169
+ "Durable",
170
+ "Tooth-grip",
171
+ "Additional-leverage",
172
+ "Flat-surface",
173
+ "Robust",
174
+ "Efficient",
175
+ "Simple-mechanism",
176
+ "Handheld"
177
+ ],
178
+ "open parcel": [
179
+ "Sharp-blade",
180
+ "Safety-lock",
181
+ "Comfortable-handle",
182
+ "Compact",
183
+ "Lightweight",
184
+ "Sturdy",
185
+ "Durable",
186
+ "Easy-grip",
187
+ "Reliable",
188
+ "Efficient",
189
+ "Handy",
190
+ "Precise",
191
+ "Convenient",
192
+ "Safe",
193
+ "Effective",
194
+ "Non-slip",
195
+ "Versatile",
196
+ "Ergonomic-design",
197
+ "Robust",
198
+ "Protective"
199
+ ],
200
+ "serve wine": [
201
+ "Elegant",
202
+ "Clear",
203
+ "Long-stem",
204
+ "Wine-glass",
205
+ "Comfortable-grip",
206
+ "Balanced",
207
+ "Crystal",
208
+ "Smooth-rim",
209
+ "Sturdy-base",
210
+ "Pour-spout",
211
+ "Corkscrew",
212
+ "Aerator",
213
+ "Decanter",
214
+ "Stylish",
215
+ "Sophisticated",
216
+ "Secure",
217
+ "Reliable",
218
+ "Convenient",
219
+ "Pour-control",
220
+ "Refined"
221
+ ],
222
+ "pour sugar": [
223
+ "Spout",
224
+ "Even-flow",
225
+ "Controlled-pour",
226
+ "Sugar-dispenser",
227
+ "Ergonomic-handle",
228
+ "Secure-lid",
229
+ "Clear-container",
230
+ "Stable-base",
231
+ "Compact",
232
+ "Lightweight",
233
+ "Convenient",
234
+ "Precise",
235
+ "Handy",
236
+ "Safe",
237
+ "Efficient",
238
+ "Reliable",
239
+ "Versatile",
240
+ "Non-slip",
241
+ "Balanced",
242
+ "Pour-control"
243
+ ],
244
+ "smear butter": [
245
+ "Smooth-edge",
246
+ "Comfortable-handle",
247
+ "Even-spread",
248
+ "Durable",
249
+ "Lightweight",
250
+ "Compact",
251
+ "Ergonomic-design",
252
+ "Flexible-blade",
253
+ "Efficient",
254
+ "Precise",
255
+ "Handy",
256
+ "Sturdy",
257
+ "Reliable",
258
+ "Convenient",
259
+ "Non-slip",
260
+ "Versatile",
261
+ "Sharp",
262
+ "Safe",
263
+ "Easy-grip",
264
+ "Soft-butter"
265
+ ],
266
+ "extinguish fire": [
267
+ "Fire-extinguisher",
268
+ "Hose",
269
+ "Nozzle",
270
+ "Effective-spray",
271
+ "Durable",
272
+ "Reliable",
273
+ "Safe",
274
+ "Sturdy",
275
+ "Compact",
276
+ "Lightweight",
277
+ "Easy-grip",
278
+ "Fire-resistant",
279
+ "Handy",
280
+ "Efficient",
281
+ "Convenient",
282
+ "Quick-release",
283
+ "Non-slip",
284
+ "Ergonomic-design",
285
+ "Stable",
286
+ "Secure"
287
+ ],
288
+ "pound carpet": [
289
+ "Sturdy-handle",
290
+ "Heavy-duty",
291
+ "Durable",
292
+ "Comfortable-grip",
293
+ "Effective",
294
+ "Reliable",
295
+ "Compact",
296
+ "Lightweight",
297
+ "Robust",
298
+ "Precise",
299
+ "Non-slip",
300
+ "Ergonomic-design",
301
+ "Stable",
302
+ "Convenient",
303
+ "Handy",
304
+ "Versatile",
305
+ "Safe",
306
+ "Firm",
307
+ "Even-pounding",
308
+ "Shock-absorbing"
309
+ ],
310
+ "Gain elevated observation point": [
311
+ "Stable",
312
+ "Sturdy",
313
+ "Balanced",
314
+ "Robust",
315
+ "Durable",
316
+ "Firm",
317
+ "Supportive",
318
+ "Safe",
319
+ "Secure",
320
+ "Reliable",
321
+ "Heavy-duty",
322
+ "Reinforced",
323
+ "Stable-base",
324
+ "Sturdy-base",
325
+ "Flat-surface",
326
+ "Non-slip",
327
+ "Traction-enhanced",
328
+ "Comfortable",
329
+ "Foot-friendly",
330
+ "Anti-fatigue"
331
+ ],
332
+
333
+ "Cross a small gap or obstacle": [
334
+ "Stable",
335
+ "Sturdy",
336
+ "Robust",
337
+ "Durable",
338
+ "Firm",
339
+ "Safe",
340
+ "Secure",
341
+ "Reliable",
342
+ "Balanced",
343
+ "Stable-base",
344
+ "Sturdy-base",
345
+ "Flat-surface",
346
+ "Heavy-duty",
347
+ "Traction-enhanced",
348
+ "Non-slip",
349
+ "Supportive",
350
+ "Additional-leverage",
351
+ "Even-spread",
352
+ "Comfortable",
353
+ "Anti-fatigue"
354
+ ],
355
+
356
+ "Provide temporary seating for an injured person": [
357
+ "Comfortable",
358
+ "Cushioned",
359
+ "Padded",
360
+ "Supportive",
361
+ "Stable",
362
+ "Sturdy",
363
+ "Safe",
364
+ "Secure",
365
+ "Soft",
366
+ "Relaxing",
367
+ "Ergonomic",
368
+ "Posture-friendly",
369
+ "Spacious",
370
+ "Firm",
371
+ "Durable",
372
+ "Cozy",
373
+ "Balanced",
374
+ "Reliable",
375
+ "Plush",
376
+ "Flexible"
377
+ ],
378
+
379
+ "Send a visual signal (light)": [
380
+ "Clear",
381
+ "Balanced",
382
+ "Effective",
383
+ "Efficient",
384
+ "Precise",
385
+ "Reliable",
386
+ "Safe",
387
+ "Secure",
388
+ "Stable",
389
+ "Sturdy",
390
+ "Durable",
391
+ "Convenient",
392
+ "Handy",
393
+ "Compact",
394
+ "Lightweight",
395
+ "Versatile",
396
+ "Controlled-flow",
397
+ "Adjustable-flow",
398
+ "Even-distribution",
399
+ "Pour-control"
400
+ ],
401
+
402
+ "Protect from rain": [
403
+ "Weather-resistant",
404
+ "Durable",
405
+ "Sturdy",
406
+ "Stable",
407
+ "Protective",
408
+ "Safe",
409
+ "Secure",
410
+ "Reliable",
411
+ "Robust",
412
+ "Heavy-duty",
413
+ "Resistant",
414
+ "Balanced",
415
+ "Compact",
416
+ "Lightweight",
417
+ "Convenient",
418
+ "Handy",
419
+ "Versatile",
420
+ "Water-holding",
421
+ "Clear",
422
+ "Comfortable-grip"
423
+ ],
424
+
425
+ "Carry supplies over distance": [
426
+ "Lightweight",
427
+ "Compact",
428
+ "Spacious",
429
+ "Comfortable",
430
+ "Comfortable-grip",
431
+ "Comfortable-handle",
432
+ "Ergonomic-handle",
433
+ "Ergonomic-design",
434
+ "Durable",
435
+ "Reliable",
436
+ "Sturdy",
437
+ "Stable",
438
+ "Heavy-duty",
439
+ "Secure",
440
+ "Safe",
441
+ "Balanced",
442
+ "Handy",
443
+ "Convenient",
444
+ "Versatile",
445
+ "Easy-grip"
446
+ ],
447
+
448
+ "Protect fragile items during transport": [
449
+ "Cushioned",
450
+ "Padded",
451
+ "Shock-absorbing",
452
+ "Durable",
453
+ "Reliable",
454
+ "Protective",
455
+ "Safe",
456
+ "Stable",
457
+ "Sturdy",
458
+ "Compact",
459
+ "Lightweight",
460
+ "Secure",
461
+ "Robust",
462
+ "Heavy-duty",
463
+ "Efficient",
464
+ "Convenient",
465
+ "Handy",
466
+ "Versatile",
467
+ "Non-slip",
468
+ "Stable-base"
469
+ ],
470
+
471
+ "Illuminate a dark area for inspection": [
472
+ "Clear",
473
+ "Precise",
474
+ "Effective",
475
+ "Efficient",
476
+ "Reliable",
477
+ "Safe",
478
+ "Stable",
479
+ "Sturdy",
480
+ "Durable",
481
+ "Convenient",
482
+ "Handy",
483
+ "Compact",
484
+ "Lightweight",
485
+ "Versatile",
486
+ "Adjustable",
487
+ "Adjustable-flow",
488
+ "Controlled-flow",
489
+ "Even-distribution",
490
+ "Ergonomic-design",
491
+ "Comfortable-grip"
492
+ ]
493
+ }
task2item.json ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "step on": [
3
+ { "id": 15, "name": "bench" },
4
+ { "id": 62, "name": "chair" },
5
+ { "id": 63, "name": "couch" },
6
+ { "id": 65, "name": "bed" },
7
+ { "id": 67, "name": "dining table" }
8
+ ],
9
+
10
+ "sit comfortably": [
11
+ { "id": 62, "name": "chair" },
12
+ { "id": 15, "name": "bench" },
13
+ { "id": 63, "name": "couch" },
14
+ { "id": 65, "name": "bed" }
15
+ ],
16
+
17
+ "place flowers": [
18
+ { "id": 86, "name": "vase" },
19
+ { "id": 44, "name": "bottle" },
20
+ { "id": 47, "name": "cup" },
21
+ { "id": 51, "name": "bowl" },
22
+ { "id": 46, "name": "wine glass" }
23
+ ],
24
+
25
+ "get potatoes out of fire": [
26
+ { "id": 48, "name": "fork" },
27
+ { "id": 50, "name": "spoon" },
28
+ { "id": 49, "name": "knife" },
29
+ { "id": 51, "name": "bowl" }
30
+ ],
31
+
32
+ "water plant": [
33
+ { "id": 44, "name": "bottle" },
34
+ { "id": 47, "name": "cup" },
35
+ { "id": 51, "name": "bowl" },
36
+ { "id": 46, "name": "wine glass" }
37
+ ],
38
+
39
+ "get lemon out of tea": [
40
+ { "id": 50, "name": "spoon" },
41
+ { "id": 48, "name": "fork" },
42
+ { "id": 49, "name": "knife" }
43
+ ],
44
+
45
+ "dig hole": [
46
+ { "id": 50, "name": "spoon" },
47
+ { "id": 48, "name": "fork" },
48
+ { "id": 49, "name": "knife" },
49
+ { "id": 39, "name": "baseball bat" }
50
+ ],
51
+
52
+ "open bottle of beer": [
53
+ { "id": 49, "name": "knife" },
54
+ { "id": 48, "name": "fork" },
55
+ { "id": 50, "name": "spoon" }
56
+ ],
57
+
58
+ "open parcel": [
59
+ { "id": 49, "name": "knife" },
60
+ { "id": 87, "name": "scissors" }
61
+ ],
62
+
63
+ "serve wine": [
64
+ { "id": 46, "name": "wine glass" },
65
+ { "id": 47, "name": "cup" },
66
+ { "id": 44, "name": "bottle" },
67
+ { "id": 67, "name": "dining table" }
68
+ ],
69
+
70
+ "pour sugar": [
71
+ { "id": 50, "name": "spoon" },
72
+ { "id": 51, "name": "bowl" },
73
+ { "id": 47, "name": "cup" },
74
+ { "id": 44, "name": "bottle" }
75
+ ],
76
+
77
+ "smear butter": [
78
+ { "id": 49, "name": "knife" },
79
+ { "id": 50, "name": "spoon" }
80
+ ],
81
+
82
+ "extinguish fire": [
83
+ { "id": 44, "name": "bottle" },
84
+ { "id": 51, "name": "bowl" },
85
+ { "id": 47, "name": "cup" },
86
+ { "id": 81, "name": "sink" },
87
+ { "id": 27, "name": "backpack" }
88
+ ],
89
+
90
+ "pound carpet": [
91
+ { "id": 39, "name": "baseball bat" },
92
+ { "id": 43, "name": "tennis racket" }
93
+ ],
94
+
95
+ "Gain elevated observation point": [
96
+ { "id": 15, "name": "bench" },
97
+ { "id": 62, "name": "chair" },
98
+ { "id": 63, "name": "couch" },
99
+ { "id": 65, "name": "bed" },
100
+ { "id": 67, "name": "dining table" },
101
+ { "id": 3, "name": "car" },
102
+ { "id": 6, "name": "bus" },
103
+ { "id": 8, "name": "truck" }
104
+ ],
105
+
106
+ "Cross a small gap or obstacle": [
107
+ { "id": 15, "name": "bench" },
108
+ { "id": 63, "name": "couch" },
109
+ { "id": 65, "name": "bed" },
110
+ { "id": 67, "name": "dining table" },
111
+ { "id": 41, "name": "skateboard" },
112
+ { "id": 42, "name": "surfboard" },
113
+ { "id": 35, "name": "skis" },
114
+ { "id": 36, "name": "snowboard" }
115
+ ],
116
+
117
+ "Provide temporary seating for an injured person": [
118
+ { "id": 62, "name": "chair" },
119
+ { "id": 15, "name": "bench" },
120
+ { "id": 63, "name": "couch" },
121
+ { "id": 65, "name": "bed" }
122
+ ],
123
+
124
+ "Send a visual signal (light)": [
125
+ { "id": 77, "name": "cell phone" },
126
+ { "id": 73, "name": "laptop" },
127
+ { "id": 72, "name": "tv" },
128
+ { "id": 10, "name": "traffic light" },
129
+ { "id": 3, "name": "car" },
130
+ { "id": 6, "name": "bus" },
131
+ { "id": 8, "name": "truck" }
132
+ ],
133
+
134
+ "Protect from rain": [
135
+ { "id": 28, "name": "umbrella" },
136
+ { "id": 27, "name": "backpack" },
137
+ { "id": 31, "name": "handbag" },
138
+ { "id": 33, "name": "suitcase" },
139
+ { "id": 3, "name": "car" },
140
+ { "id": 6, "name": "bus" },
141
+ { "id": 8, "name": "truck" },
142
+ { "id": 7, "name": "train" }
143
+ ],
144
+
145
+ "Carry supplies over distance": [
146
+ { "id": 27, "name": "backpack" },
147
+ { "id": 31, "name": "handbag" },
148
+ { "id": 33, "name": "suitcase" },
149
+ { "id": 2, "name": "bicycle" },
150
+ { "id": 3, "name": "car" },
151
+ { "id": 8, "name": "truck" }
152
+ ],
153
+
154
+ "Protect fragile items during transport": [
155
+ { "id": 27, "name": "backpack" },
156
+ { "id": 31, "name": "handbag" },
157
+ { "id": 33, "name": "suitcase" },
158
+ { "id": 82, "name": "refrigerator" }
159
+ ],
160
+
161
+ "Illuminate a dark area for inspection": [
162
+ { "id": 77, "name": "cell phone" },
163
+ { "id": 73, "name": "laptop" },
164
+ { "id": 72, "name": "tv" },
165
+ { "id": 10, "name": "traffic light" }
166
+ ]
167
+ }
task_create.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
task_name.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tasks": [
3
+ "step on",
4
+ "sit comfortably",
5
+ "place flowers",
6
+ "get potatoes out of fire",
7
+ "water plant",
8
+ "get lemon out of tea",
9
+ "dig hole",
10
+ "open bottle of beer",
11
+ "open parcel",
12
+ "serve wine",
13
+ "pour sugar",
14
+ "smear butter",
15
+ "extinguish fire",
16
+ "pound carpet"
17
+ ]
18
+ }
utils.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ from PIL import Image
4
+ from collections import OrderedDict
5
+ import os
6
+ from pathlib import Path
7
+
8
+ def crop_image(ocvimg, bbox_list):
9
+ H, W = ocvimg.shape[:2]
10
+ res = OrderedDict()
11
+
12
+ for idx, (x0, y0, x1, y1) in enumerate(bbox_list):
13
+ # clamp to image bounds
14
+ x0 = max(0, min(W, int(x0)))
15
+ y0 = max(0, min(H, int(y0)))
16
+ x1 = max(0, min(W, int(x1)))
17
+ y1 = max(0, min(H, int(y1)))
18
+
19
+ # skip invalid/empty crops
20
+ if x1 <= x0 or y1 <= y0:
21
+ # print(f"Invalid bbox after clamp: {(x0,y0,x1,y1)}")
22
+ continue
23
+
24
+ crop_bgr = ocvimg[y0:y1, x0:x1]
25
+ crop_rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB)
26
+ res[idx] = Image.fromarray(crop_rgb)
27
+
28
+ return res
29
+
30
+ def draw_bboxes(ocvimg, bbox_list, color=(0, 255, 0), thickness=4, clamp=True):
31
+ img = ocvimg.copy()
32
+ H, W = img.shape[:2]
33
+
34
+ for bbox in bbox_list:
35
+ x0, y0, x1, y1 = [int(round(v)) for v in bbox]
36
+
37
+ if clamp:
38
+ x0 = max(0, min(W - 1, x0))
39
+ y0 = max(0, min(H - 1, y0))
40
+ x1 = max(0, min(W - 1, x1))
41
+ y1 = max(0, min(H - 1, y1))
42
+
43
+ # skip invalid boxes
44
+ if x1 <= x0 or y1 <= y0:
45
+ continue
46
+
47
+ cv2.rectangle(img, (x0, y0), (x1, y1), color, thickness)
48
+
49
+ return img
50
+
51
+
52
+ def save_image(img, save_path):
53
+ os.makedirs(os.path.dirname(save_path) or ".", exist_ok=True)
54
+ ok = cv2.imwrite(save_path, img)
55
+ if not ok:
56
+ raise IOError(f"cv2.imwrite failed for: {save_path}")
57
+ return save_path
58
+
59
+ def find_same_class(predict_res, score, visited, index, List_class, List_score, threshold):
60
+ target_class = List_class[index]
61
+ for i in range(len(score)):
62
+ if List_class[i] == target_class:
63
+ if score[i] > threshold:
64
+ predict_res[i]["score"] = score[i]
65
+ visited[i] = 1
66
+ predict_res[i]["category_id"] = 1
67
+ else:
68
+ # predict_res[i]["score"] = float(List_score[i])*float(score[i])
69
+ if List_score[index] > 0.8 and List_score[i] > 0.8:
70
+ predict_res[i]["score"] = float(score[i])
71
+ visited[i] = 1
72
+ predict_res[i]["category_id"] = 1
73
+
74
+ def open_image_follow_symlink(path: str):
75
+ p = Path(path)
76
+
77
+ real = p.resolve(strict=True)
78
+
79
+ if not real.is_file():
80
+ raise FileNotFoundError(f"Resolved path is not a file: {real}")
81
+
82
+ return Image.open(real)
web.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ uvicorn webui.app:app --host 0.0.0.0 --port 8000
webui/app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ from fastapi import FastAPI, Request, UploadFile, File, Form
6
+ from fastapi.responses import HTMLResponse, JSONResponse
7
+ from fastapi.staticfiles import StaticFiles
8
+ from fastapi.templating import Jinja2Templates
9
+
10
+ from webui.runner import ModelRunner
11
+
12
+ PROJECT_ROOT = Path(__file__).resolve().parents[1] # project/
13
+ WEBUI_DIR = Path(__file__).resolve().parent
14
+ UPLOAD_DIR = WEBUI_DIR / "uploads"
15
+ RESULT_DIR = WEBUI_DIR / "results"
16
+ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
17
+ RESULT_DIR.mkdir(parents=True, exist_ok=True)
18
+
19
+ app = FastAPI()
20
+ templates = Jinja2Templates(directory=str(WEBUI_DIR / "templates"))
21
+
22
+ app.mount("/static", StaticFiles(directory=str(WEBUI_DIR / "static")), name="static")
23
+ app.mount("/results", StaticFiles(directory=str(RESULT_DIR)), name="results")
24
+
25
+ VLM_CHOICES = [
26
+ {"label": "imagebind", "value": "imagebind", "folder": "imagebind"},
27
+ {"label": "ViT-B", "value": "vit-b", "folder": "ViT-B"},
28
+ {"label": "ViT-L", "value": "vit-l", "folder": "ViT-L"},
29
+ ]
30
+ VLM_VALUE_TO_FOLDER = {x["value"]: x["folder"] for x in VLM_CHOICES}
31
+
32
+ SCORE_FUNCS = ["default", "HDC"]
33
+ HDV_DIMS = [128, 256, 512, 1024]
34
+
35
+ DEFAULT_VLM = "imagebind"
36
+ DEFAULT_HDV = 256
37
+ DEFAULT_TASKCLIP_CKPT = "./test_model/default/decoder.pt"
38
+ DEFAULT_SCORE_FUNC = "default"
39
+
40
+ OD_CHOICES = [
41
+ {"label": "nano", "value": "nano", "ckpt": "./.checkpoints/yolo12n.pt"},
42
+ {"label": "small", "value": "small", "ckpt": "./.checkpoints/yolo12s.pt"},
43
+ {"label": "median", "value": "median", "ckpt": "./.checkpoints/yolo12m.pt"},
44
+ {"label": "large", "value": "large", "ckpt": "./.checkpoints/yolo12l.pt"},
45
+ {"label": "xlarge", "value": "xlarge", "ckpt": "./.checkpoints/yolo12x.pt"},
46
+ ]
47
+ OD_VALUE_TO_CKPT = {x["value"]: x["ckpt"] for x in OD_CHOICES}
48
+ DEFAULT_OD = "xlarge"
49
+
50
+ # Load models ONCE at startup
51
+ runner = ModelRunner(
52
+ project_root=str(PROJECT_ROOT),
53
+ device="cuda:0", # change if needed
54
+ yolo_ckpt="./.checkpoints/yolo12x.pt",
55
+ id2task_name_file="./id2task_name.json",
56
+ task2prompt_file="./task20.json",
57
+ threshold=0.01,
58
+ forward=True,
59
+ cluster=True,
60
+ forward_thre=0.1,
61
+ )
62
+
63
+ @app.get("/", response_class=HTMLResponse)
64
+ def index(request: Request):
65
+ return templates.TemplateResponse(
66
+ "index.html",
67
+ {
68
+ "request": request,
69
+ "vlm_choices": VLM_CHOICES,
70
+ "default_vlm": DEFAULT_VLM,
71
+ "score_funcs": SCORE_FUNCS,
72
+ "default_score_func": DEFAULT_SCORE_FUNC,
73
+ "hdv_dims": HDV_DIMS,
74
+ "default_hdv_dim": DEFAULT_HDV,
75
+ "od_choices": OD_CHOICES,
76
+ "default_od": DEFAULT_OD,
77
+ "task_ids": runner.list_task_ids(),
78
+ },
79
+ )
80
+
81
+
82
+ @app.post("/api/run")
83
+ async def api_run(
84
+ vlm_model: str = Form(DEFAULT_VLM),
85
+ od_model: str = Form(DEFAULT_OD),
86
+ task_id: int = Form(1),
87
+ score_function: str = Form(DEFAULT_SCORE_FUNC),
88
+ hdv_dim: int = Form(DEFAULT_HDV),
89
+ viz_mode: str = Form("bbox"),
90
+ upload: UploadFile = File(...),
91
+ ):
92
+ # compute taskclip checkpoint
93
+ if score_function not in SCORE_FUNCS:
94
+ return JSONResponse({"ok": False, "error": f"Unknown score_function: {score_function}"}, status_code=400)
95
+
96
+ if score_function == "HDC":
97
+ if hdv_dim not in HDV_DIMS:
98
+ return JSONResponse({"ok": False, "error": f"Unsupported hdv_dim: {hdv_dim}"}, status_code=400)
99
+
100
+ vlm_folder = VLM_VALUE_TO_FOLDER.get(vlm_model)
101
+ if not vlm_folder:
102
+ return JSONResponse({"ok": False, "error": f"Unknown vlm_model: {vlm_model}"}, status_code=400)
103
+
104
+ taskclip_ckpt = f"./test_model/{vlm_folder}/8Layer_4Head_HDV_{hdv_dim}/decoder.pt"
105
+ else:
106
+ taskclip_ckpt = DEFAULT_TASKCLIP_CKPT
107
+
108
+ if score_function == "default" and vlm_model != "imagebind":
109
+ return JSONResponse(
110
+ {"ok": False, "error": "score_function=default only supports vlm_model=imagebind. Use HDC for vit-b/vit-l."},
111
+ status_code=400
112
+ )
113
+
114
+ # get yolo checkpoint
115
+ yolo_ckpt = OD_VALUE_TO_CKPT.get(od_model)
116
+ if not yolo_ckpt:
117
+ return JSONResponse({"ok": False, "error": f"Unknown od_model size: {od_model}"}, status_code=400)
118
+
119
+ # Save upload
120
+ suffix = Path(upload.filename).suffix or ".jpg"
121
+ job_id = uuid.uuid4().hex
122
+ upload_path = UPLOAD_DIR / f"{job_id}{suffix}"
123
+ upload_path.write_bytes(await upload.read())
124
+
125
+ # Run inference
126
+ try:
127
+ # print("[API] vlm_model", vlm_model, "score_function", score_function, "hdv_dim", hdv_dim, "taskclip_ckpt", taskclip_ckpt)
128
+ out = runner.run(
129
+ image_path=str(upload_path),
130
+ task_id=int(task_id),
131
+ vlm_model=vlm_model,
132
+ od_model='yolo',
133
+ yolo_ckpt=yolo_ckpt,
134
+ score_function=score_function,
135
+ hdv_dim=hdv_dim,
136
+ taskclip_ckpt=taskclip_ckpt,
137
+ viz_mode=viz_mode,
138
+ )
139
+ except Exception as e:
140
+ return JSONResponse({"ok": False, "error": repr(e)}, status_code=500)
141
+
142
+
143
+ # Save 3 images to results/<job_id>/
144
+ job_dir = RESULT_DIR / job_id
145
+ job_dir.mkdir(parents=True, exist_ok=True)
146
+
147
+ p_in = job_dir / "input.jpg"
148
+ p_yolo = job_dir / "yolo.jpg"
149
+ p_sel = job_dir / "selected.jpg"
150
+
151
+ out["images"]["original"].save(p_in, quality=95)
152
+ out["images"]["yolo"].save(p_yolo, quality=95)
153
+ out["images"]["selected"].save(p_sel, quality=95)
154
+
155
+ return {
156
+ "ok": True,
157
+ "job_id": job_id,
158
+ "task_id": out["task_id"],
159
+ "task_name": out["task_name"],
160
+ "selected_indices": out["selected_indices"],
161
+ "image_urls": {
162
+ "input": f"/results/{job_id}/input.jpg",
163
+ "yolo": f"/results/{job_id}/yolo.jpg",
164
+ "selected": f"/results/{job_id}/selected.jpg",
165
+ },
166
+ }
webui/runner.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Dict, Any, List, Tuple
4
+
5
+ import numpy as np
6
+ import torch
7
+ from PIL import Image, ImageDraw
8
+
9
+ from ultralytics import YOLO, SAM
10
+
11
+ from ImageBind.imagebind import data
12
+ from ImageBind.imagebind.models import imagebind_model
13
+ from ImageBind.imagebind.models.imagebind_model import ModalityType
14
+
15
+ import open_clip
16
+
17
+ from models.TaskCLIP import TaskCLIP
18
+
19
+
20
+ def _draw_boxes_pil(
21
+ img: Image.Image,
22
+ boxes_xyxy: np.ndarray,
23
+ color: Tuple[int, int, int],
24
+ width: int = 3,
25
+ ) -> Image.Image:
26
+ out = img.copy()
27
+ draw = ImageDraw.Draw(out)
28
+ if boxes_xyxy is None or len(boxes_xyxy) == 0:
29
+ return out
30
+ for (x0, y0, x1, y1) in boxes_xyxy.tolist():
31
+ draw.rectangle([x0, y0, x1, y1], outline=color, width=width)
32
+ return out
33
+
34
+
35
+ def _crop_pil(img: Image.Image, bbox_list: List[List[float]]) -> Tuple[List[Image.Image], List[int]]:
36
+ """Return list of cropped PIL images + indices mapping back to bbox_list."""
37
+ W, H = img.size
38
+ crops = []
39
+ idxs = []
40
+ for i, (x0, y0, x1, y1) in enumerate(bbox_list):
41
+ x0 = max(0, min(W, int(x0)))
42
+ y0 = max(0, min(H, int(y0)))
43
+ x1 = max(0, min(W, int(x1)))
44
+ y1 = max(0, min(H, int(y1)))
45
+ if x1 <= x0 or y1 <= y0:
46
+ continue
47
+ crops.append(img.crop((x0, y0, x1, y1)))
48
+ idxs.append(i)
49
+ return crops, idxs
50
+
51
+
52
+ def overlay_masks(
53
+ img: Image.Image,
54
+ masks: np.ndarray,
55
+ alpha: float = 0.40,
56
+ color: Tuple[int, int, int] = (255, 0, 0),
57
+ ) -> Image.Image:
58
+ if masks is None or len(masks) == 0:
59
+ return img
60
+
61
+ base = np.array(img).astype(np.float32)
62
+ union = np.any(masks.astype(bool), axis=0) # (H, W)
63
+ if not np.any(union):
64
+ return img
65
+
66
+ overlay = base.copy()
67
+ overlay[union] = overlay[union] * 0.2 + np.array(color, dtype=np.float32) * 0.8
68
+ out = base * (1 - alpha) + overlay * alpha
69
+ return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
70
+
71
+
72
+ class ModelRunner:
73
+ """
74
+ WebUI runner:
75
+ - YOLO detects bboxes
76
+ - VLM (ImageBind or OpenCLIP) embeds text prompts and crops (+ global image)
77
+ - TaskCLIP scores and selects bboxes
78
+ - optionally visualize bbox or SAM masks
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ project_root: str,
84
+ device: str = "cuda:0",
85
+ yolo_ckpt: str = "./.checkpoints/yolo12x.pt",
86
+ sam_ckpt: str = "./.checkpoints/sam2.1_l.pt",
87
+ id2task_name_file: str = "./id2task_name.json",
88
+ task2prompt_file: str = "./task20.json",
89
+ threshold: float = 0.01,
90
+ forward: bool = True,
91
+ cluster: bool = True,
92
+ forward_thre: float = 0.1,
93
+ ):
94
+ self.root = Path(project_root).resolve()
95
+ self.device = device
96
+ self.threshold = float(threshold)
97
+ self.forward = bool(forward)
98
+ self.cluster = bool(cluster)
99
+ self.forward_thre = float(forward_thre)
100
+
101
+ # files
102
+ self.id2task_name_path = (self.root / id2task_name_file).resolve()
103
+ self.task2prompt_path = (self.root / task2prompt_file).resolve()
104
+ self.yolo_ckpt_path = (self.root / yolo_ckpt).resolve()
105
+
106
+ # load task metadata
107
+ self.id2task_name = json.loads(self.id2task_name_path.read_text())
108
+ self.task2prompt = json.loads(self.task2prompt_path.read_text())
109
+
110
+ # caches
111
+ self._vlm_cache = {}
112
+ self._yolo_cache = {}
113
+ self._taskclip_cache = {}
114
+
115
+ sam_ckpt_path = (self.root / sam_ckpt).resolve() if str(sam_ckpt).startswith(".") else Path(sam_ckpt)
116
+ self.sam = SAM(str(sam_ckpt_path))
117
+
118
+ # lock for single GPU servers
119
+ self._lock = torch.multiprocessing.RLock()
120
+
121
+ def _get_yolo(self, ckpt_path: str):
122
+ ckpt_abs = str((self.root / ckpt_path).resolve()) if ckpt_path.startswith(".") else ckpt_path
123
+ if ckpt_abs not in self._yolo_cache:
124
+ self._yolo_cache[ckpt_abs] = YOLO(ckpt_abs)
125
+ return self._yolo_cache[ckpt_abs]
126
+
127
+ def _get_vlm(self, vlm_model: str):
128
+ if vlm_model in self._vlm_cache:
129
+ return self._vlm_cache[vlm_model]
130
+
131
+ if vlm_model == "imagebind":
132
+ m = imagebind_model.imagebind_huge(pretrained=True).to(self.device).eval()
133
+ pack = {"kind": "imagebind", "model": m}
134
+ elif vlm_model == "vit-b":
135
+ m, _, preprocess = open_clip.create_model_and_transforms(
136
+ "ViT-B-32", pretrained="laion2b_s34b_b79k"
137
+ )
138
+ m = m.to(self.device).eval()
139
+ tokenizer = open_clip.get_tokenizer("ViT-B-32")
140
+ pack = {"kind": "openclip", "model": m, "preprocess": preprocess, "tokenizer": tokenizer}
141
+ elif vlm_model == "vit-l":
142
+ m, _, preprocess = open_clip.create_model_and_transforms(
143
+ "ViT-L-14", pretrained="laion2b_s32b_b82k"
144
+ )
145
+ m = m.to(self.device).eval()
146
+ tokenizer = open_clip.get_tokenizer("ViT-L-14")
147
+ pack = {"kind": "openclip", "model": m, "preprocess": preprocess, "tokenizer": tokenizer}
148
+ else:
149
+ raise ValueError(f"Unknown vlm_model: {vlm_model}")
150
+
151
+ self._vlm_cache[vlm_model] = pack
152
+ return pack
153
+
154
+ def _encode_vlm(self, vlm_model: str, prompt_use, seg_list, full_img_pil):
155
+ pack = self._get_vlm(vlm_model)
156
+
157
+ with torch.inference_mode():
158
+ if pack["kind"] == "imagebind":
159
+ input_pack = {
160
+ ModalityType.TEXT: data.load_and_transform_text(prompt_use, self.device),
161
+ ModalityType.VISION: data.read_and_transform_vision_data(seg_list, self.device),
162
+ }
163
+ emb = pack["model"](input_pack)
164
+ text_embeddings = emb[ModalityType.TEXT]
165
+ bbox_embeddings = emb[ModalityType.VISION]
166
+
167
+ input_pack2 = {ModalityType.VISION: data.read_and_transform_vision_data([full_img_pil], self.device)}
168
+ emb2 = pack["model"](input_pack2)
169
+ image_embedding = emb2[ModalityType.VISION].squeeze(0)
170
+
171
+ return text_embeddings, bbox_embeddings, image_embedding
172
+
173
+ # openclip branch
174
+ m = pack["model"]
175
+ preprocess = pack["preprocess"]
176
+ tokenizer = pack["tokenizer"]
177
+
178
+ # text
179
+ text = tokenizer(prompt_use).to(self.device)
180
+ text_embeddings = m.encode_text(text).float()
181
+ text_embeddings = text_embeddings / text_embeddings.norm(dim=-1, keepdim=True)
182
+
183
+ # bbox crops
184
+ crop_tensors = [preprocess(im) for im in seg_list]
185
+ crop_batch = torch.stack(crop_tensors, dim=0).to(self.device)
186
+ bbox_embeddings = m.encode_image(crop_batch).float()
187
+ bbox_embeddings = bbox_embeddings / bbox_embeddings.norm(dim=-1, keepdim=True)
188
+
189
+ # global image
190
+ img_tensor = preprocess(full_img_pil).unsqueeze(0).to(self.device)
191
+ image_embedding = m.encode_image(img_tensor).float().squeeze(0)
192
+ image_embedding = image_embedding / image_embedding.norm(dim=-1, keepdim=True)
193
+
194
+ return text_embeddings, bbox_embeddings, image_embedding
195
+
196
+ def list_task_ids(self) -> List[int]:
197
+ ids = []
198
+ for k in self.id2task_name.keys():
199
+ try:
200
+ ids.append(int(k))
201
+ except Exception:
202
+ pass
203
+ return sorted(ids)
204
+
205
+ @staticmethod
206
+ def _unwrap_state_dict(obj: Any) -> Dict[str, torch.Tensor]:
207
+ # supports {"state_dict": ...} style checkpoints
208
+ if isinstance(obj, dict) and "state_dict" in obj and isinstance(obj["state_dict"], dict):
209
+ return obj["state_dict"]
210
+ if isinstance(obj, dict):
211
+ return obj
212
+ raise TypeError(f"Unsupported checkpoint format: {type(obj)}")
213
+
214
+ def _infer_ckpt_flags(self, state: Dict[str, torch.Tensor]) -> Tuple[bool, bool, int]:
215
+ # infer (is_hdc, has_cross_attention, ckpt_d_model)
216
+ keys = list(state.keys())
217
+ is_hdc = any(k.startswith("ScoreFunction.HDReason.") for k in keys)
218
+ has_cross = any("cross_attn_text" in k for k in keys)
219
+
220
+ if "decoder_norm.weight" in state:
221
+ ckpt_d_model = int(state["decoder_norm.weight"].shape[0])
222
+ elif "ScoreFunction.norm.weight" in state:
223
+ ckpt_d_model = int(state["ScoreFunction.norm.weight"].shape[0])
224
+ else:
225
+ ckpt_d_model = -1
226
+
227
+ return is_hdc, has_cross, ckpt_d_model
228
+
229
+ def _get_taskclip(
230
+ self,
231
+ ckpt_path: str,
232
+ d_model: int,
233
+ n_words: int,
234
+ score_function: str,
235
+ hdv_dim: int,
236
+ cross_attention: bool,
237
+ ):
238
+ ckpt_abs = str((self.root / ckpt_path).resolve()) if ckpt_path.startswith(".") else ckpt_path
239
+ if not Path(ckpt_abs).exists():
240
+ raise FileNotFoundError(f"TaskCLIP checkpoint not found: {ckpt_abs}")
241
+
242
+ eff_hdv_dim = int(hdv_dim) if score_function == "HDC" else 0
243
+
244
+ # IMPORTANT: cache key must include cross_attention + score_function
245
+ key = (ckpt_abs, int(d_model), int(n_words), str(score_function), int(eff_hdv_dim), bool(cross_attention))
246
+ if key in self._taskclip_cache:
247
+ return self._taskclip_cache[key]
248
+
249
+ state_raw = torch.load(ckpt_abs, map_location="cpu")
250
+ state = self._unwrap_state_dict(state_raw)
251
+
252
+ ckpt_is_hdc, ckpt_has_cross, ckpt_d_model = self._infer_ckpt_flags(state)
253
+
254
+ # Validate score_function against checkpoint
255
+ if score_function == "HDC" and not ckpt_is_hdc:
256
+ raise RuntimeError(f"Checkpoint is NOT HDC but score_function=HDC was selected. ckpt={ckpt_abs}")
257
+ if score_function != "HDC" and ckpt_is_hdc:
258
+ raise RuntimeError(f"Checkpoint IS HDC but score_function=default was selected. ckpt={ckpt_abs}")
259
+
260
+ # Validate cross_attention against checkpoint (your training differs by family)
261
+ if bool(cross_attention) != bool(ckpt_has_cross):
262
+ raise RuntimeError(
263
+ f"cross_attention mismatch: runtime={cross_attention} but checkpoint has_cross_attention={ckpt_has_cross}. ckpt={ckpt_abs}"
264
+ )
265
+
266
+ # Validate d_model against checkpoint
267
+ if ckpt_d_model != -1 and int(d_model) != int(ckpt_d_model):
268
+ raise RuntimeError(
269
+ f"d_model mismatch: VLM produced d_model={int(d_model)} but checkpoint expects d_model={int(ckpt_d_model)}. ckpt={ckpt_abs}"
270
+ )
271
+
272
+ model_config = {
273
+ "num_layers": 8,
274
+ "norm": None,
275
+ "return_intermediate": False,
276
+ "d_model": int(d_model),
277
+ "nhead": 4,
278
+ "dim_feedforward": 2048,
279
+ "dropout": 0.1,
280
+ "N_words": int(n_words),
281
+ "activation": "gelu",
282
+ "normalize_before": False,
283
+ "device": self.device,
284
+ "ratio_text": 0.3,
285
+ "ratio_image": 0.3,
286
+ "ratio_glob": 0.3,
287
+ "norm_before": True,
288
+ "norm_after": False,
289
+ "MIN_VAL": 10.0,
290
+ "MAX_VAL": 30.0,
291
+ "cross_attention": bool(cross_attention),
292
+ "score_function": "HDC" if score_function == "HDC" else "default",
293
+ "HDV_D": int(eff_hdv_dim),
294
+ }
295
+
296
+ m = TaskCLIP(model_config, normalize_before=model_config["normalize_before"], device=model_config["device"])
297
+ m.load_state_dict(state, strict=True)
298
+ m = m.to(self.device).eval()
299
+
300
+ self._taskclip_cache[key] = m
301
+ return m
302
+
303
+ def _find_same_class(self, predict_res, score, visited, i, classes, confs, forward_thre):
304
+ cls_i = classes[i]
305
+ for j in range(len(score)):
306
+ if visited[j] == 1:
307
+ continue
308
+ if classes[j] == cls_i and float(score[j]) > forward_thre:
309
+ visited[j] = 1
310
+ predict_res[j]["category_id"] = 1
311
+ predict_res[j]["score"] = float(score[j])
312
+
313
+ def _sam_masks_from_bboxes(self, image_path: str, bbox_list: List[List[float]], img_h: int, img_w: int) -> np.ndarray:
314
+ if not bbox_list:
315
+ return np.zeros((0, img_h, img_w), dtype=bool)
316
+
317
+ bboxes = [[float(x0), float(y0), float(x1), float(y1)] for x0, y0, x1, y1 in bbox_list]
318
+
319
+ try:
320
+ res = self.sam(image_path, bboxes=bboxes)
321
+ r0 = res[0]
322
+ if r0.masks is None:
323
+ return np.zeros((0, img_h, img_w), dtype=bool)
324
+ masks = r0.masks.data.detach().cpu().numpy().astype(bool)
325
+ return masks
326
+ except Exception:
327
+ masks_list = []
328
+ for bb in bboxes:
329
+ rr = self.sam(image_path, bboxes=bb)[0]
330
+ if rr.masks is None:
331
+ continue
332
+ m = rr.masks.data.detach().cpu().numpy().astype(bool)
333
+ masks_list.append(m[0])
334
+ if len(masks_list) == 0:
335
+ return np.zeros((0, img_h, img_w), dtype=bool)
336
+ return np.stack(masks_list, axis=0)
337
+
338
+ def run(
339
+ self,
340
+ image_path: str,
341
+ task_id: int,
342
+ vlm_model: str = "imagebind",
343
+ od_model: str = "yolo",
344
+ yolo_ckpt: str = "./.checkpoints/yolo12x.pt",
345
+ score_function: str = "default",
346
+ hdv_dim: int = 256,
347
+ taskclip_ckpt: str = "./test_model/default/decoder.pt",
348
+ viz_mode: str = "bbox",
349
+ ) -> Dict[str, Any]:
350
+ if vlm_model not in ["imagebind", "vit-b", "vit-l"]:
351
+ raise ValueError(f"Unknown vlm_model: {vlm_model}")
352
+
353
+ if od_model != "yolo":
354
+ raise ValueError("Currently only od_model='yolo' is supported.")
355
+
356
+ if viz_mode not in ["bbox", "mask"]:
357
+ raise ValueError(f"Unknown viz_mode={viz_mode}")
358
+
359
+ # training truth:
360
+ # - default used cross_attention=True
361
+ # - HDC used cross_attention=False
362
+ cross_attention = (score_function != "HDC")
363
+
364
+ with self._lock:
365
+ img = Image.open(image_path).convert("RGB")
366
+
367
+ task_name = self.id2task_name[str(task_id)]
368
+ prompt_words = self.task2prompt[task_name]
369
+ prompt_use = ["The item is " + w for w in prompt_words]
370
+
371
+ # YOLO detect
372
+ yolo = self._get_yolo(yolo_ckpt)
373
+ outputs = yolo(image_path)
374
+ bbox_list = outputs[0].boxes.xyxy.tolist()
375
+ classes = outputs[0].boxes.cls.tolist()
376
+ confidences = outputs[0].boxes.conf.tolist()
377
+
378
+ H, W = img.size[1], img.size[0]
379
+ all_boxes = np.asarray(bbox_list, dtype=np.float32)
380
+
381
+ # visualize all detections
382
+ if viz_mode == "bbox":
383
+ img_yolo = _draw_boxes_pil(img, all_boxes, color=(0, 255, 0), width=3)
384
+ all_masks = None
385
+ else:
386
+ all_masks = self._sam_masks_from_bboxes(image_path, bbox_list, img_h=H, img_w=W)
387
+ img_yolo = overlay_masks(img, all_masks, alpha=0.35, color=(0, 255, 0))
388
+
389
+ # crop bboxes
390
+ seg_list, seg_idxs = _crop_pil(img, bbox_list)
391
+ if len(seg_list) == 0:
392
+ return {
393
+ "task_id": task_id,
394
+ "task_name": task_name,
395
+ "bbox_list": bbox_list,
396
+ "selected_indices": [],
397
+ "images": {"original": img, "yolo": img_yolo, "selected": img.copy()},
398
+ }
399
+
400
+ # VLM embeddings
401
+ text_embeddings, bbox_embeddings, image_embedding = self._encode_vlm(
402
+ vlm_model=vlm_model,
403
+ prompt_use=prompt_use,
404
+ seg_list=seg_list,
405
+ full_img_pil=img,
406
+ )
407
+
408
+ # Ensure dims are consistent
409
+ if int(bbox_embeddings.shape[-1]) != int(image_embedding.shape[-1]):
410
+ raise RuntimeError(
411
+ f"Embedding dim mismatch: bbox_embeddings dim={bbox_embeddings.shape[-1]} vs image_embedding dim={image_embedding.shape[-1]}"
412
+ )
413
+
414
+ d_model = int(image_embedding.shape[-1])
415
+ n_words = int(text_embeddings.shape[0])
416
+
417
+ # TaskCLIP (load correct arch)
418
+ taskclip = self._get_taskclip(
419
+ ckpt_path=taskclip_ckpt,
420
+ d_model=d_model,
421
+ n_words=n_words,
422
+ score_function=score_function,
423
+ hdv_dim=hdv_dim,
424
+ cross_attention=cross_attention,
425
+ )
426
+
427
+ # Score
428
+ with torch.inference_mode():
429
+ tgt = bbox_embeddings
430
+ memory = text_embeddings
431
+ image_embedding_2d = image_embedding.view(1, -1)
432
+ _, _, score_res, _ = taskclip(tgt, memory, image_embedding_2d)
433
+ score = score_res.view(-1).detach().cpu().numpy().tolist()
434
+
435
+ # post-process
436
+ predict_res = []
437
+ for i in range(len(bbox_list)):
438
+ predict_res.append({"category_id": -1, "score": -1, "class": int(classes[i])})
439
+
440
+ visited = [0] * len(score)
441
+ for i, x in enumerate(score):
442
+ if visited[i] == 1:
443
+ continue
444
+ if float(x) > self.threshold:
445
+ visited[i] = 1
446
+ predict_res[i]["category_id"] = 1
447
+ predict_res[i]["score"] = float(x)
448
+ if self.forward:
449
+ self._find_same_class(predict_res, score, visited, i, classes, confidences, self.forward_thre)
450
+ else:
451
+ predict_res[i]["category_id"] = 0
452
+ predict_res[i]["score"] = 1.0 - float(x)
453
+
454
+ # cluster optimization
455
+ if self.cluster and self.forward and len(seg_list) > 1:
456
+ cluster_scores = {}
457
+ for p in predict_res:
458
+ if int(p["category_id"]) == 1:
459
+ c = p["class"]
460
+ cluster_scores.setdefault(c, []).append(p["score"])
461
+
462
+ if len(cluster_scores) > 1:
463
+ cluster_ave = {c: float(np.mean(v)) for c, v in cluster_scores.items()}
464
+ select_class = max(cluster_ave, key=lambda k: cluster_ave[k])
465
+ for p in predict_res:
466
+ if p["category_id"] == 1 and p["class"] != select_class:
467
+ p["category_id"] = 0
468
+
469
+ selected_indices = [i for i, p in enumerate(predict_res) if int(p["category_id"]) == 1]
470
+ selected_boxes = all_boxes[selected_indices] if len(selected_indices) > 0 else np.zeros((0, 4), dtype=np.float32)
471
+
472
+ # visualize selected
473
+ if viz_mode == "bbox":
474
+ img_selected = _draw_boxes_pil(img, selected_boxes, color=(255, 0, 0), width=4)
475
+ else:
476
+ if all_masks is not None and all_masks.shape[0] > 0 and len(selected_indices) > 0:
477
+ sel_masks = all_masks[selected_indices]
478
+ else:
479
+ sel_masks = np.zeros((0, H, W), dtype=bool)
480
+ img_selected = overlay_masks(img, sel_masks, alpha=0.45, color=(255, 0, 0))
481
+
482
+ return {
483
+ "task_id": task_id,
484
+ "task_name": task_name,
485
+ "bbox_list": bbox_list,
486
+ "classes": classes,
487
+ "confidences": confidences,
488
+ "scores": score,
489
+ "selected_indices": selected_indices,
490
+ "images": {"original": img, "yolo": img_yolo, "selected": img_selected},
491
+ }
webui/static/main.js ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ window.addEventListener("error", (e) => {
2
+ const log = document.querySelector("#statusLog");
3
+ if (log) log.textContent = "JS error: " + (e.message || e.error) + "\n" + log.textContent;
4
+ });
5
+
6
+ const $ = (sel) => document.querySelector(sel);
7
+
8
+ const form = $("#runForm");
9
+ const runBtn = $("#runBtn");
10
+ const runBtnText = $("#runBtnText");
11
+ const spinner = $("#spinner");
12
+ const resetBtn = $("#resetBtn");
13
+
14
+ const fileInput = $("#fileInput");
15
+ const dropzone = $("#dropzone");
16
+ const fileMeta = $("#fileMeta");
17
+ const previewWrap = $("#previewWrap");
18
+ const previewImg = $("#previewImg");
19
+
20
+ const statusDot = $("#statusDot");
21
+ const statusText = $("#statusText");
22
+ const statusLog = $("#statusLog");
23
+ const jobPill = $("#jobPill");
24
+
25
+ const imgInput = $("#imgInput");
26
+ const imgYolo = $("#imgYolo");
27
+ const imgSelected = $("#imgSelected");
28
+ const meta = $("#meta");
29
+
30
+ const dlInput = $("#dlInput");
31
+ const dlYolo = $("#dlYolo");
32
+ const dlSelected = $("#dlSelected");
33
+ const copyMetaBtn = $("#copyMetaBtn");
34
+
35
+ function setStatus(kind, text, logLine) {
36
+ // kind: idle | run | ok | bad
37
+ statusDot.className = `dot ${kind}`;
38
+ statusText.textContent = text;
39
+ if (logLine) statusLog.textContent = logLine + "\n" + statusLog.textContent;
40
+ }
41
+
42
+ function setRunning(isRunning) {
43
+ runBtn.disabled = isRunning;
44
+ spinner.classList.toggle("hidden", !isRunning);
45
+ runBtnText.textContent = isRunning ? "Running…" : "Run";
46
+ }
47
+
48
+ function clearResults() {
49
+ imgInput.removeAttribute("src");
50
+ imgYolo.removeAttribute("src");
51
+ imgSelected.removeAttribute("src");
52
+ meta.textContent = "";
53
+ jobPill.textContent = "job: —";
54
+
55
+ [dlInput, dlYolo, dlSelected].forEach(a => {
56
+ a.classList.add("hidden");
57
+ a.removeAttribute("href");
58
+ });
59
+ }
60
+
61
+ function setPreview(file) {
62
+ if (!file) {
63
+ previewWrap.classList.add("hidden");
64
+ previewImg.removeAttribute("src");
65
+ fileMeta.textContent = "No file selected";
66
+ return;
67
+ }
68
+ fileMeta.textContent = `${file.name} • ${(file.size / 1024).toFixed(1)} KB`;
69
+ const url = URL.createObjectURL(file);
70
+ previewImg.src = url;
71
+ previewWrap.classList.remove("hidden");
72
+ }
73
+
74
+ dropzone.addEventListener("click", () => fileInput.click());
75
+ dropzone.addEventListener("keydown", (e) => {
76
+ if (e.key === "Enter" || e.key === " ") fileInput.click();
77
+ });
78
+
79
+ fileInput.addEventListener("change", () => {
80
+ const file = fileInput.files && fileInput.files[0];
81
+ setPreview(file);
82
+ });
83
+
84
+ ["dragenter", "dragover"].forEach(evt => {
85
+ dropzone.addEventListener(evt, (e) => {
86
+ e.preventDefault();
87
+ e.stopPropagation();
88
+ dropzone.classList.add("drag");
89
+ });
90
+ });
91
+
92
+ ["dragleave", "drop"].forEach(evt => {
93
+ dropzone.addEventListener(evt, (e) => {
94
+ e.preventDefault();
95
+ e.stopPropagation();
96
+ dropzone.classList.remove("drag");
97
+ });
98
+ });
99
+
100
+ dropzone.addEventListener("drop", (e) => {
101
+ const file = e.dataTransfer.files && e.dataTransfer.files[0];
102
+ if (!file) return;
103
+
104
+ // Set preview
105
+ setPreview(file);
106
+
107
+ // Safely assign to input (works across browsers)
108
+ const dt = new DataTransfer();
109
+ dt.items.add(file);
110
+ fileInput.files = dt.files;
111
+ });
112
+
113
+ resetBtn.addEventListener("click", () => {
114
+ form.reset();
115
+ fileInput.value = "";
116
+ setPreview(null);
117
+ clearResults();
118
+ statusLog.textContent = "Waiting for input…";
119
+ setStatus("idle", "Idle", "Reset UI.");
120
+ });
121
+
122
+ copyMetaBtn.addEventListener("click", async () => {
123
+ const text = meta.textContent || "";
124
+ if (!text) return;
125
+ await navigator.clipboard.writeText(text);
126
+ setStatus("ok", "Done", "Copied metadata to clipboard.");
127
+ });
128
+
129
+ form.addEventListener("submit", async (e) => {
130
+ e.preventDefault();
131
+
132
+ const file = fileInput.files && fileInput.files[0];
133
+ if (!file) {
134
+ setStatus("bad", "Error", "No file selected.");
135
+ return;
136
+ }
137
+
138
+ setRunning(true);
139
+ setStatus("run", "Running", "Submitting request to /api/run …");
140
+
141
+ const fd = new FormData(form);
142
+
143
+ try {
144
+ const resp = await fetch("/api/run", { method: "POST", body: fd });
145
+ const data = await resp.json();
146
+
147
+ if (!resp.ok || !data.ok) {
148
+ throw new Error(data?.error || `HTTP ${resp.status}`);
149
+ }
150
+
151
+ jobPill.textContent = `job: ${data.job_id}`;
152
+ setStatus("ok", "Done", `Inference finished. job_id=${data.job_id}`);
153
+
154
+ // Update images (cache-bust)
155
+ const bust = `t=${Date.now()}`;
156
+ imgInput.src = `${data.image_urls.input}?${bust}`;
157
+ imgYolo.src = `${data.image_urls.yolo}?${bust}`;
158
+ imgSelected.src = `${data.image_urls.selected}?${bust}`;
159
+
160
+ // Open links
161
+ dlInput.href = data.image_urls.input;
162
+ dlYolo.href = data.image_urls.yolo;
163
+ dlSelected.href = data.image_urls.selected;
164
+ [dlInput, dlYolo, dlSelected].forEach(a => a.classList.remove("hidden"));
165
+
166
+ // Meta
167
+ meta.textContent = JSON.stringify({
168
+ task_id: data.task_id,
169
+ task_name: data.task_name,
170
+ selected_indices: data.selected_indices,
171
+ job_id: data.job_id,
172
+ }, null, 2);
173
+
174
+ } catch (err) {
175
+ setStatus("bad", "Error", String(err));
176
+ } finally {
177
+ setRunning(false);
178
+ }
179
+ });
webui/static/style.css ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root{
2
+ --bg0:#070A10;
3
+ --bg1:#0B1020;
4
+ --card: rgba(255,255,255,.06);
5
+ --card2: rgba(255,255,255,.09);
6
+ --stroke: rgba(255,255,255,.10);
7
+ --stroke2: rgba(255,255,255,.18);
8
+ --text:#EAF0FF;
9
+ --muted:#A8B3D6;
10
+ --accent:#6AE4FF;
11
+ --accent2:#A78BFA;
12
+ --good:#34D399;
13
+ --warn:#FBBF24;
14
+ --bad:#FB7185;
15
+ --shadow: 0 18px 60px rgba(0,0,0,.55);
16
+ --r: 18px;
17
+ --r2: 26px;
18
+ --mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
19
+ }
20
+
21
+ *{box-sizing:border-box}
22
+ html,body{height:100%}
23
+ body{
24
+ margin:0;
25
+ font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
26
+ background:
27
+ radial-gradient(1200px 600px at 22% 10%, rgba(106,228,255,.20), transparent 60%),
28
+ radial-gradient(900px 700px at 80% 18%, rgba(167,139,250,.18), transparent 55%),
29
+ radial-gradient(1400px 900px at 50% 90%, rgba(34,211,238,.08), transparent 60%),
30
+ linear-gradient(180deg, var(--bg0), var(--bg1));
31
+ color: var(--text);
32
+ overflow-x:hidden;
33
+ }
34
+
35
+ /* Layout */
36
+ .app{
37
+ display:grid;
38
+ grid-template-columns: 460px 1fr;
39
+ gap:14px;
40
+ height:100vh;
41
+ padding:14px;
42
+ }
43
+ .sidebar, .topbar, .card{
44
+ border:1px solid var(--stroke);
45
+ background: linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03));
46
+ border-radius: var(--r2);
47
+ box-shadow: var(--shadow);
48
+ }
49
+ .sidebar{
50
+ overflow:hidden;
51
+ display:flex;
52
+ flex-direction:column;
53
+ min-width: 380px;
54
+ }
55
+ .main{
56
+ display:flex;
57
+ flex-direction:column;
58
+ gap:14px;
59
+ min-width: 680px;
60
+ }
61
+
62
+ /* Sidebar header */
63
+ .sideTop{
64
+ padding:14px;
65
+ border-bottom: 1px solid rgba(255,255,255,.08);
66
+ background: rgba(255,255,255,.03);
67
+ }
68
+ .sideTitle{
69
+ display:flex;
70
+ align-items:center;
71
+ gap:12px;
72
+ }
73
+ .logo{
74
+ width:38px;height:38px;border-radius:14px;
75
+ background: radial-gradient(circle at 30% 30%, rgba(106,228,255,.85), rgba(167,139,250,.65));
76
+ border:1px solid rgba(255,255,255,.20);
77
+ box-shadow: 0 10px 28px rgba(106,228,255,.18);
78
+ position:relative;
79
+ }
80
+ .logo:after{
81
+ content:"";
82
+ position:absolute; inset:8px;
83
+ border-radius:12px;
84
+ border:1px dashed rgba(255,255,255,.35);
85
+ opacity:.55;
86
+ }
87
+ .title{font-weight:900; letter-spacing:.04em}
88
+ .sub{font-size:12px; color:var(--muted); margin-top:2px}
89
+
90
+ .sideScroll{padding:12px 14px; overflow:auto; flex:1}
91
+
92
+ /* Cards */
93
+ .section{
94
+ padding:12px;
95
+ border-radius: 22px;
96
+ }
97
+ .sectionTitle{
98
+ display:flex;
99
+ align-items:center;
100
+ gap:10px;
101
+ font-size:12px;
102
+ font-weight:900;
103
+ letter-spacing:.06em;
104
+ text-transform:uppercase;
105
+ margin-bottom:10px;
106
+ color: rgba(255,255,255,.88);
107
+ }
108
+ .divider{height:1px; background: rgba(255,255,255,.08); margin:12px 0}
109
+
110
+ /* Fields */
111
+ .field{margin:10px 0}
112
+ label{
113
+ display:block;
114
+ font-size:12px;
115
+ color: rgba(255,255,255,.82);
116
+ margin-bottom:6px;
117
+ }
118
+ .hint{
119
+ font-size:11px;
120
+ color: var(--muted);
121
+ margin-top:6px;
122
+ line-height:1.35;
123
+ }
124
+ select, input[type="text"], textarea{
125
+ width:100%;
126
+ padding:10px 10px;
127
+ border-radius: 14px;
128
+ border:1px solid rgba(255,255,255,.10);
129
+ background: rgba(0,0,0,.22);
130
+ color: var(--text);
131
+ outline:none;
132
+ transition: border-color .12s ease;
133
+ font-size:12px;
134
+ }
135
+ select:focus, input[type="text"]:focus, textarea:focus{border-color: rgba(106,228,255,.45);}
136
+
137
+ .grid2{
138
+ display:grid;
139
+ grid-template-columns: 1fr 1fr;
140
+ gap:10px;
141
+ }
142
+
143
+ /* Buttons */
144
+ .btn{
145
+ appearance:none;
146
+ border:1px solid var(--stroke);
147
+ background: linear-gradient(180deg, rgba(255,255,255,.08), rgba(255,255,255,.03));
148
+ color:var(--text);
149
+ border-radius: 14px;
150
+ padding:10px 12px;
151
+ font-weight:800;
152
+ font-size:12px;
153
+ cursor:pointer;
154
+ transition: transform .12s ease, border-color .12s ease;
155
+ display:inline-flex;
156
+ align-items:center;
157
+ gap:8px;
158
+ justify-content:center;
159
+ }
160
+ .btn:hover{transform: translateY(-1px); border-color: var(--stroke2);}
161
+ .btn:active{transform: translateY(0px) scale(.99);}
162
+ .btn.primary{
163
+ border-color: rgba(106,228,255,.38);
164
+ background: linear-gradient(180deg, rgba(106,228,255,.18), rgba(167,139,250,.10));
165
+ box-shadow: 0 12px 30px rgba(106,228,255,.10);
166
+ }
167
+ .btn.ghost{background: transparent; border-color: rgba(255,255,255,.10);}
168
+ .btnRow{display:flex; gap:10px; margin-top:10px}
169
+ .btnRow .btn{flex:1}
170
+
171
+ .tinyBtn{padding:8px 10px; font-weight:900}
172
+ .hidden{display:none !important}
173
+
174
+ /* Spinner */
175
+ .spinner{
176
+ width:14px;height:14px;border-radius:50%;
177
+ border:2px solid rgba(255,255,255,.22);
178
+ border-top-color: rgba(106,228,255,.85);
179
+ animation: spin .8s linear infinite;
180
+ }
181
+ @keyframes spin{to{transform: rotate(360deg);}}
182
+
183
+ /* Dropzone */
184
+ .dropzone{
185
+ display:flex;
186
+ gap:12px;
187
+ align-items:center;
188
+ border-radius: 18px;
189
+ border:1px dashed rgba(255,255,255,.22);
190
+ background: rgba(0,0,0,.14);
191
+ padding:12px;
192
+ cursor:pointer;
193
+ transition: border-color .12s ease, background .12s ease;
194
+ }
195
+ .dropzone:hover{
196
+ border-color: rgba(106,228,255,.52);
197
+ background: rgba(106,228,255,.05);
198
+ }
199
+ .dropzone.drag{
200
+ border-color: rgba(167,139,250,.65);
201
+ background: rgba(167,139,250,.06);
202
+ }
203
+ .dzLeft{
204
+ width:38px;height:38px;border-radius:14px;
205
+ display:flex;align-items:center;justify-content:center;
206
+ background: rgba(106,228,255,.10);
207
+ border:1px solid rgba(106,228,255,.22);
208
+ }
209
+ .dzRight{flex:1}
210
+ .dzTitle{font-weight:900; letter-spacing:.02em}
211
+ .dzSub{font-size:12px; color: var(--muted); margin-top:2px}
212
+ .dzMeta{font-size:11px; color: rgba(255,255,255,.70); margin-top:6px; font-family: var(--mono);}
213
+
214
+ .previewWrap{
215
+ margin-top:10px;
216
+ border:1px solid rgba(255,255,255,.10);
217
+ border-radius: 18px;
218
+ overflow:hidden;
219
+ background: rgba(0,0,0,.18);
220
+ }
221
+ .previewWrap img{display:block; width:100%; height:auto; max-height: 220px; object-fit: contain}
222
+
223
+ /* Status */
224
+ .statusRow{display:flex; gap:10px; flex-wrap:wrap; align-items:center}
225
+ .pill{
226
+ display:inline-flex;
227
+ align-items:center;
228
+ gap:8px;
229
+ padding:8px 10px;
230
+ border:1px solid var(--stroke);
231
+ border-radius: 999px;
232
+ background: rgba(255,255,255,.04);
233
+ font-size:12px;
234
+ color: var(--muted);
235
+ }
236
+ .dot{
237
+ width:8px;height:8px;border-radius:50%;
238
+ background: var(--muted);
239
+ box-shadow:0 0 0 3px rgba(168,179,214,.10);
240
+ }
241
+ .dot.idle{background: var(--muted);}
242
+ .dot.run{background: var(--warn); box-shadow:0 0 0 3px rgba(251,191,36,.12);}
243
+ .dot.ok{background: var(--good); box-shadow:0 0 0 3px rgba(52,211,153,.12);}
244
+ .dot.bad{background: var(--bad); box-shadow:0 0 0 3px rgba(251,113,133,.12);}
245
+ .mono{font-family: var(--mono);}
246
+ .logBox{
247
+ margin-top:10px;
248
+ border:1px solid rgba(255,255,255,.10);
249
+ background: rgba(0,0,0,.20);
250
+ border-radius: 16px;
251
+ padding:10px;
252
+ font-size:11px;
253
+ line-height:1.55;
254
+ white-space:pre-wrap;
255
+ max-height: 200px;
256
+ overflow:auto;
257
+ }
258
+
259
+ /* Topbar */
260
+ .topbar{
261
+ padding: 12px 14px;
262
+ display:flex;
263
+ align-items:center;
264
+ justify-content:space-between;
265
+ gap:12px;
266
+ }
267
+ .topTitle{font-weight:900; letter-spacing:.04em}
268
+ .topSub{font-size:12px; color: var(--muted); margin-top:2px}
269
+ .topLeft{display:flex; flex-direction:column}
270
+ .topRight{display:flex; gap:10px; align-items:center}
271
+ .muted{color: var(--muted)}
272
+
273
+ /* Result grid */
274
+ .grid3{
275
+ display:grid;
276
+ grid-template-columns: 1fr 1fr 1fr;
277
+ gap:12px;
278
+ }
279
+ .resultCard{overflow:hidden}
280
+ .cardHeader{
281
+ padding:10px 12px;
282
+ border-bottom: 1px solid rgba(255,255,255,.08);
283
+ background: rgba(0,0,0,.16);
284
+ display:flex;
285
+ align-items:center;
286
+ justify-content:space-between;
287
+ }
288
+ .cardHeaderTitle{
289
+ display:flex;
290
+ align-items:center;
291
+ gap:8px;
292
+ font-weight:900;
293
+ font-size:12px;
294
+ letter-spacing:.06em;
295
+ text-transform:uppercase;
296
+ color: rgba(255,255,255,.88);
297
+ }
298
+ .imgWrap{
299
+ padding:10px;
300
+ height: 360px;
301
+ display:flex;
302
+ align-items:center;
303
+ justify-content:center;
304
+ background: rgba(0,0,0,.18);
305
+ }
306
+ .imgWrap img{
307
+ max-width:100%;
308
+ max-height:100%;
309
+ border-radius: 18px;
310
+ border:1px solid rgba(255,255,255,.10);
311
+ background: rgba(0,0,0,.14);
312
+ }
313
+ .miniLink{
314
+ font-size:12px;
315
+ color: rgba(255,255,255,.75);
316
+ text-decoration:none;
317
+ border:1px solid rgba(255,255,255,.12);
318
+ padding:6px 10px;
319
+ border-radius: 999px;
320
+ background: rgba(255,255,255,.04);
321
+ }
322
+ .miniLink:hover{border-color: rgba(106,228,255,.38);}
323
+
324
+ .metaCard .meta{
325
+ margin:0;
326
+ padding:12px;
327
+ font-size:11px;
328
+ line-height:1.6;
329
+ background: rgba(0,0,0,.20);
330
+ border-top: 1px solid rgba(255,255,255,.08);
331
+ border-bottom-left-radius: var(--r2);
332
+ border-bottom-right-radius: var(--r2);
333
+ overflow:auto;
334
+ max-height: 220px;
335
+ }
336
+
337
+ /* Responsive */
338
+ @media (max-width: 1180px){
339
+ .app{grid-template-columns: 1fr; height:auto}
340
+ .main{min-width:0}
341
+ .sidebar{min-height: 420px}
342
+ .grid3{grid-template-columns: 1fr}
343
+ .imgWrap{height: auto}
344
+ }
345
+
346
+ .fileHidden{
347
+ position:absolute;
348
+ left:-9999px;
349
+ width:1px;
350
+ height:1px;
351
+ opacity:0;
352
+ pointer-events:none;
353
+ }
webui/templates/index.html ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <title>TaskCLIP Web UI</title>
7
+
8
+ <!-- Fonts / Icons (same “style family” as your advisor’s demo) -->
9
+ <link rel="preconnect" href="https://fonts.googleapis.com">
10
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
12
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
13
+
14
+ <link rel="stylesheet" href="/static/style.css?v=2">
15
+ </head>
16
+
17
+ <body>
18
+ <div class="app">
19
+
20
+ <!-- Left: Controls -->
21
+ <aside class="sidebar">
22
+ <div class="sideTop">
23
+ <div class="sideTitle">
24
+ <span class="logo"></span>
25
+ <div>
26
+ <div class="title">TaskCLIP Demo</div>
27
+ <div class="sub">YOLO → VLM Embedding → TaskCLIP Selection</div>
28
+ </div>
29
+ </div>
30
+ </div>
31
+
32
+ <div class="sideScroll">
33
+ <form id="runForm" class="card section">
34
+ <div class="sectionTitle">
35
+ <i class="fa-solid fa-sliders"></i>
36
+ <span>Controls</span>
37
+ </div>
38
+
39
+ <div class="grid2">
40
+ <div class="field">
41
+ <label>VLM Model</label>
42
+ <select name="vlm_model">
43
+ {% for x in vlm_choices %}
44
+ <option value="{{x.value}}" {% if x.value == default_vlm %}selected{% endif %}>
45
+ {{x.label}}
46
+ </option>
47
+ {% endfor %}
48
+ </select>
49
+ </div>
50
+
51
+ <div class="field">
52
+ <label>Score Function</label>
53
+ <select name="score_function">
54
+ <option value="default" selected>default</option>
55
+ <option value="HDC">HDC</option>
56
+ </select>
57
+ </div>
58
+
59
+ <div class="field">
60
+ <label>HDV Dim</label>
61
+ <select name="hdv_dim">
62
+ {% for d in hdv_dims %}
63
+ <option value="{{d}}" {% if d == default_hdv_dim %}selected{% endif %}>{{d}}</option>
64
+ {% endfor %}
65
+ </select>
66
+ <div class="hint">Only used when Score Function = HDC</div>
67
+ </div>
68
+
69
+ <div class="field">
70
+ <label>OD Model Size</label>
71
+ <select name="od_model">
72
+ {% for x in od_choices %}
73
+ <option value="{{x.value}}" {% if x.value == default_od %}selected{% endif %}>
74
+ {{x.label}}
75
+ </option>
76
+ {% endfor %}
77
+ </select>
78
+ <div class="hint">YOLO backend fixed; dropdown changes checkpoint size</div>
79
+ </div>
80
+
81
+ <div class="field">
82
+ <label>Task ID</label>
83
+ <select name="task_id">
84
+ {% for t in task_ids %}
85
+ <option value="{{t}}">{{t}}</option>
86
+ {% endfor %}
87
+ </select>
88
+ </div>
89
+
90
+ <div class="field">
91
+ <label>Visualization</label>
92
+ <select name="viz_mode">
93
+ <option value="bbox" selected>bbox</option>
94
+ <option value="mask">mask</option>
95
+ </select>
96
+ </div>
97
+ </div>
98
+
99
+ <div class="divider"></div>
100
+
101
+ <div class="field">
102
+ <label>Upload Image</label>
103
+
104
+ <input id="fileInput" name="upload" type="file" accept="image/*" class="fileHidden" required />
105
+
106
+ <!-- Fancy dropzone -->
107
+ <div id="dropzone" class="dropzone" role="button" tabindex="0">
108
+ <div class="dzLeft">
109
+ <i class="fa-solid fa-file-arrow-up"></i>
110
+ </div>
111
+ <div class="dzRight">
112
+ <div class="dzTitle">Drop image here</div>
113
+ <div class="dzSub">or click to choose (PNG/JPG)</div>
114
+ <div class="dzMeta" id="fileMeta">No file selected</div>
115
+ </div>
116
+ </div>
117
+
118
+ <div class="previewWrap hidden" id="previewWrap">
119
+ <img id="previewImg" alt="preview" />
120
+ </div>
121
+ </div>
122
+
123
+ <div class="btnRow">
124
+ <button id="runBtn" class="btn primary" type="submit">
125
+ <span class="spinner hidden" id="spinner"></span>
126
+ <i class="fa-solid fa-bolt"></i>
127
+ <span id="runBtnText">Run</span>
128
+ </button>
129
+ <button id="resetBtn" class="btn ghost" type="button">
130
+ <i class="fa-solid fa-rotate-right"></i>
131
+ Reset
132
+ </button>
133
+ </div>
134
+ </form>
135
+
136
+ <div class="card section">
137
+ <div class="sectionTitle">
138
+ <i class="fa-solid fa-circle-info"></i>
139
+ <span>Run Status</span>
140
+ </div>
141
+
142
+ <div class="statusRow">
143
+ <div class="pill" id="statusPill">
144
+ <span class="dot idle" id="statusDot"></span>
145
+ <span id="statusText">Idle</span>
146
+ </div>
147
+ <div class="pill mono" id="jobPill">job: —</div>
148
+ </div>
149
+
150
+ <div class="logBox mono" id="statusLog">Waiting for input…</div>
151
+ </div>
152
+ </div>
153
+ </aside>
154
+
155
+ <!-- Right: Results -->
156
+ <main class="main">
157
+ <header class="topbar card">
158
+ <div class="topLeft">
159
+ <div class="topTitle">Results</div>
160
+ <div class="topSub">Input • YOLO detections • TaskCLIP selected</div>
161
+ </div>
162
+ <div class="topRight">
163
+ <div class="pill">
164
+ <i class="fa-solid fa-gpu"></i>
165
+ <span class="muted">Backend:</span> FastAPI
166
+ </div>
167
+ </div>
168
+ </header>
169
+
170
+ <section class="grid3">
171
+ <div class="card resultCard">
172
+ <div class="cardHeader">
173
+ <div class="cardHeaderTitle"><i class="fa-regular fa-image"></i> Input</div>
174
+ <a id="dlInput" class="miniLink hidden" target="_blank" rel="noreferrer">
175
+ <i class="fa-solid fa-arrow-up-right-from-square"></i> open
176
+ </a>
177
+ </div>
178
+ <div class="imgWrap">
179
+ <img id="imgInput" />
180
+ </div>
181
+ </div>
182
+
183
+ <div class="card resultCard">
184
+ <div class="cardHeader">
185
+ <div class="cardHeaderTitle"><i class="fa-solid fa-border-all"></i> All detections</div>
186
+ <a id="dlYolo" class="miniLink hidden" target="_blank" rel="noreferrer">
187
+ <i class="fa-solid fa-arrow-up-right-from-square"></i> open
188
+ </a>
189
+ </div>
190
+ <div class="imgWrap">
191
+ <img id="imgYolo" />
192
+ </div>
193
+ </div>
194
+
195
+ <div class="card resultCard">
196
+ <div class="cardHeader">
197
+ <div class="cardHeaderTitle"><i class="fa-solid fa-crosshairs"></i> Selected</div>
198
+ <a id="dlSelected" class="miniLink hidden" target="_blank" rel="noreferrer">
199
+ <i class="fa-solid fa-arrow-up-right-from-square"></i> open
200
+ </a>
201
+ </div>
202
+ <div class="imgWrap">
203
+ <img id="imgSelected" />
204
+ </div>
205
+ </div>
206
+ </section>
207
+
208
+ <section class="card metaCard">
209
+ <div class="cardHeader">
210
+ <div class="cardHeaderTitle"><i class="fa-solid fa-code"></i> Metadata</div>
211
+ <button class="btn tinyBtn ghost" id="copyMetaBtn" type="button">
212
+ <i class="fa-regular fa-copy"></i> Copy
213
+ </button>
214
+ </div>
215
+ <pre class="mono meta" id="meta"></pre>
216
+ </section>
217
+ </main>
218
+ </div>
219
+
220
+ <script src="/static/main.js"></script>
221
+ </body>
222
+ </html>