[
  {
    "path": ".gitignore",
    "content": "**__pycache__\n.vscode\n.idea/\n.python-version\nbuild/\nimagebind.egg-info\n.DS_Store\nvenv/"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to make participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\nadvances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\naddress, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\nprofessional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies within all project spaces, and it also applies when\nan individual is representing the project or its community in public spaces.\nExamples of representing a project or community include using an official\nproject e-mail address, posting via an official social media account, or acting\nas an appointed representative at an online or offline event. Representation of\na project may be further defined and clarified by project maintainers.\n\nThis Code of Conduct also applies outside the project spaces when there is a\nreasonable belief that an individual's behavior may have a negative impact on\nthe project or its community.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at <opensource-conduct@fb.com>. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to ImageBind\nWe want to make contributing to this project as easy and transparent as\npossible.\n\n## Pull Requests\nWe actively welcome your pull requests.\n\n1. Fork the repo and create your branch from `main`.\n2. If you've added code that should be tested, add tests.\n3. If you've changed APIs, update the documentation.\n4. Ensure the test suite passes.\n5. Make sure your code lints.\n6. If you haven't already, complete the Contributor License Agreement (\"CLA\").\n\n## Contributor License Agreement (\"CLA\")\nIn order to accept your pull request, we need you to submit a CLA. You only need\nto do this once to work on any of Meta's open source projects.\n\nComplete your CLA here: <https://code.facebook.com/cla>\n\n## Issues\nWe use GitHub issues to track public bugs. Please ensure your description is\nclear and has sufficient instructions to be able to reproduce the issue.\n\nMeta has a [bounty program](https://www.facebook.com/whitehat/) for the safe\ndisclosure of security bugs. In those cases, please go through the process\noutlined on that page and do not file a public issue.\n\n## License\nBy contributing to Omnivore, you agree that your contributions will be licensed\nunder the [LICENSE](LICENSE) file in the root directory of this source tree.\n"
  },
  {
    "path": "LICENSE",
    "content": "Attribution-NonCommercial-ShareAlike 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n    wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More considerations\n     for the public:\n    wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International\nPublic License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution-NonCommercial-ShareAlike 4.0 International Public License\n(\"Public License\"). To the extent this Public License may be\ninterpreted as a contract, You are granted the Licensed Rights in\nconsideration of Your acceptance of these terms and conditions, and the\nLicensor grants You such rights in consideration of benefits the\nLicensor receives from making the Licensed Material available under\nthese terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. BY-NC-SA Compatible License means a license listed at\n     creativecommons.org/compatiblelicenses, approved by Creative\n     Commons as essentially the equivalent of this Public License.\n\n  d. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  e. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  f. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  g. License Elements means the license attributes listed in the name\n     of a Creative Commons Public License. The License Elements of this\n     Public License are Attribution, NonCommercial, and ShareAlike.\n\n  h. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  i. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  j. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  k. NonCommercial means not primarily intended for or directed towards\n     commercial advantage or monetary compensation. For purposes of\n     this Public License, the exchange of the Licensed Material for\n     other material subject to Copyright and Similar Rights by digital\n     file-sharing or similar means is NonCommercial provided there is\n     no payment of monetary compensation in connection with the\n     exchange.\n\n  l. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  m. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  n. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part, for NonCommercial purposes only; and\n\n            b. produce, reproduce, and Share Adapted Material for\n               NonCommercial purposes only.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. Additional offer from the Licensor -- Adapted Material.\n               Every recipient of Adapted Material from You\n               automatically receives an offer from the Licensor to\n               exercise the Licensed Rights in the Adapted Material\n               under the conditions of the Adapter's License You apply.\n\n            c. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties, including when\n          the Licensed Material is used other than for NonCommercial\n          purposes.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n  b. ShareAlike.\n\n     In addition to the conditions in Section 3(a), if You Share\n     Adapted Material You produce, the following conditions also apply.\n\n       1. The Adapter's License You apply must be a Creative Commons\n          license with the same License Elements, this version or\n          later, or a BY-NC-SA Compatible License.\n\n       2. You must include the text of, or the URI or hyperlink to, the\n          Adapter's License You apply. You may satisfy this condition\n          in any reasonable manner based on the medium, means, and\n          context in which You Share Adapted Material.\n\n       3. You may not offer or impose any additional or different terms\n          or conditions on, or apply any Effective Technological\n          Measures to, Adapted Material that restrict exercise of the\n          rights granted under the Adapter's License You apply.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database for NonCommercial purposes\n     only;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material,\n     including for purposes of Section 3(b); and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org."
  },
  {
    "path": "README.md",
    "content": "# ImageBind: One Embedding Space To Bind Them All\n\n**[FAIR, Meta AI](https://ai.facebook.com/research/)** \n\nRohit Girdhar*,\nAlaaeldin El-Nouby*,\nZhuang Liu,\nMannat Singh,\nKalyan Vasudev Alwala,\nArmand Joulin,\nIshan Misra*\n\nTo appear at CVPR 2023 (*Highlighted paper*)\n\n[[`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)]\n\nPyTorch 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)**.\n\nImageBind 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.\n\n\n\n![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)\n\n## ImageBind model\n\nEmergent zero-shot classification performance.\n\n<table style=\"margin: auto\">\n  <tr>\n    <th>Model</th>\n    <th><span style=\"color:blue\">IN1k</span></th>\n    <th><span style=\"color:purple\">K400</span></th>\n    <th><span style=\"color:green\">NYU-D</span></th>\n    <th><span style=\"color:LightBlue\">ESC</span></th>\n    <th><span style=\"color:orange\">LLVIP</span></th>\n    <th><span style=\"color:purple\">Ego4D</span></th>\n    <th>download</th>\n  </tr>\n  <tr>\n    <td>imagebind_huge</td>\n    <td align=\"right\">77.7</td>\n    <td align=\"right\">50.0</td>\n    <td align=\"right\">54.0</td>\n    <td align=\"right\">66.9</td>\n    <td align=\"right\">63.4</td>\n    <td align=\"right\">25.0</td>\n    <td><a href=\"https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth\">checkpoint</a></td>\n  </tr>\n  \n</table>\n\n## Usage\n\nInstall pytorch 2.0+ and other 3rd party dependencies.\n\n```shell\nconda create --name imagebind python=3.10 -y\nconda activate imagebind\n\npip install .\n```\n\nFor windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)\n\n```\npip install soundfile\n```\n\n\nExtract and compare features across modalities (e.g. Image, Text and Audio).\n\n```python\nfrom imagebind import data\nimport torch\nfrom imagebind.models import imagebind_model\nfrom imagebind.models.imagebind_model import ModalityType\n\ntext_list=[\"A dog.\", \"A car\", \"A bird\"]\nimage_paths=[\".assets/dog_image.jpg\", \".assets/car_image.jpg\", \".assets/bird_image.jpg\"]\naudio_paths=[\".assets/dog_audio.wav\", \".assets/car_audio.wav\", \".assets/bird_audio.wav\"]\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n\n# Instantiate model\nmodel = imagebind_model.imagebind_huge(pretrained=True)\nmodel.eval()\nmodel.to(device)\n\n# Load data\ninputs = {\n    ModalityType.TEXT: data.load_and_transform_text(text_list, device),\n    ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),\n    ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),\n}\n\nwith torch.no_grad():\n    embeddings = model(inputs)\n\nprint(\n    \"Vision x Text: \",\n    torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),\n)\nprint(\n    \"Audio x Text: \",\n    torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),\n)\nprint(\n    \"Vision x Audio: \",\n    torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),\n)\n\n# Expected output:\n#\n# Vision x Text:\n# tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],\n#         [3.3836e-05, 9.9994e-01, 2.4118e-05],\n#         [4.7997e-05, 1.3496e-02, 9.8646e-01]])\n#\n# Audio x Text:\n# tensor([[1., 0., 0.],\n#         [0., 1., 0.],\n#         [0., 0., 1.]])\n#\n# Vision x Audio:\n# tensor([[0.8070, 0.1088, 0.0842],\n#         [0.1036, 0.7884, 0.1079],\n#         [0.0018, 0.0022, 0.9960]])\n\n```\n\n## Model card\nPlease see the [model card](model_card.md) for details.\n\n## License\n\nImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.\n\n## Contributing\n\nSee [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).\n\n## Citing ImageBind\n\nIf you find this repository useful, please consider giving a star :star: and citation\n\n```\n@inproceedings{girdhar2023imagebind,\n  title={ImageBind: One Embedding Space To Bind Them All},\n  author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang\nand Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},\n  booktitle={CVPR},\n  year={2023}\n}\n```\n"
  },
  {
    "path": "imagebind/__init__.py",
    "content": "from imagebind import data\nfrom imagebind.models import imagebind_model\nfrom imagebind.models.imagebind_model import ModalityType"
  },
  {
    "path": "imagebind/data.py",
    "content": "#!/usr/bin/env python3\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\nimport math\nimport pkg_resources\n\nimport torch\nimport torch.nn as nn\nimport torchaudio\nfrom PIL import Image\nfrom pytorchvideo import transforms as pv_transforms\nfrom pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler\nfrom pytorchvideo.data.encoded_video import EncodedVideo\nfrom torchvision import transforms\n\nfrom imagebind.models.multimodal_preprocessors import SimpleTokenizer\n\nDEFAULT_AUDIO_FRAME_SHIFT_MS = 10  # in milliseconds\n\n\ndef return_bpe_path():\n    return pkg_resources.resource_filename(\n        \"imagebind\", \"bpe/bpe_simple_vocab_16e6.txt.gz\"\n    )\n\n\ndef waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):\n    # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102\n    waveform -= waveform.mean()\n    fbank = torchaudio.compliance.kaldi.fbank(\n        waveform,\n        htk_compat=True,\n        sample_frequency=sample_rate,\n        use_energy=False,\n        window_type=\"hanning\",\n        num_mel_bins=num_mel_bins,\n        dither=0.0,\n        frame_length=25,\n        frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,\n    )\n    # Convert to [mel_bins, num_frames] shape\n    fbank = fbank.transpose(0, 1)\n    # Pad to target_length\n    n_frames = fbank.size(1)\n    p = target_length - n_frames\n    # if p is too large (say >20%), flash a warning\n    if abs(p) / n_frames > 0.2:\n        logging.warning(\n            \"Large gap between audio n_frames(%d) and \"\n            \"target_length (%d). Is the audio_target_length \"\n            \"setting correct?\",\n            n_frames,\n            target_length,\n        )\n    # cut and pad\n    if p > 0:\n        fbank = torch.nn.functional.pad(fbank, (0, p), mode=\"constant\", value=0)\n    elif p < 0:\n        fbank = fbank[:, 0:target_length]\n    # Convert to [1, mel_bins, num_frames] shape, essentially like a 1\n    # channel image\n    fbank = fbank.unsqueeze(0)\n    return fbank\n\n\ndef get_clip_timepoints(clip_sampler, duration):\n    # Read out all clips in this video\n    all_clips_timepoints = []\n    is_last_clip = False\n    end = 0.0\n    while not is_last_clip:\n        start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)\n        all_clips_timepoints.append((start, end))\n    return all_clips_timepoints\n\n\ndef load_and_transform_vision_data(image_paths, device):\n    if image_paths is None:\n        return None\n\n    image_outputs = []\n\n    data_transform = transforms.Compose(\n        [\n            transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),\n            transforms.CenterCrop(224),\n            transforms.ToTensor(),\n            transforms.Normalize(\n                mean=(0.48145466, 0.4578275, 0.40821073),\n                std=(0.26862954, 0.26130258, 0.27577711),\n            ),\n        ]\n    )\n\n    for image_path in image_paths:\n        with open(image_path, \"rb\") as fopen:\n            image = Image.open(fopen).convert(\"RGB\")\n\n        image = data_transform(image).to(device)\n        image_outputs.append(image)\n    return torch.stack(image_outputs, dim=0)\n\n\ndef load_and_transform_text(text, device):\n    if text is None:\n        return None\n    tokenizer = SimpleTokenizer(bpe_path=return_bpe_path())\n    tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]\n    tokens = torch.cat(tokens, dim=0)\n    return tokens\n\n\ndef load_and_transform_audio_data(\n    audio_paths,\n    device,\n    num_mel_bins=128,\n    target_length=204,\n    sample_rate=16000,\n    clip_duration=2,\n    clips_per_video=3,\n    mean=-4.268,\n    std=9.138,\n):\n    if audio_paths is None:\n        return None\n\n    audio_outputs = []\n    clip_sampler = ConstantClipsPerVideoSampler(\n        clip_duration=clip_duration, clips_per_video=clips_per_video\n    )\n\n    for audio_path in audio_paths:\n        waveform, sr = torchaudio.load(audio_path)\n        if sample_rate != sr:\n            waveform = torchaudio.functional.resample(\n                waveform, orig_freq=sr, new_freq=sample_rate\n            )\n        all_clips_timepoints = get_clip_timepoints(\n            clip_sampler, waveform.size(1) / sample_rate\n        )\n        all_clips = []\n        for clip_timepoints in all_clips_timepoints:\n            waveform_clip = waveform[\n                :,\n                int(clip_timepoints[0] * sample_rate) : int(\n                    clip_timepoints[1] * sample_rate\n                ),\n            ]\n            waveform_melspec = waveform2melspec(\n                waveform_clip, sample_rate, num_mel_bins, target_length\n            )\n            all_clips.append(waveform_melspec)\n\n        normalize = transforms.Normalize(mean=mean, std=std)\n        all_clips = [normalize(ac).to(device) for ac in all_clips]\n\n        all_clips = torch.stack(all_clips, dim=0)\n        audio_outputs.append(all_clips)\n\n    return torch.stack(audio_outputs, dim=0)\n\n\ndef crop_boxes(boxes, x_offset, y_offset):\n    \"\"\"\n    Perform crop on the bounding boxes given the offsets.\n    Args:\n        boxes (ndarray or None): bounding boxes to perform crop. The dimension\n            is `num boxes` x 4.\n        x_offset (int): cropping offset in the x axis.\n        y_offset (int): cropping offset in the y axis.\n    Returns:\n        cropped_boxes (ndarray or None): the cropped boxes with dimension of\n            `num boxes` x 4.\n    \"\"\"\n    cropped_boxes = boxes.copy()\n    cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset\n    cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset\n\n    return cropped_boxes\n\n\ndef uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):\n    \"\"\"\n    Perform uniform spatial sampling on the images and corresponding boxes.\n    Args:\n        images (tensor): images to perform uniform crop. The dimension is\n            `num frames` x `channel` x `height` x `width`.\n        size (int): size of height and weight to crop the images.\n        spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width\n            is larger than height. Or 0, 1, or 2 for top, center, and bottom\n            crop if height is larger than width.\n        boxes (ndarray or None): optional. Corresponding boxes to images.\n            Dimension is `num boxes` x 4.\n        scale_size (int): optinal. If not None, resize the images to scale_size before\n            performing any crop.\n    Returns:\n        cropped (tensor): images with dimension of\n            `num frames` x `channel` x `size` x `size`.\n        cropped_boxes (ndarray or None): the cropped boxes with dimension of\n            `num boxes` x 4.\n    \"\"\"\n    assert spatial_idx in [0, 1, 2]\n    ndim = len(images.shape)\n    if ndim == 3:\n        images = images.unsqueeze(0)\n    height = images.shape[2]\n    width = images.shape[3]\n\n    if scale_size is not None:\n        if width <= height:\n            width, height = scale_size, int(height / width * scale_size)\n        else:\n            width, height = int(width / height * scale_size), scale_size\n        images = torch.nn.functional.interpolate(\n            images,\n            size=(height, width),\n            mode=\"bilinear\",\n            align_corners=False,\n        )\n\n    y_offset = int(math.ceil((height - size) / 2))\n    x_offset = int(math.ceil((width - size) / 2))\n\n    if height > width:\n        if spatial_idx == 0:\n            y_offset = 0\n        elif spatial_idx == 2:\n            y_offset = height - size\n    else:\n        if spatial_idx == 0:\n            x_offset = 0\n        elif spatial_idx == 2:\n            x_offset = width - size\n    cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]\n    cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None\n    if ndim == 3:\n        cropped = cropped.squeeze(0)\n    return cropped, cropped_boxes\n\n\nclass SpatialCrop(nn.Module):\n    \"\"\"\n    Convert the video into 3 smaller clips spatially. Must be used after the\n        temporal crops to get spatial crops, and should be used with\n        -2 in the spatial crop at the slowfast augmentation stage (so full\n        frames are passed in here). Will return a larger list with the\n        3x spatial crops as well.\n    \"\"\"\n\n    def __init__(self, crop_size: int = 224, num_crops: int = 3):\n        super().__init__()\n        self.crop_size = crop_size\n        if num_crops == 3:\n            self.crops_to_ext = [0, 1, 2]\n            self.flipped_crops_to_ext = []\n        elif num_crops == 1:\n            self.crops_to_ext = [1]\n            self.flipped_crops_to_ext = []\n        else:\n            raise NotImplementedError(\"Nothing else supported yet\")\n\n    def forward(self, videos):\n        \"\"\"\n        Args:\n            videos: A list of C, T, H, W videos.\n        Returns:\n            videos: A list with 3x the number of elements. Each video converted\n                to C, T, H', W' by spatial cropping.\n        \"\"\"\n        assert isinstance(videos, list), \"Must be a list of videos after temporal crops\"\n        assert all([video.ndim == 4 for video in videos]), \"Must be (C,T,H,W)\"\n        res = []\n        for video in videos:\n            for spatial_idx in self.crops_to_ext:\n                res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])\n            if not self.flipped_crops_to_ext:\n                continue\n            flipped_video = transforms.functional.hflip(video)\n            for spatial_idx in self.flipped_crops_to_ext:\n                res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])\n        return res\n\n\nclass NormalizeVideo:\n    def __init__(self, mean, std, inplace=False):\n        self.mean = mean\n        self.std = std\n        self.inplace = inplace\n\n    def __call__(self, clip):\n        if not self.inplace:\n            clip = clip.clone()\n        mean = torch.as_tensor(self.mean, dtype=clip.dtype, device=clip.device)\n        std = torch.as_tensor(self.std, dtype=clip.dtype, device=clip.device)\n        clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])\n        return clip\n\n\ndef load_and_transform_video_data(\n    video_paths,\n    device,\n    clip_duration=2,\n    clips_per_video=5,\n    sample_rate=16000,\n):\n    if video_paths is None:\n        return None\n\n    video_outputs = []\n    video_transform = transforms.Compose(\n        [\n            pv_transforms.ShortSideScale(224),\n            NormalizeVideo(\n                mean=(0.48145466, 0.4578275, 0.40821073),\n                std=(0.26862954, 0.26130258, 0.27577711),\n            ),\n        ]\n    )\n\n    clip_sampler = ConstantClipsPerVideoSampler(\n        clip_duration=clip_duration, clips_per_video=clips_per_video\n    )\n    frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)\n\n    for video_path in video_paths:\n        video = EncodedVideo.from_path(\n            video_path,\n            decoder=\"decord\",\n            decode_audio=False,\n            **{\"sample_rate\": sample_rate},\n        )\n\n        all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)\n\n        all_video = []\n        for clip_timepoints in all_clips_timepoints:\n            # Read the clip, get frames\n            clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])\n            if clip is None:\n                raise ValueError(\"No clip found\")\n            video_clip = frame_sampler(clip[\"video\"])\n            video_clip = video_clip / 255.0  # since this is float, need 0-1\n\n            all_video.append(video_clip)\n\n        all_video = [video_transform(clip) for clip in all_video]\n        all_video = SpatialCrop(224, num_crops=3)(all_video)\n\n        all_video = torch.stack(all_video, dim=0)\n        video_outputs.append(all_video)\n\n    return torch.stack(video_outputs, dim=0).to(device)\n"
  },
  {
    "path": "imagebind/models/__init__.py",
    "content": ""
  },
  {
    "path": "imagebind/models/helpers.py",
    "content": "#!/usr/bin/env python3\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nimport einops\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\n\nclass Normalize(nn.Module):\n    def __init__(self, dim: int) -> None:\n        super().__init__()\n        self.dim = dim\n\n    def forward(self, x):\n        return torch.nn.functional.normalize(x, dim=self.dim, p=2)\n\n\nclass LearnableLogitScaling(nn.Module):\n    def __init__(\n        self,\n        logit_scale_init: float = 1 / 0.07,\n        learnable: bool = True,\n        max_logit_scale: float = 100,\n    ) -> None:\n        super().__init__()\n        self.max_logit_scale = max_logit_scale\n        self.logit_scale_init = logit_scale_init\n        self.learnable = learnable\n        log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)\n        if learnable:\n            self.log_logit_scale = nn.Parameter(log_logit_scale)\n        else:\n            self.register_buffer(\"log_logit_scale\", log_logit_scale)\n\n    def forward(self, x):\n        return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x\n\n    def extra_repr(self):\n        st = f\"logit_scale_init={self.logit_scale_init},learnable={self.learnable},\" \\\n             f\" max_logit_scale={self.max_logit_scale}\"\n        return st\n\n\nclass EinOpsRearrange(nn.Module):\n    def __init__(self, rearrange_expr: str, **kwargs) -> None:\n        super().__init__()\n        self.rearrange_expr = rearrange_expr\n        self.kwargs = kwargs\n\n    def forward(self, x):\n        assert isinstance(x, torch.Tensor)\n        return einops.rearrange(x, self.rearrange_expr, **self.kwargs)\n\n\nclass VerboseNNModule(nn.Module):\n    \"\"\"\n    Wrapper around nn.Module that prints registered buffers and parameter names.\n    \"\"\"\n\n    @staticmethod\n    def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:\n        st = (\n            \"(\"\n            + name\n            + \"): \"\n            + \"tensor(\"\n            + str(tuple(tensor[1].shape))\n            + \", requires_grad=\"\n            + str(tensor[1].requires_grad)\n            + \")\\n\"\n        )\n        return st\n\n    def extra_repr(self) -> str:\n        named_modules = set()\n        for p in self.named_modules():\n            named_modules.update([p[0]])\n        named_modules = list(named_modules)\n\n        string_repr = \"\"\n        for p in self.named_parameters():\n            name = p[0].split(\".\")[0]\n            if name not in named_modules:\n                string_repr += self.get_readable_tensor_repr(name, p)\n\n        for p in self.named_buffers():\n            name = p[0].split(\".\")[0]\n            string_repr += self.get_readable_tensor_repr(name, p)\n\n        return string_repr\n\n\ndef cast_if_src_dtype(\n    tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype\n):\n    updated = False\n    if tensor.dtype == src_dtype:\n        tensor = tensor.to(dtype=tgt_dtype)\n        updated = True\n    return tensor, updated\n\n\nclass QuickGELU(nn.Module):\n    # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166\n    def forward(self, x: torch.Tensor):\n        return x * torch.sigmoid(1.702 * x)\n\n\nclass SelectElement(nn.Module):\n    def __init__(self, index) -> None:\n        super().__init__()\n        self.index = index\n\n    def forward(self, x):\n        assert x.ndim >= 3\n        return x[:, self.index, ...]\n\n\nclass SelectEOSAndProject(nn.Module):\n    \"\"\"\n    Text Pooling used in OpenCLIP\n    \"\"\"\n\n    def __init__(self, proj: nn.Module) -> None:\n        super().__init__()\n        self.proj = proj\n\n    def forward(self, x, seq_len):\n        assert x.ndim == 3\n        # x is of shape B x L x D\n        # take features from the eot embedding (eot_token is the highest number in each sequence)\n        x = x[torch.arange(x.shape[0]), seq_len]\n        x = self.proj(x)\n        return x\n"
  },
  {
    "path": "imagebind/models/imagebind_model.py",
    "content": "#!/usr/bin/env python3\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nimport os\nfrom functools import partial\nfrom types import SimpleNamespace\n\nimport torch\nimport torch.nn as nn\n\nfrom imagebind.models.helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize,\n                            SelectElement, SelectEOSAndProject)\nfrom imagebind.models.multimodal_preprocessors import (AudioPreprocessor,\n                                             IMUPreprocessor, PadIm2Video,\n                                             PatchEmbedGeneric,\n                                             RGBDTPreprocessor,\n                                             SpatioTemporalPosEmbeddingHelper,\n                                             TextPreprocessor,\n                                             ThermalPreprocessor)\nfrom imagebind.models.transformer import MultiheadAttention, SimpleTransformer\n\nModalityType = SimpleNamespace(\n    VISION=\"vision\",\n    TEXT=\"text\",\n    AUDIO=\"audio\",\n    THERMAL=\"thermal\",\n    DEPTH=\"depth\",\n    IMU=\"imu\",\n)\n\n\nclass ImageBindModel(nn.Module):\n    def __init__(\n        self,\n        video_frames=2,\n        kernel_size=(2, 14, 14),\n        audio_kernel_size=16,\n        audio_stride=10,\n        out_embed_dim=768,\n        vision_embed_dim=1024,\n        vision_num_blocks=24,\n        vision_num_heads=16,\n        audio_embed_dim=768,\n        audio_num_blocks=12,\n        audio_num_heads=12,\n        audio_num_mel_bins=128,\n        audio_target_len=204,\n        audio_drop_path=0.1,\n        text_embed_dim=768,\n        text_num_blocks=12,\n        text_num_heads=12,\n        depth_embed_dim=384,\n        depth_kernel_size=16,\n        depth_num_blocks=12,\n        depth_num_heads=8,\n        depth_drop_path=0.0,\n        thermal_embed_dim=768,\n        thermal_kernel_size=16,\n        thermal_num_blocks=12,\n        thermal_num_heads=12,\n        thermal_drop_path=0.0,\n        imu_embed_dim=512,\n        imu_kernel_size=8,\n        imu_num_blocks=6,\n        imu_num_heads=8,\n        imu_drop_path=0.7,\n    ):\n        super().__init__()\n\n        self.modality_preprocessors = self._create_modality_preprocessors(\n            video_frames,\n            vision_embed_dim,\n            kernel_size,\n            text_embed_dim,\n            audio_embed_dim,\n            audio_kernel_size,\n            audio_stride,\n            audio_num_mel_bins,\n            audio_target_len,\n            depth_embed_dim,\n            depth_kernel_size,\n            thermal_embed_dim,\n            thermal_kernel_size,\n            imu_embed_dim,\n        )\n\n        self.modality_trunks = self._create_modality_trunks(\n            vision_embed_dim,\n            vision_num_blocks,\n            vision_num_heads,\n            text_embed_dim,\n            text_num_blocks,\n            text_num_heads,\n            audio_embed_dim,\n            audio_num_blocks,\n            audio_num_heads,\n            audio_drop_path,\n            depth_embed_dim,\n            depth_num_blocks,\n            depth_num_heads,\n            depth_drop_path,\n            thermal_embed_dim,\n            thermal_num_blocks,\n            thermal_num_heads,\n            thermal_drop_path,\n            imu_embed_dim,\n            imu_num_blocks,\n            imu_num_heads,\n            imu_drop_path,\n        )\n\n        self.modality_heads = self._create_modality_heads(\n            out_embed_dim,\n            vision_embed_dim,\n            text_embed_dim,\n            audio_embed_dim,\n            depth_embed_dim,\n            thermal_embed_dim,\n            imu_embed_dim,\n        )\n\n        self.modality_postprocessors = self._create_modality_postprocessors(\n            out_embed_dim\n        )\n\n    def _create_modality_preprocessors(\n        self,\n        video_frames=2,\n        vision_embed_dim=1024,\n        kernel_size=(2, 14, 14),\n        text_embed_dim=768,\n        audio_embed_dim=768,\n        audio_kernel_size=16,\n        audio_stride=10,\n        audio_num_mel_bins=128,\n        audio_target_len=204,\n        depth_embed_dim=768,\n        depth_kernel_size=16,\n        thermal_embed_dim=768,\n        thermal_kernel_size=16,\n        imu_embed_dim=512,\n    ):\n        rgbt_stem = PatchEmbedGeneric(\n            proj_stem=[\n                PadIm2Video(pad_type=\"repeat\", ntimes=2),\n                nn.Conv3d(\n                    in_channels=3,\n                    kernel_size=kernel_size,\n                    out_channels=vision_embed_dim,\n                    stride=kernel_size,\n                    bias=False,\n                ),\n            ]\n        )\n        rgbt_preprocessor = RGBDTPreprocessor(\n            img_size=[3, video_frames, 224, 224],\n            num_cls_tokens=1,\n            pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),\n            rgbt_stem=rgbt_stem,\n            depth_stem=None,\n        )\n\n        text_preprocessor = TextPreprocessor(\n            context_length=77,\n            vocab_size=49408,\n            embed_dim=text_embed_dim,\n            causal_masking=True,\n        )\n\n        audio_stem = PatchEmbedGeneric(\n            proj_stem=[\n                nn.Conv2d(\n                    in_channels=1,\n                    kernel_size=audio_kernel_size,\n                    stride=audio_stride,\n                    out_channels=audio_embed_dim,\n                    bias=False,\n                ),\n            ],\n            norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),\n        )\n        audio_preprocessor = AudioPreprocessor(\n            img_size=[1, audio_num_mel_bins, audio_target_len],\n            num_cls_tokens=1,\n            pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),\n            audio_stem=audio_stem,\n        )\n\n        depth_stem = PatchEmbedGeneric(\n            [\n                nn.Conv2d(\n                    kernel_size=depth_kernel_size,\n                    in_channels=1,\n                    out_channels=depth_embed_dim,\n                    stride=depth_kernel_size,\n                    bias=False,\n                ),\n            ],\n            norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),\n        )\n\n        depth_preprocessor = RGBDTPreprocessor(\n            img_size=[1, 224, 224],\n            num_cls_tokens=1,\n            pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),\n            rgbt_stem=None,\n            depth_stem=depth_stem,\n        )\n\n        thermal_stem = PatchEmbedGeneric(\n            [\n                nn.Conv2d(\n                    kernel_size=thermal_kernel_size,\n                    in_channels=1,\n                    out_channels=thermal_embed_dim,\n                    stride=thermal_kernel_size,\n                    bias=False,\n                ),\n            ],\n            norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),\n        )\n        thermal_preprocessor = ThermalPreprocessor(\n            img_size=[1, 224, 224],\n            num_cls_tokens=1,\n            pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),\n            thermal_stem=thermal_stem,\n        )\n\n        imu_stem = PatchEmbedGeneric(\n            [\n                nn.Linear(\n                    in_features=48,\n                    out_features=imu_embed_dim,\n                    bias=False,\n                ),\n            ],\n            norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),\n        )\n\n        imu_preprocessor = IMUPreprocessor(\n            img_size=[6, 2000],\n            num_cls_tokens=1,\n            kernel_size=8,\n            embed_dim=imu_embed_dim,\n            pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),\n            imu_stem=imu_stem,\n        )\n\n        modality_preprocessors = {\n            ModalityType.VISION: rgbt_preprocessor,\n            ModalityType.TEXT: text_preprocessor,\n            ModalityType.AUDIO: audio_preprocessor,\n            ModalityType.DEPTH: depth_preprocessor,\n            ModalityType.THERMAL: thermal_preprocessor,\n            ModalityType.IMU: imu_preprocessor,\n        }\n\n        return nn.ModuleDict(modality_preprocessors)\n\n    def _create_modality_trunks(\n        self,\n        vision_embed_dim=1024,\n        vision_num_blocks=24,\n        vision_num_heads=16,\n        text_embed_dim=768,\n        text_num_blocks=12,\n        text_num_heads=12,\n        audio_embed_dim=768,\n        audio_num_blocks=12,\n        audio_num_heads=12,\n        audio_drop_path=0.0,\n        depth_embed_dim=768,\n        depth_num_blocks=12,\n        depth_num_heads=12,\n        depth_drop_path=0.0,\n        thermal_embed_dim=768,\n        thermal_num_blocks=12,\n        thermal_num_heads=12,\n        thermal_drop_path=0.0,\n        imu_embed_dim=512,\n        imu_num_blocks=6,\n        imu_num_heads=8,\n        imu_drop_path=0.7,\n    ):\n        def instantiate_trunk(\n            embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path\n        ):\n            return SimpleTransformer(\n                embed_dim=embed_dim,\n                num_blocks=num_blocks,\n                ffn_dropout_rate=0.0,\n                drop_path_rate=drop_path,\n                attn_target=partial(\n                    MultiheadAttention,\n                    embed_dim=embed_dim,\n                    num_heads=num_heads,\n                    bias=True,\n                    add_bias_kv=add_bias_kv,\n                ),\n                pre_transformer_layer=nn.Sequential(\n                    nn.LayerNorm(embed_dim, eps=1e-6)\n                    if pre_transformer_ln\n                    else nn.Identity(),\n                    EinOpsRearrange(\"b l d -> l b d\"),\n                ),\n                post_transformer_layer=EinOpsRearrange(\"l b d -> b l d\"),\n            )\n\n        modality_trunks = {}\n        modality_trunks[ModalityType.VISION] = instantiate_trunk(\n            vision_embed_dim,\n            vision_num_blocks,\n            vision_num_heads,\n            pre_transformer_ln=True,\n            add_bias_kv=False,\n            drop_path=0.0,\n        )\n        modality_trunks[ModalityType.TEXT] = instantiate_trunk(\n            text_embed_dim,\n            text_num_blocks,\n            text_num_heads,\n            pre_transformer_ln=False,\n            add_bias_kv=False,\n            drop_path=0.0,\n        )\n        modality_trunks[ModalityType.AUDIO] = instantiate_trunk(\n            audio_embed_dim,\n            audio_num_blocks,\n            audio_num_heads,\n            pre_transformer_ln=False,\n            add_bias_kv=True,\n            drop_path=audio_drop_path,\n        )\n        modality_trunks[ModalityType.DEPTH] = instantiate_trunk(\n            depth_embed_dim,\n            depth_num_blocks,\n            depth_num_heads,\n            pre_transformer_ln=False,\n            add_bias_kv=True,\n            drop_path=depth_drop_path,\n        )\n        modality_trunks[ModalityType.THERMAL] = instantiate_trunk(\n            thermal_embed_dim,\n            thermal_num_blocks,\n            thermal_num_heads,\n            pre_transformer_ln=False,\n            add_bias_kv=True,\n            drop_path=thermal_drop_path,\n        )\n        modality_trunks[ModalityType.IMU] = instantiate_trunk(\n            imu_embed_dim,\n            imu_num_blocks,\n            imu_num_heads,\n            pre_transformer_ln=False,\n            add_bias_kv=True,\n            drop_path=imu_drop_path,\n        )\n\n        return nn.ModuleDict(modality_trunks)\n\n    def _create_modality_heads(\n        self,\n        out_embed_dim,\n        vision_embed_dim,\n        text_embed_dim,\n        audio_embed_dim,\n        depth_embed_dim,\n        thermal_embed_dim,\n        imu_embed_dim,\n    ):\n        modality_heads = {}\n\n        modality_heads[ModalityType.VISION] = nn.Sequential(\n            nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),\n            SelectElement(index=0),\n            nn.Linear(vision_embed_dim, out_embed_dim, bias=False),\n        )\n\n        modality_heads[ModalityType.TEXT] = SelectEOSAndProject(\n            proj=nn.Sequential(\n                nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),\n                nn.Linear(text_embed_dim, out_embed_dim, bias=False),\n            )\n        )\n\n        modality_heads[ModalityType.AUDIO] = nn.Sequential(\n            nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),\n            SelectElement(index=0),\n            nn.Linear(audio_embed_dim, out_embed_dim, bias=False),\n        )\n\n        modality_heads[ModalityType.DEPTH] = nn.Sequential(\n            nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),\n            SelectElement(index=0),\n            nn.Linear(depth_embed_dim, out_embed_dim, bias=False),\n        )\n\n        modality_heads[ModalityType.THERMAL] = nn.Sequential(\n            nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),\n            SelectElement(index=0),\n            nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),\n        )\n\n        modality_heads[ModalityType.IMU] = nn.Sequential(\n            nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),\n            SelectElement(index=0),\n            nn.Dropout(p=0.5),\n            nn.Linear(imu_embed_dim, out_embed_dim, bias=False),\n        )\n\n        return nn.ModuleDict(modality_heads)\n\n    def _create_modality_postprocessors(self, out_embed_dim):\n        modality_postprocessors = {}\n\n        modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)\n        modality_postprocessors[ModalityType.TEXT] = nn.Sequential(\n            Normalize(dim=-1), LearnableLogitScaling(learnable=True)\n        )\n        modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(\n            Normalize(dim=-1),\n            LearnableLogitScaling(logit_scale_init=20.0, learnable=False),\n        )\n        modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(\n            Normalize(dim=-1),\n            LearnableLogitScaling(logit_scale_init=5.0, learnable=False),\n        )\n        modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(\n            Normalize(dim=-1),\n            LearnableLogitScaling(logit_scale_init=10.0, learnable=False),\n        )\n        modality_postprocessors[ModalityType.IMU] = nn.Sequential(\n            Normalize(dim=-1),\n            LearnableLogitScaling(logit_scale_init=5.0, learnable=False),\n        )\n\n        return nn.ModuleDict(modality_postprocessors)\n\n    def forward(self, inputs):\n        outputs = {}\n        for modality_key, modality_value in inputs.items():\n            reduce_list = (\n                modality_value.ndim >= 5\n            )  # Audio and Video inputs consist of multiple clips\n            if reduce_list:\n                B, S = modality_value.shape[:2]\n                modality_value = modality_value.reshape(\n                    B * S, *modality_value.shape[2:]\n                )\n\n            if modality_value is not None:\n                modality_value = self.modality_preprocessors[modality_key](\n                    **{modality_key: modality_value}\n                )\n                trunk_inputs = modality_value[\"trunk\"]\n                head_inputs = modality_value[\"head\"]\n                modality_value = self.modality_trunks[modality_key](**trunk_inputs)\n                modality_value = self.modality_heads[modality_key](\n                    modality_value, **head_inputs\n                )\n                modality_value = self.modality_postprocessors[modality_key](\n                    modality_value\n                )\n\n                if reduce_list:\n                    modality_value = modality_value.reshape(B, S, -1)\n                    modality_value = modality_value.mean(dim=1)\n\n                outputs[modality_key] = modality_value\n\n        return outputs\n\n\ndef imagebind_huge(pretrained=False):\n    model = ImageBindModel(\n        vision_embed_dim=1280,\n        vision_num_blocks=32,\n        vision_num_heads=16,\n        text_embed_dim=1024,\n        text_num_blocks=24,\n        text_num_heads=16,\n        out_embed_dim=1024,\n        audio_drop_path=0.1,\n        imu_drop_path=0.7,\n    )\n\n    if pretrained:\n        if not os.path.exists(\".checkpoints/imagebind_huge.pth\"):\n            print(\n                \"Downloading imagebind weights to .checkpoints/imagebind_huge.pth ...\"\n            )\n            os.makedirs(\".checkpoints\", exist_ok=True)\n            torch.hub.download_url_to_file(\n                \"https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth\",\n                \".checkpoints/imagebind_huge.pth\",\n                progress=True,\n            )\n\n        model.load_state_dict(torch.load(\".checkpoints/imagebind_huge.pth\", weights_only=True))\n\n    return model\n"
  },
  {
    "path": "imagebind/models/multimodal_preprocessors.py",
    "content": "#!/usr/bin/env python3\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport gzip\nimport html\nimport io\nimport math\nfrom functools import lru_cache\nfrom typing import Callable, List, Optional, Tuple\n\nimport ftfy\nimport numpy as np\nimport regex as re\nimport torch\nimport torch.nn as nn\nfrom iopath.common.file_io import g_pathmgr\nfrom timm.layers import trunc_normal_\n\nfrom imagebind.models.helpers import VerboseNNModule, cast_if_src_dtype\n\n\ndef get_sinusoid_encoding_table(n_position, d_hid):\n    \"\"\"Sinusoid position encoding table\"\"\"\n\n    # TODO: make it with torch instead of numpy\n    def get_position_angle_vec(position):\n        return [\n            position / np.power(10000, 2 * (hid_j // 2) / d_hid)\n            for hid_j in range(d_hid)\n        ]\n\n    sinusoid_table = np.array(\n        [get_position_angle_vec(pos_i) for pos_i in range(n_position)]\n    )\n    sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2])  # dim 2i\n    sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2])  # dim 2i+1\n\n    return torch.FloatTensor(sinusoid_table).unsqueeze(0)\n\n\ndef interpolate_pos_encoding_2d(target_spatial_size, pos_embed):\n    N = pos_embed.shape[1]\n    if N == target_spatial_size:\n        return pos_embed\n    dim = pos_embed.shape[-1]\n    # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32\n    pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)\n    pos_embed = nn.functional.interpolate(\n        pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(\n            0, 3, 1, 2\n        ),\n        scale_factor=math.sqrt(target_spatial_size / N),\n        mode=\"bicubic\",\n    )\n    if updated:\n        pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)\n    pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)\n    return pos_embed\n\n\ndef interpolate_pos_encoding(\n    npatch_per_img,\n    pos_embed,\n    patches_layout,\n    input_shape=None,\n    first_patch_idx=1,\n):\n    assert first_patch_idx == 0 or first_patch_idx == 1, \"there is 1 CLS token or none\"\n    N = pos_embed.shape[1] - first_patch_idx  # since it's 1 if cls_token exists\n    if npatch_per_img == N:\n        return pos_embed\n\n    assert (\n        patches_layout[-1] == patches_layout[-2]\n    ), \"Interpolation of pos embed not supported for non-square layouts\"\n\n    class_emb = pos_embed[:, :first_patch_idx]\n    pos_embed = pos_embed[:, first_patch_idx:]\n\n    if input_shape is None or patches_layout[0] == 1:\n        # simple 2D pos embedding, no temporal component\n        pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)\n    elif patches_layout[0] > 1:\n        # pos embed has a temporal component\n        assert len(input_shape) == 4, \"temporal interpolation not supported\"\n        # we only support 2D interpolation in this case\n        num_frames = patches_layout[0]\n        num_spatial_tokens = patches_layout[1] * patches_layout[2]\n        pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)\n        # interpolate embedding for zeroth frame\n        pos_embed = interpolate_pos_encoding_2d(\n            npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)\n        )\n    else:\n        raise ValueError(\"This type of interpolation isn't implemented\")\n\n    return torch.cat((class_emb, pos_embed), dim=1)\n\n\ndef _get_pos_embedding(\n    npatch_per_img,\n    pos_embed,\n    patches_layout,\n    input_shape,\n    first_patch_idx=1,\n):\n    pos_embed = interpolate_pos_encoding(\n        npatch_per_img,\n        pos_embed,\n        patches_layout,\n        input_shape=input_shape,\n        first_patch_idx=first_patch_idx,\n    )\n    return pos_embed\n\n\nclass PatchEmbedGeneric(nn.Module):\n    \"\"\"\n    PatchEmbed from Hydra\n    \"\"\"\n\n    def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):\n        super().__init__()\n\n        if len(proj_stem) > 1:\n            self.proj = nn.Sequential(*proj_stem)\n        else:\n            # Special case to be able to load pre-trained models that were\n            # trained with a standard stem\n            self.proj = proj_stem[0]\n        self.norm_layer = norm_layer\n\n    def get_patch_layout(self, img_size):\n        with torch.no_grad():\n            dummy_img = torch.zeros(\n                [\n                    1,\n                ]\n                + img_size\n            )\n            dummy_out = self.proj(dummy_img)\n        embed_dim = dummy_out.shape[1]\n        patches_layout = tuple(dummy_out.shape[2:])\n        num_patches = np.prod(patches_layout)\n        return patches_layout, num_patches, embed_dim\n\n    def forward(self, x):\n        x = self.proj(x)\n        # B C (T) H W -> B (T)HW C\n        x = x.flatten(2).transpose(1, 2)\n        if self.norm_layer is not None:\n            x = self.norm_layer(x)\n        return x\n\n\nclass SpatioTemporalPosEmbeddingHelper(VerboseNNModule):\n    def __init__(\n        self,\n        patches_layout: List,\n        num_patches: int,\n        num_cls_tokens: int,\n        embed_dim: int,\n        learnable: bool,\n    ) -> None:\n        super().__init__()\n        self.num_cls_tokens = num_cls_tokens\n        self.patches_layout = patches_layout\n        self.num_patches = num_patches\n        self.num_tokens = num_cls_tokens + num_patches\n        self.learnable = learnable\n        if self.learnable:\n            self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))\n            trunc_normal_(self.pos_embed, std=0.02)\n        else:\n            self.register_buffer(\n                \"pos_embed\", get_sinusoid_encoding_table(self.num_tokens, embed_dim)\n            )\n\n    def get_pos_embedding(self, vision_input, all_vision_tokens):\n        input_shape = vision_input.shape\n        pos_embed = _get_pos_embedding(\n            all_vision_tokens.size(1) - self.num_cls_tokens,\n            pos_embed=self.pos_embed,\n            patches_layout=self.patches_layout,\n            input_shape=input_shape,\n            first_patch_idx=self.num_cls_tokens,\n        )\n        return pos_embed\n\n\nclass RGBDTPreprocessor(VerboseNNModule):\n    def __init__(\n        self,\n        rgbt_stem: PatchEmbedGeneric,\n        depth_stem: Optional[PatchEmbedGeneric],\n        img_size: Tuple = (3, 224, 224),\n        num_cls_tokens: int = 1,\n        pos_embed_fn: Optional[Callable] = None,\n        use_type_embed: bool = False,\n        init_param_style: str = \"openclip\",\n    ) -> None:\n        super().__init__()\n        stem = rgbt_stem if rgbt_stem is not None else depth_stem\n        (\n            self.patches_layout,\n            self.num_patches,\n            self.embed_dim,\n        ) = stem.get_patch_layout(img_size)\n        self.rgbt_stem = rgbt_stem\n        self.depth_stem = depth_stem\n        self.use_pos_embed = pos_embed_fn is not None\n        self.use_type_embed = use_type_embed\n        self.num_cls_tokens = num_cls_tokens\n\n        if self.use_pos_embed:\n            self.pos_embedding_helper = pos_embed_fn(\n                patches_layout=self.patches_layout,\n                num_cls_tokens=num_cls_tokens,\n                num_patches=self.num_patches,\n                embed_dim=self.embed_dim,\n            )\n        if self.num_cls_tokens > 0:\n            self.cls_token = nn.Parameter(\n                torch.zeros(1, self.num_cls_tokens, self.embed_dim)\n            )\n        if self.use_type_embed:\n            self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))\n\n        self.init_parameters(init_param_style)\n\n    @torch.no_grad()\n    def init_parameters(self, init_param_style):\n        if init_param_style == \"openclip\":\n            # OpenCLIP style initialization\n            scale = self.embed_dim**-0.5\n            if self.use_pos_embed:\n                nn.init.normal_(self.pos_embedding_helper.pos_embed)\n                self.pos_embedding_helper.pos_embed *= scale\n\n            if self.num_cls_tokens > 0:\n                nn.init.normal_(self.cls_token)\n                self.cls_token *= scale\n        elif init_param_style == \"vit\":\n            self.cls_token.data.fill_(0)\n        else:\n            raise ValueError(f\"Unknown init {init_param_style}\")\n\n        if self.use_type_embed:\n            nn.init.normal_(self.type_embed)\n\n    def tokenize_input_and_cls_pos(self, input, stem, mask):\n        # tokens is of shape B x L x D\n        tokens = stem(input)\n        assert tokens.ndim == 3\n        assert tokens.shape[2] == self.embed_dim\n        B = tokens.shape[0]\n        if self.num_cls_tokens > 0:\n            class_tokens = self.cls_token.expand(\n                B, -1, -1\n            )  # stole class_tokens impl from Phil Wang, thanks\n            tokens = torch.cat((class_tokens, tokens), dim=1)\n        if self.use_pos_embed:\n            pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)\n            tokens = tokens + pos_embed\n        if self.use_type_embed:\n            tokens = tokens + self.type_embed.expand(B, -1, -1)\n        return tokens\n\n    def forward(self, vision=None, depth=None, patch_mask=None):\n        if patch_mask is not None:\n            raise NotImplementedError()\n\n        if vision is not None:\n            vision_tokens = self.tokenize_input_and_cls_pos(\n                vision, self.rgbt_stem, patch_mask\n            )\n\n        if depth is not None:\n            depth_tokens = self.tokenize_input_and_cls_pos(\n                depth, self.depth_stem, patch_mask\n            )\n\n        # aggregate tokens\n        if vision is not None and depth is not None:\n            final_tokens = vision_tokens + depth_tokens\n        else:\n            final_tokens = vision_tokens if vision is not None else depth_tokens\n        return_dict = {\n            \"trunk\": {\n                \"tokens\": final_tokens,\n            },\n            \"head\": {},\n        }\n        return return_dict\n\n\nclass AudioPreprocessor(RGBDTPreprocessor):\n    def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:\n        super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)\n\n    def forward(self, audio=None):\n        return super().forward(vision=audio)\n\n\nclass ThermalPreprocessor(RGBDTPreprocessor):\n    def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:\n        super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)\n\n    def forward(self, thermal=None):\n        return super().forward(vision=thermal)\n\n\ndef build_causal_attention_mask(context_length):\n    # lazily create causal attention mask, with full attention between the vision tokens\n    # pytorch uses additive attention mask; fill with -inf\n    mask = torch.empty(context_length, context_length, requires_grad=False)\n    mask.fill_(float(\"-inf\"))\n    mask.triu_(1)  # zero out the lower diagonal\n    return mask\n\n\nclass TextPreprocessor(VerboseNNModule):\n    def __init__(\n        self,\n        vocab_size: int,\n        context_length: int,\n        embed_dim: int,\n        causal_masking: bool,\n        supply_seq_len_to_head: bool = True,\n        num_cls_tokens: int = 0,\n        init_param_style: str = \"openclip\",\n    ) -> None:\n        super().__init__()\n        self.vocab_size = vocab_size\n        self.context_length = context_length\n        self.token_embedding = nn.Embedding(vocab_size, embed_dim)\n        self.pos_embed = nn.Parameter(\n            torch.empty(1, self.context_length + num_cls_tokens, embed_dim)\n        )\n        self.causal_masking = causal_masking\n        if self.causal_masking:\n            mask = build_causal_attention_mask(self.context_length)\n            # register the mask as a buffer so it can be moved to the right device\n            self.register_buffer(\"mask\", mask)\n\n        self.supply_seq_len_to_head = supply_seq_len_to_head\n        self.num_cls_tokens = num_cls_tokens\n        self.embed_dim = embed_dim\n        if num_cls_tokens > 0:\n            assert self.causal_masking is False, \"Masking + CLS token isn't implemented\"\n            self.cls_token = nn.Parameter(\n                torch.zeros(1, self.num_cls_tokens, embed_dim)\n            )\n\n        self.init_parameters(init_param_style)\n\n    @torch.no_grad()\n    def init_parameters(self, init_param_style=\"openclip\"):\n        # OpenCLIP style initialization\n        nn.init.normal_(self.token_embedding.weight, std=0.02)\n        nn.init.normal_(self.pos_embed, std=0.01)\n\n        if init_param_style == \"openclip\":\n            # OpenCLIP style initialization\n            scale = self.embed_dim**-0.5\n            if self.num_cls_tokens > 0:\n                nn.init.normal_(self.cls_token)\n                self.cls_token *= scale\n        elif init_param_style == \"vit\":\n            self.cls_token.data.fill_(0)\n        else:\n            raise ValueError(f\"Unknown init {init_param_style}\")\n\n    def forward(self, text):\n        # text tokens are of shape B x L x D\n        text_tokens = self.token_embedding(text)\n        # concat CLS tokens if any\n        if self.num_cls_tokens > 0:\n            B = text_tokens.shape[0]\n            class_tokens = self.cls_token.expand(\n                B, -1, -1\n            )  # stole class_tokens impl from Phil Wang, thanks\n            text_tokens = torch.cat((class_tokens, text_tokens), dim=1)\n        text_tokens = text_tokens + self.pos_embed\n        return_dict = {\n            \"trunk\": {\n                \"tokens\": text_tokens,\n            },\n            \"head\": {},\n        }\n        # Compute sequence length after adding CLS tokens\n        if self.supply_seq_len_to_head:\n            text_lengths = text.argmax(dim=-1)\n            return_dict[\"head\"] = {\n                \"seq_len\": text_lengths,\n            }\n        if self.causal_masking:\n            return_dict[\"trunk\"].update({\"attn_mask\": self.mask})\n        return return_dict\n\n\nclass Im2Video(nn.Module):\n    \"\"\"Convert an image into a trivial video.\"\"\"\n\n    def __init__(self, time_dim=2):\n        super().__init__()\n        self.time_dim = time_dim\n\n    def forward(self, x):\n        if x.ndim == 4:\n            # B, C, H, W -> B, C, T, H, W\n            return x.unsqueeze(self.time_dim)\n        elif x.ndim == 5:\n            return x\n        else:\n            raise ValueError(f\"Dimension incorrect {x.shape}\")\n\n\nclass PadIm2Video(Im2Video):\n    def __init__(self, ntimes, pad_type, time_dim=2):\n        super().__init__(time_dim=time_dim)\n        assert ntimes > 0\n        assert pad_type in [\"zero\", \"repeat\"]\n        self.ntimes = ntimes\n        self.pad_type = pad_type\n\n    def forward(self, x):\n        x = super().forward(x)\n        if x.shape[self.time_dim] == 1:\n            if self.pad_type == \"repeat\":\n                new_shape = [1] * len(x.shape)\n                new_shape[self.time_dim] = self.ntimes\n                x = x.repeat(new_shape)\n            elif self.pad_type == \"zero\":\n                padarg = [0, 0] * len(x.shape)\n                padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]\n                x = nn.functional.pad(x, padarg)\n        return x\n\n\n# Modified from github.com/openai/CLIP\n@lru_cache()\ndef bytes_to_unicode():\n    \"\"\"\n    Returns list of utf-8 byte and a corresponding list of unicode strings.\n    The reversible bpe codes work on unicode strings.\n    This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n    When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.\n    This is a signficant percentage of your normal, say, 32K bpe vocab.\n    To avoid that, we want lookup tables between utf-8 bytes and unicode strings.\n    And avoids mapping to whitespace/control characters the bpe code barfs on.\n    \"\"\"\n    bs = (\n        list(range(ord(\"!\"), ord(\"~\") + 1))\n        + list(range(ord(\"¡\"), ord(\"¬\") + 1))\n        + list(range(ord(\"®\"), ord(\"ÿ\") + 1))\n    )\n    cs = bs[:]\n    n = 0\n    for b in range(2**8):\n        if b not in bs:\n            bs.append(b)\n            cs.append(2**8 + n)\n            n += 1\n    cs = [chr(n) for n in cs]\n    return dict(zip(bs, cs))\n\n\ndef get_pairs(word):\n    \"\"\"Return set of symbol pairs in a word.\n    Word is represented as tuple of symbols (symbols being variable-length strings).\n    \"\"\"\n    pairs = set()\n    prev_char = word[0]\n    for char in word[1:]:\n        pairs.add((prev_char, char))\n        prev_char = char\n    return pairs\n\n\ndef basic_clean(text):\n    text = ftfy.fix_text(text)\n    text = html.unescape(html.unescape(text))\n    return text.strip()\n\n\ndef whitespace_clean(text):\n    text = re.sub(r\"\\s+\", \" \", text)\n    text = text.strip()\n    return text\n\n\nclass SimpleTokenizer(object):\n    def __init__(self, bpe_path: str, context_length=77):\n        self.byte_encoder = bytes_to_unicode()\n        self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}\n\n        with g_pathmgr.open(bpe_path, \"rb\") as fh:\n            bpe_bytes = io.BytesIO(fh.read())\n            merges: List[str] = gzip.open(bpe_bytes).read().decode(\"utf-8\").split(\"\\n\")\n        merges = merges[1 : 49152 - 256 - 2 + 1]\n        merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges]\n        vocab = list(bytes_to_unicode().values())\n        vocab = vocab + [v + \"</w>\" for v in vocab]\n        for merge in merges:\n            vocab.append(\"\".join(merge))\n        vocab.extend([\"<|startoftext|>\", \"<|endoftext|>\"])\n        self.encoder = dict(zip(vocab, range(len(vocab))))\n        self.decoder = {v: k for k, v in self.encoder.items()}\n        self.bpe_ranks = dict(zip(merges, range(len(merges))))\n        self.cache = {\n            \"<|startoftext|>\": \"<|startoftext|>\",\n            \"<|endoftext|>\": \"<|endoftext|>\",\n        }\n        self.pat = re.compile(\n            r\"\"\"<\\|startoftext\\|>|<\\|endoftext\\|>|'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+\"\"\",\n            re.IGNORECASE,\n        )\n        self.context_length = context_length\n\n    def bpe(self, token):\n        if token in self.cache:\n            return self.cache[token]\n        word = tuple(token[:-1]) + (token[-1] + \"</w>\",)\n        pairs = get_pairs(word)\n\n        if not pairs:\n            return token + \"</w>\"\n\n        while True:\n            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float(\"inf\")))\n            if bigram not in self.bpe_ranks:\n                break\n            first, second = bigram\n            new_word = []\n            i = 0\n            while i < len(word):\n                try:\n                    j = word.index(first, i)\n                    new_word.extend(word[i:j])\n                    i = j\n                except:\n                    new_word.extend(word[i:])\n                    break\n\n                if word[i] == first and i < len(word) - 1 and word[i + 1] == second:\n                    new_word.append(first + second)\n                    i += 2\n                else:\n                    new_word.append(word[i])\n                    i += 1\n            new_word = tuple(new_word)\n            word = new_word\n            if len(word) == 1:\n                break\n            else:\n                pairs = get_pairs(word)\n        word = \" \".join(word)\n        self.cache[token] = word\n        return word\n\n    def encode(self, text):\n        bpe_tokens = []\n        text = whitespace_clean(basic_clean(text)).lower()\n        for token in re.findall(self.pat, text):\n            token = \"\".join(self.byte_encoder[b] for b in token.encode(\"utf-8\"))\n            bpe_tokens.extend(\n                self.encoder[bpe_token] for bpe_token in self.bpe(token).split(\" \")\n            )\n        return bpe_tokens\n\n    def decode(self, tokens):\n        text = \"\".join([self.decoder[token] for token in tokens])\n        text = (\n            bytearray([self.byte_decoder[c] for c in text])\n            .decode(\"utf-8\", errors=\"replace\")\n            .replace(\"</w>\", \" \")\n        )\n        return text\n\n    def __call__(self, texts, context_length=None):\n        if not context_length:\n            context_length = self.context_length\n\n        if isinstance(texts, str):\n            texts = [texts]\n\n        sot_token = self.encoder[\"<|startoftext|>\"]\n        eot_token = self.encoder[\"<|endoftext|>\"]\n        all_tokens = [[sot_token] + self.encode(text) for text in texts]\n        result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)\n\n        for i, tokens in enumerate(all_tokens):\n            tokens = tokens[:context_length - 1] + [eot_token]\n            result[i, : len(tokens)] = torch.tensor(tokens)\n\n        if len(result) == 1:\n            return result[0]\n        return result\n\n\nclass IMUPreprocessor(VerboseNNModule):\n    def __init__(\n        self,\n        kernel_size: int,\n        imu_stem: PatchEmbedGeneric,\n        embed_dim: int,\n        img_size: Tuple = (6, 2000),\n        num_cls_tokens: int = 1,\n        pos_embed_fn: Optional[Callable] = None,\n        init_param_style: str = \"openclip\",\n    ) -> None:\n        super().__init__()\n        self.imu_stem = imu_stem\n        self.embed_dim = embed_dim\n        self.use_pos_embed = pos_embed_fn is not None\n        self.num_cls_tokens = num_cls_tokens\n        self.kernel_size = kernel_size\n        self.pos_embed = nn.Parameter(\n            torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)\n        )\n\n        if self.num_cls_tokens > 0:\n            self.cls_token = nn.Parameter(\n                torch.zeros(1, self.num_cls_tokens, self.embed_dim)\n            )\n\n        self.init_parameters(init_param_style)\n\n    @torch.no_grad()\n    def init_parameters(self, init_param_style):\n        nn.init.normal_(self.pos_embed, std=0.01)\n\n        if init_param_style == \"openclip\":\n            # OpenCLIP style initialization\n            scale = self.embed_dim**-0.5\n\n            if self.num_cls_tokens > 0:\n                nn.init.normal_(self.cls_token)\n                self.cls_token *= scale\n        elif init_param_style == \"vit\":\n            self.cls_token.data.fill_(0)\n        else:\n            raise ValueError(f\"Unknown init {init_param_style}\")\n\n    def tokenize_input_and_cls_pos(self, input, stem):\n        # tokens is of shape B x L x D\n        tokens = stem.norm_layer(stem.proj(input))\n        assert tokens.ndim == 3\n        assert tokens.shape[2] == self.embed_dim\n        B = tokens.shape[0]\n        if self.num_cls_tokens > 0:\n            class_tokens = self.cls_token.expand(\n                B, -1, -1\n            )  # stole class_tokens impl from Phil Wang, thanks\n            tokens = torch.cat((class_tokens, tokens), dim=1)\n        if self.use_pos_embed:\n            tokens = tokens + self.pos_embed\n        return tokens\n\n    def forward(self, imu):\n        # Patchify\n        imu = imu.unfold(\n            -1,\n            self.kernel_size,\n            self.kernel_size,\n        ).permute(0, 2, 1, 3)\n        imu = imu.reshape(imu.size(0), imu.size(1), -1)\n\n        imu_tokens = self.tokenize_input_and_cls_pos(\n            imu,\n            self.imu_stem,\n        )\n\n        return_dict = {\n            \"trunk\": {\n                \"tokens\": imu_tokens,\n            },\n            \"head\": {},\n        }\n        return return_dict\n"
  },
  {
    "path": "imagebind/models/transformer.py",
    "content": "#!/usr/bin/env python3\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Code modified from\n# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;\n# https://github.com/facebookresearch/deit/blob/main/models.py\n# and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py\n\n\nfrom functools import partial\nfrom typing import Callable, List, Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.checkpoint as checkpoint\nfrom timm.layers import DropPath, trunc_normal_\n\n\nclass Attention(nn.Module):\n    def __init__(\n        self,\n        dim,\n        num_heads=8,\n        qkv_bias=False,\n        qk_scale=None,\n        attn_drop=0.0,\n        proj_drop=0.0,\n    ):\n        super().__init__()\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        # NOTE scale factor was wrong in my original version,\n        # can set manually to be compat with prev weights\n        self.scale = qk_scale or head_dim**-0.5\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.attn_drop = nn.Dropout(attn_drop)\n        self.proj = nn.Linear(dim, dim)\n        self.proj_drop = nn.Dropout(proj_drop)\n\n    def forward(self, x):\n        B, N, C = x.shape\n        qkv = (\n            self.qkv(x)\n            .reshape(B, N, 3, self.num_heads, C // self.num_heads)\n            .permute(2, 0, 3, 1, 4)\n        )\n        q, k, v = (\n            qkv[0],\n            qkv[1],\n            qkv[2],\n        )  # make torchscript happy (cannot use tensor as tuple)\n\n        attn = (q @ k.transpose(-2, -1)) * self.scale\n        attn = attn.softmax(dim=-1)\n        attn = self.attn_drop(attn)\n\n        x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n        x = self.proj(x)\n        x = self.proj_drop(x)\n        return x\n\n\nclass Mlp(nn.Module):\n    def __init__(\n        self,\n        in_features,\n        hidden_features=None,\n        out_features=None,\n        act_layer=nn.GELU,\n        drop=0.0,\n    ):\n        super().__init__()\n        out_features = out_features or in_features\n        hidden_features = hidden_features or in_features\n        self.fc1 = nn.Linear(in_features, hidden_features)\n        self.act = act_layer()\n        self.fc2 = nn.Linear(hidden_features, out_features)\n        self.drop = nn.Dropout(drop)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = self.act(x)\n        x = self.drop(x)\n        x = self.fc2(x)\n        x = self.drop(x)\n        return x\n\n\nclass MultiheadAttention(nn.MultiheadAttention):\n    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):\n        return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]\n\n\nclass ViTAttention(Attention):\n    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):\n        assert attn_mask is None\n        return super().forward(x)\n\n\nclass BlockWithMasking(nn.Module):\n    def __init__(\n        self,\n        dim: int,\n        attn_target: Callable,\n        mlp_ratio: int = 4,\n        act_layer: Callable = nn.GELU,\n        norm_layer: Callable = nn.LayerNorm,\n        ffn_dropout_rate: float = 0.0,\n        drop_path: float = 0.0,\n        layer_scale_type: Optional[str] = None,\n        layer_scale_init_value: float = 1e-4,\n    ):\n        super().__init__()\n\n        assert not isinstance(\n            attn_target, nn.Module\n        ), \"attn_target should be a Callable. Otherwise attn_target is shared across blocks!\"\n        self.attn = attn_target()\n        if drop_path > 0.0:\n            self.drop_path = DropPath(drop_path)\n        else:\n            self.drop_path = nn.Identity()\n        self.norm_1 = norm_layer(dim)\n        mlp_hidden_dim = int(mlp_ratio * dim)\n        self.mlp = Mlp(\n            in_features=dim,\n            hidden_features=mlp_hidden_dim,\n            act_layer=act_layer,\n            drop=ffn_dropout_rate,\n        )\n        self.norm_2 = norm_layer(dim)\n        self.layer_scale_type = layer_scale_type\n        if self.layer_scale_type is not None:\n            assert self.layer_scale_type in [\n                \"per_channel\",\n                \"scalar\",\n            ], f\"Found Layer scale type {self.layer_scale_type}\"\n            if self.layer_scale_type == \"per_channel\":\n                # one gamma value per channel\n                gamma_shape = [1, 1, dim]\n            elif self.layer_scale_type == \"scalar\":\n                # single gamma value for all channels\n                gamma_shape = [1, 1, 1]\n            # two gammas: for each part of the fwd in the encoder\n            self.layer_scale_gamma1 = nn.Parameter(\n                torch.ones(size=gamma_shape) * layer_scale_init_value,\n                requires_grad=True,\n            )\n            self.layer_scale_gamma2 = nn.Parameter(\n                torch.ones(size=gamma_shape) * layer_scale_init_value,\n                requires_grad=True,\n            )\n\n    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):\n        if self.layer_scale_type is None:\n            x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))\n            x = x + self.drop_path(self.mlp(self.norm_2(x)))\n        else:\n            x = (\n                x\n                + self.drop_path(self.attn(self.norm_1(x), attn_mask))\n                * self.layer_scale_gamma1\n            )\n            x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2\n        return x\n\n\n_LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)\n\n\nclass SimpleTransformer(nn.Module):\n    def __init__(\n        self,\n        attn_target: Callable,\n        embed_dim: int,\n        num_blocks: int,\n        block: Callable = BlockWithMasking,\n        pre_transformer_layer: Optional[Callable] = None,\n        post_transformer_layer: Optional[Callable] = None,\n        drop_path_rate: float = 0.0,\n        drop_path_type: str = \"progressive\",\n        norm_layer: Callable = _LAYER_NORM,\n        mlp_ratio: int = 4,\n        ffn_dropout_rate: float = 0.0,\n        layer_scale_type: Optional[str] = None,  # from cait; possible values are None, \"per_channel\", \"scalar\"\n        layer_scale_init_value: float = 1e-4,  # from cait; float\n        weight_init_style: str = \"jax\",  # possible values jax or pytorch\n    ):\n        \"\"\"\n        Simple Transformer with the following features\n        1. Supports masked attention\n        2. Supports DropPath\n        3. Supports LayerScale\n        4. Supports Dropout in Attention and FFN\n        5. Makes few assumptions about the input except that it is a Tensor\n        \"\"\"\n        super().__init__()\n        self.pre_transformer_layer = pre_transformer_layer\n        if drop_path_type == \"progressive\":\n            dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]\n        elif drop_path_type == \"uniform\":\n            dpr = [drop_path_rate for i in range(num_blocks)]\n        else:\n            raise ValueError(f\"Unknown drop_path_type: {drop_path_type}\")\n\n        self.blocks = nn.Sequential(\n            *[\n                block(\n                    dim=embed_dim,\n                    attn_target=attn_target,\n                    mlp_ratio=mlp_ratio,\n                    ffn_dropout_rate=ffn_dropout_rate,\n                    drop_path=dpr[i],\n                    norm_layer=norm_layer,\n                    layer_scale_type=layer_scale_type,\n                    layer_scale_init_value=layer_scale_init_value,\n                )\n                for i in range(num_blocks)\n            ]\n        )\n        self.post_transformer_layer = post_transformer_layer\n        self.weight_init_style = weight_init_style\n        self.apply(self._init_weights)\n\n    def _init_weights(self, m):\n        if isinstance(m, nn.Linear):\n            if self.weight_init_style == \"jax\":\n                # Based on MAE and official Jax ViT implementation\n                torch.nn.init.xavier_uniform_(m.weight)\n            elif self.weight_init_style == \"pytorch\":\n                # PyTorch ViT uses trunc_normal_\n                trunc_normal_(m.weight, std=0.02)\n\n            if m.bias is not None:\n                nn.init.constant_(m.bias, 0)\n        elif isinstance(m, (nn.LayerNorm)):\n            nn.init.constant_(m.bias, 0)\n            nn.init.constant_(m.weight, 1.0)\n\n    def forward(\n        self,\n        tokens: torch.Tensor,\n        attn_mask: torch.Tensor = None,\n        use_checkpoint: bool = False,\n        checkpoint_every_n: int = 1,\n        checkpoint_blk_ids: Optional[List[int]] = None,\n    ):\n        \"\"\"\n        Inputs\n        - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)\n        - attn: mask of shape L x L\n\n        Output\n        - x: data of shape N x L x D (or L x N x D depending on the attention implementation)\n        \"\"\"\n        if self.pre_transformer_layer:\n            tokens = self.pre_transformer_layer(tokens)\n        if use_checkpoint and checkpoint_blk_ids is None:\n            checkpoint_blk_ids = [\n                blk_id\n                for blk_id in range(len(self.blocks))\n                if blk_id % checkpoint_every_n == 0\n            ]\n        if checkpoint_blk_ids:\n            checkpoint_blk_ids = set(checkpoint_blk_ids)\n        for blk_id, blk in enumerate(self.blocks):\n            if use_checkpoint and blk_id in checkpoint_blk_ids:\n                tokens = checkpoint.checkpoint(\n                    blk, tokens, attn_mask, use_reentrant=False\n                )\n            else:\n                tokens = blk(tokens, attn_mask=attn_mask)\n        if self.post_transformer_layer:\n            tokens = self.post_transformer_layer(tokens)\n        return tokens\n"
  },
  {
    "path": "model_card.md",
    "content": "# Model Card for ImageBind\n\nMultimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.\nInput any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.\n\n# Model Details\n\n## Model Description\n\n<!-- Provide a longer summary of what this model is/does. -->\nMultimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images\n\n- **Developed by:** Meta AI\n- **Model type:** Multimodal model\n- **Language(s) (NLP):** en\n- **License:** CC BY-NC-SA 4.0\n- **Resources for more information:**\n    - [GitHub Repo](https://github.com/facebookresearch/ImageBind)\n\n\n# Uses\n\n<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->\nThis 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.\nWe 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.\n\n## Out-of-Scope Use\n\n<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->\n<!-- If the user enters content, print that. If not, but they enter a task in the list, use that. If neither, say \"more info needed.\" -->\n\nThis model is *NOT* intended to be used in any real world application -- commercial or otherwise.\nIt may produce harmful associations with different inputs.\nThe model needs to be investigated and likely re-trained on specific data for any such application.\nThe model is expected to work better on web-based visual data since it was trained on such data.\nThe text encoder is likely to work only on English language text because of the underlying training datasets.\n\n# Bias, Risks, and Limitations\n\n<!-- This section is meant to convey both technical and sociotechnical limitations. -->\nOpen-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).\nSince our model uses such models as initialization, it will exhibit such biases too.\nMoreover, 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.\n\n\n\n# Training Details\n\n## Training Data\n\n<!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->\n\nImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.\nIn particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.\nWe 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.\nWe provide the exact training data details in the paper.\n\n\n## Training Procedure\n\n<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->\nPlease refer to the research paper and github repo for exact details on this.\n\n# Evaluation\n\n## Testing Data, Factors & Metrics\n\nWe evaluate the model on a variety of different classification benchmarks for each modality.\nThe evaluation details are presented in the paper.\nThe models performance is measured using standard classification metrics such as accuracy and mAP.\n\n# Citation\n\n<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->\n\n**BibTeX:**\n```\n@inproceedings{girdhar2023imagebind,\n  title={ImageBind: One Embedding Space To Bind Them All},\n  author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang\nand Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},\n  booktitle={CVPR},\n  year={2023}\n}\n```\n\n\n# Model Card Contact\n\nPlease reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com\n\n# How to Get Started with the Model\n\nOur github repo provides a simple example to extract embeddings from images, audio etc.\n"
  },
  {
    "path": "requirements.txt",
    "content": "torch>=2.0.0\ntorchvision  # because torch version already specific, the right torchvision will be derived automatically\ntorchaudio  # because torch version already specific, the right torchaudio will be derived automatically\npytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@6cdc929315aab1b5674b6dcf73b16ec99147735f\ntimm\nftfy\nregex\neinops\niopath\nnumpy>=1.19\ntypes-regex\n"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n    required = f.read().splitlines()\n\nsetup(\n    name='imagebind',\n    version='0.1.0',\n    packages=find_packages(),\n    package_data={\n        'imagebind': ['bpe/bpe_simple_vocab_16e6.txt.gz'],\n    },\n    description='A brief description of the package',\n    long_description=open('README.md', encoding='utf-8').read(),\n    long_description_content_type=\"text/markdown\",\n    url='https://github.com/facebookresearch/ImageBind',\n    classifiers=[\n        'Programming Language :: Python :: 3',\n        'License :: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',\n    ],\n    install_requires=required,\n    dependency_links=['https://download.pytorch.org/whl/cu113'],\n)\n"
  }
]