haiphamcse commited on
Commit
6a00010
·
verified ·
1 Parent(s): 9855f47

Upload folder using huggingface_hub

Browse files
Files changed (46) hide show
  1. .gitattributes +10 -0
  2. ImageBind/.assets/Alexandre-Lacroix-voix.oga +3 -0
  3. ImageBind/.assets/bird_audio.wav +3 -0
  4. ImageBind/.assets/bird_image.jpg +3 -0
  5. ImageBind/.assets/car_audio.wav +3 -0
  6. ImageBind/.assets/car_image.jpg +0 -0
  7. ImageBind/.assets/dog_audio.wav +3 -0
  8. ImageBind/.assets/dog_cat.webp +3 -0
  9. ImageBind/.assets/dog_image.jpg +0 -0
  10. ImageBind/.assets/dragon-studio-cat-meow-401729.mp3 +0 -0
  11. ImageBind/.assets/dragon-studio-dog-barking-406629.mp3 +3 -0
  12. ImageBind/.assets/emily.avif +0 -0
  13. ImageBind/.assets/emily.jpg +3 -0
  14. ImageBind/.assets/female.flac +3 -0
  15. ImageBind/.gitignore +8 -0
  16. ImageBind/CODE_OF_CONDUCT.md +80 -0
  17. ImageBind/CONTRIBUTING.md +31 -0
  18. ImageBind/LEGRAD_IMAGEBIND_USAGE.md +83 -0
  19. ImageBind/LICENSE +437 -0
  20. ImageBind/README.md +155 -0
  21. ImageBind/imagebind.egg-info/PKG-INFO +183 -0
  22. ImageBind/imagebind.egg-info/SOURCES.txt +16 -0
  23. ImageBind/imagebind.egg-info/dependency_links.txt +1 -0
  24. ImageBind/imagebind.egg-info/requires.txt +11 -0
  25. ImageBind/imagebind.egg-info/top_level.txt +1 -0
  26. ImageBind/imagebind/__init__.py +8 -0
  27. ImageBind/imagebind/__pycache__/__init__.cpython-312.pyc +0 -0
  28. ImageBind/imagebind/__pycache__/data.cpython-312.pyc +0 -0
  29. ImageBind/imagebind/__pycache__/legrad_wrapper.cpython-312.pyc +0 -0
  30. ImageBind/imagebind/bpe/bpe_simple_vocab_16e6.txt.gz +3 -0
  31. ImageBind/imagebind/data.py +357 -0
  32. ImageBind/imagebind/legrad_wrapper.py +316 -0
  33. ImageBind/imagebind/models/__init__.py +0 -0
  34. ImageBind/imagebind/models/__pycache__/__init__.cpython-312.pyc +0 -0
  35. ImageBind/imagebind/models/__pycache__/helpers.cpython-312.pyc +0 -0
  36. ImageBind/imagebind/models/__pycache__/imagebind_model.cpython-312.pyc +0 -0
  37. ImageBind/imagebind/models/__pycache__/multimodal_preprocessors.cpython-312.pyc +0 -0
  38. ImageBind/imagebind/models/__pycache__/transformer.cpython-312.pyc +0 -0
  39. ImageBind/imagebind/models/helpers.py +140 -0
  40. ImageBind/imagebind/models/imagebind_model.py +534 -0
  41. ImageBind/imagebind/models/multimodal_preprocessors.py +685 -0
  42. ImageBind/imagebind/models/transformer.py +336 -0
  43. ImageBind/legrad_imagebind.ipynb +3 -0
  44. ImageBind/model_card.md +94 -0
  45. ImageBind/requirements.txt +11 -0
  46. ImageBind/setup.py +23 -0
.gitattributes CHANGED
@@ -47,3 +47,13 @@ perception_models/apps/pe/docs/assets/train.wav filter=lfs diff=lfs merge=lfs -t
47
  perception_models/apps/plm/docs/plm_main_fig.png filter=lfs diff=lfs merge=lfs -text
48
  perception_models/core/tests/Rock-climbing-Canada-1920x1147.jpg filter=lfs diff=lfs merge=lfs -text
49
  perception_models/core/tests/selfie_cathedral_peak.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
47
  perception_models/apps/plm/docs/plm_main_fig.png filter=lfs diff=lfs merge=lfs -text
48
  perception_models/core/tests/Rock-climbing-Canada-1920x1147.jpg filter=lfs diff=lfs merge=lfs -text
49
  perception_models/core/tests/selfie_cathedral_peak.jpg filter=lfs diff=lfs merge=lfs -text
50
+ ImageBind/.assets/Alexandre-Lacroix-voix.oga filter=lfs diff=lfs merge=lfs -text
51
+ ImageBind/.assets/bird_audio.wav filter=lfs diff=lfs merge=lfs -text
52
+ ImageBind/.assets/bird_image.jpg filter=lfs diff=lfs merge=lfs -text
53
+ ImageBind/.assets/car_audio.wav filter=lfs diff=lfs merge=lfs -text
54
+ ImageBind/.assets/dog_audio.wav filter=lfs diff=lfs merge=lfs -text
55
+ ImageBind/.assets/dog_cat.webp filter=lfs diff=lfs merge=lfs -text
56
+ ImageBind/.assets/dragon-studio-dog-barking-406629.mp3 filter=lfs diff=lfs merge=lfs -text
57
+ ImageBind/.assets/emily.jpg filter=lfs diff=lfs merge=lfs -text
58
+ ImageBind/.assets/female.flac filter=lfs diff=lfs merge=lfs -text
59
+ ImageBind/legrad_imagebind.ipynb filter=lfs diff=lfs merge=lfs -text
ImageBind/.assets/Alexandre-Lacroix-voix.oga ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab2e893e715de3fe82f6597675fea5f15d9ba9e712a820b1932af0a8de386c6e
3
+ size 136302
ImageBind/.assets/bird_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8b0c17e3b8b3e5b1324d83a8f598ac9129998877b697d32c194b2a1fe11681a
3
+ size 882078
ImageBind/.assets/bird_image.jpg ADDED

Git LFS Details

  • SHA256: 1d9d891f7785a0a7b85556f5c8e7bedd82edce78b46b7f55a569f4b2f3e9e5d1
  • Pointer size: 131 Bytes
  • Size of remote file: 115 kB
ImageBind/.assets/car_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79e2335cf1fa4b0a6be7d2a93007f630acd89e178405ae2fabf45ee3af801fda
3
+ size 441044
ImageBind/.assets/car_image.jpg ADDED
ImageBind/.assets/dog_audio.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b4dca689971840c140e4d206ad43dc35ecf7c2c1b661f478268bc6de9ad50b3
3
+ size 460518
ImageBind/.assets/dog_cat.webp ADDED

Git LFS Details

  • SHA256: 6a8944771abd72d96f10615a8f3617bddc0bbef2ad0b83c967632cf4244c5e77
  • Pointer size: 131 Bytes
  • Size of remote file: 208 kB
ImageBind/.assets/dog_image.jpg ADDED
ImageBind/.assets/dragon-studio-cat-meow-401729.mp3 ADDED
Binary file (39.2 kB). View file
 
ImageBind/.assets/dragon-studio-dog-barking-406629.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6017f455f08a91f03aefba74b7a2d6deb9476573ce6007d1cf16d7d4ba2e45e
3
+ size 403968
ImageBind/.assets/emily.avif ADDED
ImageBind/.assets/emily.jpg ADDED

Git LFS Details

  • SHA256: 249462791e5a72806550e48ef2fc85f505a4dabfc203beeb8f5fdff4272f0d7f
  • Pointer size: 131 Bytes
  • Size of remote file: 216 kB
ImageBind/.assets/female.flac ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d45727e9d90500cb741e1dd2ee4fcebfd5eb682675cc2fa2891b189c664ec964
3
+ size 2325394
ImageBind/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ **__pycache__
2
+ .vscode
3
+ .idea/
4
+ .python-version
5
+ build/
6
+ imagebind.egg-info
7
+ .DS_Store
8
+ venv/
ImageBind/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@fb.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
ImageBind/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ImageBind
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Meta's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to Omnivore, you agree that your contributions will be licensed
31
+ under the [LICENSE](LICENSE) file in the root directory of this source tree.
ImageBind/LEGRAD_IMAGEBIND_USAGE.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LeGrad + ImageBind Notebook Usage
2
+
3
+ This folder includes `legrad_imagebind.ipynb`, a notebook that demonstrates **LeGrad** explanations for the **ImageBind** model using `ImageBindLeWrapper` (`imagebind/legrad_wrapper.py`).
4
+
5
+ ## 1. Environment and installation
6
+
7
+ From the `ImageBind` repo root:
8
+
9
+ ```bash
10
+ pip install -e .
11
+ ```
12
+
13
+ Install **LeGrad** and make sure it is on `PYTHONPATH`:
14
+
15
+ ```bash
16
+ pip install -e /path/to/LeGrad
17
+ ```
18
+
19
+ or set `PYTHONPATH` so that the `legrad` package is importable.
20
+
21
+ You also need a working CUDA‑enabled PyTorch environment for GPU execution.
22
+
23
+ ## 2. Open the notebook
24
+
25
+ From this folder:
26
+
27
+ ```bash
28
+ cd xai/ImageBind
29
+ jupyter lab legrad_imagebind.ipynb
30
+ ```
31
+
32
+ ## 3. What the notebook does
33
+
34
+ The notebook walks through:
35
+
36
+ 1. **Importing ImageBind and LeGrad**
37
+ - Adds the local `LeGrad` repo to `sys.path`.
38
+ - Imports `imagebind_model`, `ModalityType`, and utility functions from `imagebind.data`.
39
+ 2. **Loading text and image inputs**
40
+ - Defines `text_list` (e.g. `"A dog."`, `"A car"`, `"A bird"`).
41
+ - Loads and preprocesses images from `.assets/*.jpg` using `data.load_and_transform_vision_data`.
42
+ 3. **Running the base ImageBind model**
43
+ - Creates `model = imagebind_model.imagebind_huge(pretrained=True)`.
44
+ - Moves it to CUDA and evaluates vanilla similarity scores `embeddings[VISION] @ embeddings[TEXT].T`.
45
+ 4. **Wrapping with LeGrad**
46
+ - Uses `ImageBindLeWrapper` from `imagebind/legrad_wrapper.py`.
47
+ - Hooks transformer blocks and `nn.MultiheadAttention` to keep attention probabilities (`attention_maps`) in the autograd graph.
48
+ 5. **Computing explanations**
49
+ - Vision: spatial heatmaps over image patches (`compute_legrad_image(...)` / `compute_legrad_image_one_layer(...)`).
50
+ - Text: per‑token relevance scores (`compute_legrad_text(...)` / `compute_legrad_text_one_layer(...)`).
51
+ 6. **Visualizing results**
52
+ - Converts heatmaps to numpy and overlays them on the input images; plots token relevance over the prompt.
53
+
54
+ ## 4. Minimal code sketch (inside the notebook)
55
+
56
+ The core pattern is:
57
+
58
+ ```python
59
+ import torch
60
+ from imagebind import data
61
+ from imagebind.models import imagebind_model
62
+ from imagebind.models.imagebind_model import ModalityType
63
+ from imagebind.legrad_wrapper import ImageBindLeWrapper
64
+
65
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
66
+ model = imagebind_model.imagebind_huge(pretrained=True).to(device).eval()
67
+
68
+ wrapper = ImageBindLeWrapper(model, layer_index=-2, trunk_key=ModalityType.VISION)
69
+
70
+ text_list = ["A dog.", "A car", "A bird"]
71
+ image_paths = [".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
72
+
73
+ inputs = {
74
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
75
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
76
+ }
77
+ ```
78
+
79
+ You can then call the wrapper’s `compute_legrad_*` helpers in the notebook to obtain:
80
+
81
+ - **Vision heatmaps** for each (image, text) pair.
82
+ - **Text token relevance** for a chosen image or batch of images.
83
+
ImageBind/LICENSE ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial-ShareAlike 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58
+ Public License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial-ShareAlike 4.0 International Public License
63
+ ("Public License"). To the extent this Public License may be
64
+ interpreted as a contract, You are granted the Licensed Rights in
65
+ consideration of Your acceptance of these terms and conditions, and the
66
+ Licensor grants You such rights in consideration of benefits the
67
+ Licensor receives from making the Licensed Material available under
68
+ these terms and conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. BY-NC-SA Compatible License means a license listed at
88
+ creativecommons.org/compatiblelicenses, approved by Creative
89
+ Commons as essentially the equivalent of this Public License.
90
+
91
+ d. Copyright and Similar Rights means copyright and/or similar rights
92
+ closely related to copyright including, without limitation,
93
+ performance, broadcast, sound recording, and Sui Generis Database
94
+ Rights, without regard to how the rights are labeled or
95
+ categorized. For purposes of this Public License, the rights
96
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
97
+ Rights.
98
+
99
+ e. Effective Technological Measures means those measures that, in the
100
+ absence of proper authority, may not be circumvented under laws
101
+ fulfilling obligations under Article 11 of the WIPO Copyright
102
+ Treaty adopted on December 20, 1996, and/or similar international
103
+ agreements.
104
+
105
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
106
+ any other exception or limitation to Copyright and Similar Rights
107
+ that applies to Your use of the Licensed Material.
108
+
109
+ g. License Elements means the license attributes listed in the name
110
+ of a Creative Commons Public License. The License Elements of this
111
+ Public License are Attribution, NonCommercial, and ShareAlike.
112
+
113
+ h. Licensed Material means the artistic or literary work, database,
114
+ or other material to which the Licensor applied this Public
115
+ License.
116
+
117
+ i. Licensed Rights means the rights granted to You subject to the
118
+ terms and conditions of this Public License, which are limited to
119
+ all Copyright and Similar Rights that apply to Your use of the
120
+ Licensed Material and that the Licensor has authority to license.
121
+
122
+ j. Licensor means the individual(s) or entity(ies) granting rights
123
+ under this Public License.
124
+
125
+ k. NonCommercial means not primarily intended for or directed towards
126
+ commercial advantage or monetary compensation. For purposes of
127
+ this Public License, the exchange of the Licensed Material for
128
+ other material subject to Copyright and Similar Rights by digital
129
+ file-sharing or similar means is NonCommercial provided there is
130
+ no payment of monetary compensation in connection with the
131
+ exchange.
132
+
133
+ l. Share means to provide material to the public by any means or
134
+ process that requires permission under the Licensed Rights, such
135
+ as reproduction, public display, public performance, distribution,
136
+ dissemination, communication, or importation, and to make material
137
+ available to the public including in ways that members of the
138
+ public may access the material from a place and at a time
139
+ individually chosen by them.
140
+
141
+ m. Sui Generis Database Rights means rights other than copyright
142
+ resulting from Directive 96/9/EC of the European Parliament and of
143
+ the Council of 11 March 1996 on the legal protection of databases,
144
+ as amended and/or succeeded, as well as other essentially
145
+ equivalent rights anywhere in the world.
146
+
147
+ n. You means the individual or entity exercising the Licensed Rights
148
+ under this Public License. Your has a corresponding meaning.
149
+
150
+
151
+ Section 2 -- Scope.
152
+
153
+ a. License grant.
154
+
155
+ 1. Subject to the terms and conditions of this Public License,
156
+ the Licensor hereby grants You a worldwide, royalty-free,
157
+ non-sublicensable, non-exclusive, irrevocable license to
158
+ exercise the Licensed Rights in the Licensed Material to:
159
+
160
+ a. reproduce and Share the Licensed Material, in whole or
161
+ in part, for NonCommercial purposes only; and
162
+
163
+ b. produce, reproduce, and Share Adapted Material for
164
+ NonCommercial purposes only.
165
+
166
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
167
+ Exceptions and Limitations apply to Your use, this Public
168
+ License does not apply, and You do not need to comply with
169
+ its terms and conditions.
170
+
171
+ 3. Term. The term of this Public License is specified in Section
172
+ 6(a).
173
+
174
+ 4. Media and formats; technical modifications allowed. The
175
+ Licensor authorizes You to exercise the Licensed Rights in
176
+ all media and formats whether now known or hereafter created,
177
+ and to make technical modifications necessary to do so. The
178
+ Licensor waives and/or agrees not to assert any right or
179
+ authority to forbid You from making technical modifications
180
+ necessary to exercise the Licensed Rights, including
181
+ technical modifications necessary to circumvent Effective
182
+ Technological Measures. For purposes of this Public License,
183
+ simply making modifications authorized by this Section 2(a)
184
+ (4) never produces Adapted Material.
185
+
186
+ 5. Downstream recipients.
187
+
188
+ a. Offer from the Licensor -- Licensed Material. Every
189
+ recipient of the Licensed Material automatically
190
+ receives an offer from the Licensor to exercise the
191
+ Licensed Rights under the terms and conditions of this
192
+ Public License.
193
+
194
+ b. Additional offer from the Licensor -- Adapted Material.
195
+ Every recipient of Adapted Material from You
196
+ automatically receives an offer from the Licensor to
197
+ exercise the Licensed Rights in the Adapted Material
198
+ under the conditions of the Adapter's License You apply.
199
+
200
+ c. No downstream restrictions. You may not offer or impose
201
+ any additional or different terms or conditions on, or
202
+ apply any Effective Technological Measures to, the
203
+ Licensed Material if doing so restricts exercise of the
204
+ Licensed Rights by any recipient of the Licensed
205
+ Material.
206
+
207
+ 6. No endorsement. Nothing in this Public License constitutes or
208
+ may be construed as permission to assert or imply that You
209
+ are, or that Your use of the Licensed Material is, connected
210
+ with, or sponsored, endorsed, or granted official status by,
211
+ the Licensor or others designated to receive attribution as
212
+ provided in Section 3(a)(1)(A)(i).
213
+
214
+ b. Other rights.
215
+
216
+ 1. Moral rights, such as the right of integrity, are not
217
+ licensed under this Public License, nor are publicity,
218
+ privacy, and/or other similar personality rights; however, to
219
+ the extent possible, the Licensor waives and/or agrees not to
220
+ assert any such rights held by the Licensor to the limited
221
+ extent necessary to allow You to exercise the Licensed
222
+ Rights, but not otherwise.
223
+
224
+ 2. Patent and trademark rights are not licensed under this
225
+ Public License.
226
+
227
+ 3. To the extent possible, the Licensor waives any right to
228
+ collect royalties from You for the exercise of the Licensed
229
+ Rights, whether directly or through a collecting society
230
+ under any voluntary or waivable statutory or compulsory
231
+ licensing scheme. In all other cases the Licensor expressly
232
+ reserves any right to collect such royalties, including when
233
+ the Licensed Material is used other than for NonCommercial
234
+ purposes.
235
+
236
+
237
+ Section 3 -- License Conditions.
238
+
239
+ Your exercise of the Licensed Rights is expressly made subject to the
240
+ following conditions.
241
+
242
+ a. Attribution.
243
+
244
+ 1. If You Share the Licensed Material (including in modified
245
+ form), You must:
246
+
247
+ a. retain the following if it is supplied by the Licensor
248
+ with the Licensed Material:
249
+
250
+ i. identification of the creator(s) of the Licensed
251
+ Material and any others designated to receive
252
+ attribution, in any reasonable manner requested by
253
+ the Licensor (including by pseudonym if
254
+ designated);
255
+
256
+ ii. a copyright notice;
257
+
258
+ iii. a notice that refers to this Public License;
259
+
260
+ iv. a notice that refers to the disclaimer of
261
+ warranties;
262
+
263
+ v. a URI or hyperlink to the Licensed Material to the
264
+ extent reasonably practicable;
265
+
266
+ b. indicate if You modified the Licensed Material and
267
+ retain an indication of any previous modifications; and
268
+
269
+ c. indicate the Licensed Material is licensed under this
270
+ Public License, and include the text of, or the URI or
271
+ hyperlink to, this Public License.
272
+
273
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
274
+ reasonable manner based on the medium, means, and context in
275
+ which You Share the Licensed Material. For example, it may be
276
+ reasonable to satisfy the conditions by providing a URI or
277
+ hyperlink to a resource that includes the required
278
+ information.
279
+ 3. If requested by the Licensor, You must remove any of the
280
+ information required by Section 3(a)(1)(A) to the extent
281
+ reasonably practicable.
282
+
283
+ b. ShareAlike.
284
+
285
+ In addition to the conditions in Section 3(a), if You Share
286
+ Adapted Material You produce, the following conditions also apply.
287
+
288
+ 1. The Adapter's License You apply must be a Creative Commons
289
+ license with the same License Elements, this version or
290
+ later, or a BY-NC-SA Compatible License.
291
+
292
+ 2. You must include the text of, or the URI or hyperlink to, the
293
+ Adapter's License You apply. You may satisfy this condition
294
+ in any reasonable manner based on the medium, means, and
295
+ context in which You Share Adapted Material.
296
+
297
+ 3. You may not offer or impose any additional or different terms
298
+ or conditions on, or apply any Effective Technological
299
+ Measures to, Adapted Material that restrict exercise of the
300
+ rights granted under the Adapter's License You apply.
301
+
302
+
303
+ Section 4 -- Sui Generis Database Rights.
304
+
305
+ Where the Licensed Rights include Sui Generis Database Rights that
306
+ apply to Your use of the Licensed Material:
307
+
308
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309
+ to extract, reuse, reproduce, and Share all or a substantial
310
+ portion of the contents of the database for NonCommercial purposes
311
+ only;
312
+
313
+ b. if You include all or a substantial portion of the database
314
+ contents in a database in which You have Sui Generis Database
315
+ Rights, then the database in which You have Sui Generis Database
316
+ Rights (but not its individual contents) is Adapted Material,
317
+ including for purposes of Section 3(b); and
318
+
319
+ c. You must comply with the conditions in Section 3(a) if You Share
320
+ all or a substantial portion of the contents of the database.
321
+
322
+ For the avoidance of doubt, this Section 4 supplements and does not
323
+ replace Your obligations under this Public License where the Licensed
324
+ Rights include other Copyright and Similar Rights.
325
+
326
+
327
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328
+
329
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339
+
340
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349
+
350
+ c. The disclaimer of warranties and limitation of liability provided
351
+ above shall be interpreted in a manner that, to the extent
352
+ possible, most closely approximates an absolute disclaimer and
353
+ waiver of all liability.
354
+
355
+
356
+ Section 6 -- Term and Termination.
357
+
358
+ a. This Public License applies for the term of the Copyright and
359
+ Similar Rights licensed here. However, if You fail to comply with
360
+ this Public License, then Your rights under this Public License
361
+ terminate automatically.
362
+
363
+ b. Where Your right to use the Licensed Material has terminated under
364
+ Section 6(a), it reinstates:
365
+
366
+ 1. automatically as of the date the violation is cured, provided
367
+ it is cured within 30 days of Your discovery of the
368
+ violation; or
369
+
370
+ 2. upon express reinstatement by the Licensor.
371
+
372
+ For the avoidance of doubt, this Section 6(b) does not affect any
373
+ right the Licensor may have to seek remedies for Your violations
374
+ of this Public License.
375
+
376
+ c. For the avoidance of doubt, the Licensor may also offer the
377
+ Licensed Material under separate terms or conditions or stop
378
+ distributing the Licensed Material at any time; however, doing so
379
+ will not terminate this Public License.
380
+
381
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382
+ License.
383
+
384
+
385
+ Section 7 -- Other Terms and Conditions.
386
+
387
+ a. The Licensor shall not be bound by any additional or different
388
+ terms or conditions communicated by You unless expressly agreed.
389
+
390
+ b. Any arrangements, understandings, or agreements regarding the
391
+ Licensed Material not stated herein are separate from and
392
+ independent of the terms and conditions of this Public License.
393
+
394
+
395
+ Section 8 -- Interpretation.
396
+
397
+ a. For the avoidance of doubt, this Public License does not, and
398
+ shall not be interpreted to, reduce, limit, restrict, or impose
399
+ conditions on any use of the Licensed Material that could lawfully
400
+ be made without permission under this Public License.
401
+
402
+ b. To the extent possible, if any provision of this Public License is
403
+ deemed unenforceable, it shall be automatically reformed to the
404
+ minimum extent necessary to make it enforceable. If the provision
405
+ cannot be reformed, it shall be severed from this Public License
406
+ without affecting the enforceability of the remaining terms and
407
+ conditions.
408
+
409
+ c. No term or condition of this Public License will be waived and no
410
+ failure to comply consented to unless expressly agreed to by the
411
+ Licensor.
412
+
413
+ d. Nothing in this Public License constitutes or may be interpreted
414
+ as a limitation upon, or waiver of, any privileges and immunities
415
+ that apply to the Licensor or You, including from the legal
416
+ processes of any jurisdiction or authority.
417
+
418
+ =======================================================================
419
+
420
+ Creative Commons is not a party to its public
421
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
422
+ its public licenses to material it publishes and in those instances
423
+ will be considered the “Licensor.” The text of the Creative Commons
424
+ public licenses is dedicated to the public domain under the CC0 Public
425
+ Domain Dedication. Except for the limited purpose of indicating that
426
+ material is shared under a Creative Commons public license or as
427
+ otherwise permitted by the Creative Commons policies published at
428
+ creativecommons.org/policies, Creative Commons does not authorize the
429
+ use of the trademark "Creative Commons" or any other trademark or logo
430
+ of Creative Commons without its prior written consent including,
431
+ without limitation, in connection with any unauthorized modifications
432
+ to any of its public licenses or any other arrangements,
433
+ understandings, or agreements concerning use of licensed material. For
434
+ the avoidance of doubt, this paragraph does not form part of the
435
+ public licenses.
436
+
437
+ Creative Commons may be contacted at creativecommons.org.
ImageBind/README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ImageBind: One Embedding Space To Bind Them All
2
+
3
+ **[FAIR, Meta AI](https://ai.facebook.com/research/)**
4
+
5
+ Rohit Girdhar*,
6
+ Alaaeldin El-Nouby*,
7
+ Zhuang Liu,
8
+ Mannat Singh,
9
+ Kalyan Vasudev Alwala,
10
+ Armand Joulin,
11
+ Ishan Misra*
12
+
13
+ To appear at CVPR 2023 (*Highlighted paper*)
14
+
15
+ [[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)]
16
+
17
+ PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
18
+
19
+ ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
20
+
21
+
22
+
23
+ ![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)
24
+
25
+ ## ImageBind model
26
+
27
+ Emergent zero-shot classification performance.
28
+
29
+ <table style="margin: auto">
30
+ <tr>
31
+ <th>Model</th>
32
+ <th><span style="color:blue">IN1k</span></th>
33
+ <th><span style="color:purple">K400</span></th>
34
+ <th><span style="color:green">NYU-D</span></th>
35
+ <th><span style="color:LightBlue">ESC</span></th>
36
+ <th><span style="color:orange">LLVIP</span></th>
37
+ <th><span style="color:purple">Ego4D</span></th>
38
+ <th>download</th>
39
+ </tr>
40
+ <tr>
41
+ <td>imagebind_huge</td>
42
+ <td align="right">77.7</td>
43
+ <td align="right">50.0</td>
44
+ <td align="right">54.0</td>
45
+ <td align="right">66.9</td>
46
+ <td align="right">63.4</td>
47
+ <td align="right">25.0</td>
48
+ <td><a href="https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth">checkpoint</a></td>
49
+ </tr>
50
+
51
+ </table>
52
+
53
+ ## Usage
54
+
55
+ Install pytorch 2.0+ and other 3rd party dependencies.
56
+
57
+ ```shell
58
+ conda create --name imagebind python=3.10 -y
59
+ conda activate imagebind
60
+
61
+ pip install .
62
+ ```
63
+
64
+ For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
65
+
66
+ ```
67
+ pip install soundfile
68
+ ```
69
+
70
+
71
+ Extract and compare features across modalities (e.g. Image, Text and Audio).
72
+
73
+ ```python
74
+ from imagebind import data
75
+ import torch
76
+ from imagebind.models import imagebind_model
77
+ from imagebind.models.imagebind_model import ModalityType
78
+
79
+ text_list=["A dog.", "A car", "A bird"]
80
+ image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
81
+ audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
82
+
83
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
84
+
85
+ # Instantiate model
86
+ model = imagebind_model.imagebind_huge(pretrained=True)
87
+ model.eval()
88
+ model.to(device)
89
+
90
+ # Load data
91
+ inputs = {
92
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
93
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
94
+ ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
95
+ }
96
+
97
+ with torch.no_grad():
98
+ embeddings = model(inputs)
99
+
100
+ print(
101
+ "Vision x Text: ",
102
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
103
+ )
104
+ print(
105
+ "Audio x Text: ",
106
+ torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
107
+ )
108
+ print(
109
+ "Vision x Audio: ",
110
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
111
+ )
112
+
113
+ # Expected output:
114
+ #
115
+ # Vision x Text:
116
+ # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
117
+ # [3.3836e-05, 9.9994e-01, 2.4118e-05],
118
+ # [4.7997e-05, 1.3496e-02, 9.8646e-01]])
119
+ #
120
+ # Audio x Text:
121
+ # tensor([[1., 0., 0.],
122
+ # [0., 1., 0.],
123
+ # [0., 0., 1.]])
124
+ #
125
+ # Vision x Audio:
126
+ # tensor([[0.8070, 0.1088, 0.0842],
127
+ # [0.1036, 0.7884, 0.1079],
128
+ # [0.0018, 0.0022, 0.9960]])
129
+
130
+ ```
131
+
132
+ ## Model card
133
+ Please see the [model card](model_card.md) for details.
134
+
135
+ ## License
136
+
137
+ ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
138
+
139
+ ## Contributing
140
+
141
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
142
+
143
+ ## Citing ImageBind
144
+
145
+ If you find this repository useful, please consider giving a star :star: and citation
146
+
147
+ ```
148
+ @inproceedings{girdhar2023imagebind,
149
+ title={ImageBind: One Embedding Space To Bind Them All},
150
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
151
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
152
+ booktitle={CVPR},
153
+ year={2023}
154
+ }
155
+ ```
ImageBind/imagebind.egg-info/PKG-INFO ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: imagebind
3
+ Version: 0.1.0
4
+ Summary: A brief description of the package
5
+ Home-page: https://github.com/facebookresearch/ImageBind
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: torch>=2.0.0
11
+ Requires-Dist: torchvision
12
+ Requires-Dist: torchaudio
13
+ Requires-Dist: pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@6cdc929315aab1b5674b6dcf73b16ec99147735f
14
+ Requires-Dist: timm
15
+ Requires-Dist: ftfy
16
+ Requires-Dist: regex
17
+ Requires-Dist: einops
18
+ Requires-Dist: iopath
19
+ Requires-Dist: numpy>=1.19
20
+ Requires-Dist: types-regex
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
28
+
29
+ # ImageBind: One Embedding Space To Bind Them All
30
+
31
+ **[FAIR, Meta AI](https://ai.facebook.com/research/)**
32
+
33
+ Rohit Girdhar*,
34
+ Alaaeldin El-Nouby*,
35
+ Zhuang Liu,
36
+ Mannat Singh,
37
+ Kalyan Vasudev Alwala,
38
+ Armand Joulin,
39
+ Ishan Misra*
40
+
41
+ To appear at CVPR 2023 (*Highlighted paper*)
42
+
43
+ [[`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)]
44
+
45
+ PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**.
46
+
47
+ ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation.
48
+
49
+
50
+
51
+ ![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif)
52
+
53
+ ## ImageBind model
54
+
55
+ Emergent zero-shot classification performance.
56
+
57
+ <table style="margin: auto">
58
+ <tr>
59
+ <th>Model</th>
60
+ <th><span style="color:blue">IN1k</span></th>
61
+ <th><span style="color:purple">K400</span></th>
62
+ <th><span style="color:green">NYU-D</span></th>
63
+ <th><span style="color:LightBlue">ESC</span></th>
64
+ <th><span style="color:orange">LLVIP</span></th>
65
+ <th><span style="color:purple">Ego4D</span></th>
66
+ <th>download</th>
67
+ </tr>
68
+ <tr>
69
+ <td>imagebind_huge</td>
70
+ <td align="right">77.7</td>
71
+ <td align="right">50.0</td>
72
+ <td align="right">54.0</td>
73
+ <td align="right">66.9</td>
74
+ <td align="right">63.4</td>
75
+ <td align="right">25.0</td>
76
+ <td><a href="https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth">checkpoint</a></td>
77
+ </tr>
78
+
79
+ </table>
80
+
81
+ ## Usage
82
+
83
+ Install pytorch 2.0+ and other 3rd party dependencies.
84
+
85
+ ```shell
86
+ conda create --name imagebind python=3.10 -y
87
+ conda activate imagebind
88
+
89
+ pip install .
90
+ ```
91
+
92
+ For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977)
93
+
94
+ ```
95
+ pip install soundfile
96
+ ```
97
+
98
+
99
+ Extract and compare features across modalities (e.g. Image, Text and Audio).
100
+
101
+ ```python
102
+ from imagebind import data
103
+ import torch
104
+ from imagebind.models import imagebind_model
105
+ from imagebind.models.imagebind_model import ModalityType
106
+
107
+ text_list=["A dog.", "A car", "A bird"]
108
+ image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"]
109
+ audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"]
110
+
111
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
112
+
113
+ # Instantiate model
114
+ model = imagebind_model.imagebind_huge(pretrained=True)
115
+ model.eval()
116
+ model.to(device)
117
+
118
+ # Load data
119
+ inputs = {
120
+ ModalityType.TEXT: data.load_and_transform_text(text_list, device),
121
+ ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device),
122
+ ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device),
123
+ }
124
+
125
+ with torch.no_grad():
126
+ embeddings = model(inputs)
127
+
128
+ print(
129
+ "Vision x Text: ",
130
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1),
131
+ )
132
+ print(
133
+ "Audio x Text: ",
134
+ torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1),
135
+ )
136
+ print(
137
+ "Vision x Audio: ",
138
+ torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1),
139
+ )
140
+
141
+ # Expected output:
142
+ #
143
+ # Vision x Text:
144
+ # tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05],
145
+ # [3.3836e-05, 9.9994e-01, 2.4118e-05],
146
+ # [4.7997e-05, 1.3496e-02, 9.8646e-01]])
147
+ #
148
+ # Audio x Text:
149
+ # tensor([[1., 0., 0.],
150
+ # [0., 1., 0.],
151
+ # [0., 0., 1.]])
152
+ #
153
+ # Vision x Audio:
154
+ # tensor([[0.8070, 0.1088, 0.0842],
155
+ # [0.1036, 0.7884, 0.1079],
156
+ # [0.0018, 0.0022, 0.9960]])
157
+
158
+ ```
159
+
160
+ ## Model card
161
+ Please see the [model card](model_card.md) for details.
162
+
163
+ ## License
164
+
165
+ ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
166
+
167
+ ## Contributing
168
+
169
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
170
+
171
+ ## Citing ImageBind
172
+
173
+ If you find this repository useful, please consider giving a star :star: and citation
174
+
175
+ ```
176
+ @inproceedings{girdhar2023imagebind,
177
+ title={ImageBind: One Embedding Space To Bind Them All},
178
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
179
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
180
+ booktitle={CVPR},
181
+ year={2023}
182
+ }
183
+ ```
ImageBind/imagebind.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ imagebind/__init__.py
5
+ imagebind/data.py
6
+ imagebind.egg-info/PKG-INFO
7
+ imagebind.egg-info/SOURCES.txt
8
+ imagebind.egg-info/dependency_links.txt
9
+ imagebind.egg-info/requires.txt
10
+ imagebind.egg-info/top_level.txt
11
+ imagebind/bpe/bpe_simple_vocab_16e6.txt.gz
12
+ imagebind/models/__init__.py
13
+ imagebind/models/helpers.py
14
+ imagebind/models/imagebind_model.py
15
+ imagebind/models/multimodal_preprocessors.py
16
+ imagebind/models/transformer.py
ImageBind/imagebind.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ https://download.pytorch.org/whl/cu113
ImageBind/imagebind.egg-info/requires.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ torchvision
3
+ torchaudio
4
+ pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@6cdc929315aab1b5674b6dcf73b16ec99147735f
5
+ timm
6
+ ftfy
7
+ regex
8
+ einops
9
+ iopath
10
+ numpy>=1.19
11
+ types-regex
ImageBind/imagebind.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ imagebind
ImageBind/imagebind/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from imagebind import data
2
+ from imagebind.models import imagebind_model
3
+ from imagebind.models.imagebind_model import ModalityType
4
+
5
+ try:
6
+ from imagebind.legrad_wrapper import ImageBindLeWrapper
7
+ except ImportError: # pragma: no cover — optional LeGrad dependency
8
+ ImageBindLeWrapper = None # type: ignore
ImageBind/imagebind/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (472 Bytes). View file
 
ImageBind/imagebind/__pycache__/data.cpython-312.pyc ADDED
Binary file (14.3 kB). View file
 
ImageBind/imagebind/__pycache__/legrad_wrapper.cpython-312.pyc ADDED
Binary file (18.1 kB). View file
 
ImageBind/imagebind/bpe/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
ImageBind/imagebind/data.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import math
10
+ import pkg_resources
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torchaudio
15
+ from PIL import Image
16
+ from pytorchvideo import transforms as pv_transforms
17
+ from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
18
+ from pytorchvideo.data.encoded_video import EncodedVideo
19
+ from torchvision import transforms
20
+
21
+ from imagebind.models.multimodal_preprocessors import SimpleTokenizer
22
+
23
+ DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
24
+
25
+
26
+ def return_bpe_path():
27
+ return pkg_resources.resource_filename(
28
+ "imagebind", "bpe/bpe_simple_vocab_16e6.txt.gz"
29
+ )
30
+
31
+
32
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
33
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
34
+ waveform -= waveform.mean()
35
+ fbank = torchaudio.compliance.kaldi.fbank(
36
+ waveform,
37
+ htk_compat=True,
38
+ sample_frequency=sample_rate,
39
+ use_energy=False,
40
+ window_type="hanning",
41
+ num_mel_bins=num_mel_bins,
42
+ dither=0.0,
43
+ frame_length=25,
44
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
45
+ )
46
+ # Convert to [mel_bins, num_frames] shape
47
+ fbank = fbank.transpose(0, 1)
48
+ # Pad to target_length
49
+ n_frames = fbank.size(1)
50
+ p = target_length - n_frames
51
+ # if p is too large (say >20%), flash a warning
52
+ if abs(p) / n_frames > 0.2:
53
+ logging.warning(
54
+ "Large gap between audio n_frames(%d) and "
55
+ "target_length (%d). Is the audio_target_length "
56
+ "setting correct?",
57
+ n_frames,
58
+ target_length,
59
+ )
60
+ # cut and pad
61
+ if p > 0:
62
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
63
+ elif p < 0:
64
+ fbank = fbank[:, 0:target_length]
65
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
66
+ # channel image
67
+ fbank = fbank.unsqueeze(0)
68
+ return fbank
69
+
70
+
71
+ def get_clip_timepoints(clip_sampler, duration):
72
+ # Read out all clips in this video
73
+ all_clips_timepoints = []
74
+ is_last_clip = False
75
+ end = 0.0
76
+ while not is_last_clip:
77
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
78
+ all_clips_timepoints.append((start, end))
79
+ return all_clips_timepoints
80
+
81
+
82
+ def load_and_transform_vision_data(image_paths, device):
83
+ if image_paths is None:
84
+ return None
85
+
86
+ image_outputs = []
87
+
88
+ data_transform = transforms.Compose(
89
+ [
90
+ transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
91
+ transforms.CenterCrop(224),
92
+ transforms.ToTensor(),
93
+ transforms.Normalize(
94
+ mean=(0.48145466, 0.4578275, 0.40821073),
95
+ std=(0.26862954, 0.26130258, 0.27577711),
96
+ ),
97
+ ]
98
+ )
99
+
100
+ for image_path in image_paths:
101
+ with open(image_path, "rb") as fopen:
102
+ image = Image.open(fopen).convert("RGB")
103
+
104
+ image = data_transform(image).to(device)
105
+ image_outputs.append(image)
106
+ return torch.stack(image_outputs, dim=0)
107
+
108
+
109
+ def load_and_transform_text(text, device):
110
+ if text is None:
111
+ return None
112
+ tokenizer = SimpleTokenizer(bpe_path=return_bpe_path())
113
+ tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
114
+ tokens = torch.cat(tokens, dim=0)
115
+ return tokens
116
+
117
+
118
+ def load_and_transform_audio_data(
119
+ audio_paths,
120
+ device,
121
+ num_mel_bins=128,
122
+ target_length=204,
123
+ sample_rate=16000,
124
+ clip_duration=2,
125
+ clips_per_video=3,
126
+ mean=-4.268,
127
+ std=9.138,
128
+ ):
129
+ if audio_paths is None:
130
+ return None
131
+
132
+ audio_outputs = []
133
+ clip_sampler = ConstantClipsPerVideoSampler(
134
+ clip_duration=clip_duration, clips_per_video=clips_per_video
135
+ )
136
+
137
+ for audio_path in audio_paths:
138
+ waveform, sr = torchaudio.load(audio_path)
139
+ if sample_rate != sr:
140
+ waveform = torchaudio.functional.resample(
141
+ waveform, orig_freq=sr, new_freq=sample_rate
142
+ )
143
+ all_clips_timepoints = get_clip_timepoints(
144
+ clip_sampler, waveform.size(1) / sample_rate
145
+ )
146
+ all_clips = []
147
+ for clip_timepoints in all_clips_timepoints:
148
+ waveform_clip = waveform[
149
+ :,
150
+ int(clip_timepoints[0] * sample_rate) : int(
151
+ clip_timepoints[1] * sample_rate
152
+ ),
153
+ ]
154
+ waveform_melspec = waveform2melspec(
155
+ waveform_clip, sample_rate, num_mel_bins, target_length
156
+ )
157
+ all_clips.append(waveform_melspec)
158
+
159
+ normalize = transforms.Normalize(mean=mean, std=std)
160
+ all_clips = [normalize(ac).to(device) for ac in all_clips]
161
+
162
+ all_clips = torch.stack(all_clips, dim=0)
163
+ audio_outputs.append(all_clips)
164
+
165
+ return torch.stack(audio_outputs, dim=0)
166
+
167
+
168
+ def crop_boxes(boxes, x_offset, y_offset):
169
+ """
170
+ Perform crop on the bounding boxes given the offsets.
171
+ Args:
172
+ boxes (ndarray or None): bounding boxes to perform crop. The dimension
173
+ is `num boxes` x 4.
174
+ x_offset (int): cropping offset in the x axis.
175
+ y_offset (int): cropping offset in the y axis.
176
+ Returns:
177
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
178
+ `num boxes` x 4.
179
+ """
180
+ cropped_boxes = boxes.copy()
181
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
182
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
183
+
184
+ return cropped_boxes
185
+
186
+
187
+ def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
188
+ """
189
+ Perform uniform spatial sampling on the images and corresponding boxes.
190
+ Args:
191
+ images (tensor): images to perform uniform crop. The dimension is
192
+ `num frames` x `channel` x `height` x `width`.
193
+ size (int): size of height and weight to crop the images.
194
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
195
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
196
+ crop if height is larger than width.
197
+ boxes (ndarray or None): optional. Corresponding boxes to images.
198
+ Dimension is `num boxes` x 4.
199
+ scale_size (int): optinal. If not None, resize the images to scale_size before
200
+ performing any crop.
201
+ Returns:
202
+ cropped (tensor): images with dimension of
203
+ `num frames` x `channel` x `size` x `size`.
204
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
205
+ `num boxes` x 4.
206
+ """
207
+ assert spatial_idx in [0, 1, 2]
208
+ ndim = len(images.shape)
209
+ if ndim == 3:
210
+ images = images.unsqueeze(0)
211
+ height = images.shape[2]
212
+ width = images.shape[3]
213
+
214
+ if scale_size is not None:
215
+ if width <= height:
216
+ width, height = scale_size, int(height / width * scale_size)
217
+ else:
218
+ width, height = int(width / height * scale_size), scale_size
219
+ images = torch.nn.functional.interpolate(
220
+ images,
221
+ size=(height, width),
222
+ mode="bilinear",
223
+ align_corners=False,
224
+ )
225
+
226
+ y_offset = int(math.ceil((height - size) / 2))
227
+ x_offset = int(math.ceil((width - size) / 2))
228
+
229
+ if height > width:
230
+ if spatial_idx == 0:
231
+ y_offset = 0
232
+ elif spatial_idx == 2:
233
+ y_offset = height - size
234
+ else:
235
+ if spatial_idx == 0:
236
+ x_offset = 0
237
+ elif spatial_idx == 2:
238
+ x_offset = width - size
239
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
240
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
241
+ if ndim == 3:
242
+ cropped = cropped.squeeze(0)
243
+ return cropped, cropped_boxes
244
+
245
+
246
+ class SpatialCrop(nn.Module):
247
+ """
248
+ Convert the video into 3 smaller clips spatially. Must be used after the
249
+ temporal crops to get spatial crops, and should be used with
250
+ -2 in the spatial crop at the slowfast augmentation stage (so full
251
+ frames are passed in here). Will return a larger list with the
252
+ 3x spatial crops as well.
253
+ """
254
+
255
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
256
+ super().__init__()
257
+ self.crop_size = crop_size
258
+ if num_crops == 3:
259
+ self.crops_to_ext = [0, 1, 2]
260
+ self.flipped_crops_to_ext = []
261
+ elif num_crops == 1:
262
+ self.crops_to_ext = [1]
263
+ self.flipped_crops_to_ext = []
264
+ else:
265
+ raise NotImplementedError("Nothing else supported yet")
266
+
267
+ def forward(self, videos):
268
+ """
269
+ Args:
270
+ videos: A list of C, T, H, W videos.
271
+ Returns:
272
+ videos: A list with 3x the number of elements. Each video converted
273
+ to C, T, H', W' by spatial cropping.
274
+ """
275
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
276
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
277
+ res = []
278
+ for video in videos:
279
+ for spatial_idx in self.crops_to_ext:
280
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
281
+ if not self.flipped_crops_to_ext:
282
+ continue
283
+ flipped_video = transforms.functional.hflip(video)
284
+ for spatial_idx in self.flipped_crops_to_ext:
285
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
286
+ return res
287
+
288
+
289
+ class NormalizeVideo:
290
+ def __init__(self, mean, std, inplace=False):
291
+ self.mean = mean
292
+ self.std = std
293
+ self.inplace = inplace
294
+
295
+ def __call__(self, clip):
296
+ if not self.inplace:
297
+ clip = clip.clone()
298
+ mean = torch.as_tensor(self.mean, dtype=clip.dtype, device=clip.device)
299
+ std = torch.as_tensor(self.std, dtype=clip.dtype, device=clip.device)
300
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
301
+ return clip
302
+
303
+
304
+ def load_and_transform_video_data(
305
+ video_paths,
306
+ device,
307
+ clip_duration=2,
308
+ clips_per_video=5,
309
+ sample_rate=16000,
310
+ ):
311
+ if video_paths is None:
312
+ return None
313
+
314
+ video_outputs = []
315
+ video_transform = transforms.Compose(
316
+ [
317
+ pv_transforms.ShortSideScale(224),
318
+ NormalizeVideo(
319
+ mean=(0.48145466, 0.4578275, 0.40821073),
320
+ std=(0.26862954, 0.26130258, 0.27577711),
321
+ ),
322
+ ]
323
+ )
324
+
325
+ clip_sampler = ConstantClipsPerVideoSampler(
326
+ clip_duration=clip_duration, clips_per_video=clips_per_video
327
+ )
328
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
329
+
330
+ for video_path in video_paths:
331
+ video = EncodedVideo.from_path(
332
+ video_path,
333
+ decoder="decord",
334
+ decode_audio=False,
335
+ **{"sample_rate": sample_rate},
336
+ )
337
+
338
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
339
+
340
+ all_video = []
341
+ for clip_timepoints in all_clips_timepoints:
342
+ # Read the clip, get frames
343
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
344
+ if clip is None:
345
+ raise ValueError("No clip found")
346
+ video_clip = frame_sampler(clip["video"])
347
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
348
+
349
+ all_video.append(video_clip)
350
+
351
+ all_video = [video_transform(clip) for clip in all_video]
352
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
353
+
354
+ all_video = torch.stack(all_video, dim=0)
355
+ video_outputs.append(all_video)
356
+
357
+ return torch.stack(video_outputs, dim=0).to(device)
ImageBind/imagebind/legrad_wrapper.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LeGrad for ImageBind — same spirit as ``legrad.wrapper.LeWrapper`` / ``legrad_api.ipynb``:
3
+ hook residual blocks + PyTorch ``nn.MultiheadAttention``, then
4
+ ``grad(sum(text · vision))`` w.r.t. attention probabilities.
5
+
6
+ Requires the ``legrad`` package (``pip install -e /path/to/LeGrad`` or PYTHONPATH).
7
+
8
+ Vision: heatmap over image patches (CLS query → patch keys).
9
+ Text: relevance vector over context positions (EOS query row → all keys).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import types
16
+ from typing import List, Optional, Sequence
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from imagebind.models.imagebind_model import ImageBindModel, ModalityType
23
+
24
+
25
+ def _import_legrad_utils():
26
+ try:
27
+ from legrad.utils import hooked_torch_multi_head_attention_forward, min_max
28
+
29
+ return hooked_torch_multi_head_attention_forward, min_max
30
+ except ImportError as e: # pragma: no cover
31
+ raise ImportError(
32
+ "ImageBind LeGrad needs the `legrad` package. Install with "
33
+ "`pip install -e <path-to-LeGrad>` or add LeGrad to PYTHONPATH."
34
+ ) from e
35
+
36
+
37
+ def hooked_imagebind_block_forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
38
+ """Store features after attention and after MLP (ImageBind ``BlockWithMasking``)."""
39
+ if self.layer_scale_type is None:
40
+ x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
41
+ self.feat_post_attn = x
42
+ x = x + self.drop_path(self.mlp(self.norm_2(x)))
43
+ self.feat_post_mlp = x
44
+ else:
45
+ x = (
46
+ x
47
+ + self.drop_path(self.attn(self.norm_1(x), attn_mask))
48
+ * self.layer_scale_gamma1
49
+ )
50
+ self.feat_post_attn = x
51
+ x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
52
+ self.feat_post_mlp = x
53
+ return x
54
+
55
+
56
+ def _make_hooked_imagebind_mha_forward(hooked_torch_mha_forward):
57
+ def hooked_imagebind_mha_forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
58
+ """Adapter: LeGrad hooked MHA expects ``(q,k,v,...)``; ImageBind calls ``(x, attn_mask)``."""
59
+ out, _ = hooked_torch_mha_forward(
60
+ self,
61
+ x,
62
+ x,
63
+ x,
64
+ key_padding_mask=None,
65
+ need_weights=True,
66
+ attn_mask=attn_mask,
67
+ )
68
+ return out
69
+
70
+ return hooked_imagebind_mha_forward
71
+
72
+
73
+ class ImageBindLeWrapper(nn.Module):
74
+ """
75
+ Thin wrapper around ``ImageBindModel`` for LeGrad (vision and/or text branches).
76
+
77
+ Mirrors ``LeWrapper`` from ``legrad/wrapper.py``: copies public attributes/methods from
78
+ the base model, patches transformer blocks and attention with hooks, and provides
79
+ ``compute_legrad_*`` helpers similar to ``compute_legrad_coca`` / ``compute_legrad_clip``.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ model: ImageBindModel,
85
+ layer_index: int = -2,
86
+ trunk_key: str = ModalityType.VISION,
87
+ ):
88
+ super().__init__()
89
+ for attr in dir(model):
90
+ if not attr.startswith("__"):
91
+ setattr(self, attr, getattr(model, attr))
92
+
93
+ self._legrad_trunk_key = trunk_key
94
+ hooked_torch_mha_forward, self._min_max = _import_legrad_utils()
95
+ self._hooked_mha_fn = _make_hooked_imagebind_mha_forward(hooked_torch_mha_forward)
96
+ self._activate_hooks(layer_index=layer_index, trunk_key=trunk_key)
97
+
98
+ def _trunk(self, key: Optional[str] = None):
99
+ key = key or self._legrad_trunk_key
100
+ return self.modality_trunks[key]
101
+
102
+ def _activate_hooks(self, layer_index: int, trunk_key: str) -> None:
103
+ trunk = self._trunk(trunk_key)
104
+ n_blocks = len(trunk.blocks)
105
+ self.starting_depth = (
106
+ layer_index if layer_index >= 0 else n_blocks + layer_index
107
+ )
108
+ self.starting_depth = max(0, min(self.starting_depth, n_blocks - 1))
109
+
110
+ prefix = f"modality_trunks.{trunk_key}.blocks"
111
+ for name, param in self.named_parameters():
112
+ param.requires_grad = False
113
+ if name.startswith(prefix):
114
+ depth = int(name.split(f"{prefix}.")[-1].split(".")[0])
115
+ if depth >= self.starting_depth:
116
+ param.requires_grad = True
117
+
118
+ for layer in range(self.starting_depth, n_blocks):
119
+ blk = trunk.blocks[layer]
120
+ blk.forward = types.MethodType(hooked_imagebind_block_forward, blk)
121
+ blk.attn.forward = types.MethodType(self._hooked_mha_fn, blk.attn)
122
+
123
+ print(
124
+ f"LeGrad (ImageBind): hooks on `{trunk_key}` blocks "
125
+ f"[{self.starting_depth}, {n_blocks - 1}] — gradients enabled from block "
126
+ f"{self.starting_depth} onward."
127
+ )
128
+
129
+ def _encode_vision_trunk(self, vision: torch.Tensor) -> torch.Tensor:
130
+ p = self.modality_preprocessors[ModalityType.VISION](vision=vision)
131
+ return self.modality_trunks[ModalityType.VISION](**p["trunk"])
132
+
133
+ def _encode_text_trunk(self, text: torch.Tensor) -> torch.Tensor:
134
+ p = self.modality_preprocessors[ModalityType.TEXT](text=text)
135
+ self._text_head_kwargs = dict(p.get("head", {}))
136
+ return self.modality_trunks[ModalityType.TEXT](**p["trunk"])
137
+
138
+ def _vision_embed_from_layer(self, layer_idx: int) -> torch.Tensor:
139
+ x_bld = (
140
+ self._trunk(ModalityType.VISION).blocks[layer_idx].feat_post_mlp.permute(
141
+ 1, 0, 2
142
+ )
143
+ )
144
+ h = self.modality_heads[ModalityType.VISION](x_bld)
145
+ return self.modality_postprocessors[ModalityType.VISION](h)
146
+
147
+ def _text_embed_from_layer(self, layer_idx: int) -> torch.Tensor:
148
+ x_bld = (
149
+ self._trunk(ModalityType.TEXT).blocks[layer_idx].feat_post_mlp.permute(
150
+ 1, 0, 2
151
+ )
152
+ )
153
+ h = self.modality_heads[ModalityType.TEXT](x_bld, **self._text_head_kwargs)
154
+ return self.modality_postprocessors[ModalityType.TEXT](h)
155
+
156
+ @staticmethod
157
+ def _cls_to_patch_relevance(
158
+ attn_grad: torch.Tensor, batch_size: int, num_heads: int
159
+ ) -> torch.Tensor:
160
+ """attn_grad: (B*H, L, L) -> (B, num_patches) CLS row, patch columns."""
161
+ L = attn_grad.shape[-1]
162
+ g = attn_grad.view(batch_size, num_heads, L, L).clamp(min=0.0)
163
+ g = g.mean(dim=1)
164
+ return g[:, 0, 1:]
165
+
166
+ @staticmethod
167
+ def _relevance_to_spatial_map(
168
+ relevance: torch.Tensor, patches_layout: Sequence[int], out_hw: tuple = (224, 224)
169
+ ) -> torch.Tensor:
170
+ """relevance: (num_patches,) → (1,1,H,W) upsampled."""
171
+ pl = tuple(patches_layout)
172
+ if len(pl) == 3:
173
+ t, h, w = pl
174
+ g = relevance.reshape(t, h, w).float()
175
+ g = g.mean(dim=0) if t > 1 else g[0]
176
+ elif len(pl) == 2:
177
+ g = relevance.reshape(pl[0], pl[1]).float()
178
+ else:
179
+ side = int(math.sqrt(relevance.numel()))
180
+ g = relevance.reshape(side, side).float()
181
+ m = g.unsqueeze(0).unsqueeze(0)
182
+ return F.interpolate(m, size=out_hw, mode="bilinear", align_corners=False)
183
+
184
+ def compute_legrad_imagebind(
185
+ self,
186
+ text_embedding: torch.Tensor,
187
+ vision: Optional[torch.Tensor] = None,
188
+ normalize: bool = True,
189
+ ) -> torch.Tensor:
190
+ """
191
+ Accumulate LeGrad maps over vision blocks ``[starting_depth, n_blocks)`` (CLIP-style).
192
+
193
+ ``text_embedding``: (B, D) same ordering as ``vision`` batch, L2-normalized like
194
+ ``model({TEXT: ...})`` outputs.
195
+ """
196
+ if vision is not None:
197
+ _ = self._encode_vision_trunk(vision)
198
+
199
+ trunk = self._trunk(ModalityType.VISION)
200
+ blocks: List = list(trunk.blocks)
201
+ layout = self.modality_preprocessors[ModalityType.VISION].patches_layout
202
+ num_heads = blocks[0].attn.num_heads
203
+ bsz = text_embedding.shape[0]
204
+
205
+ accum = 0.0
206
+ for layer in range(self.starting_depth, len(blocks)):
207
+ self.zero_grad(set_to_none=True)
208
+ vision_emb = self._vision_embed_from_layer(layer)
209
+ one_hot = (text_embedding * vision_emb).sum()
210
+ attn_map = blocks[layer].attn.attention_maps
211
+ grad = torch.autograd.grad(
212
+ one_hot, [attn_map], retain_graph=True, create_graph=True
213
+ )[0]
214
+ rel = self._cls_to_patch_relevance(grad, bsz, num_heads)
215
+ expl = self._relevance_to_spatial_map(rel[0], layout)
216
+ accum = accum + expl
217
+
218
+ if normalize:
219
+ accum = self._min_max(accum)
220
+ return accum
221
+
222
+ def compute_legrad_imagebind_one_layer(
223
+ self,
224
+ text_embedding: torch.Tensor,
225
+ vision: Optional[torch.Tensor] = None,
226
+ layer_idx: Optional[int] = None,
227
+ normalize: bool = True,
228
+ ) -> torch.Tensor:
229
+ """Single vision block (``legrad_api.compute_legrad_coca_one_layer`` style)."""
230
+ if vision is not None:
231
+ _ = self._encode_vision_trunk(vision)
232
+
233
+ trunk = self._trunk(ModalityType.VISION)
234
+ blocks = trunk.blocks
235
+ n_blocks = len(blocks)
236
+ if layer_idx is None:
237
+ layer_idx = n_blocks - 1
238
+ if layer_idx < self.starting_depth or layer_idx >= n_blocks:
239
+ raise ValueError(
240
+ f"layer_idx must be in [{self.starting_depth}, {n_blocks - 1}], got {layer_idx}"
241
+ )
242
+
243
+ layout = self.modality_preprocessors[ModalityType.VISION].patches_layout
244
+ num_heads = blocks[layer_idx].attn.num_heads
245
+ bsz = text_embedding.shape[0]
246
+
247
+ self.zero_grad(set_to_none=True)
248
+ vision_emb = self._vision_embed_from_layer(layer_idx)
249
+ one_hot = (text_embedding * vision_emb).sum()
250
+ attn_map = blocks[layer_idx].attn.attention_maps
251
+ grad = torch.autograd.grad(
252
+ one_hot, [attn_map], retain_graph=True, create_graph=True
253
+ )[0]
254
+ rel = self._cls_to_patch_relevance(grad, bsz, num_heads)
255
+ expl = self._relevance_to_spatial_map(rel[0], layout)
256
+ if normalize:
257
+ expl = (expl - expl.min()) / (expl.max() - expl.min() + 1e-8)
258
+ return expl
259
+
260
+ def compute_legrad_text_imagebind(
261
+ self,
262
+ vision_embedding: torch.Tensor,
263
+ text: torch.Tensor,
264
+ layer_idx: Optional[int] = None,
265
+ normalize: bool = True,
266
+ ) -> torch.Tensor:
267
+ """
268
+ Text-branch LeGrad: gradient of ``sum(vision · text)`` w.r.t. attention at one layer.
269
+
270
+ ``vision_embedding``: (B, D) detached reference (e.g. from ``model({VISION})``).
271
+ ``text``: token ids (B, L). Returns (B, L_ctx) relevance over token positions for EOS
272
+ query row (uses ``seq_len`` from the text preprocessor).
273
+ """
274
+ if self._legrad_trunk_key != ModalityType.TEXT:
275
+ raise RuntimeError(
276
+ "compute_legrad_text_imagebind requires wrapping with trunk_key=TEXT. "
277
+ "Instantiate ImageBindLeWrapper(model, layer_index=..., trunk_key=ModalityType.TEXT)."
278
+ )
279
+
280
+ _ = self._encode_text_trunk(text)
281
+
282
+ trunk = self._trunk(ModalityType.TEXT)
283
+ blocks = trunk.blocks
284
+ n_blocks = len(blocks)
285
+ if layer_idx is None:
286
+ layer_idx = n_blocks - 1
287
+ seq_len = self._text_head_kwargs["seq_len"]
288
+ num_heads = blocks[layer_idx].attn.num_heads
289
+ bsz = vision_embedding.shape[0]
290
+
291
+ self.zero_grad(set_to_none=True)
292
+ text_emb = self._text_embed_from_layer(layer_idx)
293
+ one_hot = (vision_embedding.detach() * text_emb).sum()
294
+ attn_map = blocks[layer_idx].attn.attention_maps
295
+ grad = torch.autograd.grad(
296
+ one_hot, [attn_map], retain_graph=True, create_graph=True
297
+ )[0]
298
+ # (B*H, L, L) → EOS query → key importances
299
+ L = grad.shape[-1]
300
+ g = grad.view(bsz, num_heads, L, L).clamp(min=0.0).mean(dim=1)
301
+ idx = torch.arange(bsz, device=g.device)
302
+ eos_rel = g[idx, seq_len, :]
303
+ if normalize:
304
+ eos_rel = self._min_max(eos_rel)
305
+ return eos_rel
306
+
307
+ def compute_legrad(
308
+ self,
309
+ text_embedding: torch.Tensor,
310
+ vision: Optional[torch.Tensor] = None,
311
+ trunk: str = "vision",
312
+ ) -> torch.Tensor:
313
+ """Dispatch: ``trunk=='vision'`` → ``compute_legrad_imagebind`` (multi-layer sum)."""
314
+ if trunk in ("vision", ModalityType.VISION):
315
+ return self.compute_legrad_imagebind(text_embedding, vision=vision)
316
+ raise ValueError(f"Unknown trunk {trunk!r}; use compute_legrad_* methods directly.")
ImageBind/imagebind/models/__init__.py ADDED
File without changes
ImageBind/imagebind/models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (164 Bytes). View file
 
ImageBind/imagebind/models/__pycache__/helpers.cpython-312.pyc ADDED
Binary file (7.84 kB). View file
 
ImageBind/imagebind/models/__pycache__/imagebind_model.cpython-312.pyc ADDED
Binary file (14.9 kB). View file
 
ImageBind/imagebind/models/__pycache__/multimodal_preprocessors.cpython-312.pyc ADDED
Binary file (33.3 kB). View file
 
ImageBind/imagebind/models/__pycache__/transformer.cpython-312.pyc ADDED
Binary file (15.2 kB). View file
 
ImageBind/imagebind/models/helpers.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+
9
+ import einops
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+
14
+
15
+ class Normalize(nn.Module):
16
+ def __init__(self, dim: int) -> None:
17
+ super().__init__()
18
+ self.dim = dim
19
+
20
+ def forward(self, x):
21
+ return torch.nn.functional.normalize(x, dim=self.dim, p=2)
22
+
23
+
24
+ class LearnableLogitScaling(nn.Module):
25
+ def __init__(
26
+ self,
27
+ logit_scale_init: float = 1 / 0.07,
28
+ learnable: bool = True,
29
+ max_logit_scale: float = 100,
30
+ ) -> None:
31
+ super().__init__()
32
+ self.max_logit_scale = max_logit_scale
33
+ self.logit_scale_init = logit_scale_init
34
+ self.learnable = learnable
35
+ log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init)
36
+ if learnable:
37
+ self.log_logit_scale = nn.Parameter(log_logit_scale)
38
+ else:
39
+ self.register_buffer("log_logit_scale", log_logit_scale)
40
+
41
+ def forward(self, x):
42
+ return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x
43
+
44
+ def extra_repr(self):
45
+ st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \
46
+ f" max_logit_scale={self.max_logit_scale}"
47
+ return st
48
+
49
+
50
+ class EinOpsRearrange(nn.Module):
51
+ def __init__(self, rearrange_expr: str, **kwargs) -> None:
52
+ super().__init__()
53
+ self.rearrange_expr = rearrange_expr
54
+ self.kwargs = kwargs
55
+
56
+ def forward(self, x):
57
+ assert isinstance(x, torch.Tensor)
58
+ return einops.rearrange(x, self.rearrange_expr, **self.kwargs)
59
+
60
+
61
+ class VerboseNNModule(nn.Module):
62
+ """
63
+ Wrapper around nn.Module that prints registered buffers and parameter names.
64
+ """
65
+
66
+ @staticmethod
67
+ def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str:
68
+ st = (
69
+ "("
70
+ + name
71
+ + "): "
72
+ + "tensor("
73
+ + str(tuple(tensor[1].shape))
74
+ + ", requires_grad="
75
+ + str(tensor[1].requires_grad)
76
+ + ")\n"
77
+ )
78
+ return st
79
+
80
+ def extra_repr(self) -> str:
81
+ named_modules = set()
82
+ for p in self.named_modules():
83
+ named_modules.update([p[0]])
84
+ named_modules = list(named_modules)
85
+
86
+ string_repr = ""
87
+ for p in self.named_parameters():
88
+ name = p[0].split(".")[0]
89
+ if name not in named_modules:
90
+ string_repr += self.get_readable_tensor_repr(name, p)
91
+
92
+ for p in self.named_buffers():
93
+ name = p[0].split(".")[0]
94
+ string_repr += self.get_readable_tensor_repr(name, p)
95
+
96
+ return string_repr
97
+
98
+
99
+ def cast_if_src_dtype(
100
+ tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype
101
+ ):
102
+ updated = False
103
+ if tensor.dtype == src_dtype:
104
+ tensor = tensor.to(dtype=tgt_dtype)
105
+ updated = True
106
+ return tensor, updated
107
+
108
+
109
+ class QuickGELU(nn.Module):
110
+ # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166
111
+ def forward(self, x: torch.Tensor):
112
+ return x * torch.sigmoid(1.702 * x)
113
+
114
+
115
+ class SelectElement(nn.Module):
116
+ def __init__(self, index) -> None:
117
+ super().__init__()
118
+ self.index = index
119
+
120
+ def forward(self, x):
121
+ assert x.ndim >= 3
122
+ return x[:, self.index, ...]
123
+
124
+
125
+ class SelectEOSAndProject(nn.Module):
126
+ """
127
+ Text Pooling used in OpenCLIP
128
+ """
129
+
130
+ def __init__(self, proj: nn.Module) -> None:
131
+ super().__init__()
132
+ self.proj = proj
133
+
134
+ def forward(self, x, seq_len):
135
+ assert x.ndim == 3
136
+ # x is of shape B x L x D
137
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
138
+ x = x[torch.arange(x.shape[0]), seq_len]
139
+ x = self.proj(x)
140
+ return x
ImageBind/imagebind/models/imagebind_model.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+
9
+ import os
10
+ from functools import partial
11
+ from types import SimpleNamespace
12
+ from typing import Optional, Sequence
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+
17
+ from imagebind.models.helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize,
18
+ SelectElement, SelectEOSAndProject)
19
+ from imagebind.models.multimodal_preprocessors import (AudioPreprocessor,
20
+ IMUPreprocessor, PadIm2Video,
21
+ PatchEmbedGeneric,
22
+ RGBDTPreprocessor,
23
+ SpatioTemporalPosEmbeddingHelper,
24
+ TextPreprocessor,
25
+ ThermalPreprocessor)
26
+ from imagebind.models.transformer import MultiheadAttention, SimpleTransformer
27
+
28
+ ModalityType = SimpleNamespace(
29
+ VISION="vision",
30
+ TEXT="text",
31
+ AUDIO="audio",
32
+ THERMAL="thermal",
33
+ DEPTH="depth",
34
+ IMU="imu",
35
+ )
36
+
37
+
38
+ class ImageBindModel(nn.Module):
39
+ def __init__(
40
+ self,
41
+ video_frames=2,
42
+ kernel_size=(2, 14, 14),
43
+ audio_kernel_size=16,
44
+ audio_stride=10,
45
+ out_embed_dim=768,
46
+ vision_embed_dim=1024,
47
+ vision_num_blocks=24,
48
+ vision_num_heads=16,
49
+ audio_embed_dim=768,
50
+ audio_num_blocks=12,
51
+ audio_num_heads=12,
52
+ audio_num_mel_bins=128,
53
+ audio_target_len=204,
54
+ audio_drop_path=0.1,
55
+ text_embed_dim=768,
56
+ text_num_blocks=12,
57
+ text_num_heads=12,
58
+ depth_embed_dim=384,
59
+ depth_kernel_size=16,
60
+ depth_num_blocks=12,
61
+ depth_num_heads=8,
62
+ depth_drop_path=0.0,
63
+ thermal_embed_dim=768,
64
+ thermal_kernel_size=16,
65
+ thermal_num_blocks=12,
66
+ thermal_num_heads=12,
67
+ thermal_drop_path=0.0,
68
+ imu_embed_dim=512,
69
+ imu_kernel_size=8,
70
+ imu_num_blocks=6,
71
+ imu_num_heads=8,
72
+ imu_drop_path=0.7,
73
+ ):
74
+ super().__init__()
75
+
76
+ self.modality_preprocessors = self._create_modality_preprocessors(
77
+ video_frames,
78
+ vision_embed_dim,
79
+ kernel_size,
80
+ text_embed_dim,
81
+ audio_embed_dim,
82
+ audio_kernel_size,
83
+ audio_stride,
84
+ audio_num_mel_bins,
85
+ audio_target_len,
86
+ depth_embed_dim,
87
+ depth_kernel_size,
88
+ thermal_embed_dim,
89
+ thermal_kernel_size,
90
+ imu_embed_dim,
91
+ )
92
+
93
+ self.modality_trunks = self._create_modality_trunks(
94
+ vision_embed_dim,
95
+ vision_num_blocks,
96
+ vision_num_heads,
97
+ text_embed_dim,
98
+ text_num_blocks,
99
+ text_num_heads,
100
+ audio_embed_dim,
101
+ audio_num_blocks,
102
+ audio_num_heads,
103
+ audio_drop_path,
104
+ depth_embed_dim,
105
+ depth_num_blocks,
106
+ depth_num_heads,
107
+ depth_drop_path,
108
+ thermal_embed_dim,
109
+ thermal_num_blocks,
110
+ thermal_num_heads,
111
+ thermal_drop_path,
112
+ imu_embed_dim,
113
+ imu_num_blocks,
114
+ imu_num_heads,
115
+ imu_drop_path,
116
+ )
117
+
118
+ self.modality_heads = self._create_modality_heads(
119
+ out_embed_dim,
120
+ vision_embed_dim,
121
+ text_embed_dim,
122
+ audio_embed_dim,
123
+ depth_embed_dim,
124
+ thermal_embed_dim,
125
+ imu_embed_dim,
126
+ )
127
+
128
+ self.modality_postprocessors = self._create_modality_postprocessors(
129
+ out_embed_dim
130
+ )
131
+
132
+ def _create_modality_preprocessors(
133
+ self,
134
+ video_frames=2,
135
+ vision_embed_dim=1024,
136
+ kernel_size=(2, 14, 14),
137
+ text_embed_dim=768,
138
+ audio_embed_dim=768,
139
+ audio_kernel_size=16,
140
+ audio_stride=10,
141
+ audio_num_mel_bins=128,
142
+ audio_target_len=204,
143
+ depth_embed_dim=768,
144
+ depth_kernel_size=16,
145
+ thermal_embed_dim=768,
146
+ thermal_kernel_size=16,
147
+ imu_embed_dim=512,
148
+ ):
149
+ rgbt_stem = PatchEmbedGeneric(
150
+ proj_stem=[
151
+ PadIm2Video(pad_type="repeat", ntimes=2),
152
+ nn.Conv3d(
153
+ in_channels=3,
154
+ kernel_size=kernel_size,
155
+ out_channels=vision_embed_dim,
156
+ stride=kernel_size,
157
+ bias=False,
158
+ ),
159
+ ]
160
+ )
161
+ rgbt_preprocessor = RGBDTPreprocessor(
162
+ img_size=[3, video_frames, 224, 224],
163
+ num_cls_tokens=1,
164
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
165
+ rgbt_stem=rgbt_stem,
166
+ depth_stem=None,
167
+ )
168
+
169
+ text_preprocessor = TextPreprocessor(
170
+ context_length=77,
171
+ vocab_size=49408,
172
+ embed_dim=text_embed_dim,
173
+ causal_masking=True,
174
+ )
175
+
176
+ audio_stem = PatchEmbedGeneric(
177
+ proj_stem=[
178
+ nn.Conv2d(
179
+ in_channels=1,
180
+ kernel_size=audio_kernel_size,
181
+ stride=audio_stride,
182
+ out_channels=audio_embed_dim,
183
+ bias=False,
184
+ ),
185
+ ],
186
+ norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim),
187
+ )
188
+ audio_preprocessor = AudioPreprocessor(
189
+ img_size=[1, audio_num_mel_bins, audio_target_len],
190
+ num_cls_tokens=1,
191
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
192
+ audio_stem=audio_stem,
193
+ )
194
+
195
+ depth_stem = PatchEmbedGeneric(
196
+ [
197
+ nn.Conv2d(
198
+ kernel_size=depth_kernel_size,
199
+ in_channels=1,
200
+ out_channels=depth_embed_dim,
201
+ stride=depth_kernel_size,
202
+ bias=False,
203
+ ),
204
+ ],
205
+ norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim),
206
+ )
207
+
208
+ depth_preprocessor = RGBDTPreprocessor(
209
+ img_size=[1, 224, 224],
210
+ num_cls_tokens=1,
211
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
212
+ rgbt_stem=None,
213
+ depth_stem=depth_stem,
214
+ )
215
+
216
+ thermal_stem = PatchEmbedGeneric(
217
+ [
218
+ nn.Conv2d(
219
+ kernel_size=thermal_kernel_size,
220
+ in_channels=1,
221
+ out_channels=thermal_embed_dim,
222
+ stride=thermal_kernel_size,
223
+ bias=False,
224
+ ),
225
+ ],
226
+ norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim),
227
+ )
228
+ thermal_preprocessor = ThermalPreprocessor(
229
+ img_size=[1, 224, 224],
230
+ num_cls_tokens=1,
231
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
232
+ thermal_stem=thermal_stem,
233
+ )
234
+
235
+ imu_stem = PatchEmbedGeneric(
236
+ [
237
+ nn.Linear(
238
+ in_features=48,
239
+ out_features=imu_embed_dim,
240
+ bias=False,
241
+ ),
242
+ ],
243
+ norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim),
244
+ )
245
+
246
+ imu_preprocessor = IMUPreprocessor(
247
+ img_size=[6, 2000],
248
+ num_cls_tokens=1,
249
+ kernel_size=8,
250
+ embed_dim=imu_embed_dim,
251
+ pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True),
252
+ imu_stem=imu_stem,
253
+ )
254
+
255
+ modality_preprocessors = {
256
+ ModalityType.VISION: rgbt_preprocessor,
257
+ ModalityType.TEXT: text_preprocessor,
258
+ ModalityType.AUDIO: audio_preprocessor,
259
+ ModalityType.DEPTH: depth_preprocessor,
260
+ ModalityType.THERMAL: thermal_preprocessor,
261
+ ModalityType.IMU: imu_preprocessor,
262
+ }
263
+
264
+ return nn.ModuleDict(modality_preprocessors)
265
+
266
+ def _create_modality_trunks(
267
+ self,
268
+ vision_embed_dim=1024,
269
+ vision_num_blocks=24,
270
+ vision_num_heads=16,
271
+ text_embed_dim=768,
272
+ text_num_blocks=12,
273
+ text_num_heads=12,
274
+ audio_embed_dim=768,
275
+ audio_num_blocks=12,
276
+ audio_num_heads=12,
277
+ audio_drop_path=0.0,
278
+ depth_embed_dim=768,
279
+ depth_num_blocks=12,
280
+ depth_num_heads=12,
281
+ depth_drop_path=0.0,
282
+ thermal_embed_dim=768,
283
+ thermal_num_blocks=12,
284
+ thermal_num_heads=12,
285
+ thermal_drop_path=0.0,
286
+ imu_embed_dim=512,
287
+ imu_num_blocks=6,
288
+ imu_num_heads=8,
289
+ imu_drop_path=0.7,
290
+ ):
291
+ def instantiate_trunk(
292
+ embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path
293
+ ):
294
+ return SimpleTransformer(
295
+ embed_dim=embed_dim,
296
+ num_blocks=num_blocks,
297
+ ffn_dropout_rate=0.0,
298
+ drop_path_rate=drop_path,
299
+ attn_target=partial(
300
+ MultiheadAttention,
301
+ embed_dim=embed_dim,
302
+ num_heads=num_heads,
303
+ bias=True,
304
+ add_bias_kv=add_bias_kv,
305
+ ),
306
+ pre_transformer_layer=nn.Sequential(
307
+ nn.LayerNorm(embed_dim, eps=1e-6)
308
+ if pre_transformer_ln
309
+ else nn.Identity(),
310
+ EinOpsRearrange("b l d -> l b d"),
311
+ ),
312
+ post_transformer_layer=EinOpsRearrange("l b d -> b l d"),
313
+ )
314
+
315
+ modality_trunks = {}
316
+ modality_trunks[ModalityType.VISION] = instantiate_trunk(
317
+ vision_embed_dim,
318
+ vision_num_blocks,
319
+ vision_num_heads,
320
+ pre_transformer_ln=True,
321
+ add_bias_kv=False,
322
+ drop_path=0.0,
323
+ )
324
+ modality_trunks[ModalityType.TEXT] = instantiate_trunk(
325
+ text_embed_dim,
326
+ text_num_blocks,
327
+ text_num_heads,
328
+ pre_transformer_ln=False,
329
+ add_bias_kv=False,
330
+ drop_path=0.0,
331
+ )
332
+ modality_trunks[ModalityType.AUDIO] = instantiate_trunk(
333
+ audio_embed_dim,
334
+ audio_num_blocks,
335
+ audio_num_heads,
336
+ pre_transformer_ln=False,
337
+ add_bias_kv=True,
338
+ drop_path=audio_drop_path,
339
+ )
340
+ modality_trunks[ModalityType.DEPTH] = instantiate_trunk(
341
+ depth_embed_dim,
342
+ depth_num_blocks,
343
+ depth_num_heads,
344
+ pre_transformer_ln=False,
345
+ add_bias_kv=True,
346
+ drop_path=depth_drop_path,
347
+ )
348
+ modality_trunks[ModalityType.THERMAL] = instantiate_trunk(
349
+ thermal_embed_dim,
350
+ thermal_num_blocks,
351
+ thermal_num_heads,
352
+ pre_transformer_ln=False,
353
+ add_bias_kv=True,
354
+ drop_path=thermal_drop_path,
355
+ )
356
+ modality_trunks[ModalityType.IMU] = instantiate_trunk(
357
+ imu_embed_dim,
358
+ imu_num_blocks,
359
+ imu_num_heads,
360
+ pre_transformer_ln=False,
361
+ add_bias_kv=True,
362
+ drop_path=imu_drop_path,
363
+ )
364
+
365
+ return nn.ModuleDict(modality_trunks)
366
+
367
+ def _create_modality_heads(
368
+ self,
369
+ out_embed_dim,
370
+ vision_embed_dim,
371
+ text_embed_dim,
372
+ audio_embed_dim,
373
+ depth_embed_dim,
374
+ thermal_embed_dim,
375
+ imu_embed_dim,
376
+ ):
377
+ modality_heads = {}
378
+
379
+ modality_heads[ModalityType.VISION] = nn.Sequential(
380
+ nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6),
381
+ SelectElement(index=0),
382
+ nn.Linear(vision_embed_dim, out_embed_dim, bias=False),
383
+ )
384
+
385
+ modality_heads[ModalityType.TEXT] = SelectEOSAndProject(
386
+ proj=nn.Sequential(
387
+ nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6),
388
+ nn.Linear(text_embed_dim, out_embed_dim, bias=False),
389
+ )
390
+ )
391
+
392
+ modality_heads[ModalityType.AUDIO] = nn.Sequential(
393
+ nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6),
394
+ SelectElement(index=0),
395
+ nn.Linear(audio_embed_dim, out_embed_dim, bias=False),
396
+ )
397
+
398
+ modality_heads[ModalityType.DEPTH] = nn.Sequential(
399
+ nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6),
400
+ SelectElement(index=0),
401
+ nn.Linear(depth_embed_dim, out_embed_dim, bias=False),
402
+ )
403
+
404
+ modality_heads[ModalityType.THERMAL] = nn.Sequential(
405
+ nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6),
406
+ SelectElement(index=0),
407
+ nn.Linear(thermal_embed_dim, out_embed_dim, bias=False),
408
+ )
409
+
410
+ modality_heads[ModalityType.IMU] = nn.Sequential(
411
+ nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6),
412
+ SelectElement(index=0),
413
+ nn.Dropout(p=0.5),
414
+ nn.Linear(imu_embed_dim, out_embed_dim, bias=False),
415
+ )
416
+
417
+ return nn.ModuleDict(modality_heads)
418
+
419
+ def _create_modality_postprocessors(self, out_embed_dim):
420
+ modality_postprocessors = {}
421
+
422
+ modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1)
423
+ modality_postprocessors[ModalityType.TEXT] = nn.Sequential(
424
+ Normalize(dim=-1), LearnableLogitScaling(learnable=True)
425
+ )
426
+ modality_postprocessors[ModalityType.AUDIO] = nn.Sequential(
427
+ Normalize(dim=-1),
428
+ LearnableLogitScaling(logit_scale_init=20.0, learnable=False),
429
+ )
430
+ modality_postprocessors[ModalityType.DEPTH] = nn.Sequential(
431
+ Normalize(dim=-1),
432
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
433
+ )
434
+ modality_postprocessors[ModalityType.THERMAL] = nn.Sequential(
435
+ Normalize(dim=-1),
436
+ LearnableLogitScaling(logit_scale_init=10.0, learnable=False),
437
+ )
438
+ modality_postprocessors[ModalityType.IMU] = nn.Sequential(
439
+ Normalize(dim=-1),
440
+ LearnableLogitScaling(logit_scale_init=5.0, learnable=False),
441
+ )
442
+
443
+ return nn.ModuleDict(modality_postprocessors)
444
+
445
+ def set_modality_attention_capture(
446
+ self,
447
+ modality_key: str,
448
+ enabled: bool,
449
+ block_indices: Optional[Sequence[int]] = None,
450
+ ) -> None:
451
+ """
452
+ Toggle attention-weight capture for one modality trunk (see
453
+ ``SimpleTransformer.set_attention_capture`` in ``transformer.py``).
454
+
455
+ After a forward pass with capture enabled on the last block, read weights via
456
+ ``get_modality_attention_weights(modality_key)``.
457
+ """
458
+ self.modality_trunks[modality_key].set_attention_capture(
459
+ enabled, block_indices=block_indices
460
+ )
461
+
462
+ def get_modality_attention_weights(
463
+ self, modality_key: str, block_index: int = -1
464
+ ) -> Optional[torch.Tensor]:
465
+ """Return ``last_attn_weights`` from the given block's ``MultiheadAttention``, if any."""
466
+ blk = self.modality_trunks[modality_key].blocks[block_index]
467
+ attn = blk.attn
468
+ if isinstance(attn, MultiheadAttention):
469
+ return attn.last_attn_weights
470
+ return None
471
+
472
+ def forward(self, inputs):
473
+ outputs = {}
474
+ for modality_key, modality_value in inputs.items():
475
+ reduce_list = (
476
+ modality_value.ndim >= 5
477
+ ) # Audio and Video inputs consist of multiple clips
478
+ if reduce_list:
479
+ B, S = modality_value.shape[:2]
480
+ modality_value = modality_value.reshape(
481
+ B * S, *modality_value.shape[2:]
482
+ )
483
+
484
+ if modality_value is not None:
485
+ modality_value = self.modality_preprocessors[modality_key](
486
+ **{modality_key: modality_value}
487
+ )
488
+ trunk_inputs = modality_value["trunk"]
489
+ head_inputs = modality_value["head"]
490
+ modality_value = self.modality_trunks[modality_key](**trunk_inputs)
491
+ modality_value = self.modality_heads[modality_key](
492
+ modality_value, **head_inputs
493
+ )
494
+ modality_value = self.modality_postprocessors[modality_key](
495
+ modality_value
496
+ )
497
+
498
+ if reduce_list:
499
+ modality_value = modality_value.reshape(B, S, -1)
500
+ modality_value = modality_value.mean(dim=1)
501
+
502
+ outputs[modality_key] = modality_value
503
+
504
+ return outputs
505
+
506
+
507
+ def imagebind_huge(pretrained=False):
508
+ model = ImageBindModel(
509
+ vision_embed_dim=1280,
510
+ vision_num_blocks=32,
511
+ vision_num_heads=16,
512
+ text_embed_dim=1024,
513
+ text_num_blocks=24,
514
+ text_num_heads=16,
515
+ out_embed_dim=1024,
516
+ audio_drop_path=0.1,
517
+ imu_drop_path=0.7,
518
+ )
519
+
520
+ if pretrained:
521
+ if not os.path.exists(".checkpoints/imagebind_huge.pth"):
522
+ print(
523
+ "Downloading imagebind weights to .checkpoints/imagebind_huge.pth ..."
524
+ )
525
+ os.makedirs(".checkpoints", exist_ok=True)
526
+ torch.hub.download_url_to_file(
527
+ "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth",
528
+ ".checkpoints/imagebind_huge.pth",
529
+ progress=True,
530
+ )
531
+
532
+ model.load_state_dict(torch.load(".checkpoints/imagebind_huge.pth", weights_only=True))
533
+
534
+ return model
ImageBind/imagebind/models/multimodal_preprocessors.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import gzip
9
+ import html
10
+ import io
11
+ import math
12
+ from functools import lru_cache
13
+ from typing import Callable, List, Optional, Tuple
14
+
15
+ import ftfy
16
+ import numpy as np
17
+ import regex as re
18
+ import torch
19
+ import torch.nn as nn
20
+ from iopath.common.file_io import g_pathmgr
21
+ from timm.layers import trunc_normal_
22
+
23
+ from imagebind.models.helpers import VerboseNNModule, cast_if_src_dtype
24
+
25
+
26
+ def get_sinusoid_encoding_table(n_position, d_hid):
27
+ """Sinusoid position encoding table"""
28
+
29
+ # TODO: make it with torch instead of numpy
30
+ def get_position_angle_vec(position):
31
+ return [
32
+ position / np.power(10000, 2 * (hid_j // 2) / d_hid)
33
+ for hid_j in range(d_hid)
34
+ ]
35
+
36
+ sinusoid_table = np.array(
37
+ [get_position_angle_vec(pos_i) for pos_i in range(n_position)]
38
+ )
39
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
40
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
41
+
42
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
43
+
44
+
45
+ def interpolate_pos_encoding_2d(target_spatial_size, pos_embed):
46
+ N = pos_embed.shape[1]
47
+ if N == target_spatial_size:
48
+ return pos_embed
49
+ dim = pos_embed.shape[-1]
50
+ # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32
51
+ pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32)
52
+ pos_embed = nn.functional.interpolate(
53
+ pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(
54
+ 0, 3, 1, 2
55
+ ),
56
+ scale_factor=math.sqrt(target_spatial_size / N),
57
+ mode="bicubic",
58
+ )
59
+ if updated:
60
+ pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16)
61
+ pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
62
+ return pos_embed
63
+
64
+
65
+ def interpolate_pos_encoding(
66
+ npatch_per_img,
67
+ pos_embed,
68
+ patches_layout,
69
+ input_shape=None,
70
+ first_patch_idx=1,
71
+ ):
72
+ assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none"
73
+ N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists
74
+ if npatch_per_img == N:
75
+ return pos_embed
76
+
77
+ assert (
78
+ patches_layout[-1] == patches_layout[-2]
79
+ ), "Interpolation of pos embed not supported for non-square layouts"
80
+
81
+ class_emb = pos_embed[:, :first_patch_idx]
82
+ pos_embed = pos_embed[:, first_patch_idx:]
83
+
84
+ if input_shape is None or patches_layout[0] == 1:
85
+ # simple 2D pos embedding, no temporal component
86
+ pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed)
87
+ elif patches_layout[0] > 1:
88
+ # pos embed has a temporal component
89
+ assert len(input_shape) == 4, "temporal interpolation not supported"
90
+ # we only support 2D interpolation in this case
91
+ num_frames = patches_layout[0]
92
+ num_spatial_tokens = patches_layout[1] * patches_layout[2]
93
+ pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1)
94
+ # interpolate embedding for zeroth frame
95
+ pos_embed = interpolate_pos_encoding_2d(
96
+ npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0)
97
+ )
98
+ else:
99
+ raise ValueError("This type of interpolation isn't implemented")
100
+
101
+ return torch.cat((class_emb, pos_embed), dim=1)
102
+
103
+
104
+ def _get_pos_embedding(
105
+ npatch_per_img,
106
+ pos_embed,
107
+ patches_layout,
108
+ input_shape,
109
+ first_patch_idx=1,
110
+ ):
111
+ pos_embed = interpolate_pos_encoding(
112
+ npatch_per_img,
113
+ pos_embed,
114
+ patches_layout,
115
+ input_shape=input_shape,
116
+ first_patch_idx=first_patch_idx,
117
+ )
118
+ return pos_embed
119
+
120
+
121
+ class PatchEmbedGeneric(nn.Module):
122
+ """
123
+ PatchEmbed from Hydra
124
+ """
125
+
126
+ def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None):
127
+ super().__init__()
128
+
129
+ if len(proj_stem) > 1:
130
+ self.proj = nn.Sequential(*proj_stem)
131
+ else:
132
+ # Special case to be able to load pre-trained models that were
133
+ # trained with a standard stem
134
+ self.proj = proj_stem[0]
135
+ self.norm_layer = norm_layer
136
+
137
+ def get_patch_layout(self, img_size):
138
+ with torch.no_grad():
139
+ dummy_img = torch.zeros(
140
+ [
141
+ 1,
142
+ ]
143
+ + img_size
144
+ )
145
+ dummy_out = self.proj(dummy_img)
146
+ embed_dim = dummy_out.shape[1]
147
+ patches_layout = tuple(dummy_out.shape[2:])
148
+ num_patches = np.prod(patches_layout)
149
+ return patches_layout, num_patches, embed_dim
150
+
151
+ def forward(self, x):
152
+ x = self.proj(x)
153
+ # B C (T) H W -> B (T)HW C
154
+ x = x.flatten(2).transpose(1, 2)
155
+ if self.norm_layer is not None:
156
+ x = self.norm_layer(x)
157
+ return x
158
+
159
+
160
+ class SpatioTemporalPosEmbeddingHelper(VerboseNNModule):
161
+ def __init__(
162
+ self,
163
+ patches_layout: List,
164
+ num_patches: int,
165
+ num_cls_tokens: int,
166
+ embed_dim: int,
167
+ learnable: bool,
168
+ ) -> None:
169
+ super().__init__()
170
+ self.num_cls_tokens = num_cls_tokens
171
+ self.patches_layout = patches_layout
172
+ self.num_patches = num_patches
173
+ self.num_tokens = num_cls_tokens + num_patches
174
+ self.learnable = learnable
175
+ if self.learnable:
176
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
177
+ trunc_normal_(self.pos_embed, std=0.02)
178
+ else:
179
+ self.register_buffer(
180
+ "pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim)
181
+ )
182
+
183
+ def get_pos_embedding(self, vision_input, all_vision_tokens):
184
+ input_shape = vision_input.shape
185
+ pos_embed = _get_pos_embedding(
186
+ all_vision_tokens.size(1) - self.num_cls_tokens,
187
+ pos_embed=self.pos_embed,
188
+ patches_layout=self.patches_layout,
189
+ input_shape=input_shape,
190
+ first_patch_idx=self.num_cls_tokens,
191
+ )
192
+ return pos_embed
193
+
194
+
195
+ class RGBDTPreprocessor(VerboseNNModule):
196
+ def __init__(
197
+ self,
198
+ rgbt_stem: PatchEmbedGeneric,
199
+ depth_stem: Optional[PatchEmbedGeneric],
200
+ img_size: Tuple = (3, 224, 224),
201
+ num_cls_tokens: int = 1,
202
+ pos_embed_fn: Optional[Callable] = None,
203
+ use_type_embed: bool = False,
204
+ init_param_style: str = "openclip",
205
+ ) -> None:
206
+ super().__init__()
207
+ stem = rgbt_stem if rgbt_stem is not None else depth_stem
208
+ (
209
+ self.patches_layout,
210
+ self.num_patches,
211
+ self.embed_dim,
212
+ ) = stem.get_patch_layout(img_size)
213
+ self.rgbt_stem = rgbt_stem
214
+ self.depth_stem = depth_stem
215
+ self.use_pos_embed = pos_embed_fn is not None
216
+ self.use_type_embed = use_type_embed
217
+ self.num_cls_tokens = num_cls_tokens
218
+
219
+ if self.use_pos_embed:
220
+ self.pos_embedding_helper = pos_embed_fn(
221
+ patches_layout=self.patches_layout,
222
+ num_cls_tokens=num_cls_tokens,
223
+ num_patches=self.num_patches,
224
+ embed_dim=self.embed_dim,
225
+ )
226
+ if self.num_cls_tokens > 0:
227
+ self.cls_token = nn.Parameter(
228
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
229
+ )
230
+ if self.use_type_embed:
231
+ self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
232
+
233
+ self.init_parameters(init_param_style)
234
+
235
+ @torch.no_grad()
236
+ def init_parameters(self, init_param_style):
237
+ if init_param_style == "openclip":
238
+ # OpenCLIP style initialization
239
+ scale = self.embed_dim**-0.5
240
+ if self.use_pos_embed:
241
+ nn.init.normal_(self.pos_embedding_helper.pos_embed)
242
+ self.pos_embedding_helper.pos_embed *= scale
243
+
244
+ if self.num_cls_tokens > 0:
245
+ nn.init.normal_(self.cls_token)
246
+ self.cls_token *= scale
247
+ elif init_param_style == "vit":
248
+ self.cls_token.data.fill_(0)
249
+ else:
250
+ raise ValueError(f"Unknown init {init_param_style}")
251
+
252
+ if self.use_type_embed:
253
+ nn.init.normal_(self.type_embed)
254
+
255
+ def tokenize_input_and_cls_pos(self, input, stem, mask):
256
+ # tokens is of shape B x L x D
257
+ tokens = stem(input)
258
+ assert tokens.ndim == 3
259
+ assert tokens.shape[2] == self.embed_dim
260
+ B = tokens.shape[0]
261
+ if self.num_cls_tokens > 0:
262
+ class_tokens = self.cls_token.expand(
263
+ B, -1, -1
264
+ ) # stole class_tokens impl from Phil Wang, thanks
265
+ tokens = torch.cat((class_tokens, tokens), dim=1)
266
+ if self.use_pos_embed:
267
+ pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens)
268
+ tokens = tokens + pos_embed
269
+ if self.use_type_embed:
270
+ tokens = tokens + self.type_embed.expand(B, -1, -1)
271
+ return tokens
272
+
273
+ def forward(self, vision=None, depth=None, patch_mask=None):
274
+ if patch_mask is not None:
275
+ raise NotImplementedError()
276
+
277
+ if vision is not None:
278
+ vision_tokens = self.tokenize_input_and_cls_pos(
279
+ vision, self.rgbt_stem, patch_mask
280
+ )
281
+
282
+ if depth is not None:
283
+ depth_tokens = self.tokenize_input_and_cls_pos(
284
+ depth, self.depth_stem, patch_mask
285
+ )
286
+
287
+ # aggregate tokens
288
+ if vision is not None and depth is not None:
289
+ final_tokens = vision_tokens + depth_tokens
290
+ else:
291
+ final_tokens = vision_tokens if vision is not None else depth_tokens
292
+ return_dict = {
293
+ "trunk": {
294
+ "tokens": final_tokens,
295
+ },
296
+ "head": {},
297
+ }
298
+ return return_dict
299
+
300
+
301
+ class AudioPreprocessor(RGBDTPreprocessor):
302
+ def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None:
303
+ super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs)
304
+
305
+ def forward(self, audio=None):
306
+ return super().forward(vision=audio)
307
+
308
+
309
+ class ThermalPreprocessor(RGBDTPreprocessor):
310
+ def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None:
311
+ super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs)
312
+
313
+ def forward(self, thermal=None):
314
+ return super().forward(vision=thermal)
315
+
316
+
317
+ def build_causal_attention_mask(context_length):
318
+ # lazily create causal attention mask, with full attention between the vision tokens
319
+ # pytorch uses additive attention mask; fill with -inf
320
+ mask = torch.empty(context_length, context_length, requires_grad=False)
321
+ mask.fill_(float("-inf"))
322
+ mask.triu_(1) # zero out the lower diagonal
323
+ return mask
324
+
325
+
326
+ class TextPreprocessor(VerboseNNModule):
327
+ def __init__(
328
+ self,
329
+ vocab_size: int,
330
+ context_length: int,
331
+ embed_dim: int,
332
+ causal_masking: bool,
333
+ supply_seq_len_to_head: bool = True,
334
+ num_cls_tokens: int = 0,
335
+ init_param_style: str = "openclip",
336
+ ) -> None:
337
+ super().__init__()
338
+ self.vocab_size = vocab_size
339
+ self.context_length = context_length
340
+ self.token_embedding = nn.Embedding(vocab_size, embed_dim)
341
+ self.pos_embed = nn.Parameter(
342
+ torch.empty(1, self.context_length + num_cls_tokens, embed_dim)
343
+ )
344
+ self.causal_masking = causal_masking
345
+ if self.causal_masking:
346
+ mask = build_causal_attention_mask(self.context_length)
347
+ # register the mask as a buffer so it can be moved to the right device
348
+ self.register_buffer("mask", mask)
349
+
350
+ self.supply_seq_len_to_head = supply_seq_len_to_head
351
+ self.num_cls_tokens = num_cls_tokens
352
+ self.embed_dim = embed_dim
353
+ if num_cls_tokens > 0:
354
+ assert self.causal_masking is False, "Masking + CLS token isn't implemented"
355
+ self.cls_token = nn.Parameter(
356
+ torch.zeros(1, self.num_cls_tokens, embed_dim)
357
+ )
358
+
359
+ self.init_parameters(init_param_style)
360
+
361
+ @torch.no_grad()
362
+ def init_parameters(self, init_param_style="openclip"):
363
+ # OpenCLIP style initialization
364
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
365
+ nn.init.normal_(self.pos_embed, std=0.01)
366
+
367
+ if init_param_style == "openclip":
368
+ # OpenCLIP style initialization
369
+ scale = self.embed_dim**-0.5
370
+ if self.num_cls_tokens > 0:
371
+ nn.init.normal_(self.cls_token)
372
+ self.cls_token *= scale
373
+ elif init_param_style == "vit":
374
+ self.cls_token.data.fill_(0)
375
+ else:
376
+ raise ValueError(f"Unknown init {init_param_style}")
377
+
378
+ def forward(self, text):
379
+ # text tokens are of shape B x L x D
380
+ text_tokens = self.token_embedding(text)
381
+ # concat CLS tokens if any
382
+ if self.num_cls_tokens > 0:
383
+ B = text_tokens.shape[0]
384
+ class_tokens = self.cls_token.expand(
385
+ B, -1, -1
386
+ ) # stole class_tokens impl from Phil Wang, thanks
387
+ text_tokens = torch.cat((class_tokens, text_tokens), dim=1)
388
+ text_tokens = text_tokens + self.pos_embed
389
+ return_dict = {
390
+ "trunk": {
391
+ "tokens": text_tokens,
392
+ },
393
+ "head": {},
394
+ }
395
+ # Compute sequence length after adding CLS tokens
396
+ if self.supply_seq_len_to_head:
397
+ text_lengths = text.argmax(dim=-1)
398
+ return_dict["head"] = {
399
+ "seq_len": text_lengths,
400
+ }
401
+ if self.causal_masking:
402
+ return_dict["trunk"].update({"attn_mask": self.mask})
403
+ return return_dict
404
+
405
+
406
+ class Im2Video(nn.Module):
407
+ """Convert an image into a trivial video."""
408
+
409
+ def __init__(self, time_dim=2):
410
+ super().__init__()
411
+ self.time_dim = time_dim
412
+
413
+ def forward(self, x):
414
+ if x.ndim == 4:
415
+ # B, C, H, W -> B, C, T, H, W
416
+ return x.unsqueeze(self.time_dim)
417
+ elif x.ndim == 5:
418
+ return x
419
+ else:
420
+ raise ValueError(f"Dimension incorrect {x.shape}")
421
+
422
+
423
+ class PadIm2Video(Im2Video):
424
+ def __init__(self, ntimes, pad_type, time_dim=2):
425
+ super().__init__(time_dim=time_dim)
426
+ assert ntimes > 0
427
+ assert pad_type in ["zero", "repeat"]
428
+ self.ntimes = ntimes
429
+ self.pad_type = pad_type
430
+
431
+ def forward(self, x):
432
+ x = super().forward(x)
433
+ if x.shape[self.time_dim] == 1:
434
+ if self.pad_type == "repeat":
435
+ new_shape = [1] * len(x.shape)
436
+ new_shape[self.time_dim] = self.ntimes
437
+ x = x.repeat(new_shape)
438
+ elif self.pad_type == "zero":
439
+ padarg = [0, 0] * len(x.shape)
440
+ padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim]
441
+ x = nn.functional.pad(x, padarg)
442
+ return x
443
+
444
+
445
+ # Modified from github.com/openai/CLIP
446
+ @lru_cache()
447
+ def bytes_to_unicode():
448
+ """
449
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
450
+ The reversible bpe codes work on unicode strings.
451
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
452
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
453
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
454
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
455
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
456
+ """
457
+ bs = (
458
+ list(range(ord("!"), ord("~") + 1))
459
+ + list(range(ord("¡"), ord("¬") + 1))
460
+ + list(range(ord("®"), ord("ÿ") + 1))
461
+ )
462
+ cs = bs[:]
463
+ n = 0
464
+ for b in range(2**8):
465
+ if b not in bs:
466
+ bs.append(b)
467
+ cs.append(2**8 + n)
468
+ n += 1
469
+ cs = [chr(n) for n in cs]
470
+ return dict(zip(bs, cs))
471
+
472
+
473
+ def get_pairs(word):
474
+ """Return set of symbol pairs in a word.
475
+ Word is represented as tuple of symbols (symbols being variable-length strings).
476
+ """
477
+ pairs = set()
478
+ prev_char = word[0]
479
+ for char in word[1:]:
480
+ pairs.add((prev_char, char))
481
+ prev_char = char
482
+ return pairs
483
+
484
+
485
+ def basic_clean(text):
486
+ text = ftfy.fix_text(text)
487
+ text = html.unescape(html.unescape(text))
488
+ return text.strip()
489
+
490
+
491
+ def whitespace_clean(text):
492
+ text = re.sub(r"\s+", " ", text)
493
+ text = text.strip()
494
+ return text
495
+
496
+
497
+ class SimpleTokenizer(object):
498
+ def __init__(self, bpe_path: str, context_length=77):
499
+ self.byte_encoder = bytes_to_unicode()
500
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
501
+
502
+ with g_pathmgr.open(bpe_path, "rb") as fh:
503
+ bpe_bytes = io.BytesIO(fh.read())
504
+ merges: List[str] = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
505
+ merges = merges[1 : 49152 - 256 - 2 + 1]
506
+ merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges]
507
+ vocab = list(bytes_to_unicode().values())
508
+ vocab = vocab + [v + "</w>" for v in vocab]
509
+ for merge in merges:
510
+ vocab.append("".join(merge))
511
+ vocab.extend(["<|startoftext|>", "<|endoftext|>"])
512
+ self.encoder = dict(zip(vocab, range(len(vocab))))
513
+ self.decoder = {v: k for k, v in self.encoder.items()}
514
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
515
+ self.cache = {
516
+ "<|startoftext|>": "<|startoftext|>",
517
+ "<|endoftext|>": "<|endoftext|>",
518
+ }
519
+ self.pat = re.compile(
520
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
521
+ re.IGNORECASE,
522
+ )
523
+ self.context_length = context_length
524
+
525
+ def bpe(self, token):
526
+ if token in self.cache:
527
+ return self.cache[token]
528
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
529
+ pairs = get_pairs(word)
530
+
531
+ if not pairs:
532
+ return token + "</w>"
533
+
534
+ while True:
535
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
536
+ if bigram not in self.bpe_ranks:
537
+ break
538
+ first, second = bigram
539
+ new_word = []
540
+ i = 0
541
+ while i < len(word):
542
+ try:
543
+ j = word.index(first, i)
544
+ new_word.extend(word[i:j])
545
+ i = j
546
+ except:
547
+ new_word.extend(word[i:])
548
+ break
549
+
550
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
551
+ new_word.append(first + second)
552
+ i += 2
553
+ else:
554
+ new_word.append(word[i])
555
+ i += 1
556
+ new_word = tuple(new_word)
557
+ word = new_word
558
+ if len(word) == 1:
559
+ break
560
+ else:
561
+ pairs = get_pairs(word)
562
+ word = " ".join(word)
563
+ self.cache[token] = word
564
+ return word
565
+
566
+ def encode(self, text):
567
+ bpe_tokens = []
568
+ text = whitespace_clean(basic_clean(text)).lower()
569
+ for token in re.findall(self.pat, text):
570
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
571
+ bpe_tokens.extend(
572
+ self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
573
+ )
574
+ return bpe_tokens
575
+
576
+ def decode(self, tokens):
577
+ text = "".join([self.decoder[token] for token in tokens])
578
+ text = (
579
+ bytearray([self.byte_decoder[c] for c in text])
580
+ .decode("utf-8", errors="replace")
581
+ .replace("</w>", " ")
582
+ )
583
+ return text
584
+
585
+ def __call__(self, texts, context_length=None):
586
+ if not context_length:
587
+ context_length = self.context_length
588
+
589
+ if isinstance(texts, str):
590
+ texts = [texts]
591
+
592
+ sot_token = self.encoder["<|startoftext|>"]
593
+ eot_token = self.encoder["<|endoftext|>"]
594
+ all_tokens = [[sot_token] + self.encode(text) for text in texts]
595
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
596
+
597
+ for i, tokens in enumerate(all_tokens):
598
+ tokens = tokens[:context_length - 1] + [eot_token]
599
+ result[i, : len(tokens)] = torch.tensor(tokens)
600
+
601
+ if len(result) == 1:
602
+ return result[0]
603
+ return result
604
+
605
+
606
+ class IMUPreprocessor(VerboseNNModule):
607
+ def __init__(
608
+ self,
609
+ kernel_size: int,
610
+ imu_stem: PatchEmbedGeneric,
611
+ embed_dim: int,
612
+ img_size: Tuple = (6, 2000),
613
+ num_cls_tokens: int = 1,
614
+ pos_embed_fn: Optional[Callable] = None,
615
+ init_param_style: str = "openclip",
616
+ ) -> None:
617
+ super().__init__()
618
+ self.imu_stem = imu_stem
619
+ self.embed_dim = embed_dim
620
+ self.use_pos_embed = pos_embed_fn is not None
621
+ self.num_cls_tokens = num_cls_tokens
622
+ self.kernel_size = kernel_size
623
+ self.pos_embed = nn.Parameter(
624
+ torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim)
625
+ )
626
+
627
+ if self.num_cls_tokens > 0:
628
+ self.cls_token = nn.Parameter(
629
+ torch.zeros(1, self.num_cls_tokens, self.embed_dim)
630
+ )
631
+
632
+ self.init_parameters(init_param_style)
633
+
634
+ @torch.no_grad()
635
+ def init_parameters(self, init_param_style):
636
+ nn.init.normal_(self.pos_embed, std=0.01)
637
+
638
+ if init_param_style == "openclip":
639
+ # OpenCLIP style initialization
640
+ scale = self.embed_dim**-0.5
641
+
642
+ if self.num_cls_tokens > 0:
643
+ nn.init.normal_(self.cls_token)
644
+ self.cls_token *= scale
645
+ elif init_param_style == "vit":
646
+ self.cls_token.data.fill_(0)
647
+ else:
648
+ raise ValueError(f"Unknown init {init_param_style}")
649
+
650
+ def tokenize_input_and_cls_pos(self, input, stem):
651
+ # tokens is of shape B x L x D
652
+ tokens = stem.norm_layer(stem.proj(input))
653
+ assert tokens.ndim == 3
654
+ assert tokens.shape[2] == self.embed_dim
655
+ B = tokens.shape[0]
656
+ if self.num_cls_tokens > 0:
657
+ class_tokens = self.cls_token.expand(
658
+ B, -1, -1
659
+ ) # stole class_tokens impl from Phil Wang, thanks
660
+ tokens = torch.cat((class_tokens, tokens), dim=1)
661
+ if self.use_pos_embed:
662
+ tokens = tokens + self.pos_embed
663
+ return tokens
664
+
665
+ def forward(self, imu):
666
+ # Patchify
667
+ imu = imu.unfold(
668
+ -1,
669
+ self.kernel_size,
670
+ self.kernel_size,
671
+ ).permute(0, 2, 1, 3)
672
+ imu = imu.reshape(imu.size(0), imu.size(1), -1)
673
+
674
+ imu_tokens = self.tokenize_input_and_cls_pos(
675
+ imu,
676
+ self.imu_stem,
677
+ )
678
+
679
+ return_dict = {
680
+ "trunk": {
681
+ "tokens": imu_tokens,
682
+ },
683
+ "head": {},
684
+ }
685
+ return return_dict
ImageBind/imagebind/models/transformer.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ # Code modified from
9
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ;
10
+ # https://github.com/facebookresearch/deit/blob/main/models.py
11
+ # and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py
12
+
13
+
14
+ from functools import partial
15
+ from inspect import signature
16
+ from typing import Callable, List, Optional, Sequence
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.utils.checkpoint as checkpoint
21
+ from timm.layers import DropPath, trunc_normal_
22
+
23
+
24
+ class Attention(nn.Module):
25
+ def __init__(
26
+ self,
27
+ dim,
28
+ num_heads=8,
29
+ qkv_bias=False,
30
+ qk_scale=None,
31
+ attn_drop=0.0,
32
+ proj_drop=0.0,
33
+ ):
34
+ super().__init__()
35
+ self.num_heads = num_heads
36
+ head_dim = dim // num_heads
37
+ # NOTE scale factor was wrong in my original version,
38
+ # can set manually to be compat with prev weights
39
+ self.scale = qk_scale or head_dim**-0.5
40
+
41
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
42
+ self.attn_drop = nn.Dropout(attn_drop)
43
+ self.proj = nn.Linear(dim, dim)
44
+ self.proj_drop = nn.Dropout(proj_drop)
45
+
46
+ def forward(self, x):
47
+ B, N, C = x.shape
48
+ qkv = (
49
+ self.qkv(x)
50
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
51
+ .permute(2, 0, 3, 1, 4)
52
+ )
53
+ q, k, v = (
54
+ qkv[0],
55
+ qkv[1],
56
+ qkv[2],
57
+ ) # make torchscript happy (cannot use tensor as tuple)
58
+
59
+ attn = (q @ k.transpose(-2, -1)) * self.scale
60
+ attn = attn.softmax(dim=-1)
61
+ attn = self.attn_drop(attn)
62
+
63
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
64
+ x = self.proj(x)
65
+ x = self.proj_drop(x)
66
+ return x
67
+
68
+
69
+ class Mlp(nn.Module):
70
+ def __init__(
71
+ self,
72
+ in_features,
73
+ hidden_features=None,
74
+ out_features=None,
75
+ act_layer=nn.GELU,
76
+ drop=0.0,
77
+ ):
78
+ super().__init__()
79
+ out_features = out_features or in_features
80
+ hidden_features = hidden_features or in_features
81
+ self.fc1 = nn.Linear(in_features, hidden_features)
82
+ self.act = act_layer()
83
+ self.fc2 = nn.Linear(hidden_features, out_features)
84
+ self.drop = nn.Dropout(drop)
85
+
86
+ def forward(self, x):
87
+ x = self.fc1(x)
88
+ x = self.act(x)
89
+ x = self.drop(x)
90
+ x = self.fc2(x)
91
+ x = self.drop(x)
92
+ return x
93
+
94
+
95
+ class MultiheadAttention(nn.MultiheadAttention):
96
+ """
97
+ Same as ``nn.MultiheadAttention`` for ImageBind trunks, with an optional capture path
98
+ so attention weights can be read for visualization without duplicating the forward pass.
99
+
100
+ Call ``set_attention_capture(True)`` before ``forward``; averaged weights are stored in
101
+ ``last_attn_weights`` (shape ``(B, L, L)``) when capture is enabled.
102
+ """
103
+
104
+ def __init__(self, *args, **kwargs):
105
+ super().__init__(*args, **kwargs)
106
+ self._capture_attention = False
107
+ self.last_attn_weights: Optional[torch.Tensor] = None
108
+
109
+ def set_attention_capture(self, enabled: bool) -> None:
110
+ self._capture_attention = bool(enabled)
111
+ if not enabled:
112
+ self.last_attn_weights = None
113
+
114
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
115
+ if not self._capture_attention:
116
+ return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
117
+ kwargs = dict(
118
+ key_padding_mask=None,
119
+ need_weights=True,
120
+ attn_mask=attn_mask,
121
+ average_attn_weights=True,
122
+ )
123
+ if "is_causal" in signature(super().forward).parameters:
124
+ kwargs["is_causal"] = False
125
+ out, attn_weights = super().forward(x, x, x, **kwargs)
126
+ self.last_attn_weights = attn_weights
127
+ return out
128
+
129
+
130
+ class ViTAttention(Attention):
131
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
132
+ assert attn_mask is None
133
+ return super().forward(x)
134
+
135
+
136
+ class BlockWithMasking(nn.Module):
137
+ def __init__(
138
+ self,
139
+ dim: int,
140
+ attn_target: Callable,
141
+ mlp_ratio: int = 4,
142
+ act_layer: Callable = nn.GELU,
143
+ norm_layer: Callable = nn.LayerNorm,
144
+ ffn_dropout_rate: float = 0.0,
145
+ drop_path: float = 0.0,
146
+ layer_scale_type: Optional[str] = None,
147
+ layer_scale_init_value: float = 1e-4,
148
+ ):
149
+ super().__init__()
150
+
151
+ assert not isinstance(
152
+ attn_target, nn.Module
153
+ ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!"
154
+ self.attn = attn_target()
155
+ if drop_path > 0.0:
156
+ self.drop_path = DropPath(drop_path)
157
+ else:
158
+ self.drop_path = nn.Identity()
159
+ self.norm_1 = norm_layer(dim)
160
+ mlp_hidden_dim = int(mlp_ratio * dim)
161
+ self.mlp = Mlp(
162
+ in_features=dim,
163
+ hidden_features=mlp_hidden_dim,
164
+ act_layer=act_layer,
165
+ drop=ffn_dropout_rate,
166
+ )
167
+ self.norm_2 = norm_layer(dim)
168
+ self.layer_scale_type = layer_scale_type
169
+ if self.layer_scale_type is not None:
170
+ assert self.layer_scale_type in [
171
+ "per_channel",
172
+ "scalar",
173
+ ], f"Found Layer scale type {self.layer_scale_type}"
174
+ if self.layer_scale_type == "per_channel":
175
+ # one gamma value per channel
176
+ gamma_shape = [1, 1, dim]
177
+ elif self.layer_scale_type == "scalar":
178
+ # single gamma value for all channels
179
+ gamma_shape = [1, 1, 1]
180
+ # two gammas: for each part of the fwd in the encoder
181
+ self.layer_scale_gamma1 = nn.Parameter(
182
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
183
+ requires_grad=True,
184
+ )
185
+ self.layer_scale_gamma2 = nn.Parameter(
186
+ torch.ones(size=gamma_shape) * layer_scale_init_value,
187
+ requires_grad=True,
188
+ )
189
+
190
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor):
191
+ if self.layer_scale_type is None:
192
+ x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask))
193
+ x = x + self.drop_path(self.mlp(self.norm_2(x)))
194
+ else:
195
+ x = (
196
+ x
197
+ + self.drop_path(self.attn(self.norm_1(x), attn_mask))
198
+ * self.layer_scale_gamma1
199
+ )
200
+ x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2
201
+ return x
202
+
203
+
204
+ _LAYER_NORM = partial(nn.LayerNorm, eps=1e-6)
205
+
206
+
207
+ class SimpleTransformer(nn.Module):
208
+ def __init__(
209
+ self,
210
+ attn_target: Callable,
211
+ embed_dim: int,
212
+ num_blocks: int,
213
+ block: Callable = BlockWithMasking,
214
+ pre_transformer_layer: Optional[Callable] = None,
215
+ post_transformer_layer: Optional[Callable] = None,
216
+ drop_path_rate: float = 0.0,
217
+ drop_path_type: str = "progressive",
218
+ norm_layer: Callable = _LAYER_NORM,
219
+ mlp_ratio: int = 4,
220
+ ffn_dropout_rate: float = 0.0,
221
+ layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar"
222
+ layer_scale_init_value: float = 1e-4, # from cait; float
223
+ weight_init_style: str = "jax", # possible values jax or pytorch
224
+ ):
225
+ """
226
+ Simple Transformer with the following features
227
+ 1. Supports masked attention
228
+ 2. Supports DropPath
229
+ 3. Supports LayerScale
230
+ 4. Supports Dropout in Attention and FFN
231
+ 5. Makes few assumptions about the input except that it is a Tensor
232
+ """
233
+ super().__init__()
234
+ self.pre_transformer_layer = pre_transformer_layer
235
+ if drop_path_type == "progressive":
236
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)]
237
+ elif drop_path_type == "uniform":
238
+ dpr = [drop_path_rate for i in range(num_blocks)]
239
+ else:
240
+ raise ValueError(f"Unknown drop_path_type: {drop_path_type}")
241
+
242
+ self.blocks = nn.Sequential(
243
+ *[
244
+ block(
245
+ dim=embed_dim,
246
+ attn_target=attn_target,
247
+ mlp_ratio=mlp_ratio,
248
+ ffn_dropout_rate=ffn_dropout_rate,
249
+ drop_path=dpr[i],
250
+ norm_layer=norm_layer,
251
+ layer_scale_type=layer_scale_type,
252
+ layer_scale_init_value=layer_scale_init_value,
253
+ )
254
+ for i in range(num_blocks)
255
+ ]
256
+ )
257
+ self.post_transformer_layer = post_transformer_layer
258
+ self.weight_init_style = weight_init_style
259
+ self.apply(self._init_weights)
260
+
261
+ def _init_weights(self, m):
262
+ if isinstance(m, nn.Linear):
263
+ if self.weight_init_style == "jax":
264
+ # Based on MAE and official Jax ViT implementation
265
+ torch.nn.init.xavier_uniform_(m.weight)
266
+ elif self.weight_init_style == "pytorch":
267
+ # PyTorch ViT uses trunc_normal_
268
+ trunc_normal_(m.weight, std=0.02)
269
+
270
+ if m.bias is not None:
271
+ nn.init.constant_(m.bias, 0)
272
+ elif isinstance(m, (nn.LayerNorm)):
273
+ nn.init.constant_(m.bias, 0)
274
+ nn.init.constant_(m.weight, 1.0)
275
+
276
+ def set_attention_capture(
277
+ self,
278
+ enabled: bool,
279
+ block_indices: Optional[Sequence[int]] = None,
280
+ ) -> None:
281
+ """
282
+ Enable or disable attention weight capture on ``MultiheadAttention`` blocks.
283
+
284
+ When ``enabled`` is True and ``block_indices`` is None, only the **last** block
285
+ records attention (typical for CLS–patch maps). Pass an explicit index sequence
286
+ (e.g. ``range(num_blocks)``) to capture specific layers.
287
+ """
288
+ n = len(self.blocks)
289
+ for i, blk in enumerate(self.blocks):
290
+ if not isinstance(blk.attn, MultiheadAttention):
291
+ continue
292
+ if not enabled:
293
+ blk.attn.set_attention_capture(False)
294
+ continue
295
+ if block_indices is None:
296
+ capture = i == n - 1
297
+ else:
298
+ capture = i in block_indices
299
+ blk.attn.set_attention_capture(capture)
300
+
301
+ def forward(
302
+ self,
303
+ tokens: torch.Tensor,
304
+ attn_mask: torch.Tensor = None,
305
+ use_checkpoint: bool = False,
306
+ checkpoint_every_n: int = 1,
307
+ checkpoint_blk_ids: Optional[List[int]] = None,
308
+ ):
309
+ """
310
+ Inputs
311
+ - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation)
312
+ - attn: mask of shape L x L
313
+
314
+ Output
315
+ - x: data of shape N x L x D (or L x N x D depending on the attention implementation)
316
+ """
317
+ if self.pre_transformer_layer:
318
+ tokens = self.pre_transformer_layer(tokens)
319
+ if use_checkpoint and checkpoint_blk_ids is None:
320
+ checkpoint_blk_ids = [
321
+ blk_id
322
+ for blk_id in range(len(self.blocks))
323
+ if blk_id % checkpoint_every_n == 0
324
+ ]
325
+ if checkpoint_blk_ids:
326
+ checkpoint_blk_ids = set(checkpoint_blk_ids)
327
+ for blk_id, blk in enumerate(self.blocks):
328
+ if use_checkpoint and blk_id in checkpoint_blk_ids:
329
+ tokens = checkpoint.checkpoint(
330
+ blk, tokens, attn_mask, use_reentrant=False
331
+ )
332
+ else:
333
+ tokens = blk(tokens, attn_mask=attn_mask)
334
+ if self.post_transformer_layer:
335
+ tokens = self.post_transformer_layer(tokens)
336
+ return tokens
ImageBind/legrad_imagebind.ipynb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6912a420f874b43e531664f02d0db42a31637a9cf543c0ff3366add6bf55eb2b
3
+ size 13383277
ImageBind/model_card.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card for ImageBind
2
+
3
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images.
4
+ Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks.
5
+
6
+ # Model Details
7
+
8
+ ## Model Description
9
+
10
+ <!-- Provide a longer summary of what this model is/does. -->
11
+ Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images
12
+
13
+ - **Developed by:** Meta AI
14
+ - **Model type:** Multimodal model
15
+ - **Language(s) (NLP):** en
16
+ - **License:** CC BY-NC-SA 4.0
17
+ - **Resources for more information:**
18
+ - [GitHub Repo](https://github.com/facebookresearch/ImageBind)
19
+
20
+
21
+ # Uses
22
+
23
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
24
+ This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images.
25
+ We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities.
26
+
27
+ ## Out-of-Scope Use
28
+
29
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
30
+ <!-- If the user enters content, print that. If not, but they enter a task in the list, use that. If neither, say "more info needed." -->
31
+
32
+ This model is *NOT* intended to be used in any real world application -- commercial or otherwise.
33
+ It may produce harmful associations with different inputs.
34
+ The model needs to be investigated and likely re-trained on specific data for any such application.
35
+ The model is expected to work better on web-based visual data since it was trained on such data.
36
+ The text encoder is likely to work only on English language text because of the underlying training datasets.
37
+
38
+ # Bias, Risks, and Limitations
39
+
40
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
41
+ Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness).
42
+ Since our model uses such models as initialization, it will exhibit such biases too.
43
+ Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes.
44
+
45
+
46
+
47
+ # Training Details
48
+
49
+ ## Training Data
50
+
51
+ <!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
52
+
53
+ ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data.
54
+ In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder.
55
+ We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset.
56
+ We provide the exact training data details in the paper.
57
+
58
+
59
+ ## Training Procedure
60
+
61
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
62
+ Please refer to the research paper and github repo for exact details on this.
63
+
64
+ # Evaluation
65
+
66
+ ## Testing Data, Factors & Metrics
67
+
68
+ We evaluate the model on a variety of different classification benchmarks for each modality.
69
+ The evaluation details are presented in the paper.
70
+ The models performance is measured using standard classification metrics such as accuracy and mAP.
71
+
72
+ # Citation
73
+
74
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
75
+
76
+ **BibTeX:**
77
+ ```
78
+ @inproceedings{girdhar2023imagebind,
79
+ title={ImageBind: One Embedding Space To Bind Them All},
80
+ author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang
81
+ and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
82
+ booktitle={CVPR},
83
+ year={2023}
84
+ }
85
+ ```
86
+
87
+
88
+ # Model Card Contact
89
+
90
+ Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com
91
+
92
+ # How to Get Started with the Model
93
+
94
+ Our github repo provides a simple example to extract embeddings from images, audio etc.
ImageBind/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ torchvision # because torch version already specific, the right torchvision will be derived automatically
3
+ torchaudio # because torch version already specific, the right torchaudio will be derived automatically
4
+ pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@6cdc929315aab1b5674b6dcf73b16ec99147735f
5
+ timm
6
+ ftfy
7
+ regex
8
+ einops
9
+ iopath
10
+ numpy>=1.19
11
+ types-regex
ImageBind/setup.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ with open('requirements.txt') as f:
4
+ required = f.read().splitlines()
5
+
6
+ setup(
7
+ name='imagebind',
8
+ version='0.1.0',
9
+ packages=find_packages(),
10
+ package_data={
11
+ 'imagebind': ['bpe/bpe_simple_vocab_16e6.txt.gz'],
12
+ },
13
+ description='A brief description of the package',
14
+ long_description=open('README.md', encoding='utf-8').read(),
15
+ long_description_content_type="text/markdown",
16
+ url='https://github.com/facebookresearch/ImageBind',
17
+ classifiers=[
18
+ 'Programming Language :: Python :: 3',
19
+ 'License :: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
20
+ ],
21
+ install_requires=required,
22
+ dependency_links=['https://download.pytorch.org/whl/cu113'],
23
+ )