Mirror LanguageBind source at upstream commit 7070c53375661cdb235801176b564b45f96f0648
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +17 -0
- 1/1 +1 -0
- DATASETS.md +66 -0
- DATASET_LICENSE +400 -0
- LICENSE +21 -0
- README.md +422 -0
- TRAIN_AND_VALIDATE.md +214 -0
- a_cls/class_labels_indices.csv +528 -0
- a_cls/dataloader.py +100 -0
- a_cls/datasets.py +93 -0
- a_cls/filter_eval_audio.py +21 -0
- a_cls/precision.py +12 -0
- a_cls/stats.py +57 -0
- a_cls/util.py +306 -0
- a_cls/zero_shot.py +234 -0
- a_cls/zero_shot_classifier.py +111 -0
- a_cls/zero_shot_metadata.py +184 -0
- a_cls/zeroshot_cls.py +46 -0
- al_ret/data_dataloaders.py +28 -0
- al_ret/dataloader_msrvtt_retrieval.py +114 -0
- al_ret/datasets.py +137 -0
- al_ret/metrics.py +70 -0
- al_ret/precision.py +12 -0
- al_ret/retrieval.py +266 -0
- al_ret/util.py +73 -0
- al_ret/zero_shot.py +91 -0
- assets/audio/0.wav +3 -0
- assets/audio/1.wav +3 -0
- assets/demo.png +3 -0
- assets/depth/0.png +3 -0
- assets/depth/1.png +3 -0
- assets/emergency.jpg +3 -0
- assets/iclr_dataset_sample.jpg +3 -0
- assets/image/0.jpg +0 -0
- assets/image/1.jpg +0 -0
- assets/languagebind.jpg +3 -0
- assets/languagebind_frame.jpg +3 -0
- assets/languagebind_result.jpg +3 -0
- assets/languge_result.jpg +3 -0
- assets/logo.jpg +3 -0
- assets/logo_languagebind.png +3 -0
- assets/res1.jpg +0 -0
- assets/res2.jpg +0 -0
- assets/result1.jpg +3 -0
- assets/sota.jpg +3 -0
- assets/thermal/0.jpg +0 -0
- assets/thermal/1.jpg +0 -0
- assets/video/0.mp4 +3 -0
- assets/video/1.mp4 +3 -0
- d_cls/cp_zero_shot_metadata.py +117 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,20 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
assets/audio/0.wav filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/audio/1.wav filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
assets/demo.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
assets/depth/0.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
assets/depth/1.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
assets/emergency.jpg filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
assets/iclr_dataset_sample.jpg filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
assets/languagebind.jpg filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
assets/languagebind_frame.jpg filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
assets/languagebind_result.jpg filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
assets/languge_result.jpg filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
assets/logo.jpg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
assets/logo_languagebind.png filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
assets/result1.jpg filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
assets/sota.jpg filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
assets/video/0.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
assets/video/1.mp4 filter=lfs diff=lfs merge=lfs -text
|
1/1
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
1
|
DATASETS.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Sample data
|
| 2 |
+
We are releasing sample data here so that individuals who are interested can further modify the code to train it on their own data, which includes videos, text from various sources, depth, and infrared.
|
| 3 |
+
|
| 4 |
+
<div align="center">
|
| 5 |
+
<table border="1" width="100%">
|
| 6 |
+
<tr align="center">
|
| 7 |
+
<th></th><th>Baidu Yun</th><th>Google Cloud</th><th>Peking University Yun</th>
|
| 8 |
+
</tr>
|
| 9 |
+
<tr align="center">
|
| 10 |
+
<td>DATA</td><td><a href="https://pan.baidu.com/s/1MnQUO6xrMPE5HAwveAdtZA?pwd=5ug9">Link</a></td><td><a href="https://drive.google.com/file/d/1p7y_0H3c84VbWpI-zx_m_mgn84uTZTdO/view?usp=drive_link">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/B6BDBDDCC616D47126DD0FF568CAF6CD">Link</a></td>
|
| 11 |
+
</tr>
|
| 12 |
+
<tr align="center">
|
| 13 |
+
<td>ANNOTATION</td><td><a href="https://pan.baidu.com/s/1uxxx_67VWy25q7CDilLsHA?pwd=37j3">Link</a></td><td><a href="https://drive.google.com/file/d/1WWVkt9LdbGK0VeQh-g7xy1gUGBwzwVah/view?usp=drive_link">Link</a></td><td><a href=https://disk.pku.edu.cn:443/link/67D836DE504E96457554455A597DC57F"">Link</a></td>
|
| 14 |
+
</tr>
|
| 15 |
+
</table>
|
| 16 |
+
</div>
|
| 17 |
+
|
| 18 |
+
## VIDAL-10M
|
| 19 |
+
|
| 20 |
+
### Text and Video
|
| 21 |
+
Due to policy restrictions, we are unable to directly release the videos. However, we provide the YouTube IDs, which can be used to download the videos independently. All textual sources and YouTube IDs can be downloaded from [Google Disk](https://drive.google.com/file/d/1qgm3rO9JugazLJ6KRsAKZfLIagHu3PJ-/view?usp=sharing) or [Baidu Disk](https://pan.baidu.com/s/13gY-IcFSFIuDZ-q0hMTx0g?pwd=gum9).
|
| 22 |
+
|
| 23 |
+
The organization format of `ANNOTATION` is as follows:
|
| 24 |
+
```Bash
|
| 25 |
+
{
|
| 26 |
+
"ImkVYKWqlDU": {
|
| 27 |
+
"folder": "coco_vat_9",
|
| 28 |
+
"mplug": "This video describes a group of scuba divers rolling backwards off a boat while playing an instrument. They are having fun and enjoying their time in the water.",
|
| 29 |
+
"polish_mplug": "scuba divers are seen rolling backwards off a boat while playing an instrument, displaying enjoyment and having a good time in the water.",
|
| 30 |
+
"ofa": [
|
| 31 |
+
" a man in a wet suit and a helmet on a boat",
|
| 32 |
+
" a man in a scuba suit on a boat",
|
| 33 |
+
" a person in a boat holding a diver helmet",
|
| 34 |
+
" a man in a wetsuit on a jet ski",
|
| 35 |
+
" a picture of a body of water with the words boats on it",
|
| 36 |
+
" a person in the water with the words if they rolled",
|
| 37 |
+
" a person in the water with a paddle",
|
| 38 |
+
" a person in the water with a scooter"
|
| 39 |
+
],
|
| 40 |
+
"sound_mplug": "scuba divers rolling backwards off a boat while playing an instrument showcases exuberant laughter, splashing water, and cheery melodies blending with the gentle waves.",
|
| 41 |
+
"raw": "WHY SCUBA DIVERS ROLL BACKWARDS OFF BOAT #shorts"
|
| 42 |
+
},
|
| 43 |
+
"id": {
|
| 44 |
+
"folder": "video_folder",
|
| 45 |
+
"mplug": "mplug_caption",
|
| 46 |
+
"polish_mplug": "polish_mplug_caption",
|
| 47 |
+
"ofa": [
|
| 48 |
+
"ofa_caption_0",
|
| 49 |
+
"ofa_caption_1",
|
| 50 |
+
"ofa_caption_2",
|
| 51 |
+
"ofa_caption_3",
|
| 52 |
+
"ofa_caption_4",
|
| 53 |
+
"ofa_caption_5",
|
| 54 |
+
"ofa_caption_6",
|
| 55 |
+
"ofa_caption_7"
|
| 56 |
+
],
|
| 57 |
+
"sound_mplug": "sound_mplug_caption",
|
| 58 |
+
"raw": "raw_caption#hashtags"
|
| 59 |
+
},
|
| 60 |
+
...
|
| 61 |
+
}
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
### Depth and Thermal (Infrared)
|
| 65 |
+
|
| 66 |
+
We are uploading data to [Hugging Face](https://huggingface.co/datasets/LanguageBind/VIDAL-Depth-Thermal), but based on a conservative estimate, it's approximately **20T**. Please be patient as we work on it.
|
DATASET_LICENSE
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Attribution-NonCommercial 4.0 International
|
| 3 |
+
|
| 4 |
+
=======================================================================
|
| 5 |
+
|
| 6 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 7 |
+
does not provide legal services or legal advice. Distribution of
|
| 8 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 9 |
+
other relationship. Creative Commons makes its licenses and related
|
| 10 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 11 |
+
warranties regarding its licenses, any material licensed under their
|
| 12 |
+
terms and conditions, or any related information. Creative Commons
|
| 13 |
+
disclaims all liability for damages resulting from their use to the
|
| 14 |
+
fullest extent possible.
|
| 15 |
+
|
| 16 |
+
Using Creative Commons Public Licenses
|
| 17 |
+
|
| 18 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 19 |
+
conditions that creators and other rights holders may use to share
|
| 20 |
+
original works of authorship and other material subject to copyright
|
| 21 |
+
and certain other rights specified in the public license below. The
|
| 22 |
+
following considerations are for informational purposes only, are not
|
| 23 |
+
exhaustive, and do not form part of our licenses.
|
| 24 |
+
|
| 25 |
+
Considerations for licensors: Our public licenses are
|
| 26 |
+
intended for use by those authorized to give the public
|
| 27 |
+
permission to use material in ways otherwise restricted by
|
| 28 |
+
copyright and certain other rights. Our licenses are
|
| 29 |
+
irrevocable. Licensors should read and understand the terms
|
| 30 |
+
and conditions of the license they choose before applying it.
|
| 31 |
+
Licensors should also secure all rights necessary before
|
| 32 |
+
applying our licenses so that the public can reuse the
|
| 33 |
+
material as expected. Licensors should clearly mark any
|
| 34 |
+
material not subject to the license. This includes other CC-
|
| 35 |
+
licensed material, or material used under an exception or
|
| 36 |
+
limitation to copyright. More considerations for licensors:
|
| 37 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 38 |
+
|
| 39 |
+
Considerations for the public: By using one of our public
|
| 40 |
+
licenses, a licensor grants the public permission to use the
|
| 41 |
+
licensed material under specified terms and conditions. If
|
| 42 |
+
the licensor's permission is not necessary for any reason--for
|
| 43 |
+
example, because of any applicable exception or limitation to
|
| 44 |
+
copyright--then that use is not regulated by the license. Our
|
| 45 |
+
licenses grant only permissions under copyright and certain
|
| 46 |
+
other rights that a licensor has authority to grant. Use of
|
| 47 |
+
the licensed material may still be restricted for other
|
| 48 |
+
reasons, including because others have copyright or other
|
| 49 |
+
rights in the material. A licensor may make special requests,
|
| 50 |
+
such as asking that all changes be marked or described.
|
| 51 |
+
Although not required by our licenses, you are encouraged to
|
| 52 |
+
respect those requests where reasonable. More_considerations
|
| 53 |
+
for the public:
|
| 54 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 55 |
+
|
| 56 |
+
=======================================================================
|
| 57 |
+
|
| 58 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
| 59 |
+
License
|
| 60 |
+
|
| 61 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 62 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 63 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
| 64 |
+
License"). To the extent this Public License may be interpreted as a
|
| 65 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
| 66 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
| 67 |
+
such rights in consideration of benefits the Licensor receives from
|
| 68 |
+
making the Licensed Material available under these terms and
|
| 69 |
+
conditions.
|
| 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. Copyright and Similar Rights means copyright and/or similar rights
|
| 88 |
+
closely related to copyright including, without limitation,
|
| 89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 90 |
+
Rights, without regard to how the rights are labeled or
|
| 91 |
+
categorized. For purposes of this Public License, the rights
|
| 92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 93 |
+
Rights.
|
| 94 |
+
d. Effective Technological Measures means those measures that, in the
|
| 95 |
+
absence of proper authority, may not be circumvented under laws
|
| 96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 98 |
+
agreements.
|
| 99 |
+
|
| 100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 101 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 102 |
+
that applies to Your use of the Licensed Material.
|
| 103 |
+
|
| 104 |
+
f. Licensed Material means the artistic or literary work, database,
|
| 105 |
+
or other material to which the Licensor applied this Public
|
| 106 |
+
License.
|
| 107 |
+
|
| 108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
| 109 |
+
terms and conditions of this Public License, which are limited to
|
| 110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 111 |
+
Licensed Material and that the Licensor has authority to license.
|
| 112 |
+
|
| 113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
| 114 |
+
under this Public License.
|
| 115 |
+
|
| 116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
| 117 |
+
commercial advantage or monetary compensation. For purposes of
|
| 118 |
+
this Public License, the exchange of the Licensed Material for
|
| 119 |
+
other material subject to Copyright and Similar Rights by digital
|
| 120 |
+
file-sharing or similar means is NonCommercial provided there is
|
| 121 |
+
no payment of monetary compensation in connection with the
|
| 122 |
+
exchange.
|
| 123 |
+
|
| 124 |
+
j. Share means to provide material to the public by any means or
|
| 125 |
+
process that requires permission under the Licensed Rights, such
|
| 126 |
+
as reproduction, public display, public performance, distribution,
|
| 127 |
+
dissemination, communication, or importation, and to make material
|
| 128 |
+
available to the public including in ways that members of the
|
| 129 |
+
public may access the material from a place and at a time
|
| 130 |
+
individually chosen by them.
|
| 131 |
+
|
| 132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
| 133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 135 |
+
as amended and/or succeeded, as well as other essentially
|
| 136 |
+
equivalent rights anywhere in the world.
|
| 137 |
+
|
| 138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
| 139 |
+
under this Public License. Your has a corresponding meaning.
|
| 140 |
+
|
| 141 |
+
Section 2 -- Scope.
|
| 142 |
+
|
| 143 |
+
a. License grant.
|
| 144 |
+
|
| 145 |
+
1. Subject to the terms and conditions of this Public License,
|
| 146 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 147 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 148 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 149 |
+
|
| 150 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 151 |
+
in part, for NonCommercial purposes only; and
|
| 152 |
+
|
| 153 |
+
b. produce, reproduce, and Share Adapted Material for
|
| 154 |
+
NonCommercial purposes only.
|
| 155 |
+
|
| 156 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 157 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 158 |
+
License does not apply, and You do not need to comply with
|
| 159 |
+
its terms and conditions.
|
| 160 |
+
|
| 161 |
+
3. Term. The term of this Public License is specified in Section
|
| 162 |
+
6(a).
|
| 163 |
+
|
| 164 |
+
4. Media and formats; technical modifications allowed. The
|
| 165 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 166 |
+
all media and formats whether now known or hereafter created,
|
| 167 |
+
and to make technical modifications necessary to do so. The
|
| 168 |
+
Licensor waives and/or agrees not to assert any right or
|
| 169 |
+
authority to forbid You from making technical modifications
|
| 170 |
+
necessary to exercise the Licensed Rights, including
|
| 171 |
+
technical modifications necessary to circumvent Effective
|
| 172 |
+
Technological Measures. For purposes of this Public License,
|
| 173 |
+
simply making modifications authorized by this Section 2(a)
|
| 174 |
+
(4) never produces Adapted Material.
|
| 175 |
+
|
| 176 |
+
5. Downstream recipients.
|
| 177 |
+
|
| 178 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 179 |
+
recipient of the Licensed Material automatically
|
| 180 |
+
receives an offer from the Licensor to exercise the
|
| 181 |
+
Licensed Rights under the terms and conditions of this
|
| 182 |
+
Public License.
|
| 183 |
+
|
| 184 |
+
b. No downstream restrictions. You may not offer or impose
|
| 185 |
+
any additional or different terms or conditions on, or
|
| 186 |
+
apply any Effective Technological Measures to, the
|
| 187 |
+
Licensed Material if doing so restricts exercise of the
|
| 188 |
+
Licensed Rights by any recipient of the Licensed
|
| 189 |
+
Material.
|
| 190 |
+
|
| 191 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 192 |
+
may be construed as permission to assert or imply that You
|
| 193 |
+
are, or that Your use of the Licensed Material is, connected
|
| 194 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 195 |
+
the Licensor or others designated to receive attribution as
|
| 196 |
+
provided in Section 3(a)(1)(A)(i).
|
| 197 |
+
|
| 198 |
+
b. Other rights.
|
| 199 |
+
|
| 200 |
+
1. Moral rights, such as the right of integrity, are not
|
| 201 |
+
licensed under this Public License, nor are publicity,
|
| 202 |
+
privacy, and/or other similar personality rights; however, to
|
| 203 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 204 |
+
assert any such rights held by the Licensor to the limited
|
| 205 |
+
extent necessary to allow You to exercise the Licensed
|
| 206 |
+
Rights, but not otherwise.
|
| 207 |
+
|
| 208 |
+
2. Patent and trademark rights are not licensed under this
|
| 209 |
+
Public License.
|
| 210 |
+
|
| 211 |
+
3. To the extent possible, the Licensor waives any right to
|
| 212 |
+
collect royalties from You for the exercise of the Licensed
|
| 213 |
+
Rights, whether directly or through a collecting society
|
| 214 |
+
under any voluntary or waivable statutory or compulsory
|
| 215 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 216 |
+
reserves any right to collect such royalties, including when
|
| 217 |
+
the Licensed Material is used other than for NonCommercial
|
| 218 |
+
purposes.
|
| 219 |
+
|
| 220 |
+
Section 3 -- License Conditions.
|
| 221 |
+
|
| 222 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 223 |
+
following conditions.
|
| 224 |
+
|
| 225 |
+
a. Attribution.
|
| 226 |
+
|
| 227 |
+
1. If You Share the Licensed Material (including in modified
|
| 228 |
+
form), You must:
|
| 229 |
+
|
| 230 |
+
a. retain the following if it is supplied by the Licensor
|
| 231 |
+
with the Licensed Material:
|
| 232 |
+
|
| 233 |
+
i. identification of the creator(s) of the Licensed
|
| 234 |
+
Material and any others designated to receive
|
| 235 |
+
attribution, in any reasonable manner requested by
|
| 236 |
+
the Licensor (including by pseudonym if
|
| 237 |
+
designated);
|
| 238 |
+
|
| 239 |
+
ii. a copyright notice;
|
| 240 |
+
|
| 241 |
+
iii. a notice that refers to this Public License;
|
| 242 |
+
|
| 243 |
+
iv. a notice that refers to the disclaimer of
|
| 244 |
+
warranties;
|
| 245 |
+
|
| 246 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 247 |
+
extent reasonably practicable;
|
| 248 |
+
|
| 249 |
+
b. indicate if You modified the Licensed Material and
|
| 250 |
+
retain an indication of any previous modifications; and
|
| 251 |
+
|
| 252 |
+
c. indicate the Licensed Material is licensed under this
|
| 253 |
+
Public License, and include the text of, or the URI or
|
| 254 |
+
hyperlink to, this Public License.
|
| 255 |
+
|
| 256 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 257 |
+
reasonable manner based on the medium, means, and context in
|
| 258 |
+
which You Share the Licensed Material. For example, it may be
|
| 259 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 260 |
+
hyperlink to a resource that includes the required
|
| 261 |
+
information.
|
| 262 |
+
|
| 263 |
+
3. If requested by the Licensor, You must remove any of the
|
| 264 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 265 |
+
reasonably practicable.
|
| 266 |
+
|
| 267 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
| 268 |
+
License You apply must not prevent recipients of the Adapted
|
| 269 |
+
Material from complying with this Public License.
|
| 270 |
+
|
| 271 |
+
Section 4 -- Sui Generis Database Rights.
|
| 272 |
+
|
| 273 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 274 |
+
apply to Your use of the Licensed Material:
|
| 275 |
+
|
| 276 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 277 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 278 |
+
portion of the contents of the database for NonCommercial purposes
|
| 279 |
+
only;
|
| 280 |
+
|
| 281 |
+
b. if You include all or a substantial portion of the database
|
| 282 |
+
contents in a database in which You have Sui Generis Database
|
| 283 |
+
Rights, then the database in which You have Sui Generis Database
|
| 284 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 285 |
+
|
| 286 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 287 |
+
all or a substantial portion of the contents of the database.
|
| 288 |
+
|
| 289 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 290 |
+
replace Your obligations under this Public License where the Licensed
|
| 291 |
+
Rights include other Copyright and Similar Rights.
|
| 292 |
+
|
| 293 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 294 |
+
|
| 295 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 296 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 297 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 298 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 299 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 300 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 301 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 302 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 303 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 304 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 305 |
+
|
| 306 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 307 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 308 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 309 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 310 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 311 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 312 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 313 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 314 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 315 |
+
|
| 316 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 317 |
+
above shall be interpreted in a manner that, to the extent
|
| 318 |
+
possible, most closely approximates an absolute disclaimer and
|
| 319 |
+
waiver of all liability.
|
| 320 |
+
|
| 321 |
+
Section 6 -- Term and Termination.
|
| 322 |
+
|
| 323 |
+
a. This Public License applies for the term of the Copyright and
|
| 324 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 325 |
+
this Public License, then Your rights under this Public License
|
| 326 |
+
terminate automatically.
|
| 327 |
+
|
| 328 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 329 |
+
Section 6(a), it reinstates:
|
| 330 |
+
|
| 331 |
+
1. automatically as of the date the violation is cured, provided
|
| 332 |
+
it is cured within 30 days of Your discovery of the
|
| 333 |
+
violation; or
|
| 334 |
+
|
| 335 |
+
2. upon express reinstatement by the Licensor.
|
| 336 |
+
|
| 337 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 338 |
+
right the Licensor may have to seek remedies for Your violations
|
| 339 |
+
of this Public License.
|
| 340 |
+
|
| 341 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 342 |
+
Licensed Material under separate terms or conditions or stop
|
| 343 |
+
distributing the Licensed Material at any time; however, doing so
|
| 344 |
+
will not terminate this Public License.
|
| 345 |
+
|
| 346 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 347 |
+
License.
|
| 348 |
+
|
| 349 |
+
Section 7 -- Other Terms and Conditions.
|
| 350 |
+
|
| 351 |
+
a. The Licensor shall not be bound by any additional or different
|
| 352 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 353 |
+
|
| 354 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 355 |
+
Licensed Material not stated herein are separate from and
|
| 356 |
+
independent of the terms and conditions of this Public License.
|
| 357 |
+
|
| 358 |
+
Section 8 -- Interpretation.
|
| 359 |
+
|
| 360 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 361 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 362 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 363 |
+
be made without permission under this Public License.
|
| 364 |
+
|
| 365 |
+
b. To the extent possible, if any provision of this Public License is
|
| 366 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 367 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 368 |
+
cannot be reformed, it shall be severed from this Public License
|
| 369 |
+
without affecting the enforceability of the remaining terms and
|
| 370 |
+
conditions.
|
| 371 |
+
|
| 372 |
+
c. No term or condition of this Public License will be waived and no
|
| 373 |
+
failure to comply consented to unless expressly agreed to by the
|
| 374 |
+
Licensor.
|
| 375 |
+
|
| 376 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 377 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 378 |
+
that apply to the Licensor or You, including from the legal
|
| 379 |
+
processes of any jurisdiction or authority.
|
| 380 |
+
|
| 381 |
+
=======================================================================
|
| 382 |
+
|
| 383 |
+
Creative Commons is not a party to its public
|
| 384 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 385 |
+
its public licenses to material it publishes and in those instances
|
| 386 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 387 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 388 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 389 |
+
material is shared under a Creative Commons public license or as
|
| 390 |
+
otherwise permitted by the Creative Commons policies published at
|
| 391 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 392 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 393 |
+
of Creative Commons without its prior written consent including,
|
| 394 |
+
without limitation, in connection with any unauthorized modifications
|
| 395 |
+
to any of its public licenses or any other arrangements,
|
| 396 |
+
understandings, or agreements concerning use of licensed material. For
|
| 397 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 398 |
+
public licenses.
|
| 399 |
+
|
| 400 |
+
Creative Commons may be contacted at creativecommons.org.
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2023 PKU-YUAN's Group (袁粒课题组-北大信工)
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<p align="center">
|
| 2 |
+
<img src="assets/logo.jpg" width="350" style="margin-bottom: 0.2;"/><img src="assets/sota.jpg" width="450" style="margin-bottom: 0.2;"/>
|
| 3 |
+
<p>
|
| 4 |
+
<h2 align="center"> <a href="https://arxiv.org/pdf/2310.01852.pdf">【ICLR 2024 🔥】LanguageBind: Extending Video-Language Pretraining to N-modality by Language-based Semantic Alignment</a></h2>
|
| 5 |
+
<h5 align="center"> If you like our project, please give us a star ⭐ on GitHub for latest update. </h2>
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
<h5 align="center">
|
| 9 |
+
|
| 10 |
+
[](https://huggingface.co/spaces/LanguageBind/LanguageBind)
|
| 11 |
+
[](https://huggingface.co/datasets/LanguageBind/VIDAL-Depth-Thermal)
|
| 12 |
+
[](https://arxiv.org/abs/2310.01852)
|
| 13 |
+
[](https://mp.weixin.qq.com/s/EFqLv_Euf5VU024zOtzkkg)
|
| 14 |
+
[](https://mp.weixin.qq.com/s/E5Tazm_vz1CADMwV0tdhnw)
|
| 15 |
+
[](https://zhuanlan.zhihu.com/p/660567767)
|
| 16 |
+
[](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/LICENSE)
|
| 17 |
+
[](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/DATASET_LICENSE)
|
| 18 |
+
[](https://hits.seeyoufarm.com)
|
| 19 |
+
[](https://github.com/PKU-YuanGroup/LanguageBind/issues?q=is%3Aopen+is%3Aissue)
|
| 20 |
+
[](https://github.com/PKU-YuanGroup/LanguageBind/issues?q=is%3Aissue+is%3Aclosed) <br>
|
| 21 |
+
|
| 22 |
+
</h5>
|
| 23 |
+
|
| 24 |
+
[](https://paperswithcode.com/sota/zero-shot-audio-classification-on-audioset?p=languagebind-extending-video-language) <br>
|
| 25 |
+
[](https://paperswithcode.com/sota/zero-shot-audio-classification-on-vgg-sound?p=languagebind-extending-video-language) <br>
|
| 26 |
+
[](https://paperswithcode.com/sota/zero-shot-text-to-audio-retrieval-on-clotho?p=languagebind-extending-video-language) <br>
|
| 27 |
+
[](https://paperswithcode.com/sota/zero-shot-scene-classification-unified?p=languagebind-extending-video-language) <br>
|
| 28 |
+
[](https://paperswithcode.com/sota/zero-shot-classification-unified-classes-on?p=languagebind-extending-video-language) <br>
|
| 29 |
+
[](https://paperswithcode.com/sota/zero-shot-video-retrieval-on-msvd?p=languagebind-extending-video-language) <br>
|
| 30 |
+
[](https://paperswithcode.com/sota/zero-shot-environment-sound-classification-on-1?p=languagebind-extending-video-language) <br>
|
| 31 |
+
[](https://paperswithcode.com/sota/zero-shot-text-to-audio-retrieval-on?p=languagebind-extending-video-language) <br>
|
| 32 |
+
[](https://paperswithcode.com/sota/zero-shot-video-retrieval-on-activitynet?p=languagebind-extending-video-language) <br>
|
| 33 |
+
[](https://paperswithcode.com/sota/zero-shot-video-retrieval-on-msr-vtt?p=languagebind-extending-video-language) <br>
|
| 34 |
+
[](https://paperswithcode.com/sota/zero-shot-video-retrieval-on-didemo?p=languagebind-extending-video-language) <br>
|
| 35 |
+
[](https://paperswithcode.com/sota/zero-shot-action-recognition-on-kinetics?p=languagebind-extending-video-language)
|
| 36 |
+
|
| 37 |
+
<details open><summary>💡 I also have other vision-language projects that may interest you ✨. </summary><p>
|
| 38 |
+
<!-- may -->
|
| 39 |
+
|
| 40 |
+
> [**Video-LLaVA: Learning United Visual Representation by Alignment Before Projection**](https://arxiv.org/abs/2311.10122) <br>
|
| 41 |
+
> Bin Lin, Yang Ye, Bin Zhu, Jiaxi Cui, Munan Ning, Peng Jin, Li Yuan <br>
|
| 42 |
+
[](https://github.com/PKU-YuanGroup/Video-LLaVA) [](https://github.com/PKU-YuanGroup/Video-LLaVA) [](https://arxiv.org/abs/2311.10122) <br>
|
| 43 |
+
|
| 44 |
+
> [**MoE-LLaVA: Mixture of Experts for Large Vision-Language Models**](https://github.com/PKU-YuanGroup/MoE-LLaVA/blob/main/MoE-LLaVA.pdf) <br>
|
| 45 |
+
> Bin Lin, Zhenyu Tang, Yang Ye, Jiaxi Cui, Bin Zhu, Peng Jin, Junwu Zhang, Munan Ning, Li Yuan <br>
|
| 46 |
+
[](https://github.com/PKU-YuanGroup/MoE-LLaVA) [](https://github.com/PKU-YuanGroup/MoE-LLaVA) [](https://arxiv.org/abs/2401.15947) <br>
|
| 47 |
+
|
| 48 |
+
> [**Video-Bench: A Comprehensive Benchmark and Toolkit for Evaluating Video-based Large Language Models**](https://arxiv.org/abs/2311.08046) <br>
|
| 49 |
+
> Munan Ning, Bin Zhu, Yujia Xie, Bin Lin, Jiaxi Cui, Lu Yuan, Dongdong Chen, Li Yuan <br>
|
| 50 |
+
[](https://github.com/PKU-YuanGroup/Video-Bench) [](https://github.com/PKU-YuanGroup/Video-Bench) [](https://arxiv.org/abs/2311.16103) <br>
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
</p></details>
|
| 54 |
+
|
| 55 |
+
## 📰 News
|
| 56 |
+
* **[2024.01.27]** 👀👀👀 Our [MoE-LLaVA](https://github.com/PKU-YuanGroup/MoE-LLaVA) is released! A sparse model with 3B parameters outperformed the dense model with 7B parameters.
|
| 57 |
+
* **[2024.01.16]** 🔥🔥🔥 Our LanguageBind has been accepted at ICLR 2024! We earn the score of 6(3)8(6)6(6)6(6) [here](https://openreview.net/forum?id=QmZKc7UZCy¬eId=OgsxQxAleA).
|
| 58 |
+
* **[2023.12.15]** 💪💪💪 We expand the 💥💥💥 VIDAL dataset and now have **10M video-text data**. We launch **LanguageBind_Video 1.5**, checking our [model zoo](#-model-zoo).
|
| 59 |
+
* **[2023.12.10]** We expand the 💥💥💥 VIDAL dataset and now have **10M depth and 10M thermal data**. We are in the process of uploading thermal and depth data on [Hugging Face](https://huggingface.co/datasets/LanguageBind/VIDAL-Depth-Thermal) and expect the whole process to last 1-2 months.
|
| 60 |
+
* **[2023.11.27]** 🔥🔥🔥 We have updated our [paper](https://arxiv.org/abs/2310.01852) with emergency zero-shot results., checking our ✨ [results](#emergency-results).
|
| 61 |
+
* **[2023.11.26]** 💥💥💥 We have open-sourced all textual sources and corresponding YouTube IDs [here](DATASETS.md).
|
| 62 |
+
* **[2023.11.26]** 📣📣📣 We have open-sourced fully fine-tuned **Video & Audio**, achieving improved performance once again, checking our [model zoo](#-model-zoo).
|
| 63 |
+
* **[2023.11.22]** We are about to release a fully fine-tuned version, and the **HUGE** version is currently undergoing training.
|
| 64 |
+
* **[2023.11.21]** 💥 We are releasing sample data in [DATASETS.md](DATASETS.md) so that individuals who are interested can further modify the code to train it on their own data.
|
| 65 |
+
* **[2023.11.20]** 🚀🚀🚀 [Video-LLaVA](https://github.com/PKU-YuanGroup/Video-LLaVA) builds a large visual-language model to achieve 🎉SOTA performances based on LanguageBind encoders.
|
| 66 |
+
* **[2023.10.23]** 🎶 LanguageBind-Audio achieves 🎉🎉🎉**state-of-the-art (SOTA) performance on 5 datasets**, checking our ✨ [results](#multiple-modalities)!
|
| 67 |
+
* **[2023.10.14]** 😱 Released a stronger LanguageBind-Video, checking our ✨ [results](#video-language)! The video checkpoint **have updated** on Huggingface Model Hub!
|
| 68 |
+
* **[2023.10.10]** We provide sample data, which can be found in [assets](assets), and [emergency zero-shot usage](#emergency-zero-shot) is described.
|
| 69 |
+
* **[2023.10.07]** The checkpoints are available on 🤗 [Huggingface Model](https://huggingface.co/LanguageBind).
|
| 70 |
+
* **[2023.10.04]** Code and [demo](https://huggingface.co/spaces/LanguageBind/LanguageBind) are available now! Welcome to **watch** 👀 this repository for the latest updates.
|
| 71 |
+
|
| 72 |
+
## 😮 Highlights
|
| 73 |
+
|
| 74 |
+
### 💡 High performance, but NO intermediate modality required
|
| 75 |
+
LanguageBind is a **language-centric** multimodal pretraining approach, **taking the language as the bind across different modalities** because the language modality is well-explored and contains rich semantics.
|
| 76 |
+
* The following first figure shows the architecture of LanguageBind. LanguageBind can be easily extended to segmentation, detection tasks, and potentially to unlimited modalities.
|
| 77 |
+
|
| 78 |
+
### ⚡️ A multimodal, fully aligned and voluminous dataset
|
| 79 |
+
We propose **VIDAL-10M**, **10 Million data** with **V**ideo, **I**nfrared, **D**epth, **A**udio and their corresponding **L**anguage, which greatly expands the data beyond visual modalities.
|
| 80 |
+
* The second figure shows our proposed VIDAL-10M dataset, which includes five modalities: video, infrared, depth, audio, and language.
|
| 81 |
+
|
| 82 |
+
### 🔥 Multi-view enhanced description for training
|
| 83 |
+
We make multi-view enhancements to language. We produce multi-view description that combines **meta-data**, **spatial**, and **temporal** to greatly enhance the semantic information of the language. In addition we further **enhance the language with ChatGPT** to create a good semantic space for each modality aligned language.
|
| 84 |
+
|
| 85 |
+
<p align="center">
|
| 86 |
+
<img src="assets/languagebind.jpg" width=100%>
|
| 87 |
+
</p>
|
| 88 |
+
<p align="center">
|
| 89 |
+
<img src="assets/iclr_dataset_sample.jpg" width=99%>
|
| 90 |
+
</p>
|
| 91 |
+
|
| 92 |
+
## 🤗 Demo
|
| 93 |
+
|
| 94 |
+
* **Local demo.** Highly recommend trying out our web demo, which incorporates all features currently supported by LanguageBind.
|
| 95 |
+
```bash
|
| 96 |
+
python gradio_app.py
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
* **Online demo.** We provide the [online demo](https://huggingface.co/spaces/LanguageBind/LanguageBind) in Huggingface Spaces. In this demo, you can calculate the similarity of modalities to language, such as audio-to-language, video-to-language, and depth-to-image.
|
| 100 |
+
<p align="center">
|
| 101 |
+
<img src="assets/demo.png" width=100%>
|
| 102 |
+
</p>
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
## 🚀 Main Results
|
| 107 |
+
|
| 108 |
+
### Video-Language
|
| 109 |
+
LanguageBind achieves **state-of-the-art (SOTA) performance on four datasets**, * donates the results of full tuning.
|
| 110 |
+
<p align="left">
|
| 111 |
+
<img src="assets/result1.jpg" width=80%>
|
| 112 |
+
</p>
|
| 113 |
+
|
| 114 |
+
### Multiple Modalities
|
| 115 |
+
Video-Language, Infrared-Language, Depth-Language, and Audio-Language zero-shot classification, * donates the results of full tuning.
|
| 116 |
+
<p align="left">
|
| 117 |
+
<img src="assets/res1.jpg" width=80%>
|
| 118 |
+
</p>
|
| 119 |
+
We report text-to-audio results for retrieval, * donates the results of full tuning.
|
| 120 |
+
<p align="left">
|
| 121 |
+
<img src="assets/res2.jpg" width=35%>
|
| 122 |
+
</p>
|
| 123 |
+
|
| 124 |
+
### Emergency results
|
| 125 |
+
<p align="left">
|
| 126 |
+
<img src="assets/emergency.jpg" width=60%>
|
| 127 |
+
</p>
|
| 128 |
+
|
| 129 |
+
## 🛠️ Requirements and Installation
|
| 130 |
+
* Python >= 3.8
|
| 131 |
+
* Pytorch >= 1.13.1
|
| 132 |
+
* CUDA Version >= 11.6
|
| 133 |
+
* Install required packages:
|
| 134 |
+
```bash
|
| 135 |
+
git clone https://github.com/PKU-YuanGroup/LanguageBind
|
| 136 |
+
cd LanguageBind
|
| 137 |
+
pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu116
|
| 138 |
+
pip install -r requirements.txt
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## 🐳 Model Zoo
|
| 142 |
+
|
| 143 |
+
The names in the table represent different encoder models. For example, `LanguageBind/LanguageBind_Video_FT` represents the fully fine-tuned version, while `LanguageBind/LanguageBind_Video` represents the LoRA-tuned version.
|
| 144 |
+
|
| 145 |
+
You can freely replace them in the recommended [API usage](#-api). We recommend using the fully fine-tuned version, as it offers stronger performance.
|
| 146 |
+
|
| 147 |
+
<div align="center">
|
| 148 |
+
<table border="1" width="100%">
|
| 149 |
+
<tr align="center">
|
| 150 |
+
<th>Modality</th><th>LoRA tuning</th><th>Fine-tuning</th>
|
| 151 |
+
</tr>
|
| 152 |
+
<tr align="center">
|
| 153 |
+
<td>Video</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video">LanguageBind_Video</a></td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video_FT">LanguageBind_Video_FT</a></td>
|
| 154 |
+
</tr>
|
| 155 |
+
<tr align="center">
|
| 156 |
+
<td>Audio</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Audio">LanguageBind_Audio</a></td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Audio_FT">LanguageBind_Audio_FT</a></td>
|
| 157 |
+
</tr>
|
| 158 |
+
<tr align="center">
|
| 159 |
+
<td>Depth</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Depth">LanguageBind_Depth</a></td><td>-</td>
|
| 160 |
+
</tr>
|
| 161 |
+
<tr align="center">
|
| 162 |
+
<td>Thermal</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Thermal">LanguageBind_Thermal</a></td><td>-</td>
|
| 163 |
+
</tr>
|
| 164 |
+
</table>
|
| 165 |
+
</div>
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
<div align="center">
|
| 169 |
+
<table border="1" width="100%">
|
| 170 |
+
<tr align="center">
|
| 171 |
+
<th>Version</th><th>Tuning</th><th>Model size</th><th>Num_frames</th><th>HF Link</th><th>MSR-VTT</th><th>DiDeMo</th><th>ActivityNet</th><th>MSVD</th>
|
| 172 |
+
</tr>
|
| 173 |
+
<tr align="center">
|
| 174 |
+
<td>LanguageBind_Video</td><td>LoRA</td><td>Large</td><td>8</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video">Link</a></td><td>42.6</td><td>37.8</td><td>35.1</td><td>52.2</td>
|
| 175 |
+
</tr>
|
| 176 |
+
<tr align="center">
|
| 177 |
+
<td>LanguageBind_Video_FT</td><td>Full-tuning</td><td>Large</td><td>8</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video_FT">Link</a></td><td>42.7</td><td>38.1</td><td>36.9</td><td>53.5</td>
|
| 178 |
+
</tr>
|
| 179 |
+
<tr align="center">
|
| 180 |
+
<td>LanguageBind_Video_V1.5_FT</td><td>Full-tuning</td><td>Large</td><td>8</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video_V1.5_FT">Link</a></td><td>42.8</td><td>39.7</td><td>38.4</td><td>54.1</td>
|
| 181 |
+
</tr>
|
| 182 |
+
<tr align="center">
|
| 183 |
+
<td>LanguageBind_Video_V1.5_FT</td><td>Full-tuning</td><td>Large</td><td>12</td><td>Coming soon</td>
|
| 184 |
+
</tr>
|
| 185 |
+
<tr align="center">
|
| 186 |
+
<td>LanguageBind_Video_Huge_V1.5_FT</td><td>Full-tuning</td><td>Huge</td><td>8</td><td><a href="https://huggingface.co/LanguageBind/LanguageBind_Video_Huge_V1.5_FT">Link</a></td><td>44.8</td><td>39.9</td><td>41.0</td><td>53.7</td>
|
| 187 |
+
</tr>
|
| 188 |
+
<tr align="center">
|
| 189 |
+
<td>LanguageBind_Video_Huge_V1.5_FT</td><td>Full-tuning</td><td>Huge</td><td>12</td><td>Coming soon</td>
|
| 190 |
+
</tr>
|
| 191 |
+
</table>
|
| 192 |
+
</div>
|
| 193 |
+
|
| 194 |
+
## 🤖 API
|
| 195 |
+
**We open source all modalities preprocessing code.** If you want to load the model (e.g. ```LanguageBind/LanguageBind_Thermal```) from the model hub on Huggingface or on local, you can use the following code snippets!
|
| 196 |
+
### Inference for Multi-modal Binding
|
| 197 |
+
We have provided some sample datasets in [assets](assets) to quickly see how languagebind works.
|
| 198 |
+
```python
|
| 199 |
+
import torch
|
| 200 |
+
from languagebind import LanguageBind, to_device, transform_dict, LanguageBindImageTokenizer
|
| 201 |
+
|
| 202 |
+
if __name__ == '__main__':
|
| 203 |
+
device = 'cuda:0'
|
| 204 |
+
device = torch.device(device)
|
| 205 |
+
clip_type = {
|
| 206 |
+
'video': 'LanguageBind_Video_FT', # also LanguageBind_Video
|
| 207 |
+
'audio': 'LanguageBind_Audio_FT', # also LanguageBind_Audio
|
| 208 |
+
'thermal': 'LanguageBind_Thermal',
|
| 209 |
+
'image': 'LanguageBind_Image',
|
| 210 |
+
'depth': 'LanguageBind_Depth',
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
model = LanguageBind(clip_type=clip_type, cache_dir='./cache_dir')
|
| 214 |
+
model = model.to(device)
|
| 215 |
+
model.eval()
|
| 216 |
+
pretrained_ckpt = f'lb203/LanguageBind_Image'
|
| 217 |
+
tokenizer = LanguageBindImageTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir/tokenizer_cache_dir')
|
| 218 |
+
modality_transform = {c: transform_dict[c](model.modality_config[c]) for c in clip_type.keys()}
|
| 219 |
+
|
| 220 |
+
image = ['assets/image/0.jpg', 'assets/image/1.jpg']
|
| 221 |
+
audio = ['assets/audio/0.wav', 'assets/audio/1.wav']
|
| 222 |
+
video = ['assets/video/0.mp4', 'assets/video/1.mp4']
|
| 223 |
+
depth = ['assets/depth/0.png', 'assets/depth/1.png']
|
| 224 |
+
thermal = ['assets/thermal/0.jpg', 'assets/thermal/1.jpg']
|
| 225 |
+
language = ["Training a parakeet to climb up a ladder.", 'A lion climbing a tree to catch a monkey.']
|
| 226 |
+
|
| 227 |
+
inputs = {
|
| 228 |
+
'image': to_device(modality_transform['image'](image), device),
|
| 229 |
+
'video': to_device(modality_transform['video'](video), device),
|
| 230 |
+
'audio': to_device(modality_transform['audio'](audio), device),
|
| 231 |
+
'depth': to_device(modality_transform['depth'](depth), device),
|
| 232 |
+
'thermal': to_device(modality_transform['thermal'](thermal), device),
|
| 233 |
+
}
|
| 234 |
+
inputs['language'] = to_device(tokenizer(language, max_length=77, padding='max_length',
|
| 235 |
+
truncation=True, return_tensors='pt'), device)
|
| 236 |
+
|
| 237 |
+
with torch.no_grad():
|
| 238 |
+
embeddings = model(inputs)
|
| 239 |
+
|
| 240 |
+
print("Video x Text: \n",
|
| 241 |
+
torch.softmax(embeddings['video'] @ embeddings['language'].T, dim=-1).detach().cpu().numpy())
|
| 242 |
+
print("Image x Text: \n",
|
| 243 |
+
torch.softmax(embeddings['image'] @ embeddings['language'].T, dim=-1).detach().cpu().numpy())
|
| 244 |
+
print("Depth x Text: \n",
|
| 245 |
+
torch.softmax(embeddings['depth'] @ embeddings['language'].T, dim=-1).detach().cpu().numpy())
|
| 246 |
+
print("Audio x Text: \n",
|
| 247 |
+
torch.softmax(embeddings['audio'] @ embeddings['language'].T, dim=-1).detach().cpu().numpy())
|
| 248 |
+
print("Thermal x Text: \n",
|
| 249 |
+
torch.softmax(embeddings['thermal'] @ embeddings['language'].T, dim=-1).detach().cpu().numpy())
|
| 250 |
+
```
|
| 251 |
+
Then returns the following result.
|
| 252 |
+
```bash
|
| 253 |
+
Video x Text:
|
| 254 |
+
[[9.9989331e-01 1.0667283e-04]
|
| 255 |
+
[1.3255903e-03 9.9867439e-01]]
|
| 256 |
+
Image x Text:
|
| 257 |
+
[[9.9990666e-01 9.3292067e-05]
|
| 258 |
+
[4.6132666e-08 1.0000000e+00]]
|
| 259 |
+
Depth x Text:
|
| 260 |
+
[[0.9954276 0.00457235]
|
| 261 |
+
[0.12042473 0.8795753 ]]
|
| 262 |
+
Audio x Text:
|
| 263 |
+
[[0.97634876 0.02365119]
|
| 264 |
+
[0.02917843 0.97082156]]
|
| 265 |
+
Thermal x Text:
|
| 266 |
+
[[0.9482511 0.0517489 ]
|
| 267 |
+
[0.48746133 0.5125386 ]]
|
| 268 |
+
```
|
| 269 |
+
### Emergency zero-shot
|
| 270 |
+
Since languagebind binds each modality together, we also found the **emergency zero-shot**. It's very simple to use.
|
| 271 |
+
```python
|
| 272 |
+
print("Video x Audio: \n", torch.softmax(embeddings['video'] @ embeddings['audio'].T, dim=-1).detach().cpu().numpy())
|
| 273 |
+
print("Image x Depth: \n", torch.softmax(embeddings['image'] @ embeddings['depth'].T, dim=-1).detach().cpu().numpy())
|
| 274 |
+
print("Image x Thermal: \n", torch.softmax(embeddings['image'] @ embeddings['thermal'].T, dim=-1).detach().cpu().numpy())
|
| 275 |
+
```
|
| 276 |
+
Then, you will get:
|
| 277 |
+
```
|
| 278 |
+
Video x Audio:
|
| 279 |
+
[[1.0000000e+00 0.0000000e+00]
|
| 280 |
+
[3.1150486e-32 1.0000000e+00]]
|
| 281 |
+
Image x Depth:
|
| 282 |
+
[[1. 0.]
|
| 283 |
+
[0. 1.]]
|
| 284 |
+
Image x Thermal:
|
| 285 |
+
[[1. 0.]
|
| 286 |
+
[0. 1.]]
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
### Different branches for X-Language task
|
| 290 |
+
Additionally, LanguageBind can be **disassembled into different branches** to handle different tasks. Note that we do not train Image, which just initialize from OpenCLIP.
|
| 291 |
+
#### Thermal
|
| 292 |
+
```python
|
| 293 |
+
import torch
|
| 294 |
+
from languagebind import LanguageBindThermal, LanguageBindThermalTokenizer, LanguageBindThermalProcessor
|
| 295 |
+
|
| 296 |
+
pretrained_ckpt = 'LanguageBind/LanguageBind_Thermal'
|
| 297 |
+
model = LanguageBindThermal.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 298 |
+
tokenizer = LanguageBindThermalTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 299 |
+
thermal_process = LanguageBindThermalProcessor(model.config, tokenizer)
|
| 300 |
+
|
| 301 |
+
model.eval()
|
| 302 |
+
data = thermal_process([r"your/thermal.jpg"], ['your text'], return_tensors='pt')
|
| 303 |
+
with torch.no_grad():
|
| 304 |
+
out = model(**data)
|
| 305 |
+
|
| 306 |
+
print(out.text_embeds @ out.image_embeds.T)
|
| 307 |
+
```
|
| 308 |
+
|
| 309 |
+
#### Depth
|
| 310 |
+
```python
|
| 311 |
+
import torch
|
| 312 |
+
from languagebind import LanguageBindDepth, LanguageBindDepthTokenizer, LanguageBindDepthProcessor
|
| 313 |
+
|
| 314 |
+
pretrained_ckpt = 'LanguageBind/LanguageBind_Depth'
|
| 315 |
+
model = LanguageBindDepth.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 316 |
+
tokenizer = LanguageBindDepthTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 317 |
+
depth_process = LanguageBindDepthProcessor(model.config, tokenizer)
|
| 318 |
+
|
| 319 |
+
model.eval()
|
| 320 |
+
data = depth_process([r"your/depth.png"], ['your text.'], return_tensors='pt')
|
| 321 |
+
with torch.no_grad():
|
| 322 |
+
out = model(**data)
|
| 323 |
+
|
| 324 |
+
print(out.text_embeds @ out.image_embeds.T)
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
#### Video
|
| 328 |
+
```python
|
| 329 |
+
import torch
|
| 330 |
+
from languagebind import LanguageBindVideo, LanguageBindVideoTokenizer, LanguageBindVideoProcessor
|
| 331 |
+
|
| 332 |
+
pretrained_ckpt = 'LanguageBind/LanguageBind_Video_FT' # also 'LanguageBind/LanguageBind_Video'
|
| 333 |
+
model = LanguageBindVideo.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 334 |
+
tokenizer = LanguageBindVideoTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 335 |
+
video_process = LanguageBindVideoProcessor(model.config, tokenizer)
|
| 336 |
+
|
| 337 |
+
model.eval()
|
| 338 |
+
data = video_process(["your/video.mp4"], ['your text.'], return_tensors='pt')
|
| 339 |
+
with torch.no_grad():
|
| 340 |
+
out = model(**data)
|
| 341 |
+
|
| 342 |
+
print(out.text_embeds @ out.image_embeds.T)
|
| 343 |
+
```
|
| 344 |
+
|
| 345 |
+
#### Audio
|
| 346 |
+
```python
|
| 347 |
+
import torch
|
| 348 |
+
from languagebind import LanguageBindAudio, LanguageBindAudioTokenizer, LanguageBindAudioProcessor
|
| 349 |
+
|
| 350 |
+
pretrained_ckpt = 'LanguageBind/LanguageBind_Audio_FT' # also 'LanguageBind/LanguageBind_Audio'
|
| 351 |
+
model = LanguageBindAudio.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 352 |
+
tokenizer = LanguageBindAudioTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 353 |
+
audio_process = LanguageBindAudioProcessor(model.config, tokenizer)
|
| 354 |
+
|
| 355 |
+
model.eval()
|
| 356 |
+
data = audio_process([r"your/audio.wav"], ['your audio.'], return_tensors='pt')
|
| 357 |
+
with torch.no_grad():
|
| 358 |
+
out = model(**data)
|
| 359 |
+
|
| 360 |
+
print(out.text_embeds @ out.image_embeds.T)
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
#### Image
|
| 364 |
+
Note that our image encoder is the same as OpenCLIP. **Not** as fine-tuned as other modalities.
|
| 365 |
+
```python
|
| 366 |
+
import torch
|
| 367 |
+
from languagebind import LanguageBindImage, LanguageBindImageTokenizer, LanguageBindImageProcessor
|
| 368 |
+
|
| 369 |
+
pretrained_ckpt = 'LanguageBind/LanguageBind_Image'
|
| 370 |
+
model = LanguageBindImage.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 371 |
+
tokenizer = LanguageBindImageTokenizer.from_pretrained(pretrained_ckpt, cache_dir='./cache_dir')
|
| 372 |
+
image_process = LanguageBindImageProcessor(model.config, tokenizer)
|
| 373 |
+
|
| 374 |
+
model.eval()
|
| 375 |
+
data = image_process([r"your/image.jpg"], ['your text.'], return_tensors='pt')
|
| 376 |
+
with torch.no_grad():
|
| 377 |
+
out = model(**data)
|
| 378 |
+
|
| 379 |
+
print(out.text_embeds @ out.image_embeds.T)
|
| 380 |
+
```
|
| 381 |
+
|
| 382 |
+
## 💥 VIDAL-10M
|
| 383 |
+
The datasets is in [DATASETS.md](DATASETS.md).
|
| 384 |
+
|
| 385 |
+
## 🗝️ Training & Validating
|
| 386 |
+
The training & validating instruction is in [TRAIN_AND_VALIDATE.md](TRAIN_AND_VALIDATE.md).
|
| 387 |
+
|
| 388 |
+
## 👍 Acknowledgement
|
| 389 |
+
* [OpenCLIP](https://github.com/mlfoundations/open_clip) An open source pretraining framework.
|
| 390 |
+
* [CLIP4Clip](https://github.com/ArrowLuo/CLIP4Clip) An open source Video-Text retrieval framework.
|
| 391 |
+
* [sRGB-TIR](https://github.com/rpmsnu/sRGB-TIR) An open source framework to generate infrared (thermal) images.
|
| 392 |
+
* [GLPN](https://github.com/vinvino02/GLPDepth) An open source framework to generate depth images.
|
| 393 |
+
|
| 394 |
+
## 🔒 License
|
| 395 |
+
* The majority of this project is released under the MIT license as found in the [LICENSE](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/LICENSE) file.
|
| 396 |
+
* The dataset of this project is released under the CC-BY-NC 4.0 license as found in the [DATASET_LICENSE](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/DATASET_LICENSE) file.
|
| 397 |
+
|
| 398 |
+
## ✏️ Citation
|
| 399 |
+
If you find our paper and code useful in your research, please consider giving a star :star: and citation :pencil:.
|
| 400 |
+
|
| 401 |
+
```BibTeX
|
| 402 |
+
@misc{zhu2023languagebind,
|
| 403 |
+
title={LanguageBind: Extending Video-Language Pretraining to N-modality by Language-based Semantic Alignment},
|
| 404 |
+
author={Bin Zhu and Bin Lin and Munan Ning and Yang Yan and Jiaxi Cui and Wang HongFa and Yatian Pang and Wenhao Jiang and Junwu Zhang and Zongwei Li and Cai Wan Zhang and Zhifeng Li and Wei Liu and Li Yuan},
|
| 405 |
+
year={2023},
|
| 406 |
+
eprint={2310.01852},
|
| 407 |
+
archivePrefix={arXiv},
|
| 408 |
+
primaryClass={cs.CV}
|
| 409 |
+
}
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
## ✨ Star History
|
| 414 |
+
|
| 415 |
+
[](https://star-history.com/#PKU-YuanGroup/LanguageBind&Date)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
## 🤝 Contributors
|
| 419 |
+
|
| 420 |
+
<a href="https://github.com/PKU-YuanGroup/LanguageBind/graphs/contributors">
|
| 421 |
+
<img src="https://contrib.rocks/image?repo=PKU-YuanGroup/LanguageBind" />
|
| 422 |
+
</a>
|
TRAIN_AND_VALIDATE.md
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
We provide the **off-the-shelf** scripts in the [scripts folder](scripts).
|
| 2 |
+
|
| 3 |
+
## Training LanguageBind
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
<div align="center">
|
| 7 |
+
<table border="1" width="100%">
|
| 8 |
+
<tr align="center">
|
| 9 |
+
<th>Cache of pretrained weight</th><th>Baidu Yun</th><th>Google Cloud</th><th>Peking University Yun</th>
|
| 10 |
+
</tr>
|
| 11 |
+
<tr align="center">
|
| 12 |
+
<td>Large</td><td><a href="https://pan.baidu.com/s/1co46bkuUJXr8ePPKp1WWgA?pwd=ofm6">Link</a></td><td><a href="https://drive.google.com/drive/folders/1VQYZlqfKmCMuHffypf5F96odyMCEI87H?usp=drive_link">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/9CA764E6307790B01D2D4F7E314E8E43">Link</a></td>
|
| 13 |
+
</tr>
|
| 14 |
+
<tr align="center">
|
| 15 |
+
<td>Huge</td><td><a href="https://pan.baidu.com/s/1QLpyXEYunoXS-oqGsvzKKA?pwd=vgo2">Link</a></td><td>-</td><td><a href="https://disk.pku.edu.cn:443/link/720A77A7DB9EFD167C5AC8E3FC4B6068">Link</a></td>
|
| 16 |
+
</tr>
|
| 17 |
+
</table>
|
| 18 |
+
</div>
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
For example, to **train** LanguageBind on **Depth-Language** with 8 GPUs (1 nodes x 8 GPUs).
|
| 22 |
+
* First download the cache of pretrained weight above. and specify `CACHE_DIR=path/to/LanguageBind`.
|
| 23 |
+
* The second step is to develop a path to `ANNOTATION` and `DATA` [here](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/base_datasets.py#L37) according to the [dataset preparation](https://github.com/PKU-YuanGroup/LanguageBind#-vidal-10m).
|
| 24 |
+
* Then you can run
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
CACHE_DIR="/path/to/LanguageBind"
|
| 28 |
+
ANNOTATION="path/to/data"
|
| 29 |
+
cd /path/to/LanguageBind
|
| 30 |
+
TORCH_DISTRIBUTED_DEBUG=DETAIL HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 torchrun --nnodes=1 --nproc_per_node 8 \
|
| 31 |
+
-m main \
|
| 32 |
+
--train-data ${ANNOTATION} \
|
| 33 |
+
--train-num-samples 3020000 \
|
| 34 |
+
--clip-type "dl" --max-depth 10 \
|
| 35 |
+
--do_train \
|
| 36 |
+
--lock-text --lock-image --text-type "polish_mplug" \
|
| 37 |
+
--init-temp 0.07 --learn-temp \
|
| 38 |
+
--model "ViT-L-14" --cache-dir ${CACHE_DIR} \
|
| 39 |
+
--convert_to_lora --lora_r 2 \
|
| 40 |
+
--lr 5e-4 --coef-lr 1e-3 \
|
| 41 |
+
--beta1 0.9 --beta2 0.98 --wd 0.2 --eps 1e-6 \
|
| 42 |
+
--num-frames 1 --force-patch-dropout 0.5 \
|
| 43 |
+
--epochs 1 --batch-size 128 --accum-freq 1 --warmup 200 \
|
| 44 |
+
--precision "amp" --workers 10 --video-decode-backend "imgs" \
|
| 45 |
+
--save-frequency 1 --log-every-n-steps 20 --report-to "tensorboard" --resume "latest" \
|
| 46 |
+
--do_eval \
|
| 47 |
+
--val_d_cls_data "NYUV2"
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
## Validating LanguageBind
|
| 52 |
+
|
| 53 |
+
For example, to **validate** LanguageBind on **Depth-Language** with 1 GPUs.
|
| 54 |
+
* First specify ```RESUME```.
|
| 55 |
+
* The second step is to prepare the [downstream dataset](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/TRAIN_AND_VALIDATE.md#downstream-datasets).
|
| 56 |
+
* Then you can run
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
CACHE_DIR="/path/to/LanguageBind"
|
| 60 |
+
RESUME="thermal_language.pt"
|
| 61 |
+
ANNOTATION="path/to/data"
|
| 62 |
+
cd /path/to/LanguageBind
|
| 63 |
+
TORCH_DISTRIBUTED_DEBUG=DETAIL HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 torchrun --nproc_per_node 1 \
|
| 64 |
+
-m main \
|
| 65 |
+
--train-data ${ANNOTATION} \
|
| 66 |
+
--train-num-samples 3020000 \
|
| 67 |
+
--clip-type "dl" --max-depth 10 \
|
| 68 |
+
--lock-text --lock-image --text-type "polish_mplug" \
|
| 69 |
+
--init-temp 0.07 --learn-temp \
|
| 70 |
+
--model "ViT-L-14" --cache-dir ${CACHE_DIR} \
|
| 71 |
+
--convert_to_lora --lora_r 2 \
|
| 72 |
+
--lr 5e-4 --coef-lr 1e-3 \
|
| 73 |
+
--beta1 0.9 --beta2 0.98 --wd 0.2 --eps 1e-6 \
|
| 74 |
+
--num-frames 1 --force-patch-dropout 0.5 \
|
| 75 |
+
--epochs 1 --batch-size 128 --accum-freq 1 --warmup 200 \
|
| 76 |
+
--precision "amp" --workers 10 --video-decode-backend "imgs" \
|
| 77 |
+
--save-frequency 1 --log-every-n-steps 20 --report-to "tensorboard" --resume ${RESUME} \
|
| 78 |
+
--do_eval \
|
| 79 |
+
--val_d_cls_data "NYUV2"
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Downstream datasets
|
| 83 |
+
|
| 84 |
+
### Depth
|
| 85 |
+
NYU V2 dataset is downloaded from [this repo](https://github.com/TUI-NICR/nicr-scene-analysis-datasets/tree/main/nicr_scene_analysis_datasets/datasets/nyuv2) and we reformat them to conform to the standard ImageNet format. We also provide data as follows. Change the ```data_root``` [here](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/build_datasets.py#L221).
|
| 86 |
+
|
| 87 |
+
<div align="center">
|
| 88 |
+
<table border="1" width="100%">
|
| 89 |
+
<tr align="center">
|
| 90 |
+
<th>Datasets</th><th>Baidu Yun</th><th>Google Cloud</th><th>Peking University Yun</th>
|
| 91 |
+
</tr>
|
| 92 |
+
<tr align="center">
|
| 93 |
+
<td>NYU</td><td><a href="https://pan.baidu.com/s/1AGOG8U3F7W8AvJiEmuzs-A?pwd=1dsg">Link</a></td><td><a href="https://drive.google.com/file/d/1CltzrTBLFqLxJzpztSIN-5ZosZpXQQ6u/view?usp=sharing">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/7D7B164DEA64059793D3C3E3A65C0F64">Link</a></td>
|
| 94 |
+
</tr>
|
| 95 |
+
</table>
|
| 96 |
+
</div>
|
| 97 |
+
|
| 98 |
+
### Video
|
| 99 |
+
Video datasets are downloaded from [this repo](https://github.com/jpthu17/HBI) and we show the folder structure. Change the ```data_root``` [here](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/build_datasets.py#L74).
|
| 100 |
+
|
| 101 |
+
### Audio
|
| 102 |
+
Audio datasets are downloaded from [this repo](https://github.com/OFA-Sys/ONE-PEACE/blob/main/datasets.md#audio) and Audioset from [here](https://github.com/qiuqiangkong/audioset_tagging_cnn#1-download-dataset).We reformat them to conform to the standard ImageNet format. Change the ```data_root``` [here1](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/build_datasets.py#L144) and [here2](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/build_datasets.py#L159).
|
| 103 |
+
|
| 104 |
+
### Infrared (Thermal)
|
| 105 |
+
We download LLVIP from [official website](https://bupt-ai-cz.github.io/LLVIP/), and FLIR from [here](https://www.flir.com/oem/adas/adas-dataset-form/). We reformat them to conform to the standard ImageNet format. Change the ```data_root``` [here](https://github.com/PKU-YuanGroup/LanguageBind/blob/main/data/build_datasets.py#L233). We also provide the processed data as follows.
|
| 106 |
+
|
| 107 |
+
<div align="center">
|
| 108 |
+
<table border="1" width="100%">
|
| 109 |
+
<tr align="center">
|
| 110 |
+
<th>Datasets</th><th>Baidu Yun</th><th>Google Cloud</th><th>Peking University Yun</th>
|
| 111 |
+
</tr>
|
| 112 |
+
<tr align="center">
|
| 113 |
+
<td>LLVIP</td><td><a href="https://pan.baidu.com/s/15HPVr016F7eO9005NDRJTg?pwd=46fh">Link</a></td><td><a href="https://drive.google.com/file/d/1RfKNR8q6dHiAHB4OlYecnkUSx-ghLuEO/view?usp=drive_link">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/30D592EA37AC7C411264801A74994376">Link</a></td>
|
| 114 |
+
</tr>
|
| 115 |
+
<tr align="center">
|
| 116 |
+
<td>FLIR V1</td><td><a href="https://pan.baidu.com/s/1ZDSo5VPxJ4SA7wS_rNk0uQ?pwd=l491">Link</a></td><td><a href="https://drive.google.com/file/d/1CezCLJ4GUfPMFimitPfK40OV2j2Kr8t8/view?usp=drive_link">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/AD89D6ADE2CAC2407B00650870CBBDEC">Link</a></td>
|
| 117 |
+
</tr>
|
| 118 |
+
<tr align="center">
|
| 119 |
+
<td>FLIR V2</td><td><a href="https://pan.baidu.com/s/16xdr2aQkHo3zJ4KbaTmO3Q?pwd=tj9f">Link</a></td><td><a href="https://drive.google.com/file/d/1Z2ThG5QH-9biFI2-Z8k2fBKSA6Nrees6/view?usp=drive_link">Link</a></td><td><a href="https://disk.pku.edu.cn:443/link/E06C010970B0ED51926700D2F7A21EA8">Link</a></td>
|
| 120 |
+
</tr>
|
| 121 |
+
</table>
|
| 122 |
+
</div>
|
| 123 |
+
|
| 124 |
+
### Folder structure
|
| 125 |
+
```bash
|
| 126 |
+
downstream_datasets
|
| 127 |
+
├── Audio
|
| 128 |
+
│ ├── audiocaps
|
| 129 |
+
│ │ └── audio
|
| 130 |
+
│ │ ├── test
|
| 131 |
+
│ │ ├── train
|
| 132 |
+
│ │ └── val
|
| 133 |
+
│ ├── audioset
|
| 134 |
+
│ │ ├── balanced_train_segments
|
| 135 |
+
│ │ ├── eval_segments
|
| 136 |
+
│ │ └── unbalanced_train_segments
|
| 137 |
+
│ │ ├── unbalanced_train_segments_part00
|
| 138 |
+
│ │ ├── unbalanced_train_segments_part01
|
| 139 |
+
│ │ ├── ...
|
| 140 |
+
│ │ └── unbalanced_train_segments_part40
|
| 141 |
+
│ ├── clotho
|
| 142 |
+
│ │ ├── CLOTHO_retrieval_dataset
|
| 143 |
+
│ │ └── evaluation
|
| 144 |
+
│ ├── esc50
|
| 145 |
+
│ │ └── test
|
| 146 |
+
│ │ ├── airplane
|
| 147 |
+
│ │ ├── breathing
|
| 148 |
+
│ │ ├── ...
|
| 149 |
+
│ │ └── wind
|
| 150 |
+
├── laionaudio
|
| 151 |
+
│ │ ├── audios
|
| 152 |
+
│ │ ├── freesound_no_overlap
|
| 153 |
+
│ │ └── jsons
|
| 154 |
+
├── vggsound
|
| 155 |
+
│ └── test
|
| 156 |
+
│ ├── air\ conditioning\ noise
|
| 157 |
+
│ ├── air\ horn
|
| 158 |
+
│ ├── ...
|
| 159 |
+
│ └── zebra\ braying
|
| 160 |
+
├── Depth
|
| 161 |
+
│ ├── nyuv2
|
| 162 |
+
│ │ ├── data
|
| 163 |
+
│ │ │ └── val
|
| 164 |
+
│ │ │ ├── bathroom
|
| 165 |
+
│ │ │ ├── bedroom
|
| 166 |
+
│ │ │ ├── bookstore
|
| 167 |
+
│ │ │ ├── classroom
|
| 168 |
+
│ │ │ ├── dining_room
|
| 169 |
+
│ │ │ ├── home_office
|
| 170 |
+
│ │ │ ├── kitchen
|
| 171 |
+
│ │ │ ├── living_room
|
| 172 |
+
│ │ │ ├── office
|
| 173 |
+
│ │ │ └── others
|
| 174 |
+
├── Thermal
|
| 175 |
+
│ ├── flirv1
|
| 176 |
+
│ │ └── val
|
| 177 |
+
│ │ ├── bicycle
|
| 178 |
+
│ │ ├── car
|
| 179 |
+
│ │ ├── dog
|
| 180 |
+
│ │ └── person
|
| 181 |
+
│ ├── flirv2
|
| 182 |
+
│ │ └── val
|
| 183 |
+
│ │ ├── bike
|
| 184 |
+
│ │ ├── bus
|
| 185 |
+
│ │ ├── car
|
| 186 |
+
│ │ ├── hydrant
|
| 187 |
+
│ │ ├── light
|
| 188 |
+
│ │ ├── motor
|
| 189 |
+
│ │ ├── other\ vehicle
|
| 190 |
+
│ │ ├── person
|
| 191 |
+
│ │ ├── sign
|
| 192 |
+
│ │ ├── skateboard
|
| 193 |
+
│ │ ├── stroller
|
| 194 |
+
│ │ └── truck
|
| 195 |
+
│ ├── llvip
|
| 196 |
+
│ │ ├── train
|
| 197 |
+
│ │ │ ├── background
|
| 198 |
+
│ │ │ └── person
|
| 199 |
+
│ │ └── val
|
| 200 |
+
│ │ ├── background
|
| 201 |
+
│ │ └── person
|
| 202 |
+
└── VideoTextRetrieval
|
| 203 |
+
├── vtRetdata
|
| 204 |
+
│ ├── ActivityNet
|
| 205 |
+
│ │ └── Videos
|
| 206 |
+
│ │ └── Activity_Videos
|
| 207 |
+
│ ├── Didemo
|
| 208 |
+
│ │ └── videos
|
| 209 |
+
│ ├── MSRVTT
|
| 210 |
+
│ │ └── MSRVTT_Videos
|
| 211 |
+
│ └── MSVD
|
| 212 |
+
│�� └── MSVD_Videos
|
| 213 |
+
```
|
| 214 |
+
|
a_cls/class_labels_indices.csv
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
index,mid,display_name
|
| 2 |
+
0,/m/09x0r,"Speech"
|
| 3 |
+
1,/m/05zppz,"Male speech, man speaking"
|
| 4 |
+
2,/m/02zsn,"Female speech, woman speaking"
|
| 5 |
+
3,/m/0ytgt,"Child speech, kid speaking"
|
| 6 |
+
4,/m/01h8n0,"Conversation"
|
| 7 |
+
5,/m/02qldy,"Narration, monologue"
|
| 8 |
+
6,/m/0261r1,"Babbling"
|
| 9 |
+
7,/m/0brhx,"Speech synthesizer"
|
| 10 |
+
8,/m/07p6fty,"Shout"
|
| 11 |
+
9,/m/07q4ntr,"Bellow"
|
| 12 |
+
10,/m/07rwj3x,"Whoop"
|
| 13 |
+
11,/m/07sr1lc,"Yell"
|
| 14 |
+
12,/m/04gy_2,"Battle cry"
|
| 15 |
+
13,/t/dd00135,"Children shouting"
|
| 16 |
+
14,/m/03qc9zr,"Screaming"
|
| 17 |
+
15,/m/02rtxlg,"Whispering"
|
| 18 |
+
16,/m/01j3sz,"Laughter"
|
| 19 |
+
17,/t/dd00001,"Baby laughter"
|
| 20 |
+
18,/m/07r660_,"Giggle"
|
| 21 |
+
19,/m/07s04w4,"Snicker"
|
| 22 |
+
20,/m/07sq110,"Belly laugh"
|
| 23 |
+
21,/m/07rgt08,"Chuckle, chortle"
|
| 24 |
+
22,/m/0463cq4,"Crying, sobbing"
|
| 25 |
+
23,/t/dd00002,"Baby cry, infant cry"
|
| 26 |
+
24,/m/07qz6j3,"Whimper"
|
| 27 |
+
25,/m/07qw_06,"Wail, moan"
|
| 28 |
+
26,/m/07plz5l,"Sigh"
|
| 29 |
+
27,/m/015lz1,"Singing"
|
| 30 |
+
28,/m/0l14jd,"Choir"
|
| 31 |
+
29,/m/01swy6,"Yodeling"
|
| 32 |
+
30,/m/02bk07,"Chant"
|
| 33 |
+
31,/m/01c194,"Mantra"
|
| 34 |
+
32,/t/dd00003,"Male singing"
|
| 35 |
+
33,/t/dd00004,"Female singing"
|
| 36 |
+
34,/t/dd00005,"Child singing"
|
| 37 |
+
35,/t/dd00006,"Synthetic singing"
|
| 38 |
+
36,/m/06bxc,"Rapping"
|
| 39 |
+
37,/m/02fxyj,"Humming"
|
| 40 |
+
38,/m/07s2xch,"Groan"
|
| 41 |
+
39,/m/07r4k75,"Grunt"
|
| 42 |
+
40,/m/01w250,"Whistling"
|
| 43 |
+
41,/m/0lyf6,"Breathing"
|
| 44 |
+
42,/m/07mzm6,"Wheeze"
|
| 45 |
+
43,/m/01d3sd,"Snoring"
|
| 46 |
+
44,/m/07s0dtb,"Gasp"
|
| 47 |
+
45,/m/07pyy8b,"Pant"
|
| 48 |
+
46,/m/07q0yl5,"Snort"
|
| 49 |
+
47,/m/01b_21,"Cough"
|
| 50 |
+
48,/m/0dl9sf8,"Throat clearing"
|
| 51 |
+
49,/m/01hsr_,"Sneeze"
|
| 52 |
+
50,/m/07ppn3j,"Sniff"
|
| 53 |
+
51,/m/06h7j,"Run"
|
| 54 |
+
52,/m/07qv_x_,"Shuffle"
|
| 55 |
+
53,/m/07pbtc8,"Walk, footsteps"
|
| 56 |
+
54,/m/03cczk,"Chewing, mastication"
|
| 57 |
+
55,/m/07pdhp0,"Biting"
|
| 58 |
+
56,/m/0939n_,"Gargling"
|
| 59 |
+
57,/m/01g90h,"Stomach rumble"
|
| 60 |
+
58,/m/03q5_w,"Burping, eructation"
|
| 61 |
+
59,/m/02p3nc,"Hiccup"
|
| 62 |
+
60,/m/02_nn,"Fart"
|
| 63 |
+
61,/m/0k65p,"Hands"
|
| 64 |
+
62,/m/025_jnm,"Finger snapping"
|
| 65 |
+
63,/m/0l15bq,"Clapping"
|
| 66 |
+
64,/m/01jg02,"Heart sounds, heartbeat"
|
| 67 |
+
65,/m/01jg1z,"Heart murmur"
|
| 68 |
+
66,/m/053hz1,"Cheering"
|
| 69 |
+
67,/m/028ght,"Applause"
|
| 70 |
+
68,/m/07rkbfh,"Chatter"
|
| 71 |
+
69,/m/03qtwd,"Crowd"
|
| 72 |
+
70,/m/07qfr4h,"Hubbub, speech noise, speech babble"
|
| 73 |
+
71,/t/dd00013,"Children playing"
|
| 74 |
+
72,/m/0jbk,"Animal"
|
| 75 |
+
73,/m/068hy,"Domestic animals, pets"
|
| 76 |
+
74,/m/0bt9lr,"Dog"
|
| 77 |
+
75,/m/05tny_,"Bark"
|
| 78 |
+
76,/m/07r_k2n,"Yip"
|
| 79 |
+
77,/m/07qf0zm,"Howl"
|
| 80 |
+
78,/m/07rc7d9,"Bow-wow"
|
| 81 |
+
79,/m/0ghcn6,"Growling"
|
| 82 |
+
80,/t/dd00136,"Whimper (dog)"
|
| 83 |
+
81,/m/01yrx,"Cat"
|
| 84 |
+
82,/m/02yds9,"Purr"
|
| 85 |
+
83,/m/07qrkrw,"Meow"
|
| 86 |
+
84,/m/07rjwbb,"Hiss"
|
| 87 |
+
85,/m/07r81j2,"Caterwaul"
|
| 88 |
+
86,/m/0ch8v,"Livestock, farm animals, working animals"
|
| 89 |
+
87,/m/03k3r,"Horse"
|
| 90 |
+
88,/m/07rv9rh,"Clip-clop"
|
| 91 |
+
89,/m/07q5rw0,"Neigh, whinny"
|
| 92 |
+
90,/m/01xq0k1,"Cattle, bovinae"
|
| 93 |
+
91,/m/07rpkh9,"Moo"
|
| 94 |
+
92,/m/0239kh,"Cowbell"
|
| 95 |
+
93,/m/068zj,"Pig"
|
| 96 |
+
94,/t/dd00018,"Oink"
|
| 97 |
+
95,/m/03fwl,"Goat"
|
| 98 |
+
96,/m/07q0h5t,"Bleat"
|
| 99 |
+
97,/m/07bgp,"Sheep"
|
| 100 |
+
98,/m/025rv6n,"Fowl"
|
| 101 |
+
99,/m/09b5t,"Chicken, rooster"
|
| 102 |
+
100,/m/07st89h,"Cluck"
|
| 103 |
+
101,/m/07qn5dc,"Crowing, cock-a-doodle-doo"
|
| 104 |
+
102,/m/01rd7k,"Turkey"
|
| 105 |
+
103,/m/07svc2k,"Gobble"
|
| 106 |
+
104,/m/09ddx,"Duck"
|
| 107 |
+
105,/m/07qdb04,"Quack"
|
| 108 |
+
106,/m/0dbvp,"Goose"
|
| 109 |
+
107,/m/07qwf61,"Honk"
|
| 110 |
+
108,/m/01280g,"Wild animals"
|
| 111 |
+
109,/m/0cdnk,"Roaring cats (lions, tigers)"
|
| 112 |
+
110,/m/04cvmfc,"Roar"
|
| 113 |
+
111,/m/015p6,"Bird"
|
| 114 |
+
112,/m/020bb7,"Bird vocalization, bird call, bird song"
|
| 115 |
+
113,/m/07pggtn,"Chirp, tweet"
|
| 116 |
+
114,/m/07sx8x_,"Squawk"
|
| 117 |
+
115,/m/0h0rv,"Pigeon, dove"
|
| 118 |
+
116,/m/07r_25d,"Coo"
|
| 119 |
+
117,/m/04s8yn,"Crow"
|
| 120 |
+
118,/m/07r5c2p,"Caw"
|
| 121 |
+
119,/m/09d5_,"Owl"
|
| 122 |
+
120,/m/07r_80w,"Hoot"
|
| 123 |
+
121,/m/05_wcq,"Bird flight, flapping wings"
|
| 124 |
+
122,/m/01z5f,"Canidae, dogs, wolves"
|
| 125 |
+
123,/m/06hps,"Rodents, rats, mice"
|
| 126 |
+
124,/m/04rmv,"Mouse"
|
| 127 |
+
125,/m/07r4gkf,"Patter"
|
| 128 |
+
126,/m/03vt0,"Insect"
|
| 129 |
+
127,/m/09xqv,"Cricket"
|
| 130 |
+
128,/m/09f96,"Mosquito"
|
| 131 |
+
129,/m/0h2mp,"Fly, housefly"
|
| 132 |
+
130,/m/07pjwq1,"Buzz"
|
| 133 |
+
131,/m/01h3n,"Bee, wasp, etc."
|
| 134 |
+
132,/m/09ld4,"Frog"
|
| 135 |
+
133,/m/07st88b,"Croak"
|
| 136 |
+
134,/m/078jl,"Snake"
|
| 137 |
+
135,/m/07qn4z3,"Rattle"
|
| 138 |
+
136,/m/032n05,"Whale vocalization"
|
| 139 |
+
137,/m/04rlf,"Music"
|
| 140 |
+
138,/m/04szw,"Musical instrument"
|
| 141 |
+
139,/m/0fx80y,"Plucked string instrument"
|
| 142 |
+
140,/m/0342h,"Guitar"
|
| 143 |
+
141,/m/02sgy,"Electric guitar"
|
| 144 |
+
142,/m/018vs,"Bass guitar"
|
| 145 |
+
143,/m/042v_gx,"Acoustic guitar"
|
| 146 |
+
144,/m/06w87,"Steel guitar, slide guitar"
|
| 147 |
+
145,/m/01glhc,"Tapping (guitar technique)"
|
| 148 |
+
146,/m/07s0s5r,"Strum"
|
| 149 |
+
147,/m/018j2,"Banjo"
|
| 150 |
+
148,/m/0jtg0,"Sitar"
|
| 151 |
+
149,/m/04rzd,"Mandolin"
|
| 152 |
+
150,/m/01bns_,"Zither"
|
| 153 |
+
151,/m/07xzm,"Ukulele"
|
| 154 |
+
152,/m/05148p4,"Keyboard (musical)"
|
| 155 |
+
153,/m/05r5c,"Piano"
|
| 156 |
+
154,/m/01s0ps,"Electric piano"
|
| 157 |
+
155,/m/013y1f,"Organ"
|
| 158 |
+
156,/m/03xq_f,"Electronic organ"
|
| 159 |
+
157,/m/03gvt,"Hammond organ"
|
| 160 |
+
158,/m/0l14qv,"Synthesizer"
|
| 161 |
+
159,/m/01v1d8,"Sampler"
|
| 162 |
+
160,/m/03q5t,"Harpsichord"
|
| 163 |
+
161,/m/0l14md,"Percussion"
|
| 164 |
+
162,/m/02hnl,"Drum kit"
|
| 165 |
+
163,/m/0cfdd,"Drum machine"
|
| 166 |
+
164,/m/026t6,"Drum"
|
| 167 |
+
165,/m/06rvn,"Snare drum"
|
| 168 |
+
166,/m/03t3fj,"Rimshot"
|
| 169 |
+
167,/m/02k_mr,"Drum roll"
|
| 170 |
+
168,/m/0bm02,"Bass drum"
|
| 171 |
+
169,/m/011k_j,"Timpani"
|
| 172 |
+
170,/m/01p970,"Tabla"
|
| 173 |
+
171,/m/01qbl,"Cymbal"
|
| 174 |
+
172,/m/03qtq,"Hi-hat"
|
| 175 |
+
173,/m/01sm1g,"Wood block"
|
| 176 |
+
174,/m/07brj,"Tambourine"
|
| 177 |
+
175,/m/05r5wn,"Rattle (instrument)"
|
| 178 |
+
176,/m/0xzly,"Maraca"
|
| 179 |
+
177,/m/0mbct,"Gong"
|
| 180 |
+
178,/m/016622,"Tubular bells"
|
| 181 |
+
179,/m/0j45pbj,"Mallet percussion"
|
| 182 |
+
180,/m/0dwsp,"Marimba, xylophone"
|
| 183 |
+
181,/m/0dwtp,"Glockenspiel"
|
| 184 |
+
182,/m/0dwt5,"Vibraphone"
|
| 185 |
+
183,/m/0l156b,"Steelpan"
|
| 186 |
+
184,/m/05pd6,"Orchestra"
|
| 187 |
+
185,/m/01kcd,"Brass instrument"
|
| 188 |
+
186,/m/0319l,"French horn"
|
| 189 |
+
187,/m/07gql,"Trumpet"
|
| 190 |
+
188,/m/07c6l,"Trombone"
|
| 191 |
+
189,/m/0l14_3,"Bowed string instrument"
|
| 192 |
+
190,/m/02qmj0d,"String section"
|
| 193 |
+
191,/m/07y_7,"Violin, fiddle"
|
| 194 |
+
192,/m/0d8_n,"Pizzicato"
|
| 195 |
+
193,/m/01xqw,"Cello"
|
| 196 |
+
194,/m/02fsn,"Double bass"
|
| 197 |
+
195,/m/085jw,"Wind instrument, woodwind instrument"
|
| 198 |
+
196,/m/0l14j_,"Flute"
|
| 199 |
+
197,/m/06ncr,"Saxophone"
|
| 200 |
+
198,/m/01wy6,"Clarinet"
|
| 201 |
+
199,/m/03m5k,"Harp"
|
| 202 |
+
200,/m/0395lw,"Bell"
|
| 203 |
+
201,/m/03w41f,"Church bell"
|
| 204 |
+
202,/m/027m70_,"Jingle bell"
|
| 205 |
+
203,/m/0gy1t2s,"Bicycle bell"
|
| 206 |
+
204,/m/07n_g,"Tuning fork"
|
| 207 |
+
205,/m/0f8s22,"Chime"
|
| 208 |
+
206,/m/026fgl,"Wind chime"
|
| 209 |
+
207,/m/0150b9,"Change ringing (campanology)"
|
| 210 |
+
208,/m/03qjg,"Harmonica"
|
| 211 |
+
209,/m/0mkg,"Accordion"
|
| 212 |
+
210,/m/0192l,"Bagpipes"
|
| 213 |
+
211,/m/02bxd,"Didgeridoo"
|
| 214 |
+
212,/m/0l14l2,"Shofar"
|
| 215 |
+
213,/m/07kc_,"Theremin"
|
| 216 |
+
214,/m/0l14t7,"Singing bowl"
|
| 217 |
+
215,/m/01hgjl,"Scratching (performance technique)"
|
| 218 |
+
216,/m/064t9,"Pop music"
|
| 219 |
+
217,/m/0glt670,"Hip hop music"
|
| 220 |
+
218,/m/02cz_7,"Beatboxing"
|
| 221 |
+
219,/m/06by7,"Rock music"
|
| 222 |
+
220,/m/03lty,"Heavy metal"
|
| 223 |
+
221,/m/05r6t,"Punk rock"
|
| 224 |
+
222,/m/0dls3,"Grunge"
|
| 225 |
+
223,/m/0dl5d,"Progressive rock"
|
| 226 |
+
224,/m/07sbbz2,"Rock and roll"
|
| 227 |
+
225,/m/05w3f,"Psychedelic rock"
|
| 228 |
+
226,/m/06j6l,"Rhythm and blues"
|
| 229 |
+
227,/m/0gywn,"Soul music"
|
| 230 |
+
228,/m/06cqb,"Reggae"
|
| 231 |
+
229,/m/01lyv,"Country"
|
| 232 |
+
230,/m/015y_n,"Swing music"
|
| 233 |
+
231,/m/0gg8l,"Bluegrass"
|
| 234 |
+
232,/m/02x8m,"Funk"
|
| 235 |
+
233,/m/02w4v,"Folk music"
|
| 236 |
+
234,/m/06j64v,"Middle Eastern music"
|
| 237 |
+
235,/m/03_d0,"Jazz"
|
| 238 |
+
236,/m/026z9,"Disco"
|
| 239 |
+
237,/m/0ggq0m,"Classical music"
|
| 240 |
+
238,/m/05lls,"Opera"
|
| 241 |
+
239,/m/02lkt,"Electronic music"
|
| 242 |
+
240,/m/03mb9,"House music"
|
| 243 |
+
241,/m/07gxw,"Techno"
|
| 244 |
+
242,/m/07s72n,"Dubstep"
|
| 245 |
+
243,/m/0283d,"Drum and bass"
|
| 246 |
+
244,/m/0m0jc,"Electronica"
|
| 247 |
+
245,/m/08cyft,"Electronic dance music"
|
| 248 |
+
246,/m/0fd3y,"Ambient music"
|
| 249 |
+
247,/m/07lnk,"Trance music"
|
| 250 |
+
248,/m/0g293,"Music of Latin America"
|
| 251 |
+
249,/m/0ln16,"Salsa music"
|
| 252 |
+
250,/m/0326g,"Flamenco"
|
| 253 |
+
251,/m/0155w,"Blues"
|
| 254 |
+
252,/m/05fw6t,"Music for children"
|
| 255 |
+
253,/m/02v2lh,"New-age music"
|
| 256 |
+
254,/m/0y4f8,"Vocal music"
|
| 257 |
+
255,/m/0z9c,"A capella"
|
| 258 |
+
256,/m/0164x2,"Music of Africa"
|
| 259 |
+
257,/m/0145m,"Afrobeat"
|
| 260 |
+
258,/m/02mscn,"Christian music"
|
| 261 |
+
259,/m/016cjb,"Gospel music"
|
| 262 |
+
260,/m/028sqc,"Music of Asia"
|
| 263 |
+
261,/m/015vgc,"Carnatic music"
|
| 264 |
+
262,/m/0dq0md,"Music of Bollywood"
|
| 265 |
+
263,/m/06rqw,"Ska"
|
| 266 |
+
264,/m/02p0sh1,"Traditional music"
|
| 267 |
+
265,/m/05rwpb,"Independent music"
|
| 268 |
+
266,/m/074ft,"Song"
|
| 269 |
+
267,/m/025td0t,"Background music"
|
| 270 |
+
268,/m/02cjck,"Theme music"
|
| 271 |
+
269,/m/03r5q_,"Jingle (music)"
|
| 272 |
+
270,/m/0l14gg,"Soundtrack music"
|
| 273 |
+
271,/m/07pkxdp,"Lullaby"
|
| 274 |
+
272,/m/01z7dr,"Video game music"
|
| 275 |
+
273,/m/0140xf,"Christmas music"
|
| 276 |
+
274,/m/0ggx5q,"Dance music"
|
| 277 |
+
275,/m/04wptg,"Wedding music"
|
| 278 |
+
276,/t/dd00031,"Happy music"
|
| 279 |
+
277,/t/dd00032,"Funny music"
|
| 280 |
+
278,/t/dd00033,"Sad music"
|
| 281 |
+
279,/t/dd00034,"Tender music"
|
| 282 |
+
280,/t/dd00035,"Exciting music"
|
| 283 |
+
281,/t/dd00036,"Angry music"
|
| 284 |
+
282,/t/dd00037,"Scary music"
|
| 285 |
+
283,/m/03m9d0z,"Wind"
|
| 286 |
+
284,/m/09t49,"Rustling leaves"
|
| 287 |
+
285,/t/dd00092,"Wind noise (microphone)"
|
| 288 |
+
286,/m/0jb2l,"Thunderstorm"
|
| 289 |
+
287,/m/0ngt1,"Thunder"
|
| 290 |
+
288,/m/0838f,"Water"
|
| 291 |
+
289,/m/06mb1,"Rain"
|
| 292 |
+
290,/m/07r10fb,"Raindrop"
|
| 293 |
+
291,/t/dd00038,"Rain on surface"
|
| 294 |
+
292,/m/0j6m2,"Stream"
|
| 295 |
+
293,/m/0j2kx,"Waterfall"
|
| 296 |
+
294,/m/05kq4,"Ocean"
|
| 297 |
+
295,/m/034srq,"Waves, surf"
|
| 298 |
+
296,/m/06wzb,"Steam"
|
| 299 |
+
297,/m/07swgks,"Gurgling"
|
| 300 |
+
298,/m/02_41,"Fire"
|
| 301 |
+
299,/m/07pzfmf,"Crackle"
|
| 302 |
+
300,/m/07yv9,"Vehicle"
|
| 303 |
+
301,/m/019jd,"Boat, Water vehicle"
|
| 304 |
+
302,/m/0hsrw,"Sailboat, sailing ship"
|
| 305 |
+
303,/m/056ks2,"Rowboat, canoe, kayak"
|
| 306 |
+
304,/m/02rlv9,"Motorboat, speedboat"
|
| 307 |
+
305,/m/06q74,"Ship"
|
| 308 |
+
306,/m/012f08,"Motor vehicle (road)"
|
| 309 |
+
307,/m/0k4j,"Car"
|
| 310 |
+
308,/m/0912c9,"Vehicle horn, car horn, honking"
|
| 311 |
+
309,/m/07qv_d5,"Toot"
|
| 312 |
+
310,/m/02mfyn,"Car alarm"
|
| 313 |
+
311,/m/04gxbd,"Power windows, electric windows"
|
| 314 |
+
312,/m/07rknqz,"Skidding"
|
| 315 |
+
313,/m/0h9mv,"Tire squeal"
|
| 316 |
+
314,/t/dd00134,"Car passing by"
|
| 317 |
+
315,/m/0ltv,"Race car, auto racing"
|
| 318 |
+
316,/m/07r04,"Truck"
|
| 319 |
+
317,/m/0gvgw0,"Air brake"
|
| 320 |
+
318,/m/05x_td,"Air horn, truck horn"
|
| 321 |
+
319,/m/02rhddq,"Reversing beeps"
|
| 322 |
+
320,/m/03cl9h,"Ice cream truck, ice cream van"
|
| 323 |
+
321,/m/01bjv,"Bus"
|
| 324 |
+
322,/m/03j1ly,"Emergency vehicle"
|
| 325 |
+
323,/m/04qvtq,"Police car (siren)"
|
| 326 |
+
324,/m/012n7d,"Ambulance (siren)"
|
| 327 |
+
325,/m/012ndj,"Fire engine, fire truck (siren)"
|
| 328 |
+
326,/m/04_sv,"Motorcycle"
|
| 329 |
+
327,/m/0btp2,"Traffic noise, roadway noise"
|
| 330 |
+
328,/m/06d_3,"Rail transport"
|
| 331 |
+
329,/m/07jdr,"Train"
|
| 332 |
+
330,/m/04zmvq,"Train whistle"
|
| 333 |
+
331,/m/0284vy3,"Train horn"
|
| 334 |
+
332,/m/01g50p,"Railroad car, train wagon"
|
| 335 |
+
333,/t/dd00048,"Train wheels squealing"
|
| 336 |
+
334,/m/0195fx,"Subway, metro, underground"
|
| 337 |
+
335,/m/0k5j,"Aircraft"
|
| 338 |
+
336,/m/014yck,"Aircraft engine"
|
| 339 |
+
337,/m/04229,"Jet engine"
|
| 340 |
+
338,/m/02l6bg,"Propeller, airscrew"
|
| 341 |
+
339,/m/09ct_,"Helicopter"
|
| 342 |
+
340,/m/0cmf2,"Fixed-wing aircraft, airplane"
|
| 343 |
+
341,/m/0199g,"Bicycle"
|
| 344 |
+
342,/m/06_fw,"Skateboard"
|
| 345 |
+
343,/m/02mk9,"Engine"
|
| 346 |
+
344,/t/dd00065,"Light engine (high frequency)"
|
| 347 |
+
345,/m/08j51y,"Dental drill, dentist's drill"
|
| 348 |
+
346,/m/01yg9g,"Lawn mower"
|
| 349 |
+
347,/m/01j4z9,"Chainsaw"
|
| 350 |
+
348,/t/dd00066,"Medium engine (mid frequency)"
|
| 351 |
+
349,/t/dd00067,"Heavy engine (low frequency)"
|
| 352 |
+
350,/m/01h82_,"Engine knocking"
|
| 353 |
+
351,/t/dd00130,"Engine starting"
|
| 354 |
+
352,/m/07pb8fc,"Idling"
|
| 355 |
+
353,/m/07q2z82,"Accelerating, revving, vroom"
|
| 356 |
+
354,/m/02dgv,"Door"
|
| 357 |
+
355,/m/03wwcy,"Doorbell"
|
| 358 |
+
356,/m/07r67yg,"Ding-dong"
|
| 359 |
+
357,/m/02y_763,"Sliding door"
|
| 360 |
+
358,/m/07rjzl8,"Slam"
|
| 361 |
+
359,/m/07r4wb8,"Knock"
|
| 362 |
+
360,/m/07qcpgn,"Tap"
|
| 363 |
+
361,/m/07q6cd_,"Squeak"
|
| 364 |
+
362,/m/0642b4,"Cupboard open or close"
|
| 365 |
+
363,/m/0fqfqc,"Drawer open or close"
|
| 366 |
+
364,/m/04brg2,"Dishes, pots, and pans"
|
| 367 |
+
365,/m/023pjk,"Cutlery, silverware"
|
| 368 |
+
366,/m/07pn_8q,"Chopping (food)"
|
| 369 |
+
367,/m/0dxrf,"Frying (food)"
|
| 370 |
+
368,/m/0fx9l,"Microwave oven"
|
| 371 |
+
369,/m/02pjr4,"Blender"
|
| 372 |
+
370,/m/02jz0l,"Water tap, faucet"
|
| 373 |
+
371,/m/0130jx,"Sink (filling or washing)"
|
| 374 |
+
372,/m/03dnzn,"Bathtub (filling or washing)"
|
| 375 |
+
373,/m/03wvsk,"Hair dryer"
|
| 376 |
+
374,/m/01jt3m,"Toilet flush"
|
| 377 |
+
375,/m/012xff,"Toothbrush"
|
| 378 |
+
376,/m/04fgwm,"Electric toothbrush"
|
| 379 |
+
377,/m/0d31p,"Vacuum cleaner"
|
| 380 |
+
378,/m/01s0vc,"Zipper (clothing)"
|
| 381 |
+
379,/m/03v3yw,"Keys jangling"
|
| 382 |
+
380,/m/0242l,"Coin (dropping)"
|
| 383 |
+
381,/m/01lsmm,"Scissors"
|
| 384 |
+
382,/m/02g901,"Electric shaver, electric razor"
|
| 385 |
+
383,/m/05rj2,"Shuffling cards"
|
| 386 |
+
384,/m/0316dw,"Typing"
|
| 387 |
+
385,/m/0c2wf,"Typewriter"
|
| 388 |
+
386,/m/01m2v,"Computer keyboard"
|
| 389 |
+
387,/m/081rb,"Writing"
|
| 390 |
+
388,/m/07pp_mv,"Alarm"
|
| 391 |
+
389,/m/07cx4,"Telephone"
|
| 392 |
+
390,/m/07pp8cl,"Telephone bell ringing"
|
| 393 |
+
391,/m/01hnzm,"Ringtone"
|
| 394 |
+
392,/m/02c8p,"Telephone dialing, DTMF"
|
| 395 |
+
393,/m/015jpf,"Dial tone"
|
| 396 |
+
394,/m/01z47d,"Busy signal"
|
| 397 |
+
395,/m/046dlr,"Alarm clock"
|
| 398 |
+
396,/m/03kmc9,"Siren"
|
| 399 |
+
397,/m/0dgbq,"Civil defense siren"
|
| 400 |
+
398,/m/030rvx,"Buzzer"
|
| 401 |
+
399,/m/01y3hg,"Smoke detector, smoke alarm"
|
| 402 |
+
400,/m/0c3f7m,"Fire alarm"
|
| 403 |
+
401,/m/04fq5q,"Foghorn"
|
| 404 |
+
402,/m/0l156k,"Whistle"
|
| 405 |
+
403,/m/06hck5,"Steam whistle"
|
| 406 |
+
404,/t/dd00077,"Mechanisms"
|
| 407 |
+
405,/m/02bm9n,"Ratchet, pawl"
|
| 408 |
+
406,/m/01x3z,"Clock"
|
| 409 |
+
407,/m/07qjznt,"Tick"
|
| 410 |
+
408,/m/07qjznl,"Tick-tock"
|
| 411 |
+
409,/m/0l7xg,"Gears"
|
| 412 |
+
410,/m/05zc1,"Pulleys"
|
| 413 |
+
411,/m/0llzx,"Sewing machine"
|
| 414 |
+
412,/m/02x984l,"Mechanical fan"
|
| 415 |
+
413,/m/025wky1,"Air conditioning"
|
| 416 |
+
414,/m/024dl,"Cash register"
|
| 417 |
+
415,/m/01m4t,"Printer"
|
| 418 |
+
416,/m/0dv5r,"Camera"
|
| 419 |
+
417,/m/07bjf,"Single-lens reflex camera"
|
| 420 |
+
418,/m/07k1x,"Tools"
|
| 421 |
+
419,/m/03l9g,"Hammer"
|
| 422 |
+
420,/m/03p19w,"Jackhammer"
|
| 423 |
+
421,/m/01b82r,"Sawing"
|
| 424 |
+
422,/m/02p01q,"Filing (rasp)"
|
| 425 |
+
423,/m/023vsd,"Sanding"
|
| 426 |
+
424,/m/0_ksk,"Power tool"
|
| 427 |
+
425,/m/01d380,"Drill"
|
| 428 |
+
426,/m/014zdl,"Explosion"
|
| 429 |
+
427,/m/032s66,"Gunshot, gunfire"
|
| 430 |
+
428,/m/04zjc,"Machine gun"
|
| 431 |
+
429,/m/02z32qm,"Fusillade"
|
| 432 |
+
430,/m/0_1c,"Artillery fire"
|
| 433 |
+
431,/m/073cg4,"Cap gun"
|
| 434 |
+
432,/m/0g6b5,"Fireworks"
|
| 435 |
+
433,/g/122z_qxw,"Firecracker"
|
| 436 |
+
434,/m/07qsvvw,"Burst, pop"
|
| 437 |
+
435,/m/07pxg6y,"Eruption"
|
| 438 |
+
436,/m/07qqyl4,"Boom"
|
| 439 |
+
437,/m/083vt,"Wood"
|
| 440 |
+
438,/m/07pczhz,"Chop"
|
| 441 |
+
439,/m/07pl1bw,"Splinter"
|
| 442 |
+
440,/m/07qs1cx,"Crack"
|
| 443 |
+
441,/m/039jq,"Glass"
|
| 444 |
+
442,/m/07q7njn,"Chink, clink"
|
| 445 |
+
443,/m/07rn7sz,"Shatter"
|
| 446 |
+
444,/m/04k94,"Liquid"
|
| 447 |
+
445,/m/07rrlb6,"Splash, splatter"
|
| 448 |
+
446,/m/07p6mqd,"Slosh"
|
| 449 |
+
447,/m/07qlwh6,"Squish"
|
| 450 |
+
448,/m/07r5v4s,"Drip"
|
| 451 |
+
449,/m/07prgkl,"Pour"
|
| 452 |
+
450,/m/07pqc89,"Trickle, dribble"
|
| 453 |
+
451,/t/dd00088,"Gush"
|
| 454 |
+
452,/m/07p7b8y,"Fill (with liquid)"
|
| 455 |
+
453,/m/07qlf79,"Spray"
|
| 456 |
+
454,/m/07ptzwd,"Pump (liquid)"
|
| 457 |
+
455,/m/07ptfmf,"Stir"
|
| 458 |
+
456,/m/0dv3j,"Boiling"
|
| 459 |
+
457,/m/0790c,"Sonar"
|
| 460 |
+
458,/m/0dl83,"Arrow"
|
| 461 |
+
459,/m/07rqsjt,"Whoosh, swoosh, swish"
|
| 462 |
+
460,/m/07qnq_y,"Thump, thud"
|
| 463 |
+
461,/m/07rrh0c,"Thunk"
|
| 464 |
+
462,/m/0b_fwt,"Electronic tuner"
|
| 465 |
+
463,/m/02rr_,"Effects unit"
|
| 466 |
+
464,/m/07m2kt,"Chorus effect"
|
| 467 |
+
465,/m/018w8,"Basketball bounce"
|
| 468 |
+
466,/m/07pws3f,"Bang"
|
| 469 |
+
467,/m/07ryjzk,"Slap, smack"
|
| 470 |
+
468,/m/07rdhzs,"Whack, thwack"
|
| 471 |
+
469,/m/07pjjrj,"Smash, crash"
|
| 472 |
+
470,/m/07pc8lb,"Breaking"
|
| 473 |
+
471,/m/07pqn27,"Bouncing"
|
| 474 |
+
472,/m/07rbp7_,"Whip"
|
| 475 |
+
473,/m/07pyf11,"Flap"
|
| 476 |
+
474,/m/07qb_dv,"Scratch"
|
| 477 |
+
475,/m/07qv4k0,"Scrape"
|
| 478 |
+
476,/m/07pdjhy,"Rub"
|
| 479 |
+
477,/m/07s8j8t,"Roll"
|
| 480 |
+
478,/m/07plct2,"Crushing"
|
| 481 |
+
479,/t/dd00112,"Crumpling, crinkling"
|
| 482 |
+
480,/m/07qcx4z,"Tearing"
|
| 483 |
+
481,/m/02fs_r,"Beep, bleep"
|
| 484 |
+
482,/m/07qwdck,"Ping"
|
| 485 |
+
483,/m/07phxs1,"Ding"
|
| 486 |
+
484,/m/07rv4dm,"Clang"
|
| 487 |
+
485,/m/07s02z0,"Squeal"
|
| 488 |
+
486,/m/07qh7jl,"Creak"
|
| 489 |
+
487,/m/07qwyj0,"Rustle"
|
| 490 |
+
488,/m/07s34ls,"Whir"
|
| 491 |
+
489,/m/07qmpdm,"Clatter"
|
| 492 |
+
490,/m/07p9k1k,"Sizzle"
|
| 493 |
+
491,/m/07qc9xj,"Clicking"
|
| 494 |
+
492,/m/07rwm0c,"Clickety-clack"
|
| 495 |
+
493,/m/07phhsh,"Rumble"
|
| 496 |
+
494,/m/07qyrcz,"Plop"
|
| 497 |
+
495,/m/07qfgpx,"Jingle, tinkle"
|
| 498 |
+
496,/m/07rcgpl,"Hum"
|
| 499 |
+
497,/m/07p78v5,"Zing"
|
| 500 |
+
498,/t/dd00121,"Boing"
|
| 501 |
+
499,/m/07s12q4,"Crunch"
|
| 502 |
+
500,/m/028v0c,"Silence"
|
| 503 |
+
501,/m/01v_m0,"Sine wave"
|
| 504 |
+
502,/m/0b9m1,"Harmonic"
|
| 505 |
+
503,/m/0hdsk,"Chirp tone"
|
| 506 |
+
504,/m/0c1dj,"Sound effect"
|
| 507 |
+
505,/m/07pt_g0,"Pulse"
|
| 508 |
+
506,/t/dd00125,"Inside, small room"
|
| 509 |
+
507,/t/dd00126,"Inside, large room or hall"
|
| 510 |
+
508,/t/dd00127,"Inside, public space"
|
| 511 |
+
509,/t/dd00128,"Outside, urban or manmade"
|
| 512 |
+
510,/t/dd00129,"Outside, rural or natural"
|
| 513 |
+
511,/m/01b9nn,"Reverberation"
|
| 514 |
+
512,/m/01jnbd,"Echo"
|
| 515 |
+
513,/m/096m7z,"Noise"
|
| 516 |
+
514,/m/06_y0by,"Environmental noise"
|
| 517 |
+
515,/m/07rgkc5,"Static"
|
| 518 |
+
516,/m/06xkwv,"Mains hum"
|
| 519 |
+
517,/m/0g12c5,"Distortion"
|
| 520 |
+
518,/m/08p9q4,"Sidetone"
|
| 521 |
+
519,/m/07szfh9,"Cacophony"
|
| 522 |
+
520,/m/0chx_,"White noise"
|
| 523 |
+
521,/m/0cj0r,"Pink noise"
|
| 524 |
+
522,/m/07p_0gm,"Throbbing"
|
| 525 |
+
523,/m/01jwx6,"Vibration"
|
| 526 |
+
524,/m/07c52,"Television"
|
| 527 |
+
525,/m/06bz3,"Radio"
|
| 528 |
+
526,/m/07hvw1,"Field recording"
|
a_cls/dataloader.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# @Time : 6/19/21 12:23 AM
|
| 3 |
+
# @Author : Yuan Gong
|
| 4 |
+
# @Affiliation : Massachusetts Institute of Technology
|
| 5 |
+
# @Email : yuangong@mit.edu
|
| 6 |
+
# @File : dataloader.py
|
| 7 |
+
|
| 8 |
+
# modified from:
|
| 9 |
+
# Author: David Harwath
|
| 10 |
+
# with some functions borrowed from https://github.com/SeanNaren/deepspeech.pytorch
|
| 11 |
+
|
| 12 |
+
import csv
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
import torchaudio
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn.functional
|
| 20 |
+
from torch.utils.data import Dataset
|
| 21 |
+
import random
|
| 22 |
+
|
| 23 |
+
def make_midname_dict(label_csv):
|
| 24 |
+
index_lookup = {}
|
| 25 |
+
with open(label_csv, 'r') as f:
|
| 26 |
+
csv_reader = csv.DictReader(f)
|
| 27 |
+
line_count = 0
|
| 28 |
+
for row in csv_reader:
|
| 29 |
+
index_lookup[row['mid']] = row['display_name']
|
| 30 |
+
line_count += 1
|
| 31 |
+
return index_lookup
|
| 32 |
+
|
| 33 |
+
def make_index_dict(label_csv):
|
| 34 |
+
index_lookup = {}
|
| 35 |
+
with open(label_csv, 'r') as f:
|
| 36 |
+
csv_reader = csv.DictReader(f)
|
| 37 |
+
line_count = 0
|
| 38 |
+
for row in csv_reader:
|
| 39 |
+
index_lookup[row['mid']] = row['index']
|
| 40 |
+
line_count += 1
|
| 41 |
+
return index_lookup
|
| 42 |
+
|
| 43 |
+
def make_name_dict(label_csv):
|
| 44 |
+
name_lookup = {}
|
| 45 |
+
with open(label_csv, 'r') as f:
|
| 46 |
+
csv_reader = csv.DictReader(f)
|
| 47 |
+
line_count = 0
|
| 48 |
+
for row in csv_reader:
|
| 49 |
+
name_lookup[row['index']] = row['display_name']
|
| 50 |
+
line_count += 1
|
| 51 |
+
return name_lookup
|
| 52 |
+
|
| 53 |
+
def lookup_list(index_list, label_csv):
|
| 54 |
+
label_list = []
|
| 55 |
+
table = make_name_dict(label_csv)
|
| 56 |
+
for item in index_list:
|
| 57 |
+
label_list.append(table[item])
|
| 58 |
+
return label_list
|
| 59 |
+
|
| 60 |
+
def preemphasis(signal,coeff=0.97):
|
| 61 |
+
"""perform preemphasis on the input signal.
|
| 62 |
+
|
| 63 |
+
:param signal: The signal to filter.
|
| 64 |
+
:param coeff: The preemphasis coefficient. 0 is none, default 0.97.
|
| 65 |
+
:returns: the filtered signal.
|
| 66 |
+
"""
|
| 67 |
+
return np.append(signal[0],signal[1:]-coeff*signal[:-1])
|
| 68 |
+
|
| 69 |
+
class AudiosetDataset(Dataset):
|
| 70 |
+
def __init__(self, dataset_json_file, audio_conf, label_csv=None):
|
| 71 |
+
"""
|
| 72 |
+
Dataset that manages audio recordings
|
| 73 |
+
:param audio_conf: Dictionary containing the audio loading and preprocessing settings
|
| 74 |
+
:param dataset_json_file
|
| 75 |
+
"""
|
| 76 |
+
self.datapath = dataset_json_file
|
| 77 |
+
with open(dataset_json_file, 'r') as fp:
|
| 78 |
+
data_json = json.load(fp)
|
| 79 |
+
self.data = data_json['data']
|
| 80 |
+
self.index_dict = make_index_dict(label_csv)
|
| 81 |
+
self.label_num = len(self.index_dict)
|
| 82 |
+
|
| 83 |
+
def __getitem__(self, index):
|
| 84 |
+
datum = self.data[index]
|
| 85 |
+
label_indices = np.zeros(self.label_num)
|
| 86 |
+
try:
|
| 87 |
+
fbank, mix_lambda = self._wav2fbank(datum['wav'])
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logging.warning(f"Error at {datum['wav']} with \"{e}\"")
|
| 90 |
+
return self.__getitem__(random.randint(0, self.__len__()-1))
|
| 91 |
+
for label_str in datum['labels'].split(','):
|
| 92 |
+
label_indices[int(self.index_dict[label_str])] = 1.0
|
| 93 |
+
|
| 94 |
+
label_indices = torch.FloatTensor(label_indices)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
return fbank, label_indices
|
| 98 |
+
|
| 99 |
+
def __len__(self):
|
| 100 |
+
return len(self.data)
|
a_cls/datasets.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os.path
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from data.build_datasets import DataInfo
|
| 6 |
+
from data.process_audio import get_audio_transform, torchaudio_loader
|
| 7 |
+
from torchvision import datasets
|
| 8 |
+
|
| 9 |
+
# -*- coding: utf-8 -*-
|
| 10 |
+
# @Time : 6/19/21 12:23 AM
|
| 11 |
+
# @Author : Yuan Gong
|
| 12 |
+
# @Affiliation : Massachusetts Institute of Technology
|
| 13 |
+
# @Email : yuangong@mit.edu
|
| 14 |
+
# @File : dataloader.py
|
| 15 |
+
|
| 16 |
+
# modified from:
|
| 17 |
+
# Author: David Harwath
|
| 18 |
+
# with some functions borrowed from https://github.com/SeanNaren/deepspeech.pytorch
|
| 19 |
+
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
|
| 24 |
+
import torchaudio
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn.functional
|
| 28 |
+
from torch.utils.data import Dataset
|
| 29 |
+
import random
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def make_index_dict(label_csv):
|
| 33 |
+
index_lookup = {}
|
| 34 |
+
with open(label_csv, 'r') as f:
|
| 35 |
+
csv_reader = csv.DictReader(f)
|
| 36 |
+
line_count = 0
|
| 37 |
+
for row in csv_reader:
|
| 38 |
+
index_lookup[row['mid']] = row['index']
|
| 39 |
+
line_count += 1
|
| 40 |
+
return index_lookup
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AudiosetDataset(Dataset):
|
| 44 |
+
def __init__(self, args, transform, loader):
|
| 45 |
+
self.audio_root = '/apdcephfs_cq3/share_1311970/downstream_datasets/Audio/audioset/eval_segments'
|
| 46 |
+
dataset_json_file = '/apdcephfs_cq3/share_1311970/downstream_datasets/Audio/audioset/filter_eval.json'
|
| 47 |
+
label_csv = '/apdcephfs_cq3/share_1311970/downstream_datasets/Audio/audioset/class_labels_indices.csv'
|
| 48 |
+
with open(dataset_json_file, 'r') as fp:
|
| 49 |
+
data_json = json.load(fp)
|
| 50 |
+
self.data = data_json['data']
|
| 51 |
+
self.index_dict = make_index_dict(label_csv)
|
| 52 |
+
self.label_num = len(self.index_dict)
|
| 53 |
+
|
| 54 |
+
self.args = args
|
| 55 |
+
self.transform = transform
|
| 56 |
+
self.loader = loader
|
| 57 |
+
|
| 58 |
+
def __getitem__(self, index):
|
| 59 |
+
datum = self.data[index]
|
| 60 |
+
label_indices = np.zeros(self.label_num)
|
| 61 |
+
for label_str in datum['labels'].split(','):
|
| 62 |
+
label_indices[int(self.index_dict[label_str])] = 1.0
|
| 63 |
+
label_indices = torch.FloatTensor(label_indices)
|
| 64 |
+
|
| 65 |
+
audio = self.loader(os.path.join(self.audio_root, datum['wav']))
|
| 66 |
+
audio_data = self.transform(audio)
|
| 67 |
+
return audio_data, label_indices
|
| 68 |
+
|
| 69 |
+
def __len__(self):
|
| 70 |
+
return len(self.data)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def is_valid_file(path):
|
| 75 |
+
return True
|
| 76 |
+
|
| 77 |
+
def get_audio_dataset(args):
|
| 78 |
+
data_path = args.audio_data_path
|
| 79 |
+
transform = get_audio_transform(args)
|
| 80 |
+
|
| 81 |
+
if args.val_a_cls_data.lower() == 'audioset':
|
| 82 |
+
dataset = AudiosetDataset(args, transform=transform, loader=torchaudio_loader)
|
| 83 |
+
else:
|
| 84 |
+
dataset = datasets.ImageFolder(data_path, transform=transform, loader=torchaudio_loader, is_valid_file=is_valid_file)
|
| 85 |
+
|
| 86 |
+
dataloader = torch.utils.data.DataLoader(
|
| 87 |
+
dataset,
|
| 88 |
+
batch_size=args.batch_size,
|
| 89 |
+
num_workers=args.workers,
|
| 90 |
+
sampler=None,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
return DataInfo(dataloader=dataloader, sampler=None)
|
a_cls/filter_eval_audio.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os.path
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
|
| 5 |
+
with open(r"G:\audioset\audioset\zip_audios\16k\eval.json", 'r') as f:
|
| 6 |
+
data = json.load(f)['data']
|
| 7 |
+
|
| 8 |
+
new_data = []
|
| 9 |
+
total = 0
|
| 10 |
+
success = 0
|
| 11 |
+
for i in tqdm(data):
|
| 12 |
+
total += 1
|
| 13 |
+
video_id = os.path.basename(i['wav'])
|
| 14 |
+
new_video_id = 'Y' + video_id
|
| 15 |
+
i['wav'] = new_video_id
|
| 16 |
+
if os.path.exists(f"G:/audioset/audioset/zip_audios/eval_segments/{i['wav']}") and not video_id.startswith('mW3S0u8bj58'):
|
| 17 |
+
new_data.append(i)
|
| 18 |
+
success += 1
|
| 19 |
+
print(total, success, total-success)
|
| 20 |
+
with open(r"G:\audioset\audioset\zip_audios\16k\filter_eval.json", 'w') as f:
|
| 21 |
+
data = json.dump({'data': new_data}, f, indent=2)
|
a_cls/precision.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from contextlib import suppress
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_autocast(precision):
|
| 6 |
+
if precision == 'amp':
|
| 7 |
+
return torch.cuda.amp.autocast
|
| 8 |
+
elif precision == 'amp_bfloat16' or precision == 'amp_bf16':
|
| 9 |
+
# amp_bfloat16 is more stable than amp float16 for clip training
|
| 10 |
+
return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16)
|
| 11 |
+
else:
|
| 12 |
+
return suppress
|
a_cls/stats.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy import stats
|
| 3 |
+
from sklearn import metrics
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
def d_prime(auc):
|
| 7 |
+
standard_normal = stats.norm()
|
| 8 |
+
d_prime = standard_normal.ppf(auc) * np.sqrt(2.0)
|
| 9 |
+
return d_prime
|
| 10 |
+
|
| 11 |
+
def calculate_stats(output, target):
|
| 12 |
+
"""Calculate statistics including mAP, AUC, etc.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
output: 2d array, (samples_num, classes_num)
|
| 16 |
+
target: 2d array, (samples_num, classes_num)
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
stats: list of statistic of each class.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
classes_num = target.shape[-1]
|
| 23 |
+
stats = []
|
| 24 |
+
|
| 25 |
+
# Accuracy, only used for single-label classification such as esc-50, not for multiple label one such as AudioSet
|
| 26 |
+
acc = metrics.accuracy_score(np.argmax(target, 1), np.argmax(output, 1))
|
| 27 |
+
|
| 28 |
+
# Class-wise statistics
|
| 29 |
+
for k in range(classes_num):
|
| 30 |
+
|
| 31 |
+
# Average precision
|
| 32 |
+
avg_precision = metrics.average_precision_score(
|
| 33 |
+
target[:, k], output[:, k], average=None)
|
| 34 |
+
|
| 35 |
+
# AUC
|
| 36 |
+
auc = metrics.roc_auc_score(target[:, k], output[:, k], average=None)
|
| 37 |
+
|
| 38 |
+
# Precisions, recalls
|
| 39 |
+
(precisions, recalls, thresholds) = metrics.precision_recall_curve(
|
| 40 |
+
target[:, k], output[:, k])
|
| 41 |
+
|
| 42 |
+
# FPR, TPR
|
| 43 |
+
(fpr, tpr, thresholds) = metrics.roc_curve(target[:, k], output[:, k])
|
| 44 |
+
|
| 45 |
+
save_every_steps = 1000 # Sample statistics to reduce size
|
| 46 |
+
dict = {'precisions': precisions[0::save_every_steps],
|
| 47 |
+
'recalls': recalls[0::save_every_steps],
|
| 48 |
+
'AP': avg_precision,
|
| 49 |
+
'fpr': fpr[0::save_every_steps],
|
| 50 |
+
'fnr': 1. - tpr[0::save_every_steps],
|
| 51 |
+
'auc': auc,
|
| 52 |
+
# note acc is not class-wise, this is just to keep consistent with other metrics
|
| 53 |
+
'acc': acc
|
| 54 |
+
}
|
| 55 |
+
stats.append(dict)
|
| 56 |
+
|
| 57 |
+
return stats
|
a_cls/util.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import pickle
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import random
|
| 7 |
+
from collections import namedtuple
|
| 8 |
+
|
| 9 |
+
def calc_recalls(S):
|
| 10 |
+
"""
|
| 11 |
+
Computes recall at 1, 5, and 10 given a similarity matrix S.
|
| 12 |
+
By convention, rows of S are assumed to correspond to images and columns are captions.
|
| 13 |
+
"""
|
| 14 |
+
assert(S.dim() == 2)
|
| 15 |
+
assert(S.size(0) == S.size(1))
|
| 16 |
+
if isinstance(S, torch.autograd.Variable):
|
| 17 |
+
S = S.data
|
| 18 |
+
n = S.size(0)
|
| 19 |
+
A2I_scores, A2I_ind = S.topk(10, 0)
|
| 20 |
+
I2A_scores, I2A_ind = S.topk(10, 1)
|
| 21 |
+
A_r1 = AverageMeter()
|
| 22 |
+
A_r5 = AverageMeter()
|
| 23 |
+
A_r10 = AverageMeter()
|
| 24 |
+
I_r1 = AverageMeter()
|
| 25 |
+
I_r5 = AverageMeter()
|
| 26 |
+
I_r10 = AverageMeter()
|
| 27 |
+
for i in range(n):
|
| 28 |
+
A_foundind = -1
|
| 29 |
+
I_foundind = -1
|
| 30 |
+
for ind in range(10):
|
| 31 |
+
if A2I_ind[ind, i] == i:
|
| 32 |
+
I_foundind = ind
|
| 33 |
+
if I2A_ind[i, ind] == i:
|
| 34 |
+
A_foundind = ind
|
| 35 |
+
# do r1s
|
| 36 |
+
if A_foundind == 0:
|
| 37 |
+
A_r1.update(1)
|
| 38 |
+
else:
|
| 39 |
+
A_r1.update(0)
|
| 40 |
+
if I_foundind == 0:
|
| 41 |
+
I_r1.update(1)
|
| 42 |
+
else:
|
| 43 |
+
I_r1.update(0)
|
| 44 |
+
# do r5s
|
| 45 |
+
if A_foundind >= 0 and A_foundind < 5:
|
| 46 |
+
A_r5.update(1)
|
| 47 |
+
else:
|
| 48 |
+
A_r5.update(0)
|
| 49 |
+
if I_foundind >= 0 and I_foundind < 5:
|
| 50 |
+
I_r5.update(1)
|
| 51 |
+
else:
|
| 52 |
+
I_r5.update(0)
|
| 53 |
+
# do r10s
|
| 54 |
+
if A_foundind >= 0 and A_foundind < 10:
|
| 55 |
+
A_r10.update(1)
|
| 56 |
+
else:
|
| 57 |
+
A_r10.update(0)
|
| 58 |
+
if I_foundind >= 0 and I_foundind < 10:
|
| 59 |
+
I_r10.update(1)
|
| 60 |
+
else:
|
| 61 |
+
I_r10.update(0)
|
| 62 |
+
|
| 63 |
+
recalls = {'A_r1':A_r1.avg, 'A_r5':A_r5.avg, 'A_r10':A_r10.avg,
|
| 64 |
+
'I_r1':I_r1.avg, 'I_r5':I_r5.avg, 'I_r10':I_r10.avg}
|
| 65 |
+
#'A_meanR':A_meanR.avg, 'I_meanR':I_meanR.avg}
|
| 66 |
+
|
| 67 |
+
return recalls
|
| 68 |
+
|
| 69 |
+
def computeMatchmap(I, A):
|
| 70 |
+
assert(I.dim() == 3)
|
| 71 |
+
assert(A.dim() == 2)
|
| 72 |
+
D = I.size(0)
|
| 73 |
+
H = I.size(1)
|
| 74 |
+
W = I.size(2)
|
| 75 |
+
T = A.size(1)
|
| 76 |
+
Ir = I.view(D, -1).t()
|
| 77 |
+
matchmap = torch.mm(Ir, A)
|
| 78 |
+
matchmap = matchmap.view(H, W, T)
|
| 79 |
+
return matchmap
|
| 80 |
+
|
| 81 |
+
def matchmapSim(M, simtype):
|
| 82 |
+
assert(M.dim() == 3)
|
| 83 |
+
if simtype == 'SISA':
|
| 84 |
+
return M.mean()
|
| 85 |
+
elif simtype == 'MISA':
|
| 86 |
+
M_maxH, _ = M.max(0)
|
| 87 |
+
M_maxHW, _ = M_maxH.max(0)
|
| 88 |
+
return M_maxHW.mean()
|
| 89 |
+
elif simtype == 'SIMA':
|
| 90 |
+
M_maxT, _ = M.max(2)
|
| 91 |
+
return M_maxT.mean()
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError
|
| 94 |
+
|
| 95 |
+
def sampled_margin_rank_loss(image_outputs, audio_outputs, nframes, margin=1., simtype='MISA'):
|
| 96 |
+
"""
|
| 97 |
+
Computes the triplet margin ranking loss for each anchor image/caption pair
|
| 98 |
+
The impostor image/caption is randomly sampled from the minibatch
|
| 99 |
+
"""
|
| 100 |
+
assert(image_outputs.dim() == 4)
|
| 101 |
+
assert(audio_outputs.dim() == 3)
|
| 102 |
+
n = image_outputs.size(0)
|
| 103 |
+
loss = torch.zeros(1, device=image_outputs.device, requires_grad=True)
|
| 104 |
+
for i in range(n):
|
| 105 |
+
I_imp_ind = i
|
| 106 |
+
A_imp_ind = i
|
| 107 |
+
while I_imp_ind == i:
|
| 108 |
+
I_imp_ind = np.random.randint(0, n)
|
| 109 |
+
while A_imp_ind == i:
|
| 110 |
+
A_imp_ind = np.random.randint(0, n)
|
| 111 |
+
nF = nframes[i]
|
| 112 |
+
nFimp = nframes[A_imp_ind]
|
| 113 |
+
anchorsim = matchmapSim(computeMatchmap(image_outputs[i], audio_outputs[i][:, 0:nF]), simtype)
|
| 114 |
+
Iimpsim = matchmapSim(computeMatchmap(image_outputs[I_imp_ind], audio_outputs[i][:, 0:nF]), simtype)
|
| 115 |
+
Aimpsim = matchmapSim(computeMatchmap(image_outputs[i], audio_outputs[A_imp_ind][:, 0:nFimp]), simtype)
|
| 116 |
+
A2I_simdif = margin + Iimpsim - anchorsim
|
| 117 |
+
if (A2I_simdif.data > 0).all():
|
| 118 |
+
loss = loss + A2I_simdif
|
| 119 |
+
I2A_simdif = margin + Aimpsim - anchorsim
|
| 120 |
+
if (I2A_simdif.data > 0).all():
|
| 121 |
+
loss = loss + I2A_simdif
|
| 122 |
+
loss = loss / n
|
| 123 |
+
return loss
|
| 124 |
+
|
| 125 |
+
def compute_matchmap_similarity_matrix(image_outputs, audio_outputs, nframes, simtype='MISA'):
|
| 126 |
+
"""
|
| 127 |
+
Assumes image_outputs is a (batchsize, embedding_dim, rows, height) tensor
|
| 128 |
+
Assumes audio_outputs is a (batchsize, embedding_dim, 1, time) tensor
|
| 129 |
+
Returns similarity matrix S where images are rows and audios are along the columns
|
| 130 |
+
"""
|
| 131 |
+
assert(image_outputs.dim() == 4)
|
| 132 |
+
assert(audio_outputs.dim() == 3)
|
| 133 |
+
n = image_outputs.size(0)
|
| 134 |
+
S = torch.zeros(n, n, device=image_outputs.device)
|
| 135 |
+
for image_idx in range(n):
|
| 136 |
+
for audio_idx in range(n):
|
| 137 |
+
nF = max(1, nframes[audio_idx])
|
| 138 |
+
S[image_idx, audio_idx] = matchmapSim(computeMatchmap(image_outputs[image_idx], audio_outputs[audio_idx][:, 0:nF]), simtype)
|
| 139 |
+
return S
|
| 140 |
+
|
| 141 |
+
def compute_pooldot_similarity_matrix(image_outputs, audio_outputs, nframes):
|
| 142 |
+
"""
|
| 143 |
+
Assumes image_outputs is a (batchsize, embedding_dim, rows, height) tensor
|
| 144 |
+
Assumes audio_outputs is a (batchsize, embedding_dim, 1, time) tensor
|
| 145 |
+
Returns similarity matrix S where images are rows and audios are along the columns
|
| 146 |
+
S[i][j] is computed as the dot product between the meanpooled embeddings of
|
| 147 |
+
the ith image output and jth audio output
|
| 148 |
+
"""
|
| 149 |
+
assert(image_outputs.dim() == 4)
|
| 150 |
+
assert(audio_outputs.dim() == 4)
|
| 151 |
+
n = image_outputs.size(0)
|
| 152 |
+
imagePoolfunc = nn.AdaptiveAvgPool2d((1, 1))
|
| 153 |
+
pooled_image_outputs = imagePoolfunc(image_outputs).squeeze(3).squeeze(2)
|
| 154 |
+
audioPoolfunc = nn.AdaptiveAvgPool2d((1, 1))
|
| 155 |
+
pooled_audio_outputs_list = []
|
| 156 |
+
for idx in range(n):
|
| 157 |
+
nF = max(1, nframes[idx])
|
| 158 |
+
pooled_audio_outputs_list.append(audioPoolfunc(audio_outputs[idx][:, :, 0:nF]).unsqueeze(0))
|
| 159 |
+
pooled_audio_outputs = torch.cat(pooled_audio_outputs_list).squeeze(3).squeeze(2)
|
| 160 |
+
S = torch.mm(pooled_image_outputs, pooled_audio_outputs.t())
|
| 161 |
+
return S
|
| 162 |
+
|
| 163 |
+
def one_imposter_index(i, N):
|
| 164 |
+
imp_ind = random.randint(0, N - 2)
|
| 165 |
+
if imp_ind == i:
|
| 166 |
+
imp_ind = N - 1
|
| 167 |
+
return imp_ind
|
| 168 |
+
|
| 169 |
+
def basic_get_imposter_indices(N):
|
| 170 |
+
imposter_idc = []
|
| 171 |
+
for i in range(N):
|
| 172 |
+
# Select an imposter index for example i:
|
| 173 |
+
imp_ind = one_imposter_index(i, N)
|
| 174 |
+
imposter_idc.append(imp_ind)
|
| 175 |
+
return imposter_idc
|
| 176 |
+
|
| 177 |
+
def semihardneg_triplet_loss_from_S(S, margin):
|
| 178 |
+
"""
|
| 179 |
+
Input: Similarity matrix S as an autograd.Variable
|
| 180 |
+
Output: The one-way triplet loss from rows of S to columns of S. Impostors are taken
|
| 181 |
+
to be the most similar point to the anchor that is still less similar to the anchor
|
| 182 |
+
than the positive example.
|
| 183 |
+
You would need to run this function twice, once with S and once with S.t(),
|
| 184 |
+
in order to compute the triplet loss in both directions.
|
| 185 |
+
"""
|
| 186 |
+
assert(S.dim() == 2)
|
| 187 |
+
assert(S.size(0) == S.size(1))
|
| 188 |
+
N = S.size(0)
|
| 189 |
+
loss = torch.autograd.Variable(torch.zeros(1).type(S.data.type()), requires_grad=True)
|
| 190 |
+
# Imposter - ground truth
|
| 191 |
+
Sdiff = S - torch.diag(S).view(-1, 1)
|
| 192 |
+
eps = 1e-12
|
| 193 |
+
# All examples less similar than ground truth
|
| 194 |
+
mask = (Sdiff < -eps).type(torch.LongTensor)
|
| 195 |
+
maskf = mask.type_as(S)
|
| 196 |
+
# Mask out all examples >= gt with minimum similarity
|
| 197 |
+
Sp = maskf * Sdiff + (1 - maskf) * torch.min(Sdiff).detach()
|
| 198 |
+
# Find the index maximum similar of the remaining
|
| 199 |
+
_, idc = Sp.max(dim=1)
|
| 200 |
+
idc = idc.data.cpu()
|
| 201 |
+
# Vector mask: 1 iff there exists an example < gt
|
| 202 |
+
has_neg = (mask.sum(dim=1) > 0).data.type(torch.LongTensor)
|
| 203 |
+
# Random imposter indices
|
| 204 |
+
random_imp_ind = torch.LongTensor(basic_get_imposter_indices(N))
|
| 205 |
+
# Use hardneg if there exists an example < gt, otherwise use random imposter
|
| 206 |
+
imp_idc = has_neg * idc + (1 - has_neg) * random_imp_ind
|
| 207 |
+
# This could probably be vectorized too, but I haven't.
|
| 208 |
+
for i, imp in enumerate(imp_idc):
|
| 209 |
+
local_loss = Sdiff[i, imp] + margin
|
| 210 |
+
if (local_loss.data > 0).all():
|
| 211 |
+
loss = loss + local_loss
|
| 212 |
+
loss = loss / N
|
| 213 |
+
return loss
|
| 214 |
+
|
| 215 |
+
def sampled_triplet_loss_from_S(S, margin):
|
| 216 |
+
"""
|
| 217 |
+
Input: Similarity matrix S as an autograd.Variable
|
| 218 |
+
Output: The one-way triplet loss from rows of S to columns of S. Imposters are
|
| 219 |
+
randomly sampled from the columns of S.
|
| 220 |
+
You would need to run this function twice, once with S and once with S.t(),
|
| 221 |
+
in order to compute the triplet loss in both directions.
|
| 222 |
+
"""
|
| 223 |
+
assert(S.dim() == 2)
|
| 224 |
+
assert(S.size(0) == S.size(1))
|
| 225 |
+
N = S.size(0)
|
| 226 |
+
loss = torch.autograd.Variable(torch.zeros(1).type(S.data.type()), requires_grad=True)
|
| 227 |
+
# Imposter - ground truth
|
| 228 |
+
Sdiff = S - torch.diag(S).view(-1, 1)
|
| 229 |
+
imp_ind = torch.LongTensor(basic_get_imposter_indices(N))
|
| 230 |
+
# This could probably be vectorized too, but I haven't.
|
| 231 |
+
for i, imp in enumerate(imp_ind):
|
| 232 |
+
local_loss = Sdiff[i, imp] + margin
|
| 233 |
+
if (local_loss.data > 0).all():
|
| 234 |
+
loss = loss + local_loss
|
| 235 |
+
loss = loss / N
|
| 236 |
+
return loss
|
| 237 |
+
|
| 238 |
+
class AverageMeter(object):
|
| 239 |
+
"""Computes and stores the average and current value"""
|
| 240 |
+
def __init__(self):
|
| 241 |
+
self.reset()
|
| 242 |
+
|
| 243 |
+
def reset(self):
|
| 244 |
+
self.val = 0
|
| 245 |
+
self.avg = 0
|
| 246 |
+
self.sum = 0
|
| 247 |
+
self.count = 0
|
| 248 |
+
|
| 249 |
+
def update(self, val, n=1):
|
| 250 |
+
self.val = val
|
| 251 |
+
self.sum += val * n
|
| 252 |
+
self.count += n
|
| 253 |
+
self.avg = self.sum / self.count
|
| 254 |
+
|
| 255 |
+
def adjust_learning_rate(base_lr, lr_decay, optimizer, epoch):
|
| 256 |
+
"""Sets the learning rate to the initial LR decayed by 10 every lr_decay epochs"""
|
| 257 |
+
lr = base_lr * (0.1 ** (epoch // lr_decay))
|
| 258 |
+
print('now learning rate changed to {:f}'.format(lr))
|
| 259 |
+
for param_group in optimizer.param_groups:
|
| 260 |
+
param_group['lr'] = lr
|
| 261 |
+
|
| 262 |
+
def adjust_learning_rate2(base_lr, lr_decay, optimizer, epoch):
|
| 263 |
+
"""Sets the learning rate to the initial LR decayed by 10 every lr_decay epochs"""
|
| 264 |
+
for param_group in optimizer.param_groups:
|
| 265 |
+
cur_lr = param_group['lr']
|
| 266 |
+
print('current learing rate is {:f}'.format(lr))
|
| 267 |
+
lr = cur_lr * 0.1
|
| 268 |
+
print('now learning rate changed to {:f}'.format(lr))
|
| 269 |
+
for param_group in optimizer.param_groups:
|
| 270 |
+
param_group['lr'] = lr
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def load_progress(prog_pkl, quiet=False):
|
| 274 |
+
"""
|
| 275 |
+
load progress pkl file
|
| 276 |
+
Args:
|
| 277 |
+
prog_pkl(str): path to progress pkl file
|
| 278 |
+
Return:
|
| 279 |
+
progress(list):
|
| 280 |
+
epoch(int):
|
| 281 |
+
global_step(int):
|
| 282 |
+
best_epoch(int):
|
| 283 |
+
best_avg_r10(float):
|
| 284 |
+
"""
|
| 285 |
+
def _print(msg):
|
| 286 |
+
if not quiet:
|
| 287 |
+
print(msg)
|
| 288 |
+
|
| 289 |
+
with open(prog_pkl, "rb") as f:
|
| 290 |
+
prog = pickle.load(f)
|
| 291 |
+
epoch, global_step, best_epoch, best_avg_r10, _ = prog[-1]
|
| 292 |
+
|
| 293 |
+
_print("\nPrevious Progress:")
|
| 294 |
+
msg = "[%5s %7s %5s %7s %6s]" % ("epoch", "step", "best_epoch", "best_avg_r10", "time")
|
| 295 |
+
_print(msg)
|
| 296 |
+
return prog, epoch, global_step, best_epoch, best_avg_r10
|
| 297 |
+
|
| 298 |
+
def count_parameters(model):
|
| 299 |
+
return sum([p.numel() for p in model.parameters() if p.requires_grad])
|
| 300 |
+
|
| 301 |
+
PrenetConfig = namedtuple(
|
| 302 |
+
'PrenetConfig', ['input_size', 'hidden_size', 'num_layers', 'dropout'])
|
| 303 |
+
|
| 304 |
+
RNNConfig = namedtuple(
|
| 305 |
+
'RNNConfig',
|
| 306 |
+
['input_size', 'hidden_size', 'num_layers', 'dropout', 'residual'])
|
a_cls/zero_shot.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
from open_clip import get_input_dtype, get_tokenizer
|
| 11 |
+
from open_clip.factory import HF_HUB_PREFIX
|
| 12 |
+
from .precision import get_autocast
|
| 13 |
+
from .stats import calculate_stats, d_prime
|
| 14 |
+
from .zero_shot_classifier import build_zero_shot_classifier
|
| 15 |
+
from .zero_shot_metadata import CLASSNAMES, OPENAI_IMAGENET_TEMPLATES
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def accuracy(output, target, topk=(1,)):
|
| 19 |
+
pred = output.topk(max(topk), 1, True, True)[1].t()
|
| 20 |
+
correct = pred.eq(target.view(1, -1).expand_as(pred))
|
| 21 |
+
return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def run(model, classifier, dataloader, args):
|
| 25 |
+
autocast = get_autocast(args.precision)
|
| 26 |
+
input_dtype = get_input_dtype(args.precision)
|
| 27 |
+
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
top1, top5, n = 0., 0., 0.
|
| 30 |
+
for images, target in tqdm(dataloader, unit_scale=args.batch_size):
|
| 31 |
+
images = images.to(device=args.device, dtype=input_dtype)
|
| 32 |
+
images = images.unsqueeze(2)
|
| 33 |
+
target = target.to(args.device)
|
| 34 |
+
|
| 35 |
+
with autocast():
|
| 36 |
+
# predict
|
| 37 |
+
output = model(image=images)
|
| 38 |
+
image_features = output['image_features'] if isinstance(output, dict) else output[0]
|
| 39 |
+
logits = 100. * image_features @ classifier
|
| 40 |
+
|
| 41 |
+
# measure accuracy
|
| 42 |
+
acc1, acc5 = accuracy(logits, target, topk=(1, 5))
|
| 43 |
+
top1 += acc1
|
| 44 |
+
top5 += acc5
|
| 45 |
+
n += images.size(0)
|
| 46 |
+
|
| 47 |
+
top1 = (top1 / n)
|
| 48 |
+
top5 = (top5 / n)
|
| 49 |
+
return top1, top5
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def validate(audio_model, classifier, val_loader, args, epoch):
|
| 53 |
+
epoch = epoch - 1 ########################
|
| 54 |
+
# switch to evaluate mode
|
| 55 |
+
audio_model.eval()
|
| 56 |
+
autocast = get_autocast(args.precision)
|
| 57 |
+
input_dtype = get_input_dtype(args.precision)
|
| 58 |
+
A_predictions = []
|
| 59 |
+
A_targets = []
|
| 60 |
+
A_loss = []
|
| 61 |
+
with torch.no_grad():
|
| 62 |
+
for i, (audio_input, labels) in enumerate(tqdm(val_loader)):
|
| 63 |
+
audio_input = audio_input.to(device=args.device, dtype=input_dtype)
|
| 64 |
+
|
| 65 |
+
# compute output
|
| 66 |
+
with autocast():
|
| 67 |
+
# predict
|
| 68 |
+
output = audio_model(image=audio_input)
|
| 69 |
+
image_features = output['image_features'] if isinstance(output, dict) else output[0]
|
| 70 |
+
logits = 100. * image_features @ classifier
|
| 71 |
+
audio_output = logits
|
| 72 |
+
|
| 73 |
+
# audio_output = torch.sigmoid(audio_output)
|
| 74 |
+
predictions = audio_output.to('cpu').detach()
|
| 75 |
+
|
| 76 |
+
A_predictions.append(predictions)
|
| 77 |
+
A_targets.append(labels)
|
| 78 |
+
|
| 79 |
+
# compute the loss
|
| 80 |
+
labels = labels.to(args.device)
|
| 81 |
+
loss = nn.CrossEntropyLoss()(audio_output, torch.argmax(labels.long(), dim=1))
|
| 82 |
+
A_loss.append(loss.to('cpu').detach())
|
| 83 |
+
|
| 84 |
+
audio_output = torch.cat(A_predictions)
|
| 85 |
+
target = torch.cat(A_targets)
|
| 86 |
+
loss = np.mean(A_loss)
|
| 87 |
+
stats = calculate_stats(audio_output, target)
|
| 88 |
+
|
| 89 |
+
# save the prediction here
|
| 90 |
+
args.a_cls_output_dir = os.path.join(args.log_base_path, f'a_cls/{args.val_a_cls_data.lower()}')
|
| 91 |
+
os.makedirs(args.a_cls_output_dir, exist_ok=True)
|
| 92 |
+
if os.path.exists(args.a_cls_output_dir + '/predictions') == False:
|
| 93 |
+
os.mkdir(args.a_cls_output_dir + '/predictions')
|
| 94 |
+
np.savetxt(args.a_cls_output_dir + '/predictions/target.csv', target, delimiter=',')
|
| 95 |
+
np.savetxt(args.a_cls_output_dir + '/predictions/predictions_' + str(epoch) + '.csv', audio_output,
|
| 96 |
+
delimiter=',')
|
| 97 |
+
|
| 98 |
+
valid_loss = loss
|
| 99 |
+
main_metrics = 'mAP'
|
| 100 |
+
metrics = {}
|
| 101 |
+
|
| 102 |
+
if args.do_train:
|
| 103 |
+
# ensemble results
|
| 104 |
+
cum_stats = validate_ensemble(args, epoch)
|
| 105 |
+
cum_mAP = np.mean([stat['AP'] for stat in cum_stats])
|
| 106 |
+
cum_mAUC = np.mean([stat['auc'] for stat in cum_stats])
|
| 107 |
+
cum_acc = cum_stats[0]['acc']
|
| 108 |
+
|
| 109 |
+
mAP = np.mean([stat['AP'] for stat in stats])
|
| 110 |
+
mAUC = np.mean([stat['auc'] for stat in stats])
|
| 111 |
+
acc = stats[0]['acc']
|
| 112 |
+
|
| 113 |
+
middle_ps = [stat['precisions'][int(len(stat['precisions']) / 2)] for stat in stats]
|
| 114 |
+
middle_rs = [stat['recalls'][int(len(stat['recalls']) / 2)] for stat in stats]
|
| 115 |
+
average_precision = np.mean(middle_ps)
|
| 116 |
+
average_recall = np.mean(middle_rs)
|
| 117 |
+
|
| 118 |
+
if main_metrics == 'mAP':
|
| 119 |
+
logging.info("mAP: {:.6f}".format(mAP))
|
| 120 |
+
else:
|
| 121 |
+
logging.info("acc: {:.6f}".format(acc))
|
| 122 |
+
logging.info("AUC: {:.6f}".format(mAUC))
|
| 123 |
+
logging.info("Avg Precision: {:.6f}".format(average_precision))
|
| 124 |
+
logging.info("Avg Recall: {:.6f}".format(average_recall))
|
| 125 |
+
logging.info("d_prime: {:.6f}".format(d_prime(mAUC)))
|
| 126 |
+
logging.info("valid_loss: {:.6f}".format(valid_loss))
|
| 127 |
+
|
| 128 |
+
if args.do_train:
|
| 129 |
+
logging.info("cum_mAP: {:.6f}".format(cum_mAP))
|
| 130 |
+
logging.info("cum_mAUC: {:.6f}".format(cum_mAUC))
|
| 131 |
+
|
| 132 |
+
if main_metrics == 'mAP':
|
| 133 |
+
metrics['mAP'] = float(mAP)
|
| 134 |
+
else:
|
| 135 |
+
metrics['acc'] = float(acc)
|
| 136 |
+
|
| 137 |
+
metrics['mAUC'] = float(mAUC)
|
| 138 |
+
metrics['average_precision'] = float(average_precision)
|
| 139 |
+
metrics['average_recall'] = float(average_recall)
|
| 140 |
+
metrics['d_prime_mAUC'] = float(d_prime(mAUC))
|
| 141 |
+
metrics['valid_loss'] = float(valid_loss)
|
| 142 |
+
|
| 143 |
+
if args.do_train:
|
| 144 |
+
metrics['cum_mAP'] = float(cum_mAP)
|
| 145 |
+
metrics['cum_mAUC'] = float(cum_mAUC)
|
| 146 |
+
|
| 147 |
+
return metrics
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def validate_ensemble(args, epoch):
|
| 151 |
+
exp_dir = args.a_cls_output_dir
|
| 152 |
+
target = np.loadtxt(exp_dir + '/predictions/target.csv', delimiter=',')
|
| 153 |
+
if epoch == 0:
|
| 154 |
+
cum_predictions = np.loadtxt(exp_dir + '/predictions/predictions_0.csv', delimiter=',')
|
| 155 |
+
else:
|
| 156 |
+
cum_predictions = np.loadtxt(exp_dir + '/predictions/cum_predictions.csv', delimiter=',') * (epoch - 1)
|
| 157 |
+
predictions = np.loadtxt(exp_dir + '/predictions/predictions_' + str(epoch) + '.csv', delimiter=',')
|
| 158 |
+
cum_predictions = cum_predictions + predictions
|
| 159 |
+
# remove the prediction file to save storage space
|
| 160 |
+
os.remove(exp_dir + '/predictions/predictions_' + str(epoch - 1) + '.csv')
|
| 161 |
+
|
| 162 |
+
cum_predictions = cum_predictions / (epoch + 1)
|
| 163 |
+
np.savetxt(exp_dir + '/predictions/cum_predictions.csv', cum_predictions, delimiter=',')
|
| 164 |
+
|
| 165 |
+
stats = calculate_stats(cum_predictions, target)
|
| 166 |
+
return stats
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def zero_shot_eval(model, data, epoch, args):
|
| 177 |
+
temp_val_a_cls_data = args.val_a_cls_data
|
| 178 |
+
args.val_a_cls_data = list(data.keys())
|
| 179 |
+
assert len(args.val_a_cls_data) == 1
|
| 180 |
+
args.val_a_cls_data = args.val_a_cls_data[0]
|
| 181 |
+
|
| 182 |
+
if args.val_a_cls_data not in data:
|
| 183 |
+
return {}
|
| 184 |
+
if args.zeroshot_frequency == 0:
|
| 185 |
+
return {}
|
| 186 |
+
if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs:
|
| 187 |
+
return {}
|
| 188 |
+
if args.distributed and not args.horovod:
|
| 189 |
+
model = model.module
|
| 190 |
+
|
| 191 |
+
logging.info(f'Starting zero-shot {args.val_a_cls_data.upper()}.')
|
| 192 |
+
|
| 193 |
+
logging.info('Building zero-shot classifier')
|
| 194 |
+
autocast = get_autocast(args.precision)
|
| 195 |
+
with autocast():
|
| 196 |
+
tokenizer = get_tokenizer(HF_HUB_PREFIX+args.model, cache_dir=args.cache_dir)
|
| 197 |
+
# tokenizer = get_tokenizer("ViT-L-14")
|
| 198 |
+
classifier = build_zero_shot_classifier(
|
| 199 |
+
model,
|
| 200 |
+
tokenizer=tokenizer,
|
| 201 |
+
classnames=CLASSNAMES[args.val_a_cls_data],
|
| 202 |
+
templates=OPENAI_IMAGENET_TEMPLATES,
|
| 203 |
+
num_classes_per_batch=10,
|
| 204 |
+
device=args.device,
|
| 205 |
+
use_tqdm=True,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
logging.info('Using classifier')
|
| 209 |
+
results = {}
|
| 210 |
+
if args.val_a_cls_data.lower() == 'audioset':
|
| 211 |
+
if args.val_a_cls_data in data:
|
| 212 |
+
stats = validate(model, classifier, data[args.val_a_cls_data].dataloader, args, epoch)
|
| 213 |
+
results.update(stats)
|
| 214 |
+
else:
|
| 215 |
+
if args.val_a_cls_data in data:
|
| 216 |
+
top1, top5 = run(model, classifier, data[args.val_a_cls_data].dataloader, args)
|
| 217 |
+
results[f'{args.val_a_cls_data}-zeroshot-val-top1'] = top1
|
| 218 |
+
results[f'{args.val_a_cls_data}-zeroshot-val-top5'] = top5
|
| 219 |
+
|
| 220 |
+
logging.info(f'Finished zero-shot {args.val_a_cls_data.upper()}.')
|
| 221 |
+
|
| 222 |
+
args.val_a_cls_data = temp_val_a_cls_data
|
| 223 |
+
return results
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
|
a_cls/zero_shot_classifier.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
from itertools import islice
|
| 3 |
+
from typing import Callable, List, Optional, Sequence, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def batched(iterable, n):
|
| 10 |
+
"""Batch data into lists of length *n*. The last batch may be shorter.
|
| 11 |
+
NOTE based on more-itertools impl, to be replaced by python 3.12 itertools.batched impl
|
| 12 |
+
"""
|
| 13 |
+
it = iter(iterable)
|
| 14 |
+
while True:
|
| 15 |
+
batch = list(islice(it, n))
|
| 16 |
+
if not batch:
|
| 17 |
+
break
|
| 18 |
+
yield batch
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def build_zero_shot_classifier(
|
| 22 |
+
model,
|
| 23 |
+
tokenizer,
|
| 24 |
+
classnames: Sequence[str],
|
| 25 |
+
templates: Sequence[Union[Callable, str]],
|
| 26 |
+
num_classes_per_batch: Optional[int] = 10,
|
| 27 |
+
device: Union[str, torch.device] = 'cpu',
|
| 28 |
+
use_tqdm: bool = False,
|
| 29 |
+
):
|
| 30 |
+
""" Build zero-shot classifier weights by iterating over class names in batches
|
| 31 |
+
Args:
|
| 32 |
+
model: CLIP model instance
|
| 33 |
+
tokenizer: CLIP tokenizer instance
|
| 34 |
+
classnames: A sequence of class (label) names
|
| 35 |
+
templates: A sequence of callables or format() friendly strings to produce templates per class name
|
| 36 |
+
num_classes_per_batch: The number of classes to batch together in each forward, all if None
|
| 37 |
+
device: Device to use.
|
| 38 |
+
use_tqdm: Enable TQDM progress bar.
|
| 39 |
+
"""
|
| 40 |
+
assert isinstance(templates, Sequence) and len(templates) > 0
|
| 41 |
+
assert isinstance(classnames, Sequence) and len(classnames) > 0
|
| 42 |
+
use_format = isinstance(templates[0], str)
|
| 43 |
+
num_templates = len(templates)
|
| 44 |
+
num_classes = len(classnames)
|
| 45 |
+
if use_tqdm:
|
| 46 |
+
import tqdm
|
| 47 |
+
num_iter = 1 if num_classes_per_batch is None else ((num_classes - 1) // num_classes_per_batch + 1)
|
| 48 |
+
iter_wrap = partial(tqdm.tqdm, total=num_iter, unit_scale=num_classes_per_batch)
|
| 49 |
+
else:
|
| 50 |
+
iter_wrap = iter
|
| 51 |
+
|
| 52 |
+
def _process_batch(batch_classnames):
|
| 53 |
+
num_batch_classes = len(batch_classnames)
|
| 54 |
+
texts = [template.format(c) if use_format else template(c) for c in batch_classnames for template in templates]
|
| 55 |
+
input_ids, attention_mask = tokenizer(texts)
|
| 56 |
+
input_ids, attention_mask = input_ids.to(device), attention_mask.to(device)
|
| 57 |
+
class_embeddings = F.normalize(model.encode_text(input_ids, attention_mask), dim=-1)
|
| 58 |
+
class_embeddings = class_embeddings.reshape(num_batch_classes, num_templates, -1).mean(dim=1)
|
| 59 |
+
class_embeddings = class_embeddings / class_embeddings.norm(dim=1, keepdim=True)
|
| 60 |
+
class_embeddings = class_embeddings.T
|
| 61 |
+
return class_embeddings
|
| 62 |
+
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
if num_classes_per_batch:
|
| 65 |
+
batched_embeds = [_process_batch(batch) for batch in iter_wrap(batched(classnames, num_classes_per_batch))]
|
| 66 |
+
zeroshot_weights = torch.cat(batched_embeds, dim=1)
|
| 67 |
+
else:
|
| 68 |
+
zeroshot_weights = _process_batch(classnames)
|
| 69 |
+
return zeroshot_weights
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_zero_shot_classifier_legacy(
|
| 73 |
+
model,
|
| 74 |
+
tokenizer,
|
| 75 |
+
classnames: Sequence[str],
|
| 76 |
+
templates: Sequence[Union[Callable, str]],
|
| 77 |
+
device: Union[str, torch.device] = 'cpu',
|
| 78 |
+
use_tqdm: bool = False,
|
| 79 |
+
):
|
| 80 |
+
""" Build zero-shot classifier weights by iterating over class names 1 by 1
|
| 81 |
+
Args:
|
| 82 |
+
model: CLIP model instance
|
| 83 |
+
tokenizer: CLIP tokenizer instance
|
| 84 |
+
classnames: A sequence of class (label) names
|
| 85 |
+
templates: A sequence of callables or format() friendly strings to produce templates per class name
|
| 86 |
+
device: Device to use.
|
| 87 |
+
use_tqdm: Enable TQDM progress bar.
|
| 88 |
+
"""
|
| 89 |
+
assert isinstance(templates, Sequence) and len(templates) > 0
|
| 90 |
+
assert isinstance(classnames, Sequence) and len(classnames) > 0
|
| 91 |
+
if use_tqdm:
|
| 92 |
+
import tqdm
|
| 93 |
+
iter_wrap = tqdm.tqdm
|
| 94 |
+
else:
|
| 95 |
+
iter_wrap = iter
|
| 96 |
+
|
| 97 |
+
use_format = isinstance(templates[0], str)
|
| 98 |
+
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
zeroshot_weights = []
|
| 101 |
+
for classname in iter_wrap(classnames):
|
| 102 |
+
texts = [template.format(classname) if use_format else template(classname) for template in templates]
|
| 103 |
+
texts = tokenizer(texts).to(device) # tokenize
|
| 104 |
+
class_embeddings = model.encode_text(texts)
|
| 105 |
+
class_embedding = F.normalize(class_embeddings, dim=-1).mean(dim=0)
|
| 106 |
+
class_embedding /= class_embedding.norm()
|
| 107 |
+
zeroshot_weights.append(class_embedding)
|
| 108 |
+
zeroshot_weights = torch.stack(zeroshot_weights, dim=1).to(device)
|
| 109 |
+
|
| 110 |
+
return zeroshot_weights
|
| 111 |
+
|
a_cls/zero_shot_metadata.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
OPENAI_IMAGENET_TEMPLATES = (
|
| 6 |
+
# lambda c: f'This is a sound of {c}.',
|
| 7 |
+
lambda c: f'a sound of {c}.',
|
| 8 |
+
)
|
| 9 |
+
# OPENAI_IMAGENET_TEMPLATES = (
|
| 10 |
+
# lambda c: f'a bad sound of a {c}.',
|
| 11 |
+
# lambda c: f'a sound of many {c}.',
|
| 12 |
+
# lambda c: f'a sculpture of a {c}.',
|
| 13 |
+
# lambda c: f'a sound of the hard to see {c}.',
|
| 14 |
+
# lambda c: f'a low resolution sound of the {c}.',
|
| 15 |
+
# lambda c: f'a rendering of a {c}.',
|
| 16 |
+
# lambda c: f'graffiti of a {c}.',
|
| 17 |
+
# lambda c: f'a bad sound of the {c}.',
|
| 18 |
+
# lambda c: f'a cropped sound of the {c}.',
|
| 19 |
+
# lambda c: f'a tattoo of a {c}.',
|
| 20 |
+
# lambda c: f'the embroidered {c}.',
|
| 21 |
+
# lambda c: f'a sound of a hard to see {c}.',
|
| 22 |
+
# lambda c: f'a bright sound of a {c}.',
|
| 23 |
+
# lambda c: f'a sound of a clean {c}.',
|
| 24 |
+
# lambda c: f'a sound of a dirty {c}.',
|
| 25 |
+
# lambda c: f'a dark sound of the {c}.',
|
| 26 |
+
# lambda c: f'a drawing of a {c}.',
|
| 27 |
+
# lambda c: f'a sound of my {c}.',
|
| 28 |
+
# lambda c: f'the plastic {c}.',
|
| 29 |
+
# lambda c: f'a sound of the cool {c}.',
|
| 30 |
+
# lambda c: f'a close-up sound of a {c}.',
|
| 31 |
+
# lambda c: f'a black and white sound of the {c}.',
|
| 32 |
+
# lambda c: f'a painting of the {c}.',
|
| 33 |
+
# lambda c: f'a painting of a {c}.',
|
| 34 |
+
# lambda c: f'a pixelated sound of the {c}.',
|
| 35 |
+
# lambda c: f'a sculpture of the {c}.',
|
| 36 |
+
# lambda c: f'a bright sound of the {c}.',
|
| 37 |
+
# lambda c: f'a cropped sound of a {c}.',
|
| 38 |
+
# lambda c: f'a plastic {c}.',
|
| 39 |
+
# lambda c: f'a sound of the dirty {c}.',
|
| 40 |
+
# lambda c: f'a jpeg corrupted sound of a {c}.',
|
| 41 |
+
# lambda c: f'a blurry sound of the {c}.',
|
| 42 |
+
# lambda c: f'a sound of the {c}.',
|
| 43 |
+
# lambda c: f'a good sound of the {c}.',
|
| 44 |
+
# lambda c: f'a rendering of the {c}.',
|
| 45 |
+
# lambda c: f'a {c} in a video game.',
|
| 46 |
+
# lambda c: f'a sound of one {c}.',
|
| 47 |
+
# lambda c: f'a doodle of a {c}.',
|
| 48 |
+
# lambda c: f'a close-up sound of the {c}.',
|
| 49 |
+
# lambda c: f'a sound of a {c}.',
|
| 50 |
+
# lambda c: f'the origami {c}.',
|
| 51 |
+
# lambda c: f'the {c} in a video game.',
|
| 52 |
+
# lambda c: f'a sketch of a {c}.',
|
| 53 |
+
# lambda c: f'a doodle of the {c}.',
|
| 54 |
+
# lambda c: f'a origami {c}.',
|
| 55 |
+
# lambda c: f'a low resolution sound of a {c}.',
|
| 56 |
+
# lambda c: f'the toy {c}.',
|
| 57 |
+
# lambda c: f'a rendition of the {c}.',
|
| 58 |
+
# lambda c: f'a sound of the clean {c}.',
|
| 59 |
+
# lambda c: f'a sound of a large {c}.',
|
| 60 |
+
# lambda c: f'a rendition of a {c}.',
|
| 61 |
+
# lambda c: f'a sound of a nice {c}.',
|
| 62 |
+
# lambda c: f'a sound of a weird {c}.',
|
| 63 |
+
# lambda c: f'a blurry sound of a {c}.',
|
| 64 |
+
# lambda c: f'a cartoon {c}.',
|
| 65 |
+
# lambda c: f'art of a {c}.',
|
| 66 |
+
# lambda c: f'a sketch of the {c}.',
|
| 67 |
+
# lambda c: f'a embroidered {c}.',
|
| 68 |
+
# lambda c: f'a pixelated sound of a {c}.',
|
| 69 |
+
# lambda c: f'itap of the {c}.',
|
| 70 |
+
# lambda c: f'a jpeg corrupted sound of the {c}.',
|
| 71 |
+
# lambda c: f'a good sound of a {c}.',
|
| 72 |
+
# lambda c: f'a plushie {c}.',
|
| 73 |
+
# lambda c: f'a sound of the nice {c}.',
|
| 74 |
+
# lambda c: f'a sound of the small {c}.',
|
| 75 |
+
# lambda c: f'a sound of the weird {c}.',
|
| 76 |
+
# lambda c: f'the cartoon {c}.',
|
| 77 |
+
# lambda c: f'art of the {c}.',
|
| 78 |
+
# lambda c: f'a drawing of the {c}.',
|
| 79 |
+
# lambda c: f'a sound of the large {c}.',
|
| 80 |
+
# lambda c: f'a black and white sound of a {c}.',
|
| 81 |
+
# lambda c: f'the plushie {c}.',
|
| 82 |
+
# lambda c: f'a dark sound of a {c}.',
|
| 83 |
+
# lambda c: f'itap of a {c}.',
|
| 84 |
+
# lambda c: f'graffiti of the {c}.',
|
| 85 |
+
# lambda c: f'a toy {c}.',
|
| 86 |
+
# lambda c: f'itap of my {c}.',
|
| 87 |
+
# lambda c: f'a sound of a cool {c}.',
|
| 88 |
+
# lambda c: f'a sound of a small {c}.',
|
| 89 |
+
# lambda c: f'a tattoo of the {c}.',
|
| 90 |
+
# )
|
| 91 |
+
|
| 92 |
+
# a much smaller subset of above prompts
|
| 93 |
+
# from https://github.com/openai/CLIP/blob/main/notebooks/Prompt_Engineering_for_ImageNet.ipynb
|
| 94 |
+
SIMPLE_IMAGENET_TEMPLATES = (
|
| 95 |
+
lambda c: f'itap of a {c}.',
|
| 96 |
+
lambda c: f'a bad sound of the {c}.',
|
| 97 |
+
lambda c: f'a origami {c}.',
|
| 98 |
+
lambda c: f'a sound of the large {c}.',
|
| 99 |
+
lambda c: f'a {c} in a video game.',
|
| 100 |
+
lambda c: f'art of the {c}.',
|
| 101 |
+
lambda c: f'a sound of the small {c}.',
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "class_labels_indices.csv")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
CLASSNAMES = {
|
| 109 |
+
'Audioset': tuple(pd.read_csv(PATH).values[:, 2]),
|
| 110 |
+
'ESC50': (
|
| 111 |
+
'airplane', 'breathing', 'brushing teeth', 'can opening', 'car horn', 'cat', 'chainsaw', 'chirping birds',
|
| 112 |
+
'church bells', 'clapping', 'clock alarm', 'clock tick', 'coughing', 'cow', 'crackling fire', 'crickets',
|
| 113 |
+
'crow', 'crying baby', 'dog', 'door wood creaks', 'door wood knock', 'drinking sipping', 'engine', 'fireworks',
|
| 114 |
+
'footsteps', 'frog', 'glass breaking', 'hand saw', 'helicopter', 'hen', 'insects', 'keyboard typing',
|
| 115 |
+
'laughing', 'mouse click', 'pig', 'pouring water', 'rain', 'rooster', 'sea waves', 'sheep', 'siren',
|
| 116 |
+
'sneezing', 'snoring', 'thunderstorm', 'toilet flush', 'train', 'vacuum cleaner', 'washing machine',
|
| 117 |
+
'water drops', 'wind'
|
| 118 |
+
),
|
| 119 |
+
'VGGSound': (
|
| 120 |
+
'air conditioning noise', 'air horn', 'airplane', 'airplane flyby', 'alarm clock ringing',
|
| 121 |
+
'alligators, crocodiles hissing', 'ambulance siren', 'arc welding', 'baby babbling', 'baby crying',
|
| 122 |
+
'baby laughter', 'baltimore oriole calling', 'barn swallow calling', 'basketball bounce',
|
| 123 |
+
'bathroom ventilation fan running', 'beat boxing', 'bee, wasp, etc. buzzing', 'bird chirping, tweeting',
|
| 124 |
+
'bird squawking', 'bird wings flapping', 'black capped chickadee calling', 'blowtorch igniting',
|
| 125 |
+
'bouncing on trampoline', 'bowling impact', 'bull bellowing', 'canary calling', 'cap gun shooting',
|
| 126 |
+
'car engine idling', 'car engine knocking', 'car engine starting', 'car passing by', 'cat caterwauling',
|
| 127 |
+
'cat growling', 'cat hissing', 'cat meowing', 'cat purring', 'cattle mooing', 'cattle, bovinae cowbell',
|
| 128 |
+
'cell phone buzzing', 'chainsawing trees', 'cheetah chirrup', 'chicken clucking', 'chicken crowing',
|
| 129 |
+
'child singing', 'child speech, kid speaking', 'children shouting', 'chimpanzee pant-hooting',
|
| 130 |
+
'chinchilla barking', 'chipmunk chirping', 'chopping food', 'chopping wood', 'church bell ringing',
|
| 131 |
+
'civil defense siren', 'cow lowing', 'coyote howling', 'cricket chirping', 'crow cawing', 'cuckoo bird calling',
|
| 132 |
+
'cupboard opening or closing', 'cutting hair with electric trimmers', 'dinosaurs bellowing', 'disc scratching',
|
| 133 |
+
'dog barking', 'dog baying', 'dog bow-wow', 'dog growling', 'dog howling', 'dog whimpering',
|
| 134 |
+
'donkey, ass braying', 'door slamming', 'driving buses', 'driving motorcycle', 'driving snowmobile',
|
| 135 |
+
'duck quacking', 'eagle screaming', 'eating with cutlery', 'electric grinder grinding',
|
| 136 |
+
'electric shaver, electric razor shaving', 'elephant trumpeting', 'eletric blender running', 'elk bugling',
|
| 137 |
+
'engine accelerating, revving, vroom', 'female singing', 'female speech, woman speaking', 'ferret dooking',
|
| 138 |
+
'fire crackling', 'fire truck siren', 'fireworks banging', 'firing cannon', 'firing muskets',
|
| 139 |
+
'fly, housefly buzzing', 'foghorn', 'footsteps on snow', 'forging swords', 'fox barking', 'francolin calling',
|
| 140 |
+
'frog croaking', 'gibbon howling', 'goat bleating', 'golf driving', 'goose honking', 'hail',
|
| 141 |
+
'hair dryer drying', 'hammering nails', 'heart sounds, heartbeat', 'hedge trimmer running', 'helicopter',
|
| 142 |
+
'horse clip-clop', 'horse neighing', 'ice cracking', 'ice cream truck, ice cream van', 'lathe spinning',
|
| 143 |
+
'lawn mowing', 'lighting firecrackers', 'lions growling', 'lions roaring', 'lip smacking',
|
| 144 |
+
'machine gun shooting', 'magpie calling', 'male singing', 'male speech, man speaking', 'metronome',
|
| 145 |
+
'missile launch', 'mosquito buzzing', 'motorboat, speedboat acceleration', 'mouse clicking', 'mouse pattering',
|
| 146 |
+
'mouse squeaking', 'mynah bird singing', 'ocean burbling', 'opening or closing car doors',
|
| 147 |
+
'opening or closing car electric windows', 'opening or closing drawers', 'orchestra', 'otter growling',
|
| 148 |
+
'owl hooting', 'parrot talking', 'penguins braying', 'people babbling', 'people battle cry',
|
| 149 |
+
'people belly laughing', 'people booing', 'people burping', 'people cheering', 'people clapping',
|
| 150 |
+
'people coughing', 'people crowd', 'people eating', 'people eating apple', 'people eating crisps',
|
| 151 |
+
'people eating noodle', 'people farting', 'people finger snapping', 'people gargling', 'people giggling',
|
| 152 |
+
'people hiccup', 'people humming', 'people marching', 'people nose blowing', 'people running',
|
| 153 |
+
'people screaming', 'people shuffling', 'people slapping', 'people slurping', 'people sneezing',
|
| 154 |
+
'people sniggering', 'people sobbing', 'people whispering', 'people whistling', 'pheasant crowing',
|
| 155 |
+
'pig oinking', 'pigeon, dove cooing', 'planing timber', 'plastic bottle crushing', 'playing accordion',
|
| 156 |
+
'playing acoustic guitar', 'playing badminton', 'playing bagpipes', 'playing banjo', 'playing bass drum',
|
| 157 |
+
'playing bass guitar', 'playing bassoon', 'playing bongo', 'playing bugle', 'playing castanets',
|
| 158 |
+
'playing cello', 'playing clarinet', 'playing congas', 'playing cornet', 'playing cymbal', 'playing darts',
|
| 159 |
+
'playing didgeridoo', 'playing djembe', 'playing double bass', 'playing drum kit', 'playing electric guitar',
|
| 160 |
+
'playing electronic organ', 'playing erhu', 'playing flute', 'playing french horn', 'playing glockenspiel',
|
| 161 |
+
'playing gong', 'playing guiro', 'playing hammond organ', 'playing harmonica', 'playing harp',
|
| 162 |
+
'playing harpsichord', 'playing hockey', 'playing lacrosse', 'playing mandolin', 'playing marimba, xylophone',
|
| 163 |
+
'playing oboe', 'playing piano', 'playing saxophone', 'playing shofar', 'playing sitar', 'playing snare drum',
|
| 164 |
+
'playing squash', 'playing steel guitar, slide guitar', 'playing steelpan', 'playing synthesizer',
|
| 165 |
+
'playing tabla', 'playing table tennis', 'playing tambourine', 'playing tennis', 'playing theremin',
|
| 166 |
+
'playing timbales', 'playing timpani', 'playing trombone', 'playing trumpet', 'playing tuning fork',
|
| 167 |
+
'playing tympani', 'playing ukulele', 'playing vibraphone', 'playing violin, fiddle', 'playing volleyball',
|
| 168 |
+
'playing washboard', 'playing zither', 'police car (siren)', 'police radio chatter', 'popping popcorn',
|
| 169 |
+
'printer printing', 'pumping water', 'race car, auto racing', 'railroad car, train wagon', 'raining', 'rapping',
|
| 170 |
+
'reversing beeps', 'ripping paper', 'roller coaster running', 'rope skipping', 'rowboat, canoe, kayak rowing',
|
| 171 |
+
'running electric fan', 'sailing', 'scuba diving', 'sea lion barking', 'sea waves', 'sharpen knife',
|
| 172 |
+
'sheep bleating', 'shot football', 'singing bowl', 'singing choir', 'skateboarding', 'skidding', 'skiing',
|
| 173 |
+
'sliding door', 'sloshing water', 'slot machine', 'smoke detector beeping', 'snake hissing', 'snake rattling',
|
| 174 |
+
'splashing water', 'spraying water', 'squishing water', 'stream burbling', 'strike lighter', 'striking bowling',
|
| 175 |
+
'striking pool', 'subway, metro, underground', 'swimming', 'tap dancing', 'tapping guitar',
|
| 176 |
+
'telephone bell ringing', 'thunder', 'toilet flushing', 'tornado roaring', 'tractor digging', 'train horning',
|
| 177 |
+
'train wheels squealing', 'train whistling', 'turkey gobbling', 'typing on computer keyboard',
|
| 178 |
+
'typing on typewriter', 'underwater bubbling', 'using sewing machines', 'vacuum cleaner cleaning floors',
|
| 179 |
+
'vehicle horn, car horn, honking', 'volcano explosion', 'warbler chirping', 'waterfall burbling',
|
| 180 |
+
'whale calling', 'wind chime', 'wind noise', 'wind rustling leaves', 'wood thrush calling',
|
| 181 |
+
'woodpecker pecking tree', 'writing on blackboard with chalk', 'yodelling', 'zebra braying'
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
}
|
a_cls/zeroshot_cls.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from training.distributed import is_master
|
| 6 |
+
from .zero_shot import zero_shot_eval
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import wandb
|
| 10 |
+
except ImportError:
|
| 11 |
+
wandb = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def evaluate_a_cls(model, data, epoch, args, tb_writer=None):
|
| 16 |
+
metrics = {}
|
| 17 |
+
if not is_master(args):
|
| 18 |
+
return metrics
|
| 19 |
+
model.eval()
|
| 20 |
+
|
| 21 |
+
zero_shot_metrics = zero_shot_eval(model, data, epoch, args)
|
| 22 |
+
metrics.update(zero_shot_metrics)
|
| 23 |
+
|
| 24 |
+
if not metrics:
|
| 25 |
+
return metrics
|
| 26 |
+
|
| 27 |
+
logging.info(
|
| 28 |
+
f"Eval Epoch: {epoch} "
|
| 29 |
+
+ "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in metrics.items()])
|
| 30 |
+
)
|
| 31 |
+
if args.save_logs:
|
| 32 |
+
for name, val in metrics.items():
|
| 33 |
+
if tb_writer is not None:
|
| 34 |
+
tb_writer.add_scalar(f"val/a_cls/{args.val_a_cls_data[0].lower()}/{name}", val, epoch)
|
| 35 |
+
args.a_cls_output_dir = os.path.join(args.log_base_path, f'a_cls/{args.val_a_cls_data[0].lower()}')
|
| 36 |
+
os.makedirs(args.a_cls_output_dir, exist_ok=True)
|
| 37 |
+
with open(os.path.join(args.a_cls_output_dir, "results.jsonl"), "a+") as f:
|
| 38 |
+
f.write(json.dumps(metrics))
|
| 39 |
+
f.write("\n")
|
| 40 |
+
|
| 41 |
+
if args.wandb:
|
| 42 |
+
assert wandb is not None, 'Please install wandb.'
|
| 43 |
+
for name, val in metrics.items():
|
| 44 |
+
wandb.log({f"val/{name}": val, 'epoch': epoch})
|
| 45 |
+
|
| 46 |
+
return metrics
|
al_ret/data_dataloaders.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
from torch.utils.data import DataLoader
|
| 4 |
+
|
| 5 |
+
from data.build_datasets import get_data
|
| 6 |
+
from data.process_audio import get_audio_transform
|
| 7 |
+
from .dataloader_msrvtt_retrieval import MSRVTT_DataLoader
|
| 8 |
+
|
| 9 |
+
def dataloader_msrvtt_test(args, tokenizer, subset="test"):
|
| 10 |
+
msrvtt_testset = MSRVTT_DataLoader(
|
| 11 |
+
csv_path=args.val_csv,
|
| 12 |
+
features_path=args.features_path,
|
| 13 |
+
max_words=args.max_words,
|
| 14 |
+
tokenizer=tokenizer,
|
| 15 |
+
transform=get_audio_transform(args)
|
| 16 |
+
)
|
| 17 |
+
dataloader_msrvtt = DataLoader(
|
| 18 |
+
msrvtt_testset,
|
| 19 |
+
batch_size=args.batch_size_val,
|
| 20 |
+
num_workers=args.num_thread_reader,
|
| 21 |
+
shuffle=False,
|
| 22 |
+
drop_last=False,
|
| 23 |
+
)
|
| 24 |
+
return dataloader_msrvtt, len(msrvtt_testset)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
DATALOADER_DICT = {}
|
| 28 |
+
DATALOADER_DICT["msrvtt"] = {"val":dataloader_msrvtt_test, "test":None}
|
al_ret/dataloader_msrvtt_retrieval.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
from __future__ import division
|
| 3 |
+
from __future__ import unicode_literals
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import torchaudio
|
| 9 |
+
from torch.utils.data import Dataset
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
import json
|
| 14 |
+
import random
|
| 15 |
+
|
| 16 |
+
from torchvision.io import read_video
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MSRVTT_DataLoader(Dataset):
|
| 20 |
+
"""MSRVTT dataset loader."""
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
csv_path,
|
| 24 |
+
features_path,
|
| 25 |
+
tokenizer,
|
| 26 |
+
transform=77,
|
| 27 |
+
max_words=30,
|
| 28 |
+
):
|
| 29 |
+
self.data = pd.read_csv(csv_path)
|
| 30 |
+
self.features_path = features_path
|
| 31 |
+
self.max_words = max_words
|
| 32 |
+
self.tokenizer = tokenizer
|
| 33 |
+
|
| 34 |
+
# self.rawVideoExtractor = RawVideoExtractor(framerate=feature_framerate, size=image_resolution)
|
| 35 |
+
self.transform = transform
|
| 36 |
+
self.SPECIAL_TOKEN = {"CLS_TOKEN": "<|startoftext|>", "SEP_TOKEN": "<|endoftext|>",
|
| 37 |
+
"MASK_TOKEN": "[MASK]", "UNK_TOKEN": "[UNK]", "PAD_TOKEN": "[PAD]"}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def __len__(self):
|
| 42 |
+
return len(self.data)
|
| 43 |
+
|
| 44 |
+
def _get_text(self, video_id, sentence):
|
| 45 |
+
choice_video_ids = [video_id]
|
| 46 |
+
n_caption = len(choice_video_ids)
|
| 47 |
+
|
| 48 |
+
k = n_caption
|
| 49 |
+
pairs_text = np.zeros((k, self.max_words), dtype=np.long)
|
| 50 |
+
pairs_mask = np.zeros((k, self.max_words), dtype=np.long)
|
| 51 |
+
pairs_segment = np.zeros((k, self.max_words), dtype=np.long)
|
| 52 |
+
|
| 53 |
+
for i, video_id in enumerate(choice_video_ids):
|
| 54 |
+
# words = self.tokenizer.tokenize(sentence)
|
| 55 |
+
#
|
| 56 |
+
# words = [self.SPECIAL_TOKEN["CLS_TOKEN"]] + words
|
| 57 |
+
# total_length_with_CLS = self.max_words - 1
|
| 58 |
+
# if len(words) > total_length_with_CLS:
|
| 59 |
+
# words = words[:total_length_with_CLS]
|
| 60 |
+
# words = words + [self.SPECIAL_TOKEN["SEP_TOKEN"]]
|
| 61 |
+
#
|
| 62 |
+
# input_ids = self.tokenizer.convert_tokens_to_ids(words)
|
| 63 |
+
# input_mask = [1] * len(input_ids)
|
| 64 |
+
# segment_ids = [0] * len(input_ids)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
output = self.tokenizer(sentence)
|
| 68 |
+
|
| 69 |
+
input_ids = output[0].squeeze()
|
| 70 |
+
input_mask = output[1].squeeze()
|
| 71 |
+
segment_ids = [0] * len(input_ids)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
while len(input_ids) < self.max_words:
|
| 75 |
+
input_ids.append(0)
|
| 76 |
+
input_mask.append(0)
|
| 77 |
+
segment_ids.append(0)
|
| 78 |
+
assert len(input_ids) == self.max_words
|
| 79 |
+
assert len(input_mask) == self.max_words
|
| 80 |
+
assert len(segment_ids) == self.max_words
|
| 81 |
+
|
| 82 |
+
pairs_text[i] = np.array(input_ids)
|
| 83 |
+
pairs_mask[i] = np.array(input_mask)
|
| 84 |
+
pairs_segment[i] = np.array(segment_ids)
|
| 85 |
+
|
| 86 |
+
return pairs_text, pairs_mask, pairs_segment, choice_video_ids
|
| 87 |
+
|
| 88 |
+
def _get_rawvideo(self, choice_video_ids):
|
| 89 |
+
# Pair x L x T x 3 x H x W
|
| 90 |
+
audio = np.zeros((len(choice_video_ids), 3,
|
| 91 |
+
self.transform.num_mel_bins, self.transform.target_length), dtype=np.float)
|
| 92 |
+
assert len(choice_video_ids) == 1
|
| 93 |
+
for i, video_id in enumerate(choice_video_ids):
|
| 94 |
+
# Individual for YoucokII dataset, due to it video format
|
| 95 |
+
video_path = os.path.join(self.features_path, "{}.mp4".format(video_id))
|
| 96 |
+
if os.path.exists(video_path) is False:
|
| 97 |
+
video_path = video_path.replace(".mp4", ".webm")
|
| 98 |
+
|
| 99 |
+
# raw_video_data = self.rawVideoExtractor.get_video_data(video_path)
|
| 100 |
+
# _, raw_audio_data, info = read_video(video_path, pts_unit='sec')
|
| 101 |
+
# audio_data = self.transform((raw_audio_data, info['audio_fps']))
|
| 102 |
+
|
| 103 |
+
audio_data = torchaudio.load(video_path.replace('mp4', 'wav'))
|
| 104 |
+
audio_data = self.transform(audio_data)
|
| 105 |
+
# audio[i] = audio_data
|
| 106 |
+
return audio_data
|
| 107 |
+
|
| 108 |
+
def __getitem__(self, idx):
|
| 109 |
+
video_id = self.data['video_id'].values[idx]
|
| 110 |
+
sentence = self.data['sentence'].values[idx]
|
| 111 |
+
|
| 112 |
+
pairs_text, pairs_mask, pairs_segment, choice_video_ids = self._get_text(video_id, sentence)
|
| 113 |
+
audio_data = self._get_rawvideo(choice_video_ids)
|
| 114 |
+
return audio_data, pairs_text, pairs_mask
|
al_ret/datasets.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os.path
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
from torch.utils.data import Dataset
|
| 9 |
+
from data.build_datasets import DataInfo
|
| 10 |
+
from open_clip import get_input_dtype, get_tokenizer
|
| 11 |
+
from open_clip.factory import HF_HUB_PREFIX
|
| 12 |
+
from data.process_audio import get_audio_transform, torchaudio_loader
|
| 13 |
+
|
| 14 |
+
class Audiocaps_dataset(Dataset):
|
| 15 |
+
def __init__(self, data_path, transform, loader, tokenizer):
|
| 16 |
+
super(Audiocaps_dataset, self).__init__()
|
| 17 |
+
self.audio_root = data_path
|
| 18 |
+
raw_meta = pd.read_csv(f'{self.audio_root}/audiocaps_test.tsv', delimiter='\t').values
|
| 19 |
+
audio_ids = list(set(raw_meta[:, 1].tolist()))
|
| 20 |
+
captions = {}
|
| 21 |
+
for i in raw_meta:
|
| 22 |
+
if captions.get(i[1], None) is None:
|
| 23 |
+
captions[i[1]] = [i[2]]
|
| 24 |
+
else:
|
| 25 |
+
captions[i[1]] = captions[i[1]] + [i[2]]
|
| 26 |
+
# captions = {i[:1][0]: i[1:].tolist() for i in raw_meta}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
self.sample_len = 0
|
| 30 |
+
self.sentences_dict = {}
|
| 31 |
+
self.cut_off_points = []
|
| 32 |
+
for audio_id in audio_ids:
|
| 33 |
+
assert audio_id in captions
|
| 34 |
+
for cap in captions[audio_id]:
|
| 35 |
+
cap_txt = cap
|
| 36 |
+
self.sentences_dict[len(self.sentences_dict)] = (audio_id[10:], cap_txt)
|
| 37 |
+
self.cut_off_points.append(len(self.sentences_dict))
|
| 38 |
+
|
| 39 |
+
self.multi_sentence_per_audio = True # !!! important tag for eval
|
| 40 |
+
if self.multi_sentence_per_audio:
|
| 41 |
+
# if self.subset == "val" or self.subset == "test":
|
| 42 |
+
self.sentence_num = len(self.sentences_dict)
|
| 43 |
+
self.audio_num = len(audio_ids)
|
| 44 |
+
assert len(self.cut_off_points) == self.audio_num
|
| 45 |
+
print("Sentence number: {}".format(self.sentence_num))
|
| 46 |
+
print("Video number: {}".format(self.audio_num))
|
| 47 |
+
|
| 48 |
+
self.sample_len = len(self.sentences_dict)
|
| 49 |
+
|
| 50 |
+
self.transform = transform
|
| 51 |
+
self.torchaudio_loader = loader
|
| 52 |
+
self.tokenizer = tokenizer
|
| 53 |
+
|
| 54 |
+
def __len__(self):
|
| 55 |
+
return self.sample_len
|
| 56 |
+
|
| 57 |
+
def __getitem__(self, idx):
|
| 58 |
+
audiocap_id, caption = self.sentences_dict[idx]
|
| 59 |
+
|
| 60 |
+
audio_path = os.path.join(self.audio_root, audiocap_id)
|
| 61 |
+
audio = self.torchaudio_loader(audio_path)
|
| 62 |
+
audio_data = self.transform(audio)
|
| 63 |
+
|
| 64 |
+
input_ids, attention_mask = self.tokenizer(caption)
|
| 65 |
+
return audio_data, input_ids.squeeze(), attention_mask.squeeze()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class Clotho_dataset(Dataset):
|
| 69 |
+
def __init__(self, data_path, transform, loader, tokenizer):
|
| 70 |
+
super(Clotho_dataset, self).__init__()
|
| 71 |
+
self.audio_root = data_path
|
| 72 |
+
raw_meta = pd.read_csv(f'{self.audio_root}/CLOTHO_retrieval_dataset/clotho_captions_evaluation.csv').values
|
| 73 |
+
audio_ids = raw_meta[:, 0].tolist()
|
| 74 |
+
captions = {i[:1][0]: i[1:].tolist() for i in raw_meta}
|
| 75 |
+
# self.meta = pd.DataFrame(np.vstack([np.vstack([raw_meta[:, 0], raw_meta[:, i]]).T for i in range(1, 6)]),
|
| 76 |
+
# columns=['uniq_id', 'text'])
|
| 77 |
+
|
| 78 |
+
self.sample_len = 0
|
| 79 |
+
self.sentences_dict = {}
|
| 80 |
+
self.cut_off_points = []
|
| 81 |
+
for audio_id in audio_ids:
|
| 82 |
+
assert audio_id in captions
|
| 83 |
+
for cap in captions[audio_id]:
|
| 84 |
+
cap_txt = cap
|
| 85 |
+
self.sentences_dict[len(self.sentences_dict)] = (audio_id, cap_txt)
|
| 86 |
+
self.cut_off_points.append(len(self.sentences_dict))
|
| 87 |
+
|
| 88 |
+
self.multi_sentence_per_audio = True # !!! important tag for eval
|
| 89 |
+
if self.multi_sentence_per_audio:
|
| 90 |
+
# if self.subset == "val" or self.subset == "test":
|
| 91 |
+
self.sentence_num = len(self.sentences_dict)
|
| 92 |
+
self.audio_num = len(audio_ids)
|
| 93 |
+
assert len(self.cut_off_points) == self.audio_num
|
| 94 |
+
print("Sentence number: {}".format(self.sentence_num))
|
| 95 |
+
print("Video number: {}".format(self.audio_num))
|
| 96 |
+
|
| 97 |
+
self.sample_len = len(self.sentences_dict)
|
| 98 |
+
|
| 99 |
+
self.transform = transform
|
| 100 |
+
self.torchaudio_loader = loader
|
| 101 |
+
self.tokenizer = tokenizer
|
| 102 |
+
|
| 103 |
+
def __len__(self):
|
| 104 |
+
return self.sample_len
|
| 105 |
+
|
| 106 |
+
def __getitem__(self, idx):
|
| 107 |
+
audiocap_id, caption = self.sentences_dict[idx]
|
| 108 |
+
# audiocap_id = self.meta['uniq_id'][idx]
|
| 109 |
+
audio_path = os.path.join(self.audio_root, f'evaluation/{audiocap_id}')
|
| 110 |
+
audio = self.torchaudio_loader(audio_path)
|
| 111 |
+
audio_data = self.transform(audio)
|
| 112 |
+
|
| 113 |
+
# caption = self.meta['text'][idx]
|
| 114 |
+
input_ids, attention_mask = self.tokenizer(caption)
|
| 115 |
+
return audio_data, input_ids.squeeze(), attention_mask.squeeze()
|
| 116 |
+
|
| 117 |
+
def get_audio_dataset(args):
|
| 118 |
+
data_path = args.audio_data_path
|
| 119 |
+
transform = get_audio_transform(args)
|
| 120 |
+
tokenizer = get_tokenizer(HF_HUB_PREFIX+args.model, cache_dir=args.cache_dir)
|
| 121 |
+
|
| 122 |
+
if args.val_al_ret_data.lower() == 'audiocaps':
|
| 123 |
+
dataset = Audiocaps_dataset(data_path, transform=transform, loader=torchaudio_loader, tokenizer=tokenizer)
|
| 124 |
+
elif args.val_al_ret_data.lower() == 'clotho':
|
| 125 |
+
dataset = Clotho_dataset(data_path, transform=transform, loader=torchaudio_loader, tokenizer=tokenizer)
|
| 126 |
+
else:
|
| 127 |
+
raise ValueError(f'unsupport dataset {args.val_al_ret_data}')
|
| 128 |
+
|
| 129 |
+
dataloader = torch.utils.data.DataLoader(
|
| 130 |
+
dataset,
|
| 131 |
+
batch_size=args.batch_size,
|
| 132 |
+
num_workers=args.workers,
|
| 133 |
+
shuffle=False,
|
| 134 |
+
drop_last=False,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
return dataloader
|
al_ret/metrics.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
from __future__ import division
|
| 3 |
+
from __future__ import unicode_literals
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
def compute_metrics(x):
|
| 10 |
+
sx = np.sort(-x, axis=1)
|
| 11 |
+
d = np.diag(-x)
|
| 12 |
+
d = d[:, np.newaxis]
|
| 13 |
+
ind = sx - d
|
| 14 |
+
ind = np.where(ind == 0)
|
| 15 |
+
ind = ind[1]
|
| 16 |
+
metrics = {}
|
| 17 |
+
metrics['R1'] = float(np.sum(ind == 0)) * 100 / len(ind)
|
| 18 |
+
metrics['R5'] = float(np.sum(ind < 5)) * 100 / len(ind)
|
| 19 |
+
metrics['R10'] = float(np.sum(ind < 10)) * 100 / len(ind)
|
| 20 |
+
metrics['MR'] = np.median(ind) + 1
|
| 21 |
+
metrics["MedianR"] = metrics['MR']
|
| 22 |
+
metrics["MeanR"] = np.mean(ind) + 1
|
| 23 |
+
# metrics["cols"] = [int(i) for i in list(ind)]
|
| 24 |
+
return metrics
|
| 25 |
+
|
| 26 |
+
def print_computed_metrics(metrics):
|
| 27 |
+
r1 = metrics['R1']
|
| 28 |
+
r5 = metrics['R5']
|
| 29 |
+
r10 = metrics['R10']
|
| 30 |
+
mr = metrics['MR']
|
| 31 |
+
print('R@1: {:.4f} - R@5: {:.4f} - R@10: {:.4f} - Median R: {}'.format(r1, r5, r10, mr))
|
| 32 |
+
|
| 33 |
+
# below two functions directly come from: https://github.com/Deferf/Experiments
|
| 34 |
+
def tensor_text_to_video_metrics(sim_tensor, top_k = [1,5,10]):
|
| 35 |
+
if not torch.is_tensor(sim_tensor):
|
| 36 |
+
sim_tensor = torch.tensor(sim_tensor)
|
| 37 |
+
|
| 38 |
+
# Permute sim_tensor so it represents a sequence of text-video similarity matrices.
|
| 39 |
+
# Then obtain the double argsort to position the rank on the diagonal
|
| 40 |
+
stacked_sim_matrices = sim_tensor.permute(1, 0, 2)
|
| 41 |
+
first_argsort = torch.argsort(stacked_sim_matrices, dim = -1, descending= True)
|
| 42 |
+
second_argsort = torch.argsort(first_argsort, dim = -1, descending= False)
|
| 43 |
+
|
| 44 |
+
# Extracts ranks i.e diagonals
|
| 45 |
+
ranks = torch.flatten(torch.diagonal(second_argsort, dim1 = 1, dim2 = 2))
|
| 46 |
+
|
| 47 |
+
# Now we need to extract valid ranks, as some belong to inf padding values
|
| 48 |
+
permuted_original_data = torch.flatten(torch.diagonal(sim_tensor, dim1 = 0, dim2 = 2))
|
| 49 |
+
mask = ~ torch.logical_or(torch.isinf(permuted_original_data), torch.isnan(permuted_original_data))
|
| 50 |
+
valid_ranks = ranks[mask]
|
| 51 |
+
# A quick dimension check validates our results, there may be other correctness tests pending
|
| 52 |
+
# Such as dot product localization, but that is for other time.
|
| 53 |
+
#assert int(valid_ranks.shape[0]) == sum([len(text_dict[k]) for k in text_dict])
|
| 54 |
+
if not torch.is_tensor(valid_ranks):
|
| 55 |
+
valid_ranks = torch.tensor(valid_ranks)
|
| 56 |
+
results = {f"R{k}": float(torch.sum(valid_ranks < k) * 100 / len(valid_ranks)) for k in top_k}
|
| 57 |
+
results["MedianR"] = float(torch.median(valid_ranks + 1))
|
| 58 |
+
results["MeanR"] = float(np.mean(valid_ranks.numpy() + 1))
|
| 59 |
+
results["Std_Rank"] = float(np.std(valid_ranks.numpy() + 1))
|
| 60 |
+
results['MR'] = results["MedianR"]
|
| 61 |
+
return results
|
| 62 |
+
|
| 63 |
+
def tensor_video_to_text_sim(sim_tensor):
|
| 64 |
+
if not torch.is_tensor(sim_tensor):
|
| 65 |
+
sim_tensor = torch.tensor(sim_tensor)
|
| 66 |
+
# Code to avoid nans
|
| 67 |
+
sim_tensor[sim_tensor != sim_tensor] = float('-inf')
|
| 68 |
+
# Forms a similarity matrix for use with rank at k
|
| 69 |
+
values, _ = torch.max(sim_tensor, dim=1, keepdim=True)
|
| 70 |
+
return torch.squeeze(values).T
|
al_ret/precision.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from contextlib import suppress
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_autocast(precision):
|
| 6 |
+
if precision == 'amp':
|
| 7 |
+
return torch.cuda.amp.autocast
|
| 8 |
+
elif precision == 'amp_bfloat16' or precision == 'amp_bf16':
|
| 9 |
+
# amp_bfloat16 is more stable than amp float16 for clip training
|
| 10 |
+
return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16)
|
| 11 |
+
else:
|
| 12 |
+
return suppress
|
al_ret/retrieval.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from training.distributed import is_master
|
| 9 |
+
from .zero_shot import zero_shot_eval
|
| 10 |
+
from .util import parallel_apply
|
| 11 |
+
from .metrics import compute_metrics, tensor_text_to_video_metrics, tensor_video_to_text_sim
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
try:
|
| 14 |
+
import wandb
|
| 15 |
+
except ImportError:
|
| 16 |
+
wandb = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
#
|
| 20 |
+
# def evaluate_al_ret(model, data, epoch, args, tb_writer=None):
|
| 21 |
+
# metrics = {}
|
| 22 |
+
# if not is_master(args):
|
| 23 |
+
# return metrics
|
| 24 |
+
# model.eval()
|
| 25 |
+
#
|
| 26 |
+
# zero_shot_metrics = zero_shot_eval(model, data, epoch, args)
|
| 27 |
+
# metrics.update(zero_shot_metrics)
|
| 28 |
+
#
|
| 29 |
+
# if not metrics:
|
| 30 |
+
# return metrics
|
| 31 |
+
#
|
| 32 |
+
# logging.info(
|
| 33 |
+
# f"Eval Epoch: {epoch} "
|
| 34 |
+
# + "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in metrics.items()])
|
| 35 |
+
# )
|
| 36 |
+
#
|
| 37 |
+
# if args.save_logs:
|
| 38 |
+
# for name, val in metrics.items():
|
| 39 |
+
# if tb_writer is not None:
|
| 40 |
+
# tb_writer.add_scalar(f"val/al_ret/{name}", val, epoch)
|
| 41 |
+
# args.al_ret_output_dir = os.path.join(args.log_base_path, 'al_ret')
|
| 42 |
+
# os.makedirs(args.al_ret_output_dir, exist_ok=True)
|
| 43 |
+
# with open(os.path.join(args.al_ret_output_dir, "results.jsonl"), "a+") as f:
|
| 44 |
+
# f.write(json.dumps(metrics))
|
| 45 |
+
# f.write("\n")
|
| 46 |
+
#
|
| 47 |
+
# if args.wandb:
|
| 48 |
+
# assert wandb is not None, 'Please install wandb.'
|
| 49 |
+
# for name, val in metrics.items():
|
| 50 |
+
# wandb.log({f"val/{name}": val, 'epoch': epoch})
|
| 51 |
+
#
|
| 52 |
+
# return metrics
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _run_on_single_gpu(model,
|
| 57 |
+
# batch_list_t, batch_list_v,
|
| 58 |
+
batch_sequence_output_list, batch_visual_output_list):
|
| 59 |
+
sim_matrix = []
|
| 60 |
+
for idx1 in range(len(batch_sequence_output_list)):
|
| 61 |
+
# input_mask, segment_ids, *_tmp = b1
|
| 62 |
+
sequence_output = batch_sequence_output_list[idx1]
|
| 63 |
+
each_row = []
|
| 64 |
+
for idx2 in range(len(batch_visual_output_list)):
|
| 65 |
+
# video_mask, *_tmp = b2
|
| 66 |
+
visual_output = batch_visual_output_list[idx2]
|
| 67 |
+
# b1b2_logits, *_tmp = model.get_similarity_logits(sequence_output, visual_output, input_mask, video_mask,
|
| 68 |
+
# loose_type=model.loose_type)
|
| 69 |
+
# logging.info(f"{model.logit_scale.device}, {visual_output.device}, {sequence_output.device}")
|
| 70 |
+
b1b2_logits = model.logit_scale * sequence_output @ visual_output.T
|
| 71 |
+
# print(model.logit_scale.device, visual_output.device, sequence_output.device)
|
| 72 |
+
# logging.info(f"{b1b2_logits.shape}, {b1b2_logits.device}")
|
| 73 |
+
b1b2_logits = b1b2_logits.cpu().detach().numpy()
|
| 74 |
+
each_row.append(b1b2_logits)
|
| 75 |
+
each_row = np.concatenate(tuple(each_row), axis=-1)
|
| 76 |
+
sim_matrix.append(each_row)
|
| 77 |
+
return sim_matrix
|
| 78 |
+
|
| 79 |
+
def evaluate_al_ret(model, data, epoch, args, tb_writer=None):
|
| 80 |
+
if is_master(args) and (args.val_frequency and ((epoch % args.val_frequency) == 0 or epoch == args.epochs)):
|
| 81 |
+
# print(data)
|
| 82 |
+
val_al_ret_data = list(data.keys())
|
| 83 |
+
# print(val_vl_ret_data)
|
| 84 |
+
assert len(val_al_ret_data) == 1
|
| 85 |
+
val_al_ret_data = val_al_ret_data[0]
|
| 86 |
+
test_dataloader = data[val_al_ret_data]
|
| 87 |
+
# print(len(test_dataloader))
|
| 88 |
+
# print(len(test_dataloader))
|
| 89 |
+
# print(len(test_dataloader))
|
| 90 |
+
# print(len(test_dataloader))
|
| 91 |
+
device = model.device
|
| 92 |
+
n_gpu = torch.cuda.device_count()
|
| 93 |
+
logging.info(f"\nEval Epoch: {epoch}, eval Audio-Text Retrieval under {val_al_ret_data.upper()} test data")
|
| 94 |
+
if hasattr(model, 'module'):
|
| 95 |
+
model = model.module.to(device)
|
| 96 |
+
else:
|
| 97 |
+
model = model.to(device)
|
| 98 |
+
# #################################################################
|
| 99 |
+
## below variables are used to multi-sentences retrieval
|
| 100 |
+
# multi_sentence_: important tag for eval
|
| 101 |
+
# cut_off_points: used to tag the label when calculate the metric
|
| 102 |
+
# sentence_num: used to cut the sentence representation
|
| 103 |
+
# video_num: used to cut the video representation
|
| 104 |
+
# #################################################################
|
| 105 |
+
multi_sentence_ = False
|
| 106 |
+
cut_off_points_, sentence_num_, video_num_ = [], -1, -1
|
| 107 |
+
if hasattr(test_dataloader.dataset, 'multi_sentence_per_audio') and test_dataloader.dataset.multi_sentence_per_audio:
|
| 108 |
+
# if False:
|
| 109 |
+
multi_sentence_ = True
|
| 110 |
+
cut_off_points_ = test_dataloader.dataset.cut_off_points
|
| 111 |
+
sentence_num_ = test_dataloader.dataset.sentence_num
|
| 112 |
+
video_num_ = test_dataloader.dataset.audio_num
|
| 113 |
+
cut_off_points_ = [itm - 1 for itm in cut_off_points_]
|
| 114 |
+
|
| 115 |
+
if multi_sentence_:
|
| 116 |
+
print("Eval under the multi-sentence per audio clip setting.")
|
| 117 |
+
print("sentence num: {}, video num: {}".format(sentence_num_, video_num_))
|
| 118 |
+
logging.info("Eval under the multi-sentence per audio clip setting.")
|
| 119 |
+
logging.info("sentence num: {}, video num: {}".format(sentence_num_, video_num_))
|
| 120 |
+
|
| 121 |
+
model.eval()
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
# batch_list_t = []
|
| 124 |
+
# batch_list_v = []
|
| 125 |
+
batch_sequence_output_list, batch_visual_output_list = [], []
|
| 126 |
+
total_video_num = 0
|
| 127 |
+
|
| 128 |
+
# ----------------------------
|
| 129 |
+
# 1. cache the features
|
| 130 |
+
# ----------------------------
|
| 131 |
+
for bid, batch in enumerate(test_dataloader):
|
| 132 |
+
# batch = tuple(t.to(device) for t in batch)
|
| 133 |
+
video, input_ids, attention_mask = batch
|
| 134 |
+
# print(input_ids.shape, video.shape, video.dtype)
|
| 135 |
+
input_ids = input_ids.squeeze().to(device)
|
| 136 |
+
attention_mask = attention_mask.squeeze().to(device)
|
| 137 |
+
# video = video.squeeze().permute(0, 2, 1, 3, 4).float().to(device)
|
| 138 |
+
video = video.float().to(device)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# print(input_ids.shape, video.shape, video.dtype)
|
| 143 |
+
# print(input_ids.shape, video.shape)
|
| 144 |
+
if multi_sentence_:
|
| 145 |
+
# multi-sentences retrieval means: one clip has two or more descriptions.
|
| 146 |
+
b, *_t = video.shape
|
| 147 |
+
sequence_output = model.encode_text(input_ids, attention_mask)
|
| 148 |
+
# logging.info(f'multi: {sequence_output.shape}')
|
| 149 |
+
# sequence_output = model.get_sequence_output(input_ids, segment_ids, input_mask)
|
| 150 |
+
batch_sequence_output_list.append(sequence_output)
|
| 151 |
+
# batch_list_t.append((input_mask, segment_ids,))
|
| 152 |
+
# 0 16
|
| 153 |
+
s_, e_ = total_video_num, total_video_num + b
|
| 154 |
+
filter_inds = [itm - s_ for itm in cut_off_points_ if itm >= s_ and itm < e_] # cut_off_points_ [0 4 9 14]
|
| 155 |
+
|
| 156 |
+
if len(filter_inds) > 0:
|
| 157 |
+
# video, video_mask = video[filter_inds, ...], video_mask[filter_inds, ...]
|
| 158 |
+
# print('before', video.shape)
|
| 159 |
+
video = video[filter_inds, ...]
|
| 160 |
+
# print('after', video.shape)
|
| 161 |
+
# visual_output = model.get_visual_output(video, video_mask)
|
| 162 |
+
visual_output = model.encode_image(video)
|
| 163 |
+
batch_visual_output_list.append(visual_output)
|
| 164 |
+
# batch_list_v.append((video_mask,))
|
| 165 |
+
total_video_num += b
|
| 166 |
+
else:
|
| 167 |
+
sequence_output = model.encode_text(input_ids, attention_mask)
|
| 168 |
+
visual_output = model.encode_image(video)
|
| 169 |
+
# sequence_output, visual_output = model.get_sequence_visual_output(input_ids, segment_ids, input_mask, video, video_mask)
|
| 170 |
+
|
| 171 |
+
batch_sequence_output_list.append(sequence_output)
|
| 172 |
+
# batch_list_t.append((input_mask, segment_ids,))
|
| 173 |
+
|
| 174 |
+
batch_visual_output_list.append(visual_output)
|
| 175 |
+
# batch_list_v.append((video_mask,))
|
| 176 |
+
|
| 177 |
+
print(f"Process {val_al_ret_data.upper()}: {bid}/{len(test_dataloader)}\r", end='')
|
| 178 |
+
# ----------------------------------
|
| 179 |
+
# 2. calculate the similarity
|
| 180 |
+
# ----------------------------------
|
| 181 |
+
n_gpu = torch.cuda.device_count()
|
| 182 |
+
if n_gpu > 1:
|
| 183 |
+
# print('n_gpu > 1')
|
| 184 |
+
device_ids = list(range(n_gpu))
|
| 185 |
+
# print('device_ids', device_ids)
|
| 186 |
+
batch_t_output_splits = []
|
| 187 |
+
batch_v_output_splits = []
|
| 188 |
+
bacth_len = len(batch_sequence_output_list)
|
| 189 |
+
# print(bacth_len)
|
| 190 |
+
split_len = (bacth_len + n_gpu - 1) // n_gpu
|
| 191 |
+
for dev_id in device_ids:
|
| 192 |
+
s_, e_ = dev_id * split_len, (dev_id + 1) * split_len
|
| 193 |
+
if dev_id == 0:
|
| 194 |
+
|
| 195 |
+
batch_t_output_splits.append(batch_sequence_output_list[s_:e_])
|
| 196 |
+
batch_v_output_splits.append(batch_visual_output_list)
|
| 197 |
+
# print(len(batch_sequence_output_list[s_:e_]), len(batch_visual_output_list))
|
| 198 |
+
else:
|
| 199 |
+
devc = torch.device('cuda:{}'.format(str(dev_id)))
|
| 200 |
+
|
| 201 |
+
devc_batch_list = [b.to(devc) for b in batch_sequence_output_list[s_:e_]]
|
| 202 |
+
batch_t_output_splits.append(devc_batch_list)
|
| 203 |
+
devc_batch_list = [b.to(devc) for b in batch_visual_output_list]
|
| 204 |
+
batch_v_output_splits.append(devc_batch_list)
|
| 205 |
+
# print(len(devc_batch_list), len(devc_batch_list))
|
| 206 |
+
parameters_tuple_list = [(
|
| 207 |
+
batch_t_output_splits[dev_id], batch_v_output_splits[dev_id]) for dev_id in device_ids]
|
| 208 |
+
parallel_outputs = parallel_apply(_run_on_single_gpu, model, parameters_tuple_list, device_ids)
|
| 209 |
+
sim_matrix = []
|
| 210 |
+
for idx in range(len(parallel_outputs)):
|
| 211 |
+
sim_matrix += parallel_outputs[idx]
|
| 212 |
+
sim_matrix = np.concatenate(tuple(sim_matrix), axis=0)
|
| 213 |
+
else:
|
| 214 |
+
sim_matrix = _run_on_single_gpu(model,
|
| 215 |
+
# batch_list_t, batch_list_v,
|
| 216 |
+
batch_sequence_output_list, batch_visual_output_list)
|
| 217 |
+
sim_matrix = np.concatenate(tuple(sim_matrix), axis=0)
|
| 218 |
+
#####################################################################
|
| 219 |
+
if multi_sentence_:
|
| 220 |
+
|
| 221 |
+
logging.info(f"{val_al_ret_data.upper()} before reshape, sim matrix size: {sim_matrix.shape}")
|
| 222 |
+
cut_off_points2len_ = [itm + 1 for itm in cut_off_points_]
|
| 223 |
+
max_length = max([e_-s_ for s_, e_ in zip([0]+cut_off_points2len_[:-1], cut_off_points2len_)])
|
| 224 |
+
sim_matrix_new = []
|
| 225 |
+
for s_, e_ in zip([0] + cut_off_points2len_[:-1], cut_off_points2len_):
|
| 226 |
+
sim_matrix_new.append(np.concatenate((sim_matrix[s_:e_],
|
| 227 |
+
np.full((max_length-e_+s_, sim_matrix.shape[1]), -np.inf)), axis=0))
|
| 228 |
+
sim_matrix = np.stack(tuple(sim_matrix_new), axis=0)
|
| 229 |
+
logging.info(f"{val_al_ret_data.upper()} after reshape, sim matrix size: {sim_matrix.shape}")
|
| 230 |
+
|
| 231 |
+
tv_metrics = tensor_text_to_video_metrics(sim_matrix)
|
| 232 |
+
# vt_metrics = compute_metrics(tensor_video_to_text_sim(sim_matrix))
|
| 233 |
+
else:
|
| 234 |
+
logging.info(f"{val_al_ret_data.upper()} sim matrix size: {sim_matrix.shape[0]}, {sim_matrix.shape[1]}")
|
| 235 |
+
t2v_sim_matrix = torch.from_numpy(sim_matrix).cuda()
|
| 236 |
+
# t2v_sim_matrix = t2v_sim_matrix * F.softmax(t2v_sim_matrix*10, dim=0) * len(t2v_sim_matrix)
|
| 237 |
+
tv_metrics = compute_metrics(t2v_sim_matrix.cpu().numpy())
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# vt_metrics = compute_metrics(t2v_sim_matrix.T.cpu().numpy())
|
| 241 |
+
|
| 242 |
+
logging.info('\t Length-T: {}, Length-V:{}'.format(len(sim_matrix), len(sim_matrix[0])))
|
| 243 |
+
|
| 244 |
+
logging.info(f"{val_al_ret_data.upper()} Text-to-Audio:")
|
| 245 |
+
logging.info('\t>>> R@1: {:.1f} - R@5: {:.1f} - R@10: {:.1f} - Median R: {:.1f} - Mean R: {:.1f}'.
|
| 246 |
+
format(tv_metrics['R1'], tv_metrics['R5'], tv_metrics['R10'], tv_metrics['MR'], tv_metrics['MeanR']))
|
| 247 |
+
# logging.info(f"{val_al_ret_data.upper()} Text-to-Audio:")
|
| 248 |
+
# logging.info('\t>>> V2T$R@1: {:.1f} - V2T$R@5: {:.1f} - V2T$R@10: {:.1f} - V2T$Median R: {:.1f} - V2T$Mean R: {:.1f}'.
|
| 249 |
+
# format(vt_metrics['R1'], vt_metrics['R5'], vt_metrics['R10'], vt_metrics['MR'], vt_metrics['MeanR']))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if args.save_logs:
|
| 253 |
+
for name, val in tv_metrics.items():
|
| 254 |
+
if tb_writer is not None:
|
| 255 |
+
tb_writer.add_scalar(f"val/al_ret/{val_al_ret_data}/t2a/{name}", val, epoch)
|
| 256 |
+
# for name, val in vt_metrics.items():
|
| 257 |
+
# if tb_writer is not None:
|
| 258 |
+
# tb_writer.add_scalar(f"val/al_ret/{val_al_ret_data}/v2t/{name}", val, epoch)
|
| 259 |
+
|
| 260 |
+
args.al_ret_output_dir = os.path.join(args.log_base_path, f'al_ret/{val_al_ret_data}')
|
| 261 |
+
os.makedirs(args.al_ret_output_dir, exist_ok=True)
|
| 262 |
+
with open(os.path.join(args.al_ret_output_dir, "results.jsonl"), "a+") as f:
|
| 263 |
+
f.write(json.dumps({'t2a': tv_metrics}))
|
| 264 |
+
f.write("\n")
|
| 265 |
+
# f.write(json.dumps({'v2t': vt_metrics}))
|
| 266 |
+
# f.write("\n")
|
al_ret/util.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import threading
|
| 4 |
+
from torch._utils import ExceptionWrapper
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
def get_a_var(obj):
|
| 8 |
+
if isinstance(obj, torch.Tensor):
|
| 9 |
+
return obj
|
| 10 |
+
|
| 11 |
+
if isinstance(obj, list) or isinstance(obj, tuple):
|
| 12 |
+
for result in map(get_a_var, obj):
|
| 13 |
+
if isinstance(result, torch.Tensor):
|
| 14 |
+
return result
|
| 15 |
+
if isinstance(obj, dict):
|
| 16 |
+
for result in map(get_a_var, obj.items()):
|
| 17 |
+
if isinstance(result, torch.Tensor):
|
| 18 |
+
return result
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
def parallel_apply(fct, model, inputs, device_ids):
|
| 22 |
+
modules = nn.parallel.replicate(model, device_ids)
|
| 23 |
+
assert len(modules) == len(inputs)
|
| 24 |
+
lock = threading.Lock()
|
| 25 |
+
results = {}
|
| 26 |
+
grad_enabled = torch.is_grad_enabled()
|
| 27 |
+
|
| 28 |
+
def _worker(i, module, input):
|
| 29 |
+
torch.set_grad_enabled(grad_enabled)
|
| 30 |
+
device = get_a_var(input).get_device()
|
| 31 |
+
try:
|
| 32 |
+
with torch.cuda.device(device):
|
| 33 |
+
# this also avoids accidental slicing of `input` if it is a Tensor
|
| 34 |
+
if not isinstance(input, (list, tuple)):
|
| 35 |
+
input = (input,)
|
| 36 |
+
output = fct(module, *input)
|
| 37 |
+
with lock:
|
| 38 |
+
results[i] = output
|
| 39 |
+
except Exception:
|
| 40 |
+
with lock:
|
| 41 |
+
results[i] = ExceptionWrapper(where="in replica {} on device {}".format(i, device))
|
| 42 |
+
|
| 43 |
+
if len(modules) > 1:
|
| 44 |
+
threads = [threading.Thread(target=_worker, args=(i, module, input))
|
| 45 |
+
for i, (module, input) in enumerate(zip(modules, inputs))]
|
| 46 |
+
|
| 47 |
+
for thread in threads:
|
| 48 |
+
thread.start()
|
| 49 |
+
for thread in threads:
|
| 50 |
+
thread.join()
|
| 51 |
+
else:
|
| 52 |
+
_worker(0, modules[0], inputs[0])
|
| 53 |
+
|
| 54 |
+
outputs = []
|
| 55 |
+
for i in range(len(inputs)):
|
| 56 |
+
output = results[i]
|
| 57 |
+
if isinstance(output, ExceptionWrapper):
|
| 58 |
+
output.reraise()
|
| 59 |
+
outputs.append(output)
|
| 60 |
+
return outputs
|
| 61 |
+
|
| 62 |
+
def get_logger(filename=None):
|
| 63 |
+
logger = logging.getLogger('logger')
|
| 64 |
+
logger.setLevel(logging.DEBUG)
|
| 65 |
+
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
|
| 66 |
+
datefmt='%m/%d/%Y %H:%M:%S',
|
| 67 |
+
level=logging.INFO)
|
| 68 |
+
if filename is not None:
|
| 69 |
+
handler = logging.FileHandler(filename)
|
| 70 |
+
handler.setLevel(logging.DEBUG)
|
| 71 |
+
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))
|
| 72 |
+
logging.getLogger().addHandler(handler)
|
| 73 |
+
return logger
|
al_ret/zero_shot.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
from open_clip import get_input_dtype, get_tokenizer
|
| 9 |
+
from open_clip.factory import HF_HUB_PREFIX
|
| 10 |
+
from .precision import get_autocast
|
| 11 |
+
|
| 12 |
+
def compute_metrics(x):
|
| 13 |
+
sx = np.sort(-x, axis=1)
|
| 14 |
+
d = np.diag(-x)
|
| 15 |
+
d = d[:, np.newaxis]
|
| 16 |
+
ind = sx - d
|
| 17 |
+
ind = np.where(ind == 0)
|
| 18 |
+
ind = ind[1]
|
| 19 |
+
metrics = {}
|
| 20 |
+
metrics['R1'] = float(np.sum(ind == 0)) * 100 / len(ind)
|
| 21 |
+
metrics['R5'] = float(np.sum(ind < 5)) * 100 / len(ind)
|
| 22 |
+
metrics['R10'] = float(np.sum(ind < 10)) * 100 / len(ind)
|
| 23 |
+
metrics['MR'] = np.median(ind) + 1
|
| 24 |
+
metrics["MedianR"] = metrics['MR']
|
| 25 |
+
metrics["MeanR"] = np.mean(ind) + 1
|
| 26 |
+
# metrics["cols"] = [int(i) for i in list(ind)]
|
| 27 |
+
return metrics
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _run_on_single_gpu(model, batch_sequence_output_list, batch_visual_output_list):
|
| 31 |
+
sim_matrix = []
|
| 32 |
+
logit_scale = model.logit_scale.exp()
|
| 33 |
+
for idx1, sequence_output in enumerate(batch_sequence_output_list):
|
| 34 |
+
each_row = []
|
| 35 |
+
for idx2, visual_output in enumerate(batch_visual_output_list):
|
| 36 |
+
b1b2_logits = logit_scale * torch.matmul(sequence_output, visual_output.t())
|
| 37 |
+
b1b2_logits = b1b2_logits.cpu().detach().numpy()
|
| 38 |
+
each_row.append(b1b2_logits)
|
| 39 |
+
each_row = np.concatenate(tuple(each_row), axis=-1)
|
| 40 |
+
sim_matrix.append(each_row)
|
| 41 |
+
return sim_matrix
|
| 42 |
+
|
| 43 |
+
def run(model, dataloader, args):
|
| 44 |
+
autocast = get_autocast(args.precision)
|
| 45 |
+
input_dtype = get_input_dtype(args.precision)
|
| 46 |
+
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
sequence_output_list, visual_output_list = [], []
|
| 49 |
+
for images, input_ids, attention_mask in tqdm(dataloader, unit_scale=args.batch_size):
|
| 50 |
+
images = images.to(device=args.device, dtype=input_dtype)
|
| 51 |
+
images = images.unsqueeze(2)
|
| 52 |
+
input_ids = input_ids.squeeze().to(args.device)
|
| 53 |
+
attention_mask = attention_mask.squeeze().to(args.device)
|
| 54 |
+
|
| 55 |
+
with autocast():
|
| 56 |
+
# predict
|
| 57 |
+
sequence_output = model.encode_text(input_ids, attention_mask)
|
| 58 |
+
visual_output = model.encode_image(images)
|
| 59 |
+
sequence_output_list.append(sequence_output)
|
| 60 |
+
visual_output_list.append(visual_output)
|
| 61 |
+
sim_matrix = _run_on_single_gpu(model, sequence_output_list, visual_output_list)
|
| 62 |
+
sim_matrix = np.concatenate(tuple(sim_matrix), axis=0)
|
| 63 |
+
return sim_matrix
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def zero_shot_eval(model, data, epoch, args):
|
| 67 |
+
temp_val_al_ret_data = args.val_al_ret_data
|
| 68 |
+
args.val_al_ret_data = list(data.keys())
|
| 69 |
+
assert len(args.val_al_ret_data) == 1
|
| 70 |
+
args.val_al_ret_data = args.val_al_ret_data[0]
|
| 71 |
+
|
| 72 |
+
if args.val_al_ret_data not in data:
|
| 73 |
+
return {}
|
| 74 |
+
if args.zeroshot_frequency == 0:
|
| 75 |
+
return {}
|
| 76 |
+
if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs:
|
| 77 |
+
return {}
|
| 78 |
+
if args.distributed and not args.horovod:
|
| 79 |
+
model = model.module
|
| 80 |
+
|
| 81 |
+
logging.info(f'Starting zero-shot {args.val_al_ret_data.upper()}.')
|
| 82 |
+
|
| 83 |
+
results = {}
|
| 84 |
+
if args.val_al_ret_data in data:
|
| 85 |
+
logit_matrix = run(model, data[args.val_al_ret_data].dataloader, args)
|
| 86 |
+
results = compute_metrics(logit_matrix)
|
| 87 |
+
|
| 88 |
+
logging.info(f'Finished zero-shot {args.val_al_ret_data.upper()}.')
|
| 89 |
+
|
| 90 |
+
args.val_al_ret_data = temp_val_al_ret_data
|
| 91 |
+
return results
|
assets/audio/0.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:38aff33c1d6e68dfa0bd310d1e4cff10df4ac3642b3cc96637fab2a0e74b64a9
|
| 3 |
+
size 327788
|
assets/audio/1.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25400620506fbc099ee78fe4d31379a218a264ddcfcfe658e4ba9c2255fc6c01
|
| 3 |
+
size 327788
|
assets/demo.png
ADDED
|
Git LFS Details
|
assets/depth/0.png
ADDED
|
Git LFS Details
|
assets/depth/1.png
ADDED
|
Git LFS Details
|
assets/emergency.jpg
ADDED
|
Git LFS Details
|
assets/iclr_dataset_sample.jpg
ADDED
|
Git LFS Details
|
assets/image/0.jpg
ADDED
|
assets/image/1.jpg
ADDED
|
assets/languagebind.jpg
ADDED
|
Git LFS Details
|
assets/languagebind_frame.jpg
ADDED
|
Git LFS Details
|
assets/languagebind_result.jpg
ADDED
|
Git LFS Details
|
assets/languge_result.jpg
ADDED
|
Git LFS Details
|
assets/logo.jpg
ADDED
|
Git LFS Details
|
assets/logo_languagebind.png
ADDED
|
Git LFS Details
|
assets/res1.jpg
ADDED
|
assets/res2.jpg
ADDED
|
assets/result1.jpg
ADDED
|
Git LFS Details
|
assets/sota.jpg
ADDED
|
Git LFS Details
|
assets/thermal/0.jpg
ADDED
|
assets/thermal/1.jpg
ADDED
|
assets/video/0.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d92bdf4ad672f6bc82a72c886c3c8bc7e799866bbe41b184d640a6c5f21a075
|
| 3 |
+
size 661405
|
assets/video/1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5a6dcc0228ffcadaaac4441476f02d3109c3f005af56aeb609a0ee1f66128b80
|
| 3 |
+
size 590954
|
d_cls/cp_zero_shot_metadata.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
OPENAI_IMAGENET_TEMPLATES = (
|
| 6 |
+
lambda c: f'a bad photo of a {c}.',
|
| 7 |
+
lambda c: f'a photo of many {c}.',
|
| 8 |
+
lambda c: f'a sculpture of a {c}.',
|
| 9 |
+
lambda c: f'a photo of the hard to see {c}.',
|
| 10 |
+
lambda c: f'a low resolution photo of the {c}.',
|
| 11 |
+
lambda c: f'a rendering of a {c}.',
|
| 12 |
+
lambda c: f'graffiti of a {c}.',
|
| 13 |
+
lambda c: f'a bad photo of the {c}.',
|
| 14 |
+
lambda c: f'a cropped photo of the {c}.',
|
| 15 |
+
lambda c: f'a tattoo of a {c}.',
|
| 16 |
+
lambda c: f'the embroidered {c}.',
|
| 17 |
+
lambda c: f'a photo of a hard to see {c}.',
|
| 18 |
+
lambda c: f'a bright photo of a {c}.',
|
| 19 |
+
lambda c: f'a photo of a clean {c}.',
|
| 20 |
+
lambda c: f'a photo of a dirty {c}.',
|
| 21 |
+
lambda c: f'a dark photo of the {c}.',
|
| 22 |
+
lambda c: f'a drawing of a {c}.',
|
| 23 |
+
lambda c: f'a photo of my {c}.',
|
| 24 |
+
lambda c: f'the plastic {c}.',
|
| 25 |
+
lambda c: f'a photo of the cool {c}.',
|
| 26 |
+
lambda c: f'a close-up photo of a {c}.',
|
| 27 |
+
lambda c: f'a black and white photo of the {c}.',
|
| 28 |
+
lambda c: f'a painting of the {c}.',
|
| 29 |
+
lambda c: f'a painting of a {c}.',
|
| 30 |
+
lambda c: f'a pixelated photo of the {c}.',
|
| 31 |
+
lambda c: f'a sculpture of the {c}.',
|
| 32 |
+
lambda c: f'a bright photo of the {c}.',
|
| 33 |
+
lambda c: f'a cropped photo of a {c}.',
|
| 34 |
+
lambda c: f'a plastic {c}.',
|
| 35 |
+
lambda c: f'a photo of the dirty {c}.',
|
| 36 |
+
lambda c: f'a jpeg corrupted photo of a {c}.',
|
| 37 |
+
lambda c: f'a blurry photo of the {c}.',
|
| 38 |
+
lambda c: f'a photo of the {c}.',
|
| 39 |
+
lambda c: f'a good photo of the {c}.',
|
| 40 |
+
lambda c: f'a rendering of the {c}.',
|
| 41 |
+
lambda c: f'a {c} in a video game.',
|
| 42 |
+
lambda c: f'a photo of one {c}.',
|
| 43 |
+
lambda c: f'a doodle of a {c}.',
|
| 44 |
+
lambda c: f'a close-up photo of the {c}.',
|
| 45 |
+
lambda c: f'a photo of a {c}.',
|
| 46 |
+
lambda c: f'the origami {c}.',
|
| 47 |
+
lambda c: f'the {c} in a video game.',
|
| 48 |
+
lambda c: f'a sketch of a {c}.',
|
| 49 |
+
lambda c: f'a doodle of the {c}.',
|
| 50 |
+
lambda c: f'a origami {c}.',
|
| 51 |
+
lambda c: f'a low resolution photo of a {c}.',
|
| 52 |
+
lambda c: f'the toy {c}.',
|
| 53 |
+
lambda c: f'a rendition of the {c}.',
|
| 54 |
+
lambda c: f'a photo of the clean {c}.',
|
| 55 |
+
lambda c: f'a photo of a large {c}.',
|
| 56 |
+
lambda c: f'a rendition of a {c}.',
|
| 57 |
+
lambda c: f'a photo of a nice {c}.',
|
| 58 |
+
lambda c: f'a photo of a weird {c}.',
|
| 59 |
+
lambda c: f'a blurry photo of a {c}.',
|
| 60 |
+
lambda c: f'a cartoon {c}.',
|
| 61 |
+
lambda c: f'art of a {c}.',
|
| 62 |
+
lambda c: f'a sketch of the {c}.',
|
| 63 |
+
lambda c: f'a embroidered {c}.',
|
| 64 |
+
lambda c: f'a pixelated photo of a {c}.',
|
| 65 |
+
lambda c: f'itap of the {c}.',
|
| 66 |
+
lambda c: f'a jpeg corrupted photo of the {c}.',
|
| 67 |
+
lambda c: f'a good photo of a {c}.',
|
| 68 |
+
lambda c: f'a plushie {c}.',
|
| 69 |
+
lambda c: f'a photo of the nice {c}.',
|
| 70 |
+
lambda c: f'a photo of the small {c}.',
|
| 71 |
+
lambda c: f'a photo of the weird {c}.',
|
| 72 |
+
lambda c: f'the cartoon {c}.',
|
| 73 |
+
lambda c: f'art of the {c}.',
|
| 74 |
+
lambda c: f'a drawing of the {c}.',
|
| 75 |
+
lambda c: f'a photo of the large {c}.',
|
| 76 |
+
lambda c: f'a black and white photo of a {c}.',
|
| 77 |
+
lambda c: f'the plushie {c}.',
|
| 78 |
+
lambda c: f'a dark photo of a {c}.',
|
| 79 |
+
lambda c: f'itap of a {c}.',
|
| 80 |
+
lambda c: f'graffiti of the {c}.',
|
| 81 |
+
lambda c: f'a toy {c}.',
|
| 82 |
+
lambda c: f'itap of my {c}.',
|
| 83 |
+
lambda c: f'a photo of a cool {c}.',
|
| 84 |
+
lambda c: f'a photo of a small {c}.',
|
| 85 |
+
lambda c: f'a tattoo of the {c}.',
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# a much smaller subset of above prompts
|
| 90 |
+
# from https://github.com/openai/CLIP/blob/main/notebooks/Prompt_Engineering_for_ImageNet.ipynb
|
| 91 |
+
SIMPLE_IMAGENET_TEMPLATES = (
|
| 92 |
+
lambda c: f'itap of a {c}.',
|
| 93 |
+
lambda c: f'a bad photo of the {c}.',
|
| 94 |
+
lambda c: f'a origami {c}.',
|
| 95 |
+
lambda c: f'a photo of the large {c}.',
|
| 96 |
+
lambda c: f'a {c} in a video game.',
|
| 97 |
+
lambda c: f'art of the {c}.',
|
| 98 |
+
lambda c: f'a photo of the small {c}.',
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
IMAGENET_CLASSNAMES = (
|
| 103 |
+
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
CLASSNAMES = {
|
| 108 |
+
'NYUV2': (
|
| 109 |
+
"bathroom", "bedroom", "bookstore", "classroom", "dining room",
|
| 110 |
+
"home office", "kitchen", "living room", "office", "others"
|
| 111 |
+
),
|
| 112 |
+
'SUNRGBD': (
|
| 113 |
+
"bathroom", "bedroom", "classroom", "computer room", "conference room", "corridor", "dining area",
|
| 114 |
+
"dining room", "discussion area", "furniture store", "home office", "kitchen", "lab", "lecture theatre",
|
| 115 |
+
"library", "living room", "office", "rest space", "study space"
|
| 116 |
+
),
|
| 117 |
+
}
|