├── .assets ├── bird_audio.wav ├── bird_image.jpg ├── car_audio.wav ├── car_image.jpg ├── dog_audio.wav └── dog_image.jpg ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── imagebind ├── __init__.py ├── bpe │ └── bpe_simple_vocab_16e6.txt.gz ├── data.py └── models │ ├── __init__.py │ ├── helpers.py │ ├── imagebind_model.py │ ├── multimodal_preprocessors.py │ └── transformer.py ├── model_card.md ├── requirements.txt └── setup.py /.assets/bird_audio.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/bird_audio.wav -------------------------------------------------------------------------------- /.assets/bird_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/bird_image.jpg -------------------------------------------------------------------------------- /.assets/car_audio.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/car_audio.wav -------------------------------------------------------------------------------- /.assets/car_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/car_image.jpg -------------------------------------------------------------------------------- /.assets/dog_audio.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/dog_audio.wav -------------------------------------------------------------------------------- /.assets/dog_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/.assets/dog_image.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **__pycache__ 2 | .vscode 3 | .idea/ 4 | .python-version 5 | build/ 6 | imagebind.egg-info 7 | .DS_Store 8 | venv/ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 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 . 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 -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 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: 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. 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 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 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
ModelIN1kK400NYU-DESCLLVIPEgo4Ddownload
imagebind_huge77.750.054.066.963.425.0checkpoint
52 | 53 | ## Usage 54 | 55 | Install pytorch 1.13+ 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 | ``` 156 | -------------------------------------------------------------------------------- /imagebind/__init__.py: -------------------------------------------------------------------------------- 1 | from imagebind import data 2 | from imagebind.models import imagebind_model 3 | from imagebind.models.imagebind_model import ModalityType -------------------------------------------------------------------------------- /imagebind/bpe/bpe_simple_vocab_16e6.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/imagebind/bpe/bpe_simple_vocab_16e6.txt.gz -------------------------------------------------------------------------------- /imagebind/data.py: -------------------------------------------------------------------------------- 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 | from torchvision.transforms._transforms_video import NormalizeVideo 21 | 22 | from imagebind.models.multimodal_preprocessors import SimpleTokenizer 23 | 24 | DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds 25 | 26 | 27 | def return_bpe_path(): 28 | return pkg_resources.resource_filename( 29 | "imagebind", "bpe/bpe_simple_vocab_16e6.txt.gz" 30 | ) 31 | 32 | 33 | def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length): 34 | # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102 35 | waveform -= waveform.mean() 36 | fbank = torchaudio.compliance.kaldi.fbank( 37 | waveform, 38 | htk_compat=True, 39 | sample_frequency=sample_rate, 40 | use_energy=False, 41 | window_type="hanning", 42 | num_mel_bins=num_mel_bins, 43 | dither=0.0, 44 | frame_length=25, 45 | frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS, 46 | ) 47 | # Convert to [mel_bins, num_frames] shape 48 | fbank = fbank.transpose(0, 1) 49 | # Pad to target_length 50 | n_frames = fbank.size(1) 51 | p = target_length - n_frames 52 | # if p is too large (say >20%), flash a warning 53 | if abs(p) / n_frames > 0.2: 54 | logging.warning( 55 | "Large gap between audio n_frames(%d) and " 56 | "target_length (%d). Is the audio_target_length " 57 | "setting correct?", 58 | n_frames, 59 | target_length, 60 | ) 61 | # cut and pad 62 | if p > 0: 63 | fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0) 64 | elif p < 0: 65 | fbank = fbank[:, 0:target_length] 66 | # Convert to [1, mel_bins, num_frames] shape, essentially like a 1 67 | # channel image 68 | fbank = fbank.unsqueeze(0) 69 | return fbank 70 | 71 | 72 | def get_clip_timepoints(clip_sampler, duration): 73 | # Read out all clips in this video 74 | all_clips_timepoints = [] 75 | is_last_clip = False 76 | end = 0.0 77 | while not is_last_clip: 78 | start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None) 79 | all_clips_timepoints.append((start, end)) 80 | return all_clips_timepoints 81 | 82 | 83 | def load_and_transform_vision_data(image_paths, device): 84 | if image_paths is None: 85 | return None 86 | 87 | image_outputs = [] 88 | 89 | data_transform = transforms.Compose( 90 | [ 91 | transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC), 92 | transforms.CenterCrop(224), 93 | transforms.ToTensor(), 94 | transforms.Normalize( 95 | mean=(0.48145466, 0.4578275, 0.40821073), 96 | std=(0.26862954, 0.26130258, 0.27577711), 97 | ), 98 | ] 99 | ) 100 | 101 | for image_path in image_paths: 102 | with open(image_path, "rb") as fopen: 103 | image = Image.open(fopen).convert("RGB") 104 | 105 | image = data_transform(image).to(device) 106 | image_outputs.append(image) 107 | return torch.stack(image_outputs, dim=0) 108 | 109 | 110 | def load_and_transform_text(text, device): 111 | if text is None: 112 | return None 113 | tokenizer = SimpleTokenizer(bpe_path=return_bpe_path()) 114 | tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text] 115 | tokens = torch.cat(tokens, dim=0) 116 | return tokens 117 | 118 | 119 | def load_and_transform_audio_data( 120 | audio_paths, 121 | device, 122 | num_mel_bins=128, 123 | target_length=204, 124 | sample_rate=16000, 125 | clip_duration=2, 126 | clips_per_video=3, 127 | mean=-4.268, 128 | std=9.138, 129 | ): 130 | if audio_paths is None: 131 | return None 132 | 133 | audio_outputs = [] 134 | clip_sampler = ConstantClipsPerVideoSampler( 135 | clip_duration=clip_duration, clips_per_video=clips_per_video 136 | ) 137 | 138 | for audio_path in audio_paths: 139 | waveform, sr = torchaudio.load(audio_path) 140 | if sample_rate != sr: 141 | waveform = torchaudio.functional.resample( 142 | waveform, orig_freq=sr, new_freq=sample_rate 143 | ) 144 | all_clips_timepoints = get_clip_timepoints( 145 | clip_sampler, waveform.size(1) / sample_rate 146 | ) 147 | all_clips = [] 148 | for clip_timepoints in all_clips_timepoints: 149 | waveform_clip = waveform[ 150 | :, 151 | int(clip_timepoints[0] * sample_rate) : int( 152 | clip_timepoints[1] * sample_rate 153 | ), 154 | ] 155 | waveform_melspec = waveform2melspec( 156 | waveform_clip, sample_rate, num_mel_bins, target_length 157 | ) 158 | all_clips.append(waveform_melspec) 159 | 160 | normalize = transforms.Normalize(mean=mean, std=std) 161 | all_clips = [normalize(ac).to(device) for ac in all_clips] 162 | 163 | all_clips = torch.stack(all_clips, dim=0) 164 | audio_outputs.append(all_clips) 165 | 166 | return torch.stack(audio_outputs, dim=0) 167 | 168 | 169 | def crop_boxes(boxes, x_offset, y_offset): 170 | """ 171 | Perform crop on the bounding boxes given the offsets. 172 | Args: 173 | boxes (ndarray or None): bounding boxes to perform crop. The dimension 174 | is `num boxes` x 4. 175 | x_offset (int): cropping offset in the x axis. 176 | y_offset (int): cropping offset in the y axis. 177 | Returns: 178 | cropped_boxes (ndarray or None): the cropped boxes with dimension of 179 | `num boxes` x 4. 180 | """ 181 | cropped_boxes = boxes.copy() 182 | cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset 183 | cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset 184 | 185 | return cropped_boxes 186 | 187 | 188 | def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): 189 | """ 190 | Perform uniform spatial sampling on the images and corresponding boxes. 191 | Args: 192 | images (tensor): images to perform uniform crop. The dimension is 193 | `num frames` x `channel` x `height` x `width`. 194 | size (int): size of height and weight to crop the images. 195 | spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width 196 | is larger than height. Or 0, 1, or 2 for top, center, and bottom 197 | crop if height is larger than width. 198 | boxes (ndarray or None): optional. Corresponding boxes to images. 199 | Dimension is `num boxes` x 4. 200 | scale_size (int): optinal. If not None, resize the images to scale_size before 201 | performing any crop. 202 | Returns: 203 | cropped (tensor): images with dimension of 204 | `num frames` x `channel` x `size` x `size`. 205 | cropped_boxes (ndarray or None): the cropped boxes with dimension of 206 | `num boxes` x 4. 207 | """ 208 | assert spatial_idx in [0, 1, 2] 209 | ndim = len(images.shape) 210 | if ndim == 3: 211 | images = images.unsqueeze(0) 212 | height = images.shape[2] 213 | width = images.shape[3] 214 | 215 | if scale_size is not None: 216 | if width <= height: 217 | width, height = scale_size, int(height / width * scale_size) 218 | else: 219 | width, height = int(width / height * scale_size), scale_size 220 | images = torch.nn.functional.interpolate( 221 | images, 222 | size=(height, width), 223 | mode="bilinear", 224 | align_corners=False, 225 | ) 226 | 227 | y_offset = int(math.ceil((height - size) / 2)) 228 | x_offset = int(math.ceil((width - size) / 2)) 229 | 230 | if height > width: 231 | if spatial_idx == 0: 232 | y_offset = 0 233 | elif spatial_idx == 2: 234 | y_offset = height - size 235 | else: 236 | if spatial_idx == 0: 237 | x_offset = 0 238 | elif spatial_idx == 2: 239 | x_offset = width - size 240 | cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] 241 | cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None 242 | if ndim == 3: 243 | cropped = cropped.squeeze(0) 244 | return cropped, cropped_boxes 245 | 246 | 247 | class SpatialCrop(nn.Module): 248 | """ 249 | Convert the video into 3 smaller clips spatially. Must be used after the 250 | temporal crops to get spatial crops, and should be used with 251 | -2 in the spatial crop at the slowfast augmentation stage (so full 252 | frames are passed in here). Will return a larger list with the 253 | 3x spatial crops as well. 254 | """ 255 | 256 | def __init__(self, crop_size: int = 224, num_crops: int = 3): 257 | super().__init__() 258 | self.crop_size = crop_size 259 | if num_crops == 3: 260 | self.crops_to_ext = [0, 1, 2] 261 | self.flipped_crops_to_ext = [] 262 | elif num_crops == 1: 263 | self.crops_to_ext = [1] 264 | self.flipped_crops_to_ext = [] 265 | else: 266 | raise NotImplementedError("Nothing else supported yet") 267 | 268 | def forward(self, videos): 269 | """ 270 | Args: 271 | videos: A list of C, T, H, W videos. 272 | Returns: 273 | videos: A list with 3x the number of elements. Each video converted 274 | to C, T, H', W' by spatial cropping. 275 | """ 276 | assert isinstance(videos, list), "Must be a list of videos after temporal crops" 277 | assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)" 278 | res = [] 279 | for video in videos: 280 | for spatial_idx in self.crops_to_ext: 281 | res.append(uniform_crop(video, self.crop_size, spatial_idx)[0]) 282 | if not self.flipped_crops_to_ext: 283 | continue 284 | flipped_video = transforms.functional.hflip(video) 285 | for spatial_idx in self.flipped_crops_to_ext: 286 | res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0]) 287 | return res 288 | 289 | 290 | def load_and_transform_video_data( 291 | video_paths, 292 | device, 293 | clip_duration=2, 294 | clips_per_video=5, 295 | sample_rate=16000, 296 | ): 297 | if video_paths is None: 298 | return None 299 | 300 | video_outputs = [] 301 | video_transform = transforms.Compose( 302 | [ 303 | pv_transforms.ShortSideScale(224), 304 | NormalizeVideo( 305 | mean=(0.48145466, 0.4578275, 0.40821073), 306 | std=(0.26862954, 0.26130258, 0.27577711), 307 | ), 308 | ] 309 | ) 310 | 311 | clip_sampler = ConstantClipsPerVideoSampler( 312 | clip_duration=clip_duration, clips_per_video=clips_per_video 313 | ) 314 | frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration) 315 | 316 | for video_path in video_paths: 317 | video = EncodedVideo.from_path( 318 | video_path, 319 | decoder="decord", 320 | decode_audio=False, 321 | **{"sample_rate": sample_rate}, 322 | ) 323 | 324 | all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration) 325 | 326 | all_video = [] 327 | for clip_timepoints in all_clips_timepoints: 328 | # Read the clip, get frames 329 | clip = video.get_clip(clip_timepoints[0], clip_timepoints[1]) 330 | if clip is None: 331 | raise ValueError("No clip found") 332 | video_clip = frame_sampler(clip["video"]) 333 | video_clip = video_clip / 255.0 # since this is float, need 0-1 334 | 335 | all_video.append(video_clip) 336 | 337 | all_video = [video_transform(clip) for clip in all_video] 338 | all_video = SpatialCrop(224, num_crops=3)(all_video) 339 | 340 | all_video = torch.stack(all_video, dim=0) 341 | video_outputs.append(all_video) 342 | 343 | return torch.stack(video_outputs, dim=0).to(device) 344 | -------------------------------------------------------------------------------- /imagebind/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/ImageBind/3fcf5c9039de97f6ff5528ee4a9dce903c5979b3/imagebind/models/__init__.py -------------------------------------------------------------------------------- /imagebind/models/helpers.py: -------------------------------------------------------------------------------- 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 141 | -------------------------------------------------------------------------------- /imagebind/models/imagebind_model.py: -------------------------------------------------------------------------------- 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")) 505 | 506 | return model 507 | -------------------------------------------------------------------------------- /imagebind/models/multimodal_preprocessors.py: -------------------------------------------------------------------------------- 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.models.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 + "" 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] + "",) 529 | pairs = get_pairs(word) 530 | 531 | if not pairs: 532 | return token + "" 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("", " ") 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) + [eot_token] 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] 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 686 | -------------------------------------------------------------------------------- /imagebind/models/transformer.py: -------------------------------------------------------------------------------- 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.models.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 281 | -------------------------------------------------------------------------------- /model_card.md: -------------------------------------------------------------------------------- 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 | 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 | 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 | 30 | 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 | 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 | 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 | 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 | 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. 95 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==1.13.1 2 | torchvision # because torch version already specific, the right torchvision will be derived automatically 3 | torchaudio # because torch version already specific, the right torchaudio will be derived automatically 4 | pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d 5 | timm==0.6.7 6 | ftfy 7 | regex 8 | einops 9 | fvcore 10 | eva-decord==0.6.1 11 | iopath 12 | numpy>=1.19 13 | matplotlib 14 | types-regex 15 | mayavi 16 | cartopy 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 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 | ) 24 | --------------------------------------------------------------------------------