sonithoiningombam commited on
Commit
2ad935f
·
verified ·
1 Parent(s): 3bac3f1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/fairseq/examples/MMPT/.gitignore +139 -0
  2. data/fairseq/examples/MMPT/CONFIG.md +41 -0
  3. data/fairseq/examples/MMPT/DATASET.md +34 -0
  4. data/fairseq/examples/MMPT/README.md +166 -0
  5. data/fairseq/examples/MMPT/endtask.md +41 -0
  6. data/fairseq/examples/MMPT/locallaunch.py +148 -0
  7. data/fairseq/examples/MMPT/mmpt/__init__.py +12 -0
  8. data/fairseq/examples/MMPT/mmpt/evaluators/__init__.py +13 -0
  9. data/fairseq/examples/MMPT/mmpt/evaluators/predictor.py +595 -0
  10. data/fairseq/examples/MMPT/mmpt/utils/__init__.py +68 -0
  11. data/fairseq/examples/MMPT/mmpt/utils/load_config.py +81 -0
  12. data/fairseq/examples/MMPT/mmpt/utils/shardedtensor.py +46 -0
  13. data/fairseq/examples/MMPT/pretraining.md +29 -0
  14. data/fairseq/examples/MMPT/projects/mfmmlm.yaml +59 -0
  15. data/fairseq/examples/MMPT/projects/mtm/mmfusionmtm.yaml +19 -0
  16. data/fairseq/examples/MMPT/projects/mtm/vlm.yaml +8 -0
  17. data/fairseq/examples/MMPT/projects/mtm/vlm/coin.yaml +47 -0
  18. data/fairseq/examples/MMPT/projects/mtm/vlm/crosstask.yaml +53 -0
  19. data/fairseq/examples/MMPT/projects/mtm/vlm/how2.yaml +55 -0
  20. data/fairseq/examples/MMPT/projects/mtm/vlm/test_coin.yaml +31 -0
  21. data/fairseq/examples/MMPT/projects/mtm/vlm/test_crosstask.yaml +38 -0
  22. data/fairseq/examples/MMPT/projects/mtm/vlm/test_crosstask_zs.yaml +38 -0
  23. data/fairseq/examples/MMPT/projects/mtm/vlm/test_vtt.yaml +29 -0
  24. data/fairseq/examples/MMPT/projects/mtm/vlm/test_vttqa.yaml +29 -0
  25. data/fairseq/examples/MMPT/projects/mtm/vlm/test_youcook.yaml +31 -0
  26. data/fairseq/examples/MMPT/projects/mtm/vlm/test_youcookcap.yaml +32 -0
  27. data/fairseq/examples/MMPT/projects/mtm/vlm/vtt.yaml +49 -0
  28. data/fairseq/examples/MMPT/projects/mtm/vlm/vttqa.yaml +47 -0
  29. data/fairseq/examples/MMPT/projects/mtm/vlm/youcook.yaml +47 -0
  30. data/fairseq/examples/MMPT/projects/mtm/vlm/youcookcap.yaml +45 -0
  31. data/fairseq/examples/MMPT/projects/retri/videoclip.yaml +10 -0
  32. data/fairseq/examples/MMPT/projects/retri/videoclip/coin_videoclip.yaml +49 -0
  33. data/fairseq/examples/MMPT/projects/retri/videoclip/crosstask_videoclip.yaml +55 -0
  34. data/fairseq/examples/MMPT/projects/retri/videoclip/how2.yaml +65 -0
  35. data/fairseq/examples/MMPT/projects/retri/videoclip/test_coin_videoclip.yaml +33 -0
  36. data/fairseq/examples/MMPT/projects/retri/videoclip/test_coin_zs.yaml +33 -0
  37. data/fairseq/examples/MMPT/projects/retri/videoclip/test_crosstask_videoclip.yaml +40 -0
  38. data/fairseq/examples/MMPT/projects/retri/videoclip/test_crosstask_zs_videoclip.yaml +40 -0
  39. data/fairseq/examples/MMPT/projects/retri/videoclip/test_didemo_zs.yaml +31 -0
  40. data/fairseq/examples/MMPT/projects/retri/videoclip/test_vtt_videoclip.yaml +31 -0
  41. data/fairseq/examples/MMPT/projects/retri/videoclip/test_vtt_zs.yaml +31 -0
  42. data/fairseq/examples/MMPT/projects/retri/videoclip/test_vttqa_videoclip.yaml +31 -0
  43. data/fairseq/examples/MMPT/projects/retri/videoclip/test_vttqa_zs.yaml +31 -0
  44. data/fairseq/examples/MMPT/projects/retri/videoclip/test_youcook_videoclip.yaml +33 -0
  45. data/fairseq/examples/MMPT/projects/retri/videoclip/test_youcook_zs.yaml +33 -0
  46. data/fairseq/examples/MMPT/projects/retri/videoclip/vtt_videoclip.yaml +51 -0
  47. data/fairseq/examples/MMPT/projects/retri/videoclip/vttqa_videoclip.yaml +49 -0
  48. data/fairseq/examples/MMPT/projects/retri/videoclip/youcook_videoclip.yaml +49 -0
  49. data/fairseq/examples/MMPT/projects/retri/videoretri.yaml +51 -0
  50. data/fairseq/examples/MMPT/projects/task/coin.yaml +25 -0
data/fairseq/examples/MMPT/.gitignore ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+ runs
131
+ data
132
+ pretrained_models
133
+ projects/mmfusion_*
134
+ log_test
135
+ third-party
136
+ python_log
137
+ slurm_snapshot_code
138
+ lightning_logs
139
+ demos
data/fairseq/examples/MMPT/CONFIG.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Config Files Explained
2
+
3
+ Taking `projects/mfmmlm.yaml` for example, which run pretraining using masked frame model (MFM) and masked language model (MLM) on a single BERT:
4
+
5
+ ```yaml
6
+ project_dir: mfmmlm # specify the project dir for this baseline.
7
+ run_task:
8
+ - how2.yaml # run pretraining on how2 when launching `projects/taskmfmmlm.yaml`
9
+ - [vtt.yaml, vttcap.yaml, vttqa.yaml, youcook.yaml, youcookcap.yaml, crosstask.yaml, coin.yaml] # run fine-tuning tasks.
10
+ base_dir: task # a global template folder to specify each training task.
11
+ task_group:
12
+ pretrain: # section for pretraining. Most baselines differs in this section.
13
+ task_list:
14
+ - how2.yaml # reconfig `projects/task/how2.yaml`
15
+ dataset:
16
+ aligner: MFMMLMAligner # overwrite the aligner for MFMMLM training task.
17
+ model:
18
+ model_cls: MMFusionMFMMLM # overwrite the model, which constructs negative examples for MFM on-the-fly.
19
+ loss:
20
+ loss_cls: MFMMLM # overwrite the loss as MFMMLM, which combines MFM and MLM together.
21
+ fairseq: # all fairseq args can be expecified under this name.
22
+ dataset:
23
+ batch_size: 128
24
+ finetune: # section for fine-tuning tasks, we don't need to change anything here mostly since we want to see how pretraining can contribute to finetuning.
25
+ task_list: # specify the list of downstream tasks, e.g., copy `projects/task/vtt.yaml` to `projects/mfmmlm`.
26
+ - vtt.yaml
27
+ - vttqa.yaml
28
+ - youcook.yaml
29
+ - youcookcap.yaml
30
+ - crosstask.yaml
31
+ - coin.yaml
32
+ test: # section for testing.
33
+ task_list:
34
+ - test_vtt.yaml
35
+ - test_vttqa.yaml
36
+ - test_youcook.yaml
37
+ - test_youcookcap.yaml
38
+ - test_crosstask.yaml
39
+ - test_crosstask_zs.yaml
40
+ - test_coin.yaml
41
+ ```
data/fairseq/examples/MMPT/DATASET.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset
2
+
3
+ We understand video data are challenging to download and process. For videos, we provide our preprocessing scripts under `scripts/video_feature_extractor` (deeply adapted from `https://github.com/antoine77340/video_feature_extractor`); for text, we pre-tokenizing scripts under `scripts/text_token_extractor`.
4
+
5
+ ### S3D Feature Extraction
6
+ We use pre-trained [S3D](https://github.com/antoine77340/S3D_HowTo100M) for video feature extraction. Please place the models as `pretrained_models/s3d_dict.npy` and `pretrained_models/s3d_howto100m.pth`.
7
+
8
+ We implement a `PathBuilder` to automatically track video ids, source video paths to their feature locations (you may need `conda install -c anaconda pandas`). Decoding may need `pip install ffmpeg-python`.
9
+
10
+ ### Howto100M
11
+ [Howto100M](https://www.di.ens.fr/willow/research/howto100m/) is a large-scale video pre-training datasets. You may download videos by yourself and run preprocessing of our scripts.
12
+
13
+ Several key differences of our preprocessing from existing papers: (1) we use `raw_caption.json` instead of `caption.json` to have pure self-supervision on text (`caption.json` has manual removal of stop words); (2) we remove partially duplicated texts that are originally designed for real-time readability (see `mmpt/processors/dedupprocessor.py`); (3) then we shard video/text features using `SharedTensor` in `mmpt/utils/shardedtensor.py` for fast loading during training (faster than `h5py`).
14
+
15
+ #### Steps
16
+ ##### video
17
+ To extract video features: edit and run `bash scripts/video_feature_extractor/how2/s3d.sh`. (consider to run this on multiple machines; by default, we store features in fp16 to save space and also for faster training).
18
+
19
+ Split available video ids as `data/how2/how2_s3d_train.lst` and `data/how2/how2_s3d_val.lst`.
20
+
21
+ Lastly, pack video features into `ShardedTensor` using `python scripts/video_feature_extractor/shard_feature.py`.
22
+
23
+ ##### text
24
+ Clean captions using `python -m mmpt.processors.dedupprocessor`.
25
+
26
+ Tokenize dedupped captions `data/how2/raw_caption_dedup.pkl` into sharded numpy arrays:
27
+ ```
28
+ python scripts/text_token_extractor/pretokenization.py scripts/text_token_extractor/configs/bert-base-uncased.yaml
29
+ ```
30
+
31
+ ### Youcook, MSRVTT etc.
32
+ We use the version of Youcook and MSRVTT come with Howto100M and MILNCE. Please download the data to `data/youcook` and `data/msrvtt` accordingly, you can also check `projects/task/youcook.yaml` and `projects/task/vtt.yaml` etc. in details.
33
+ We extract features for Youcook, MSRVTT similar to the first step of Howto100M but we read text from meta data directly and perform on-the-fly tokenization.
34
+
data/fairseq/examples/MMPT/README.md ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VideoCLIP and VLM
2
+
3
+ You just find this toolkit for multimodal video understanding! It contains implementation of two recent multi-modal video understanding papers [VideoCLIP](https://arxiv.org/pdf/2109.14084.pdf) (EMNLP, 2021) and [VLM](https://aclanthology.org/2021.findings-acl.370.pdf) (ACL Findings, 2021), along with high-performance toolkits that are typically lacking in existing codebase. The toolkit is desigend to contain generic performance-tuned components that can be potentially adapted to other frameworks (we initially use fairseq).
4
+
5
+ VideoCLIP is a contrastive learning model for zero-shot transfer to retrieval/classification/sequence labeling style tasks.
6
+
7
+ <img src="videoclip.png" width="350" class="center">
8
+
9
+ VLM is a masked language model style pre-training using only one encoder with masked modality model (MMM) for retrieval/generation/sequence labeling style tasks.
10
+
11
+ <img src="vlm.png" width="350" class="center">
12
+
13
+ ### News
14
+ [Oct. 2021] Initial release of implementation for the following papers:
15
+ [VideoCLIP: Contrastive Pre-training for Zero-shot Video-Text Understanding](https://arxiv.org/pdf/2109.14084.pdf) (Xu et. al., EMNLP 2021)
16
+ [VLM: Task-agnostic Video-Language Model Pre-training for Video Understanding](https://aclanthology.org/2021.findings-acl.370.pdf) (Xu et. al., ACL Findings 2021)
17
+
18
+
19
+ ### Installation
20
+ We aim to minimize the dependency of this repo on other packages.
21
+ We use fairseq as the main trainer (no models/datasets dependency on fairseq. We will support other trainer in future):
22
+ ```
23
+ git clone https://github.com/pytorch/fairseq
24
+ cd fairseq
25
+ pip install -e . # also optionally follow fairseq README for apex installation for fp16 training.
26
+ export MKL_THREADING_LAYER=GNU # fairseq may need this for numpy.
27
+ ```
28
+
29
+ Then install this toolkit:
30
+ ```
31
+ cd examples/MMPT # MMPT can be in any folder, not necessarily under fairseq/examples.
32
+ pip install -e .
33
+ ```
34
+
35
+ The code is developed under Python=3.8.8, Pytorch=1.8, cuda=11.0 with fairseq=1.0.0a0+af0389f and tested under Python=3.8.8 pytorch=1.9 cuda=11.0 fairseq=1.0.0a0+8e7bc73 during code release.
36
+ Most models require `transformers==3.4` for API compatibility `pip install transformers==3.4`.
37
+ In addition, some downstream tasks may need `conda install pandas`.
38
+
39
+
40
+ ### Usage
41
+ #### Download Checkpoints
42
+ We use pre-trained [S3D](https://github.com/antoine77340/S3D_HowTo100M) for video feature extraction. Please place the models as `pretrained_models/s3d_dict.npy` and `pretrained_models/s3d_howto100m.pth`.
43
+
44
+ Download VideoCLIP checkpoint `https://dl.fbaipublicfiles.com/MMPT/retri/videoclip/checkpoint_best.pt` to `runs/retri/videoclip` or VLM checkpoint `https://dl.fbaipublicfiles.com/MMPT/mtm/vlm/checkpoint_best.pt` to `runs/mtm/vlm`.
45
+
46
+ #### Demo of Inference
47
+ run `python locallaunch.py projects/retri/videoclip.yaml --dryrun` to get all `.yaml`s for VideoCLIP.
48
+
49
+ ```python
50
+ import torch
51
+
52
+ from mmpt.models import MMPTModel
53
+
54
+
55
+ model, tokenizer, aligner = MMPTModel.from_pretrained(
56
+ "projects/retri/videoclip/how2.yaml")
57
+
58
+ model.eval()
59
+
60
+
61
+ # B, T, FPS, H, W, C (VideoCLIP is trained on 30 fps of s3d)
62
+ video_frames = torch.randn(1, 2, 30, 224, 224, 3)
63
+ caps, cmasks = aligner._build_text_seq(
64
+ tokenizer("some text", add_special_tokens=False)["input_ids"]
65
+ )
66
+
67
+ caps, cmasks = caps[None, :], cmasks[None, :] # bsz=1
68
+
69
+ with torch.no_grad():
70
+ output = model(video_frames, caps, cmasks, return_score=True)
71
+ print(output["score"]) # dot-product
72
+ ```
73
+
74
+ #### Data Preparation
75
+ See [dataset](DATASET.md) for each dataset.
76
+
77
+ #### Global Config for Training Pipeline
78
+ We organize a global config file for a training/testing pipeline under projects (see a detailed [explanation](CONFIG.md)). For example, VideoCLIP in `projects/retri/videoclip.yaml` and VLM is in `projects/mtm/vlm.yaml`.
79
+
80
+ We wrap all cmds into `locallaunch.py` and `mmpt_cli/localjob.py`. You can check concrete cmds by `--dryrun` and then drop it for actual run.
81
+
82
+ First, run `python locallaunch.py projects/retri/videoclip.yaml --dryrun` will generate configs for all configs of pre-training, zero-shot evaluation, fine-tuning and testing, for VideoCLIP under `projects/retri/videoclip`.
83
+
84
+ Then each (either training or evaluation) process will be configed by a concrete config file (we save all complex arguments into the concrete config file for reproducibility, including fairseq args). For example, run zero-shot evaluation on youcook,
85
+ ```
86
+ python locallaunch.py projects/retri/videoclip/test_youcook_zs.yaml --jobtype local_predict # zero-shot evaluation.
87
+ python locallaunch.py projects/retri/videoclip/youcook_videoclip.yaml --jobtype local_single --dryrun # fine-tuning: use --dryrun to check cmds and drop it to make an actual run; local_small will run on two gpus (as in paper).
88
+ python locallaunch.py projects/retri/videoclip/test_youcook_videoclip.yaml --jobtype local_predict # testing on fine-tuned model.
89
+ ```
90
+
91
+ Pretraining can be run as:
92
+ ```
93
+ python locallaunch.py projects/retri/videoclip/how2.yaml --jobtype local_single --dryrun # check then drop dryrun; paper is ran on local_big as 8 gpus.
94
+ ```
95
+ You may need to change `--jobtype`, check/extend `LocalJob` in `mmpt_cli/localjob.py` for multi-gpu/multi-node pre-training.
96
+
97
+ The detailed instructions of pretraining and fine-tuning can be found at [pretraining instruction](pretraining.md) and [finetuning instruction](endtask.md).
98
+
99
+
100
+ ### Development
101
+ Several components of this toolkit can be re-used for future research (and also our ongoing research).
102
+
103
+ #### Framework Wrapper
104
+ We currently only support fairseq, but most components can be easily fit into other frameworks like huggingface. This repo is a `--user-dir` of fairseq with fairseq wrapper. For example, `mmpt/tasks` includes a `FairseqMMTTask`, which manages `mmpt/datasets` with `FairseqDataset`, `mmpt/models` with `FairseqModel`, `mmpt/losses` with `FairseqCriterion`.
105
+
106
+ #### Processors
107
+ **Multi**modal research introduces the complexity on modality alignment from different input sources to losses. Inspired by [MMF](https://github.com/facebookresearch/mmf), this toolkit leverages `mmpt/processors` to handle various needs of data preprocessing and loading, **alleviating** the needs of multiple `torch.data.utils.Dataset` (that can be tricky for ablation study).
108
+ Processors can also be decoupled from `torch.data.utils.Dataset` for offline preprocessing instead of on-the-fly data preprocessing.
109
+
110
+ We decouple a `mmpt.MMDataset` as 3 types of processors: `MetaProcessor`, `VideoProcessor`, `TextProcessor` and `Aligner`. They can be configed in `dataset` field of a config file (e.g., see `projects/task/how2.yaml`).
111
+ `MetaProcessor` is used to load the meta data about a dataset, aka, all video_ids of how2 dataset.
112
+ `VideoProcessor` is used to load the video features about a dataset. For example, S3D features for each second of a video.
113
+ `TextProcessor` is used to load the text (feature). For example, BERT pre-tokenized text clips for how2 dataset (with `start`s, `end`s of timestamps and `cap` for `token_ids`).
114
+ `Aligner` is the core class for different baselines that prepares the training data. For example, sampling a clip, masking tokens for MLM, etc.
115
+
116
+ #### Performance-tuned Components
117
+ To speed up pre-training, this toolkit uses sharded features stored in mmaped numpy, backed by `ShardedTensor` in `mmpt/utils/shardedtensor.py` (adopted from MARGE paper). This reduces the loads of IO for multi-GPU training without loading all features for a video into the memory each time and `ShardedTensor` ensure features are stored in continuous disk space for near random access. This is used for both How2 video features and texts in `mmpt/processors/how2processor.py`.
118
+
119
+
120
+ ### Citation
121
+ If this codebase is useful for your work, please cite the following papers:
122
+
123
+ ```BibTeX
124
+ @inproceedings{xu-etal-2021-videoclip,
125
+ title = "{VideoCLIP}: Contrastive Pre-training for\\Zero-shot Video-Text Understanding",
126
+ author = "Xu, Hu and
127
+ Ghosh, Gargi and
128
+ Huang, Po-Yao and
129
+ Okhonko, Dmytro and
130
+ Aghajanyan, Armen and
131
+ Metze, Florian and
132
+ Zettlemoyer, Luke and
133
+ Feichtenhofer, Christoph",
134
+ booktitle = "Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
135
+ month = nov,
136
+ year = "2021",
137
+ address = "Online",
138
+ publisher = "Association for Computational Linguistics",
139
+ }
140
+
141
+ @inproceedings{xu-etal-2021-vlm,
142
+ title = "{VLM}: Task-agnostic Video-Language Model Pre-training for Video Understanding",
143
+ author = "Xu, Hu and
144
+ Ghosh, Gargi and
145
+ Huang, Po-Yao and
146
+ Arora, Prahal and
147
+ Aminzadeh, Masoumeh and
148
+ Feichtenhofer, Christoph and
149
+ Metze, Florian and
150
+ Zettlemoyer, Luke",
151
+ booktitle = "Findings of the Association for Computational Linguistics: ACL-IJCNLP 2021",
152
+ month = aug,
153
+ year = "2021",
154
+ address = "Online",
155
+ publisher = "Association for Computational Linguistics",
156
+ url = "https://aclanthology.org/2021.findings-acl.370",
157
+ doi = "10.18653/v1/2021.findings-acl.370",
158
+ pages = "4227--4239",
159
+ }
160
+ ```
161
+
162
+ ### Bug Reports
163
+ This repo is in its initial stage, welcome bug reports to huxu@fb.com
164
+
165
+ ### Copyright
166
+ The majority of Multimodal Pre-training (MMPT) is licensed under CC-BY-NC, however portions of the project are available under separate license terms: Evaluation Codes/Models: Howto100M and HuggingFace Transformers are licensed under the Apache2.0 license; COIN and NLG-eval are licensed under the MIT license; CrossTask is licensed under the BSD-3; DiDeMo is licensed under the BSD-2 license.
data/fairseq/examples/MMPT/endtask.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Zero-shot Transfer and Finetuning
2
+
3
+ (If you are new to the ideas of `mmpt.processors`, see [README](README.md) first.)
4
+ All finetuning datasets (specifically `processors`) are defined in `mmpt.processors.dsprocessor`.
5
+ Given the complexity of different types of finetuning tasks, each task may have their own meta/video/text/aligner processors and `mmpt/evaluators/{Predictor,Metric}`.
6
+
7
+ ### Tasks
8
+
9
+ Currently, we support 5 end datasets: `MSRVTT`, `Youcook`, `COIN`, `Crosstask` and `DiDeMo` with the following tasks:
10
+ text-video retrieval: `MSRVTT`, `Youcook`, `DiDeMo`;
11
+ video captioning: `Youcook`;
12
+ Video Question and Answering: `MSRVTT-QA`.
13
+
14
+ To add your own dataset, you can specify the corresponding processors and config them in the `dataset` field of a config file, such as `projects/task/vtt.yaml`.
15
+
16
+ ### Zero-shot Transfer (no Training)
17
+ Zero-shot transfer will run the pre-trained model (e.g., VideoCLIP) directly on testing data. Configs with pattern: `projects/task/*_zs_*.yaml` are dedicated for zero-shot transfer.
18
+
19
+ ### Fine-tuning
20
+
21
+ The training of a downstream task is similar to pretraining, execept you may need to specify the `restore_file` in `fairseq.checkpoint` and reset optimizers, see `projects/task/ft.yaml` that is included by `projects/task/vtt.yaml`.
22
+
23
+ We typically do finetuning on 2 gpus (`local_small`).
24
+
25
+ ### Testing
26
+ For each finetuning dataset, you may need to specify a testing config, similar to `projects/task/test_vtt.yaml`.
27
+
28
+ We define `mmpt.evaluators.Predictor` for different types of prediction. For example, `MSRVTT` and `Youcook` are video-retrieval tasks and expecting to use `RetrievalPredictor`. You may need to define your new type of predictors and specify that in `predictor` field of a testing config.
29
+
30
+ Each task may also have their own metric for evaluation. This can be created in `mmpt.evaluators.Metric` and specified in the `metric` field of a testing config.
31
+
32
+ Launching a testing is as simple as training by specifying the path of a testing config:
33
+ ```python locallaunch.py projects/mfmmlm/test_vtt.yaml```
34
+ Testing will be launched locally by default since prediction is computationally less expensive.
35
+
36
+ ### Third-party Libraries
37
+ We list the following finetuning tasks that require third-party libraries.
38
+
39
+ Youcook captioning: `https://github.com/Maluuba/nlg-eval`
40
+
41
+ CrossTask: `https://github.com/DmZhukov/CrossTask`'s `dp` under `third-party/CrossTask` (`python setup.py build_ext --inplace`)
data/fairseq/examples/MMPT/locallaunch.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import argparse
6
+ import os
7
+
8
+ from omegaconf import OmegaConf
9
+
10
+ from mmpt.utils import recursive_config, overwrite_dir
11
+ from mmpt_cli.localjob import LocalJob
12
+
13
+
14
+ class JobLauncher(object):
15
+ JOB_CONFIG = {
16
+ "local": LocalJob,
17
+ }
18
+
19
+ def __init__(self, yaml_file):
20
+ self.yaml_file = yaml_file
21
+ job_key = "local"
22
+
23
+ if yaml_file.endswith(".yaml"):
24
+ config = recursive_config(yaml_file)
25
+ if config.task_type is not None:
26
+ job_key = config.task_type.split("_")[0]
27
+ else:
28
+ raise ValueError("unknown extension of job file:", yaml_file)
29
+ self.job_key = job_key
30
+
31
+ def __call__(self, job_type=None, dryrun=False):
32
+ if job_type is not None:
33
+ self.job_key = job_type.split("_")[0]
34
+ print("[JobLauncher] job_key", self.job_key)
35
+ job = JobLauncher.JOB_CONFIG[self.job_key](
36
+ self.yaml_file, job_type=job_type, dryrun=dryrun)
37
+ return job.submit()
38
+
39
+
40
+ class Pipeline(object):
41
+ """a job that loads yaml config."""
42
+
43
+ def __init__(self, fn):
44
+ """
45
+ load a yaml config of a job and save generated configs as yaml for each task.
46
+ return: a list of files to run as specified by `run_task`.
47
+ """
48
+ if fn.endswith(".py"):
49
+ # a python command.
50
+ self.backend = "python"
51
+ self.run_yamls = [fn]
52
+ return
53
+
54
+ job_config = recursive_config(fn)
55
+ if job_config.base_dir is None: # single file job config.
56
+ self.run_yamls = [fn]
57
+ return
58
+
59
+ self.project_dir = os.path.join("projects", job_config.project_dir)
60
+ self.run_dir = os.path.join("runs", job_config.project_dir)
61
+
62
+ if job_config.run_task is not None:
63
+ run_yamls = []
64
+ for stage in job_config.run_task:
65
+ # each stage can have multiple tasks running in parallel.
66
+ if OmegaConf.is_list(stage):
67
+ stage_yamls = []
68
+ for task_file in stage:
69
+ stage_yamls.append(
70
+ os.path.join(self.project_dir, task_file))
71
+ run_yamls.append(stage_yamls)
72
+ else:
73
+ run_yamls.append(os.path.join(self.project_dir, stage))
74
+ self.run_yamls = run_yamls
75
+ configs_to_save = self._overwrite_task(job_config)
76
+ self._save_configs(configs_to_save)
77
+
78
+ def __getitem__(self, idx):
79
+ yaml_files = self.run_yamls[idx]
80
+ if isinstance(yaml_files, list):
81
+ return [JobLauncher(yaml_file) for yaml_file in yaml_files]
82
+ return [JobLauncher(yaml_files)]
83
+
84
+ def __len__(self):
85
+ return len(self.run_yamls)
86
+
87
+ def _save_configs(self, configs_to_save: dict):
88
+ # save
89
+ os.makedirs(self.project_dir, exist_ok=True)
90
+ for config_file in configs_to_save:
91
+ config = configs_to_save[config_file]
92
+ print("saving", config_file)
93
+ OmegaConf.save(config=config, f=config_file)
94
+
95
+ def _overwrite_task(self, job_config):
96
+ configs_to_save = {}
97
+ self.base_project_dir = os.path.join("projects", job_config.base_dir)
98
+ self.base_run_dir = os.path.join("runs", job_config.base_dir)
99
+
100
+ for config_sets in job_config.task_group:
101
+ overwrite_config = job_config.task_group[config_sets]
102
+ if (
103
+ overwrite_config.task_list is None
104
+ or len(overwrite_config.task_list) == 0
105
+ ):
106
+ print(
107
+ "[warning]",
108
+ job_config.task_group,
109
+ "has no task_list specified.")
110
+ # we don't want this added to a final config.
111
+ task_list = overwrite_config.pop("task_list", None)
112
+ for config_file in task_list:
113
+ config_file_path = os.path.join(
114
+ self.base_project_dir, config_file)
115
+ config = recursive_config(config_file_path)
116
+ # overwrite it.
117
+ if overwrite_config:
118
+ config = OmegaConf.merge(config, overwrite_config)
119
+ overwrite_dir(config, self.run_dir, basedir=self.base_run_dir)
120
+ save_file_path = os.path.join(self.project_dir, config_file)
121
+ configs_to_save[save_file_path] = config
122
+ return configs_to_save
123
+
124
+
125
+ def main(args):
126
+ job_type = args.jobtype if args.jobtype else None
127
+ # parse multiple pipelines.
128
+ pipelines = [Pipeline(fn) for fn in args.yamls.split(",")]
129
+
130
+ for pipe_id, pipeline in enumerate(pipelines):
131
+ if not hasattr(pipeline, "project_dir"):
132
+ for job in pipeline[0]:
133
+ job(job_type=job_type, dryrun=args.dryrun)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ parser = argparse.ArgumentParser()
138
+ parser.add_argument("yamls", type=str)
139
+ parser.add_argument(
140
+ "--dryrun",
141
+ action="store_true",
142
+ help="run config and prepare to submit without launch the job.",
143
+ )
144
+ parser.add_argument(
145
+ "--jobtype", type=str, default="",
146
+ help="force to run jobs as specified.")
147
+ args = parser.parse_args()
148
+ main(args)
data/fairseq/examples/MMPT/mmpt/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ try:
6
+ # fairseq user dir
7
+ from .datasets import FairseqMMDataset
8
+ from .losses import FairseqCriterion
9
+ from .models import FairseqMMModel
10
+ from .tasks import FairseqMMTask
11
+ except ImportError:
12
+ pass
data/fairseq/examples/MMPT/mmpt/evaluators/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ from .metric import *
6
+ from .evaluator import *
7
+
8
+
9
+ # experimental.
10
+ try:
11
+ from .expmetric import *
12
+ except ImportError:
13
+ pass
data/fairseq/examples/MMPT/mmpt/evaluators/predictor.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import os
6
+ import random
7
+ import json
8
+ import numpy as np
9
+ import torch
10
+ import pickle
11
+ import math
12
+
13
+ from tqdm import tqdm
14
+
15
+
16
+ class Predictor(object):
17
+ """this base class is used to save predictions to disk
18
+ (and being called by a evaluator later).
19
+ Predictor has minimum support of single gpu prediction.
20
+ """
21
+ def __init__(self, config):
22
+ self.pred_dir = None # on-the-fly eval does not save the results.
23
+ if hasattr(config, "eval") and config.eval is not None:
24
+ self.pred_dir = config.eval.save_path
25
+ os.makedirs(self.pred_dir, exist_ok=True)
26
+
27
+ def __call__(self, outputs):
28
+ """extract the prediction and save it."""
29
+ raise NotImplementedError
30
+
31
+ def predict_loop(self, model, eval_dataloader, output_file=None):
32
+ """on-the-fly prediction on a single gpu."""
33
+ self.full_scores = []
34
+ model.eval()
35
+ model = model.to(0)
36
+ with torch.no_grad():
37
+ for data in eval_dataloader:
38
+ data = self.to_ctx(data)
39
+ outputs = model(**data)
40
+ outputs.update(data)
41
+ self(outputs)
42
+ return self.finalize(output_file)
43
+
44
+ def finalize(self, output_file):
45
+ pass
46
+
47
+ def to_ctx(self, data, ctx=0, dtype=None):
48
+ if isinstance(data, dict):
49
+ for key in data:
50
+ if torch.is_tensor(data[key]):
51
+ if dtype is not None and data[key].dtype == torch.float32:
52
+ data[key] = data[key].to(dtype)
53
+ data[key] = data[key].to(ctx)
54
+ return data
55
+ else:
56
+ raise ValueError("non-dict type of batch is not supported yet.")
57
+
58
+
59
+ class NLGPredictor(Predictor):
60
+ """Predicting Text from MMFusion models."""
61
+ """TODO: make a context."""
62
+ def __init__(self, config):
63
+ super().__init__(config)
64
+ from transformers import AutoTokenizer
65
+
66
+ self.tokenizer = AutoTokenizer.from_pretrained(
67
+ config.dataset.bert_name,
68
+ bos_token="[CLS]", eos_token="[SEP]")
69
+ self.bos_token_id = self.tokenizer.bos_token_id
70
+ self.eos_token_id = self.tokenizer.eos_token_id
71
+
72
+ def predict_loop(self, model, eval_dataloader, output_file=None):
73
+ """TODO: refactor base classes."""
74
+ ctx = 0
75
+ outputs = {"outputs": [], "targets": [[]]}
76
+ model.eval()
77
+ model = model.to(ctx)
78
+ with torch.no_grad():
79
+ for data in tqdm(eval_dataloader):
80
+ data = self.to_ctx(data, ctx)
81
+ self(data, model, outputs)
82
+ return self.finalize(outputs, output_file)
83
+
84
+ def __call__(self, data, model, outputs):
85
+ data.update({
86
+ "bos_token_id": self.bos_token_id,
87
+ "eos_token_id": self.eos_token_id
88
+ })
89
+
90
+ output = model.generate(**data)
91
+ assert len(output) == len(data["ref"])
92
+ for idx, _output in enumerate(output):
93
+ generated_text = self.tokenizer.decode(
94
+ _output, skip_special_tokens=True)
95
+ if generated_text == "":
96
+ generated_text = "none"
97
+ outputs["outputs"].append(generated_text)
98
+ outputs["targets"][0].append(data["ref"][idx])
99
+ if random.random() < 0.001:
100
+ print("_output", _output)
101
+ print("generated_text", generated_text)
102
+ print("ref", data["ref"][idx])
103
+
104
+ def finalize(self, outputs, output_file=None):
105
+ if output_file is not None:
106
+ with open(os.path.join(
107
+ self.pred_dir, output_file + ".json"), "w") as fw:
108
+ json.dump(outputs, fw, indent=4)
109
+ return outputs
110
+
111
+
112
+ class RetrievalPredictor(Predictor):
113
+ """generated `pooled_video` and `pooled_text`."""
114
+ def __init__(self, config):
115
+ super().__init__(config)
116
+ from transformers import AutoTokenizer
117
+ self.tokenizer = AutoTokenizer.from_pretrained(
118
+ config.dataset.bert_name)
119
+
120
+ def predict_loop(
121
+ self,
122
+ model,
123
+ eval_dataloader,
124
+ output_file="retrieval.npy"
125
+ ):
126
+ """on-the-fly prediction on a single gpu."""
127
+ full_scores = []
128
+ texts = []
129
+ model.eval()
130
+ model = model.cuda()
131
+ with torch.no_grad():
132
+ for data in eval_dataloader:
133
+ # convert to dict.
134
+ if not isinstance(data, dict):
135
+ data = {
136
+ "caps": data[0],
137
+ "cmasks": data[1],
138
+ "vfeats": data[2],
139
+ "vmasks": data[3],
140
+ "video_id": data[4]
141
+ }
142
+ data = self.to_ctx(data)
143
+ outputs = model(**data)
144
+ outputs.update(data)
145
+ self(outputs, full_scores)
146
+ for _cap in data["caps"]:
147
+ texts.append(
148
+ self.tokenizer.decode(_cap, skip_special_tokens=True)
149
+ )
150
+
151
+ return self.finalize(full_scores, texts, output_file)
152
+
153
+ def __call__(self, sample, full_scores):
154
+ scores = self._get_pooled_outputs(sample)
155
+ self._append_scores(scores, full_scores)
156
+
157
+ def finalize(self, full_scores, texts, output_file=None):
158
+ outputs = self._aggregate_scores(full_scores)
159
+ if output_file is not None:
160
+ np.save(os.path.join(self.pred_dir, output_file + ".npy"), outputs)
161
+ return {"outputs": outputs, "texts": texts}
162
+
163
+ def _get_pooled_outputs(self, outputs):
164
+ if "pooled_video" in outputs:
165
+ return outputs["pooled_video"], outputs["pooled_text"]
166
+ else:
167
+ raise ValueError("unknown format of outputs.")
168
+
169
+ def _append_scores(self, scores, full_scores):
170
+ assert len(scores) == 2
171
+ if len(full_scores) == 0:
172
+ full_scores.append([])
173
+ full_scores.append([])
174
+ full_scores[0].append(scores[0].cpu().detach().numpy())
175
+ full_scores[1].append(scores[1].cpu().detach().numpy())
176
+
177
+ def _aggregate_scores(self, scores):
178
+ assert len(scores) == 2
179
+ video_hidden = np.concatenate(scores[0], axis=0)
180
+ text_hidden = np.concatenate(scores[1], axis=0)
181
+ # clear up.
182
+ self.full_scores = []
183
+ return np.matmul(text_hidden, video_hidden.T)
184
+
185
+
186
+ class QAPredictor(Predictor):
187
+ """generated `pooled_video` and `pooled_text`."""
188
+ def __init__(self, config):
189
+ super().__init__(config)
190
+ """predictor maintains scores and aggregate them."""
191
+
192
+ def predict_loop(self, model, eval_dataloader, output_file="qa.npy"):
193
+ """on-the-fly prediction on a single gpu."""
194
+ self.full_scores = []
195
+ model.eval()
196
+ model = model.cuda()
197
+ with torch.no_grad():
198
+ for data in eval_dataloader:
199
+ # reshape ans and dup video 5 times.
200
+ v_len = data["vfeats"].size(1)
201
+ hidden_size = data["vfeats"].size(2)
202
+ data["vfeats"] = data["vfeats"].unsqueeze(1).repeat(1, 5, 1, 1).view(-1, v_len, hidden_size)
203
+ data["vmasks"] = data["vmasks"].unsqueeze(1).repeat(1, 5, 1).view(-1, v_len)
204
+
205
+ t_len = data["caps"].size(-1)
206
+ data["caps"] = data["caps"].view(-1, t_len)
207
+ data["cmasks"] = data["cmasks"].view(-1, t_len)
208
+
209
+ data = self.to_ctx(data)
210
+ outputs = model(**data)
211
+ outputs.update(data)
212
+ self(outputs)
213
+ return self.finalize(output_file)
214
+
215
+ def __call__(self, sample):
216
+ hidden_size = sample["pooled_video"].size(-1)
217
+ pooled_video = sample["pooled_video"].view(-1, 5, hidden_size)
218
+ pooled_text = sample["pooled_text"].view(-1, 5, hidden_size)
219
+ scores = torch.bmm(pooled_video, pooled_text.transpose(2, 1))
220
+ scores = scores.argmax(-1)
221
+ self._append_scores(scores[:, 0], sample["answers"], self.full_scores)
222
+
223
+ def finalize(self, output_file=None):
224
+ outputs, targets = self._aggregate_scores(self.full_scores)
225
+ if output_file is not None:
226
+ np.save(os.path.join(self.pred_dir, output_file + ".npy"), outputs)
227
+ return {"outputs": outputs, "targets": targets}
228
+
229
+ def _append_scores(self, scores, answers, full_scores):
230
+ if len(full_scores) == 0:
231
+ full_scores.append([])
232
+ full_scores.append([])
233
+ full_scores[0].append(scores.cpu().detach().numpy())
234
+ full_scores[1].append(answers.cpu().detach().numpy())
235
+
236
+ def _aggregate_scores(self, scores):
237
+ assert len(scores) == 2
238
+ outputs = np.concatenate(scores[0], axis=0)
239
+ targets = np.concatenate(scores[1], axis=0)
240
+ # clear up.
241
+ self.full_scores = []
242
+ return outputs, targets
243
+
244
+
245
+ class CrossTaskPredictor(Predictor):
246
+ """
247
+ CrossTaskPredictor needs to compute the average of logits
248
+ for overlapped sliding-window.
249
+ """
250
+ def __init__(self, config):
251
+ super().__init__(config)
252
+ self.lsm = torch.nn.LogSoftmax(dim=1)
253
+ self.max_video_len = config.dataset.max_video_len
254
+ self.sliding_window = config.dataset.sliding_window
255
+ self.sliding_window_size = config.dataset.sliding_window_size
256
+ self.annotation_path = config.dataset.annotation_path
257
+
258
+ def predict_loop(self, model, eval_dataloader, output_file="result.pkl"):
259
+ """refactored from line 144:
260
+ https://github.com/DmZhukov/CrossTask/blob/master/train.py
261
+ """
262
+ ctx = 0
263
+ model.eval()
264
+ model = model.to(ctx)
265
+ # this is not a loss but just compute neg_log_prob.
266
+ Y_pred = {}
267
+ Y_true = {}
268
+ with torch.no_grad():
269
+ for batch in eval_dataloader:
270
+ self(batch, model, Y_pred, Y_true)
271
+ return self.finalize(Y_pred, Y_true, output_file)
272
+
273
+ def __call__(self, sample, model, Y_pred, Y_true):
274
+ # please install dp from `https://github.com/DmZhukov/CrossTask`
275
+ from dp import dp
276
+ vid, task = sample['video_id'][0], sample['task'][0]
277
+ sample = self.to_ctx(sample)
278
+ # compute the average logits over sliding windows.
279
+ output = model(**sample)
280
+ batch_logits = output["logits"].cpu()
281
+
282
+ video_len = sample["video_len"][0]
283
+
284
+ # the following version is slow.
285
+ logits = torch.zeros((video_len, batch_logits.size(1)))
286
+ logits_counts = torch.zeros((video_len, 1), dtype=torch.long)
287
+ # use the same loop as aligner to recover.
288
+ batch_logit_idx = 0
289
+ for window_start in range(0, video_len, self.sliding_window):
290
+ video_end = min(video_len - window_start, self.sliding_window_size)
291
+ logits[window_start: window_start + video_end] += batch_logits[
292
+ batch_logit_idx: batch_logit_idx + video_end]
293
+ batch_logit_idx += video_end
294
+ logits_counts[window_start: window_start + video_end] += torch.ones((video_end, 1), dtype=torch.long)
295
+
296
+ if (video_len - window_start) <= self.sliding_window_size:
297
+ break
298
+
299
+ logits /= logits_counts
300
+ assert logits.size() == (video_len, batch_logits.size(1)), "{}, {}".format(logits.size(), video_len)
301
+
302
+ O = self.lsm(logits)
303
+ y = np.zeros(O.size(), dtype=np.float32)
304
+ dp(y, -O.detach().cpu().numpy())
305
+ if task not in Y_pred:
306
+ Y_pred[task] = {}
307
+ Y_pred[task][vid] = y
308
+ annot_path = os.path.join(
309
+ self.annotation_path, task+'_'+vid+'.csv')
310
+ if os.path.exists(annot_path):
311
+ if task not in Y_true:
312
+ Y_true[task] = {}
313
+ Y_true[task][vid] = self._read_assignment(
314
+ *y.shape, annot_path)
315
+
316
+ def finalize(self, Y_pred, Y_true, output_file=None):
317
+ if output_file is not None:
318
+ with open(
319
+ os.path.join(self.pred_dir, output_file + ".pkl"),
320
+ "wb") as fw:
321
+ pickle.dump(
322
+ {"Y_pred": Y_pred, "Y_true": Y_true}, fw,
323
+ protocol=pickle.HIGHEST_PROTOCOL)
324
+ return {"outputs": Y_pred, "targets": Y_true}
325
+
326
+ def _read_assignment(self, T, K, path):
327
+ """
328
+ refactored from https://github.com/DmZhukov/CrossTask/blob/master/data.py
329
+ Howto interpret contraints on loss that is going to be minimized:
330
+ lambd is a big number;
331
+ self.lambd * C is a big number for all valid position (csv stores invalids)
332
+
333
+ def forward(self, O, Y, C):
334
+ return (Y*(self.lambd * C - self.lsm(O))).mean(dim=0).sum()
335
+
336
+ This will load the csv file and fill-in the step col from start to end rows.
337
+ """
338
+
339
+ Y = np.zeros([T, K], dtype=np.uint8)
340
+ with open(path, 'r') as f:
341
+ for line in f:
342
+ step, start, end = line.strip().split(',')
343
+ start = int(math.floor(float(start)))
344
+ end = int(math.ceil(float(end)))
345
+ step = int(step) - 1
346
+ Y[start:end, step] = 1
347
+ return Y
348
+
349
+
350
+ class COINPredictor(Predictor):
351
+ """
352
+ COINPredictor is similar to CrossTask on sliding windows.
353
+ """
354
+ def __init__(self, config):
355
+ super().__init__(config)
356
+ self.max_video_len = config.dataset.max_video_len
357
+ self.sliding_window = config.dataset.sliding_window
358
+ self.sliding_window_size = config.dataset.sliding_window_size
359
+
360
+ def predict_loop(self, model, eval_dataloader, output_file="result.pkl"):
361
+ """refactored from line 144:
362
+ https://github.com/DmZhukov/CrossTask/blob/master/train.py
363
+ """
364
+ ctx = 0
365
+ model.eval()
366
+ model = model.to(ctx)
367
+ # this is not a loss but just compute neg_log_prob.
368
+ Y_pred = []
369
+ Y_true = []
370
+ with torch.no_grad():
371
+ for batch in eval_dataloader:
372
+ self(batch, model, Y_pred, Y_true)
373
+ return self.finalize(Y_pred, Y_true, output_file)
374
+
375
+ def __call__(self, sample, model, Y_pred, Y_true):
376
+ sample = self.to_ctx(sample)
377
+ # compute the average logits over sliding windows.
378
+ output = model(**sample)
379
+ logits = self._merge_windows(sample, output)
380
+ Y_pred.append(logits.argmax(dim=1))
381
+ Y_true.append(sample["video_targets"].squeeze(0).cpu())
382
+
383
+ def _merge_windows(self, sample, output):
384
+ targets = sample["targets"].reshape(-1).cpu()
385
+ valid_mask = targets != -100
386
+ targets = targets[valid_mask]
387
+ batch_logits = output["logits"].cpu()
388
+ batch_logits = batch_logits.reshape(-1, batch_logits.size(-1))
389
+ batch_logits = batch_logits[valid_mask]
390
+
391
+ video_len = sample["video_len"][0]
392
+
393
+ # the following version is slow.
394
+ logits = torch.zeros((video_len, batch_logits.size(1)))
395
+ logits_counts = torch.zeros((video_len, 1), dtype=torch.long)
396
+ # use the same loop as aligner to recover.
397
+ batch_logit_idx = 0
398
+ for window_start in range(0, video_len, self.sliding_window):
399
+ video_end = min(video_len - window_start, self.sliding_window_size)
400
+ logits[window_start: window_start + video_end] += batch_logits[
401
+ batch_logit_idx: batch_logit_idx + video_end]
402
+ batch_logit_idx += video_end
403
+ logits_counts[window_start: window_start + video_end] += torch.ones((video_end, 1), dtype=torch.long)
404
+ if (video_len - window_start) <= self.sliding_window_size:
405
+ break
406
+ logits /= logits_counts
407
+ assert logits.size() == (video_len, batch_logits.size(1)), "{}, {}".format(logits.size(), video_len)
408
+ return logits
409
+
410
+ def finalize(self, Y_pred, Y_true, output_file=None):
411
+ Y_pred = torch.cat(Y_pred, dim=0).numpy()
412
+ Y_true = torch.cat(Y_true, dim=0).numpy()
413
+ assert len(Y_pred) == len(Y_true)
414
+
415
+ error_mask = Y_pred != Y_true
416
+ print("sample error", Y_pred[error_mask][:10], Y_true[error_mask][:10])
417
+ print("sample error", Y_pred[error_mask][10:20], Y_true[error_mask][10:20])
418
+
419
+ if output_file is not None:
420
+ with open(
421
+ os.path.join(self.pred_dir, output_file + ".pkl"),
422
+ "wb") as fw:
423
+ pickle.dump(
424
+ {"Y_pred": Y_pred, "Y_true": Y_true}, fw,
425
+ protocol=pickle.HIGHEST_PROTOCOL)
426
+ return {"outputs": Y_pred, "targets": Y_true}
427
+
428
+
429
+ class COINZSPredictor(COINPredictor):
430
+ """
431
+ COINZSPredictor for COIN zero-shot prediction.
432
+ """
433
+
434
+ def __init__(self, config):
435
+ super().__init__(config)
436
+ self.dataset_config = config.dataset
437
+
438
+ def predict_loop(self, model, eval_dataloader, output_file="result.pkl"):
439
+ """refactored from line 144:
440
+ https://github.com/DmZhukov/CrossTask/blob/master/train.py
441
+ """
442
+ ctx = 0
443
+ model.eval()
444
+ model = model.to(ctx)
445
+
446
+ with torch.no_grad():
447
+ outputs = eval_dataloader.dataset.meta_processor.meta_text_labels(
448
+ self.dataset_config)
449
+ outputs = self.to_ctx(outputs, ctx)
450
+ label_hidden_states = model.forward_text(**outputs).cpu()
451
+ label_sim = label_hidden_states @ label_hidden_states.t()
452
+ num_labels = label_sim.size(0)
453
+ eye_mask = ~torch.eye(num_labels, dtype=torch.bool)
454
+ label_sim = label_sim.masked_select(eye_mask).view(num_labels, num_labels - 1)
455
+ lbd = label_sim.max()
456
+
457
+ # this is not a loss but just compute neg_log_prob.
458
+ Y_pred = []
459
+ Y_true = []
460
+ with torch.no_grad():
461
+ for batch in eval_dataloader:
462
+ self(batch, label_hidden_states, model, lbd, Y_pred, Y_true)
463
+ return self.finalize(Y_pred, Y_true, output_file)
464
+
465
+ def reshape_subsample(self, sample):
466
+ for key in sample:
467
+ if torch.is_tensor(sample[key]):
468
+ sample[key] = self.flat_subsample(sample[key])
469
+ return sample
470
+
471
+ def flat_subsample(self, tensor):
472
+ if len(tensor.size()) > 1 and tensor.size(0) == 1:
473
+ tensor = tensor.squeeze(0)
474
+ return tensor
475
+
476
+ def __call__(self, sample, label_hidden_states, model, lbd, Y_pred, Y_true):
477
+ sample = self.reshape_subsample(sample)
478
+ sample = self.to_ctx(sample)
479
+ # compute the average logits over sliding windows.
480
+ sample["output_hidden_states"] = True
481
+ video_outputs = model.forward_video(**sample).cpu()
482
+ output = {"logits": video_outputs[:, 1:sample["vmasks"].size(1)+1] @ label_hidden_states.t()}
483
+ logits = self._merge_windows(sample, output)
484
+ # logic of zero-shot for sequence labeling.
485
+ logits_argmax = logits.argmax(dim=1) + 1 # 0 is "O" label.
486
+ logits_max = logits.max(dim=1)[0]
487
+
488
+ pred = torch.zeros_like(logits_argmax)
489
+ label_select = logits_max > lbd # 73 or 74
490
+ pred[label_select] = logits_argmax[label_select]
491
+
492
+ Y_pred.append(pred)
493
+ Y_true.append(sample["video_targets"].squeeze(0).cpu())
494
+
495
+ def finalize(self, Y_pred, Y_true, output_file=None):
496
+ Y_pred = torch.cat(Y_pred, dim=0).numpy()
497
+ Y_true = torch.cat(Y_true, dim=0).numpy()
498
+ assert len(Y_pred) == len(Y_true)
499
+
500
+ error_mask = Y_pred != Y_true
501
+ print("sample error", Y_pred[error_mask][:10], Y_true[error_mask][:10])
502
+ print("sample error", Y_pred[error_mask][10:20], Y_true[error_mask][10:20])
503
+
504
+ if output_file is not None:
505
+ with open(
506
+ os.path.join(self.pred_dir, output_file + ".pkl"),
507
+ "wb") as fw:
508
+ pickle.dump(
509
+ {"Y_pred": Y_pred, "Y_true": Y_true}, fw,
510
+ protocol=pickle.HIGHEST_PROTOCOL)
511
+ return {"outputs": Y_pred, "targets": Y_true}
512
+
513
+
514
+ class DiDeMoPredictor(Predictor):
515
+ """reference: https://github.com/LisaAnne/LocalizingMoments/blob/master/utils/eval.py
516
+ https://github.com/LisaAnne/LocalizingMoments/blob/master/utils/data_processing.py
517
+ """
518
+ def __init__(self, config):
519
+ super().__init__(config)
520
+ # load targets.
521
+ with open(config.dataset.test_path) as data_file:
522
+ self.test_data = json.load(data_file)
523
+
524
+ def predict_loop(self, model, eval_dataloader, output_file="didemo.npy"):
525
+ """
526
+ TODO: two solutions here.
527
+ """
528
+ import itertools
529
+ # 21 chunks.
530
+ self.possible_segments = [(0,0), (1,1), (2,2), (3,3), (4,4), (5,5)]
531
+ for i in itertools.combinations(range(6), 2):
532
+ self.possible_segments.append(i)
533
+ # pick segments from a video.
534
+
535
+ """on-the-fly prediction on a single gpu."""
536
+ self.full_scores = []
537
+ model.eval()
538
+ model = model.cuda()
539
+ with torch.no_grad():
540
+ for data in eval_dataloader:
541
+ # TODO special forwarding logic here.
542
+ data = self.to_ctx(data)
543
+ data["output_hidden_states"] = True
544
+ hidden_video = model.forward_video(**data)
545
+ data["output_hidden_states"] = False
546
+ pooled_text = model.forward_text(**data)
547
+ outputs = {
548
+ "hidden_video": hidden_video,
549
+ "pooled_text": pooled_text
550
+ }
551
+ outputs.update(data)
552
+ self(outputs)
553
+ return self.finalize(output_file)
554
+
555
+ def __call__(self, sample):
556
+ # TODO: make an index select from self.possible_segments.
557
+ hidden_video = sample["hidden_video"]
558
+ pooled_text = sample["pooled_text"]
559
+ vmasks = sample["vmasks"]
560
+ # probably maintain valid results here.
561
+
562
+ hidden_video = hidden_video[:, 1:-1, :]
563
+ # probably maintain valid results here.
564
+ pooled_video = []
565
+ for s, e in self.possible_segments:
566
+ pooled_video.append(
567
+ torch.mean(
568
+ hidden_video[:, int(s*5):int((e+1)*5), :],
569
+ dim=1, keepdim=True)
570
+ )
571
+ pooled_video = torch.cat(pooled_video, dim=1)
572
+ scores = torch.bmm(
573
+ pooled_video, pooled_text.unsqueeze(-1)).squeeze(-1).cpu()
574
+
575
+ ranks = scores.argsort(dim=-1, descending=True)
576
+
577
+ for batch_idx, rank in enumerate(ranks):
578
+ rank_of_moment = []
579
+ for m_idx, moment in enumerate(rank):
580
+ s, e = self.possible_segments[moment.item()]
581
+ if torch.any(
582
+ vmasks[batch_idx, int(s*5):int((e+1)*5)]
583
+ ):
584
+ rank_of_moment.append((s, e))
585
+ self.full_scores.append(rank_of_moment)
586
+
587
+ def finalize(self, output_file=None):
588
+ outputs = self._aggregate_scores(self.full_scores)
589
+ if output_file is not None:
590
+ np.save(os.path.join(self.pred_dir, output_file + ".npy"), outputs)
591
+ return {"outputs": outputs, "targets": self.test_data}
592
+
593
+ def _aggregate_scores(self, scores):
594
+ self.full_scores = []
595
+ return scores
data/fairseq/examples/MMPT/mmpt/utils/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import random
6
+ import numpy as np
7
+ import torch
8
+
9
+ from .shardedtensor import *
10
+ from .load_config import *
11
+
12
+
13
+ def set_seed(seed=43211):
14
+ random.seed(seed)
15
+ np.random.seed(seed)
16
+ torch.manual_seed(seed)
17
+ torch.cuda.manual_seed_all(seed)
18
+ if torch.backends.cudnn.enabled:
19
+ torch.backends.cudnn.benchmark = False
20
+ torch.backends.cudnn.deterministic = True
21
+
22
+
23
+ def get_world_size():
24
+ if torch.distributed.is_initialized():
25
+ world_size = torch.distributed.get_world_size()
26
+ else:
27
+ world_size = 1
28
+ return world_size
29
+
30
+
31
+ def get_local_rank():
32
+ return torch.distributed.get_rank() \
33
+ if torch.distributed.is_initialized() else 0
34
+
35
+
36
+ def print_on_rank0(func):
37
+ local_rank = get_local_rank()
38
+ if local_rank == 0:
39
+ print("[INFO]", func)
40
+
41
+
42
+ class RetriMeter(object):
43
+ """
44
+ Statistics on whether retrieval yields a better pair.
45
+ """
46
+ def __init__(self, freq=1024):
47
+ self.freq = freq
48
+ self.total = 0
49
+ self.replace = 0
50
+ self.updates = 0
51
+
52
+ def __call__(self, data):
53
+ if isinstance(data, np.ndarray):
54
+ self.replace += data.shape[0] - int((data[:, 0] == -1).sum())
55
+ self.total += data.shape[0]
56
+ elif torch.is_tensor(data):
57
+ self.replace += int(data.sum())
58
+ self.total += data.size(0)
59
+ else:
60
+ raise ValueError("unsupported RetriMeter data type.", type(data))
61
+
62
+ self.updates += 1
63
+ if get_local_rank() == 0 and self.updates % self.freq == 0:
64
+ print("[INFO]", self)
65
+
66
+ def __repr__(self):
67
+ return "RetriMeter (" + str(self.replace / self.total) \
68
+ + "/" + str(self.replace) + "/" + str(self.total) + ")"
data/fairseq/examples/MMPT/mmpt/utils/load_config.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import os
6
+ import omegaconf
7
+ from omegaconf import OmegaConf
8
+
9
+
10
+ def load_config(args=None, config_file=None, overwrite_fairseq=False):
11
+ """TODO (huxu): move fairseq overwrite to another function."""
12
+ if args is not None:
13
+ config_file = args.taskconfig
14
+ config = recursive_config(config_file)
15
+
16
+ if config.dataset.subsampling is not None:
17
+ batch_size = config.fairseq.dataset.batch_size // config.dataset.subsampling
18
+ print(
19
+ "adjusting batch_size to {} due to subsampling {}.".format(
20
+ batch_size, config.dataset.subsampling
21
+ )
22
+ )
23
+ config.fairseq.dataset.batch_size = batch_size
24
+
25
+ is_test = config.dataset.split is not None and config.dataset.split == "test"
26
+ if not is_test:
27
+ if (
28
+ config.fairseq.checkpoint is None
29
+ or config.fairseq.checkpoint.save_dir is None
30
+ ):
31
+ raise ValueError("fairseq save_dir or save_path must be specified.")
32
+
33
+ save_dir = config.fairseq.checkpoint.save_dir
34
+ os.makedirs(save_dir, exist_ok=True)
35
+ if config.fairseq.common.tensorboard_logdir is not None:
36
+ tb_run_dir = suffix_rundir(
37
+ save_dir, config.fairseq.common.tensorboard_logdir
38
+ )
39
+ config.fairseq.common.tensorboard_logdir = tb_run_dir
40
+ print(
41
+ "update tensorboard_logdir as", config.fairseq.common.tensorboard_logdir
42
+ )
43
+ os.makedirs(save_dir, exist_ok=True)
44
+ OmegaConf.save(config=config, f=os.path.join(save_dir, "config.yaml"))
45
+
46
+ if overwrite_fairseq and config.fairseq is not None and args is not None:
47
+ # flatten fields.
48
+ for group in config.fairseq:
49
+ for field in config.fairseq[group]:
50
+ print("overwrite args." + field, "as", config.fairseq[group][field])
51
+ setattr(args, field, config.fairseq[group][field])
52
+ return config
53
+
54
+
55
+ def recursive_config(config_path):
56
+ """allows for stacking of configs in any depth."""
57
+ config = OmegaConf.load(config_path)
58
+ if config.includes is not None:
59
+ includes = config.includes
60
+ config.pop("includes")
61
+ base_config = recursive_config(includes)
62
+ config = OmegaConf.merge(base_config, config)
63
+ return config
64
+
65
+
66
+ def suffix_rundir(save_dir, run_dir):
67
+ max_id = -1
68
+ for search_dir in os.listdir(save_dir):
69
+ if search_dir.startswith(run_dir):
70
+ splits = search_dir.split("_")
71
+ cur_id = int(splits[1]) if len(splits) > 1 else 0
72
+ max_id = max(max_id, cur_id)
73
+ return os.path.join(save_dir, run_dir + "_" + str(max_id + 1))
74
+
75
+
76
+ def overwrite_dir(config, replace, basedir):
77
+ for key in config:
78
+ if isinstance(config[key], str) and config[key].startswith(basedir):
79
+ config[key] = config[key].replace(basedir, replace)
80
+ if isinstance(config[key], omegaconf.dictconfig.DictConfig):
81
+ overwrite_dir(config[key], replace, basedir)
data/fairseq/examples/MMPT/mmpt/utils/shardedtensor.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import os
6
+ import pickle
7
+ import numpy as np
8
+
9
+
10
+ class ShardedTensor(object):
11
+ def __init__(self, data, starts):
12
+ self.data = data
13
+ self.starts = starts
14
+ assert self.starts[0] == 0
15
+ assert self.starts[-1] == len(self.data)
16
+ assert (self.starts[1:] >= self.starts[:-1]).all()
17
+ assert (self.starts > -1).all()
18
+
19
+ @staticmethod
20
+ def from_list(xs):
21
+ starts = np.full((len(xs) + 1,), -1, dtype=np.long)
22
+ data = np.concatenate(xs, axis=0)
23
+ starts[0] = 0
24
+ for i, x in enumerate(xs):
25
+ starts[i + 1] = starts[i] + x.shape[0]
26
+ assert (starts > -1).all()
27
+ return ShardedTensor(data, starts)
28
+
29
+ def __getitem__(self, i):
30
+ return self.data[self.starts[i] : self.starts[i + 1]]
31
+
32
+ def __len__(self):
33
+ return len(self.starts) - 1
34
+
35
+ def lengths(self):
36
+ return self.starts[1:] - self.starts[:-1]
37
+
38
+ def save(self, path):
39
+ np.save(path + "_starts", self.starts)
40
+ np.save(path + "_data", self.data)
41
+
42
+ @staticmethod
43
+ def load(path, mmap_mode=None):
44
+ starts = np.load(path + "_starts.npy", mmap_mode)
45
+ data = np.load(path + "_data.npy", mmap_mode)
46
+ return ShardedTensor(data, starts)
data/fairseq/examples/MMPT/pretraining.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pretraining
2
+
3
+ (If you are new to the ideas of `mmpt.processors`, see [README](README.md) first.)
4
+ We mostly use [howto100M](https://github.com/antoine77340/howto100m) dataset for pretraining (other datasets are coming). So you are less likely to write a new `MetaProcessor`, `VideoProcessor` or `TextProcessor` but only working on a new `Aligner`, a new model and loss.
5
+
6
+ ### Data Sharding
7
+ Pretraining on Howto100M is heavy on IO since we have millions of videos or captions on the hard disk that cannot be fit into the memory.
8
+ It is desirable to have an optimized preprocessing step before the actual dataloading.
9
+
10
+ We support data sharding to pack multiple videos into a shards of training data for both videos and captions. (see [dataset](DATASET.md) for preprocessing).
11
+ These shards will be mapped into memory to reduce the frequency of IO access on millions of files. See (processors starting with `Sharded*`).
12
+ This will be the default config for a how2 dataset `projects/task/how2.yaml`.
13
+
14
+ Great thanks to Dmytro Okhonko for sharing the code from MARGE project.
15
+
16
+ ### Training
17
+ Pretraining on Howto100m is expected on one or multiple nodes, where each node has 8 GPUS with 32 GB mem.
18
+ launching a pretraing on MFM+MLM can be done, via:
19
+ ```python locallaunch.py projects/mfmmlm/how2.yaml```
20
+
21
+ ### Pre-training with a Retrieval Model (VideoCLIP)
22
+ This projects now support alternatively run a retrieval model and pre-training.
23
+ We implement a basic retrieval model that is built on the hidden states of a video and faiss.
24
+
25
+ You may need to install faiss via `conda install faiss-cpu -c pytorch`.
26
+
27
+ Right now, the hidden states of a video is computed as the average of 8 clips of their pooled visual/text hidden states.
28
+ See `mmpt/tasks/retritask.py` for more details.
29
+ The `.yaml` config for running pre-training with a retrieval model can be found at `projects/retri/videoretri.yaml`.
data/fairseq/examples/MMPT/projects/mfmmlm.yaml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ project_dir: mfmmlm
2
+ run_task:
3
+ - how2.yaml
4
+ - [vtt.yaml, vttcap.yaml, vttqa.yaml, youcook.yaml, youcookcap.yaml, crosstask.yaml, coin.yaml]
5
+ base_dir: task
6
+ task_group:
7
+ pretrain:
8
+ task_list:
9
+ - how2.yaml
10
+ dataset:
11
+ subsampling: 32
12
+ sampled_min_len: 10
13
+ sampled_max_len: 64
14
+ max_video_len: 32
15
+ max_len: 96
16
+ aligner: MFMMLMAligner
17
+ lazy_vfeat_mask: True
18
+ mfm_probability: 0.15
19
+ mlm_probability: 0.15
20
+ mm_prob: 0.5
21
+ model:
22
+ model_cls: MMFusionMFMMLM
23
+ mm_encoder_cls: MMFusionForMFMMLM
24
+ loss:
25
+ loss_cls: MFMMLM
26
+ fairseq:
27
+ common:
28
+ fp16: true
29
+ dataset:
30
+ batch_size: 256
31
+ optimization:
32
+ max_epoch: 15
33
+ finetune:
34
+ task_list:
35
+ - vtt.yaml
36
+ - vttqa.yaml
37
+ - youcook.yaml
38
+ - youcookcap.yaml
39
+ - crosstask.yaml
40
+ - coin.yaml
41
+ dataset:
42
+ max_video_len: 32
43
+ max_len: 96
44
+ fairseq:
45
+ common:
46
+ fp16: true
47
+ # do not write any model or loss here (they are expected to be fixed in mmfusion).
48
+ test:
49
+ task_list:
50
+ - test_vtt.yaml
51
+ - test_vttqa.yaml
52
+ - test_youcook.yaml
53
+ - test_youcookcap.yaml
54
+ - test_crosstask.yaml
55
+ - test_crosstask_zs.yaml
56
+ - test_coin.yaml
57
+ dataset:
58
+ max_video_len: 32
59
+ max_len: 96
data/fairseq/examples/MMPT/projects/mtm/mmfusionmtm.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ includes: projects/mfmmlm.yaml
2
+ project_dir: mtm/mmfusionmtm
3
+ task_group:
4
+ pretrain:
5
+ task: VLMTask # reproducible
6
+ dataset:
7
+ aligner: MFMMLMAligner
8
+ model:
9
+ use_seg_emb: True # reproducible
10
+ model_cls: MMFusionMTM
11
+ mm_encoder_cls: MMBertForMFMMLM
12
+ loss:
13
+ loss_cls: MTM
14
+ finetune:
15
+ model:
16
+ use_seg_emb: True # reproducible
17
+ test:
18
+ model:
19
+ use_seg_emb: True # reproducible
data/fairseq/examples/MMPT/projects/mtm/vlm.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ includes: projects/mtm/mmfusionmtm.yaml
2
+ project_dir: mtm/vlm
3
+ task_group:
4
+ pretrain:
5
+ dataset:
6
+ sampled_min_len: 8
7
+ loss:
8
+ loss_cls: MTM
data/fairseq/examples/MMPT/projects/mtm/vlm/coin.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: COINActionSegmentationMetaProcessor
5
+ train_path: data/coin/COIN.json
6
+ val_path: data/coin/COIN.json
7
+ vfeat_dir: data/feat/feat_coin_s3d
8
+ text_processor: COINActionSegmentationTextProcessor
9
+ aligner: COINActionSegmentationAligner
10
+ num_iso_layer: 12
11
+ sliding_window: 8
12
+ sliding_window_size: 32
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 1
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 8
35
+ checkpoint:
36
+ restore_file: runs/mtm/vlm/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/mtm/vlm/coin
41
+ task_type: sweep_big
42
+ model:
43
+ model_cls: MMFusionActionSegmentation
44
+ mm_encoder_cls: MMBertForTokenClassification
45
+ use_seg_emb: true
46
+ loss:
47
+ loss_cls: CrossEntropy
data/fairseq/examples/MMPT/projects/mtm/vlm/crosstask.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: CrossTaskVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: CrossTaskMetaProcessor
5
+ train_path: data/crosstask/crosstask_release/videos.csv
6
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
7
+ val_path: data/crosstask/crosstask_release/videos_val.csv
8
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
9
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
10
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
11
+ vfeat_dir: data/feat/feat_crosstask_s3d
12
+ annotation_path: data/crosstask/crosstask_release/annotations
13
+ n_train: 30
14
+ text_processor: CrossTaskTextProcessor
15
+ aligner: CrossTaskAligner
16
+ num_iso_layer: 12
17
+ sliding_window: 16
18
+ sliding_window_size: 32
19
+ max_video_len: 32
20
+ max_len: 96
21
+ fairseq:
22
+ common:
23
+ tensorboard_logdir: run
24
+ log_interval: 1000
25
+ fp16: true
26
+ dataset:
27
+ num_workers: 4
28
+ batch_size: 1
29
+ optimization:
30
+ lr:
31
+ - 5.0e-05
32
+ clip_norm: 2.0
33
+ optimizer: adam
34
+ adam_betas: (0.9, 0.98)
35
+ lr_scheduler: polynomial_decay
36
+ total_num_update: 1000000
37
+ warmup_updates: 122
38
+ weight_decay: 0.0
39
+ ddp_backend: no_c10d
40
+ max_epoch: 5
41
+ checkpoint:
42
+ restore_file: runs/mtm/vlm/checkpoint11.pt
43
+ reset_optimizer: true
44
+ reset_dataloader: true
45
+ reset_meters: true
46
+ save_dir: runs/mtm/vlm/crosstask
47
+ task_type: sweep_small
48
+ model:
49
+ model_cls: MMFusionActionLocalization
50
+ mm_encoder_cls: MMBertForJoint
51
+ use_seg_emb: true
52
+ loss:
53
+ loss_cls: BCE
data/fairseq/examples/MMPT/projects/mtm/vlm/how2.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: ShardedVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: ShardedHow2MetaProcessor
5
+ train_path: data/how2/how2_s3d_train.lst
6
+ val_path: data/how2/how2_s3d_val.lst
7
+ vfeat_dir: data/feat/feat_how2_s3d_shard_small
8
+ text_processor: ShardedTextProcessor
9
+ tfeat_dir: data/feat/feat_how2_s3d_shard_small/raw_caption_dedup.bert-base-uncased.
10
+ aligner: MFMMLMAligner
11
+ subsampling: 32
12
+ sampled_min_len: 8
13
+ sampled_max_len: 64
14
+ max_video_len: 32
15
+ max_len: 96
16
+ lazy_vfeat_mask: true
17
+ mfm_probability: 0.15
18
+ mlm_probability: 0.15
19
+ mm_prob: 0.5
20
+ fairseq:
21
+ common:
22
+ tensorboard_logdir: run
23
+ log_interval: 1000
24
+ fp16: true
25
+ dataset:
26
+ num_workers: 4
27
+ batch_size: 256
28
+ optimization:
29
+ lr:
30
+ - 5.0e-05
31
+ clip_norm: 2.0
32
+ optimizer: adam
33
+ adam_betas: (0.9, 0.98)
34
+ lr_scheduler: polynomial_decay
35
+ total_num_update: 1000000
36
+ warmup_updates: 1000
37
+ weight_decay: 0.0
38
+ ddp_backend: no_c10d
39
+ max_epoch: 15
40
+ checkpoint:
41
+ save_dir: runs/mtm/vlm
42
+ save_interval_updates: 1024
43
+ keep_interval_updates: 2
44
+ keep_last_epochs: 30
45
+ task_type: sweep_big
46
+ slurm_config: big
47
+ eval:
48
+ save_path: runs/mtm/vlm
49
+ model:
50
+ model_cls: MMFusionMTM
51
+ mm_encoder_cls: MMBertForMFMMLM
52
+ use_seg_emb: true
53
+ loss:
54
+ loss_cls: MTM
55
+ task: VLMTask
data/fairseq/examples/MMPT/projects/mtm/vlm/test_coin.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: COINActionSegmentationAligner
7
+ bert_name: bert-base-uncased
8
+ test_path: data/coin/COIN.json
9
+ meta_processor: COINActionSegmentationMetaProcessor
10
+ vfeat_dir: data/feat/feat_coin_s3d
11
+ text_processor: COINActionSegmentationTextProcessor
12
+ num_iso_layer: 12
13
+ sliding_window: 16
14
+ sliding_window_size: 32
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 1
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/mtm/vlm/coin/checkpoint_best.pt
24
+ model:
25
+ model_cls: MMFusionActionSegmentation
26
+ mm_encoder_cls: MMBertForTokenClassification
27
+ use_seg_emb: true
28
+ eval:
29
+ save_path: runs/mtm/vlm/coin/eval
30
+ metric: COINActionSegmentationMetric
31
+ predictor: COINPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_crosstask.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: CrossTaskVideoProcessor
6
+ aligner: CrossTaskAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: CrossTaskMetaProcessor
9
+ test_path: data/crosstask/crosstask_release/videos_val.csv
10
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
11
+ val_path: data/crosstask/crosstask_release/videos_val.csv
12
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
13
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
14
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
15
+ vfeat_dir: data/feat/feat_crosstask_s3d
16
+ annotation_path: data/crosstask/crosstask_release/annotations
17
+ n_train: 30
18
+ text_processor: CrossTaskTextProcessor
19
+ num_iso_layer: 12
20
+ sliding_window: 16
21
+ sliding_window_size: 32
22
+ max_video_len: 32
23
+ max_len: 96
24
+ fairseq:
25
+ dataset:
26
+ batch_size: 1
27
+ valid_subset: test
28
+ num_workers: 2
29
+ common_eval:
30
+ path: runs/mtm/vlm/crosstask/checkpoint_best.pt
31
+ model:
32
+ model_cls: MMFusionActionLocalization
33
+ mm_encoder_cls: MMBertForJoint
34
+ use_seg_emb: true
35
+ eval:
36
+ save_path: runs/mtm/vlm/crosstask/eval
37
+ metric: CrossTaskMetric
38
+ predictor: CrossTaskPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_crosstask_zs.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: CrossTaskVideoProcessor
6
+ aligner: CrossTaskAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: CrossTaskMetaProcessor
9
+ test_path: data/crosstask/crosstask_release/videos_val.csv
10
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
11
+ val_path: data/crosstask/crosstask_release/videos_val.csv
12
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
13
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
14
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
15
+ vfeat_dir: data/feat/feat_crosstask_s3d
16
+ annotation_path: data/crosstask/crosstask_release/annotations
17
+ n_train: 30
18
+ text_processor: CrossTaskTextProcessor
19
+ num_iso_layer: 12
20
+ sliding_window: 16
21
+ sliding_window_size: 32
22
+ max_video_len: 32
23
+ max_len: 96
24
+ fairseq:
25
+ dataset:
26
+ batch_size: 1
27
+ valid_subset: test
28
+ num_workers: 2
29
+ common_eval:
30
+ path: runs/mtm/vlm/checkpoint_best.pt
31
+ model:
32
+ model_cls: MMFusionActionLocalization
33
+ mm_encoder_cls: MMBertForJoint
34
+ use_seg_emb: true
35
+ eval:
36
+ save_path: runs/mtm/vlm/crosstask_zs/eval
37
+ metric: CrossTaskMetric
38
+ predictor: CrossTaskPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_vtt.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTMetaProcessor
9
+ test_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTTextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/mtm/vlm/vtt/checkpoint_last.pt
22
+ model:
23
+ model_cls: MMFusionJoint
24
+ mm_encoder_cls: MMBertForJoint
25
+ use_seg_emb: true
26
+ eval:
27
+ save_path: runs/mtm/vlm/vtt/eval
28
+ metric: RetrievalMetric
29
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_vttqa.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: MSRVTTQAAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTQAMetaProcessor
9
+ test_path: data/msrvtt-qa/MSR_MC_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTQATextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/mtm/vlm/vttqa/checkpoint_last.pt
22
+ model:
23
+ model_cls: MMFusionJoint
24
+ mm_encoder_cls: MMBertForJoint
25
+ use_seg_emb: true
26
+ eval:
27
+ save_path: runs/mtm/vlm/vttqa/eval
28
+ metric: QAMetric
29
+ predictor: QAPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_youcook.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: YoucookVideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: YoucookMetaProcessor
9
+ test_path: data/youcook/youcook_val.pkl
10
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
11
+ use_annotation_text: true
12
+ vfeat_dir: data/feat/feat_youcook_s3d
13
+ text_processor: TextProcessor
14
+ num_iso_layer: 12
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 256
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/mtm/vlm/youcook/checkpoint_last.pt
24
+ model:
25
+ model_cls: MMFusionJoint
26
+ mm_encoder_cls: MMBertForJoint
27
+ use_seg_emb: true
28
+ eval:
29
+ save_path: runs/mtm/vlm/youcook/eval
30
+ metric: RetrievalMetric
31
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/mtm/vlm/test_youcookcap.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: YoucookVideoProcessor
6
+ aligner: DSNLGAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: YoucookNLGMetaProcessor
9
+ test_path: data/youcook/val_list.txt
10
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
11
+ vfeat_dir: data/feat/feat_youcook_s3d
12
+ text_processor: NLGTextProcessor
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/mtm/vlm/youcookcap/checkpoint_best.pt
22
+ model:
23
+ model_cls: MMFusionNLG
24
+ mm_encoder_cls: MMBertForNLG
25
+ max_decode_length: 24
26
+ use_seg_emb: true
27
+ eval:
28
+ save_path: runs/mtm/vlm/youcookcap/eval
29
+ metric: NLGMetric
30
+ predictor: NLGPredictor
31
+ gen_param:
32
+ num_beams: 5
data/fairseq/examples/MMPT/projects/mtm/vlm/vtt.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: MSRVTTMetaProcessor
5
+ train_path: data/msrvtt/MSRVTT_train.csv
6
+ jsfusion_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
7
+ full_test_path: data/msrvtt/MSRVTT_FULL_test.csv
8
+ dup: 20
9
+ val_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTTextProcessor
12
+ json_path: data/msrvtt/MSRVTT_data.json
13
+ aligner: DSAligner
14
+ num_iso_layer: 12
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ common:
19
+ tensorboard_logdir: run
20
+ log_interval: 1000
21
+ fp16: true
22
+ dataset:
23
+ num_workers: 4
24
+ batch_size: 256
25
+ optimization:
26
+ lr:
27
+ - 5.0e-05
28
+ clip_norm: 2.0
29
+ optimizer: adam
30
+ adam_betas: (0.9, 0.98)
31
+ lr_scheduler: polynomial_decay
32
+ total_num_update: 1000000
33
+ warmup_updates: 122
34
+ weight_decay: 0.0
35
+ ddp_backend: no_c10d
36
+ max_epoch: 10
37
+ checkpoint:
38
+ restore_file: runs/mtm/vlm/checkpoint_best.pt
39
+ reset_optimizer: true
40
+ reset_dataloader: true
41
+ reset_meters: true
42
+ save_dir: runs/mtm/vlm/vtt
43
+ task_type: sweep_small
44
+ model:
45
+ model_cls: MMFusionJoint
46
+ mm_encoder_cls: MMBertForJoint
47
+ use_seg_emb: true
48
+ loss:
49
+ loss_cls: T2VContraLoss
data/fairseq/examples/MMPT/projects/mtm/vlm/vttqa.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: MSRVTTMetaProcessor
5
+ train_path: data/msrvtt/MSRVTT_train.csv
6
+ dup: 20
7
+ val_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
8
+ vfeat_dir: data/feat/feat_vtt_s3d
9
+ text_processor: MSRVTTTextProcessor
10
+ json_path: data/msrvtt/MSRVTT_data.json
11
+ aligner: DSAligner
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 128
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 5
35
+ checkpoint:
36
+ restore_file: runs/mtm/vlm/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/mtm/vlm/vttqa
41
+ task_type: sweep_small
42
+ model:
43
+ model_cls: MMFusionJoint
44
+ mm_encoder_cls: MMBertForJoint
45
+ use_seg_emb: true
46
+ loss:
47
+ loss_cls: V2TContraLoss
data/fairseq/examples/MMPT/projects/mtm/vlm/youcook.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: YoucookVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: YoucookMetaProcessor
5
+ train_path: data/youcook/youcook_train.pkl
6
+ val_path: data/youcook/youcook_val.pkl
7
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
8
+ use_annotation_text: true
9
+ vfeat_dir: data/feat/feat_youcook_s3d
10
+ text_processor: TextProcessor
11
+ aligner: DSAligner
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 128
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 10
35
+ checkpoint:
36
+ restore_file: runs/mtm/vlm/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/mtm/vlm/youcook
41
+ task_type: sweep_small
42
+ model:
43
+ model_cls: MMFusionJoint
44
+ mm_encoder_cls: MMBertForJoint
45
+ use_seg_emb: true
46
+ loss:
47
+ loss_cls: T2VContraLoss
data/fairseq/examples/MMPT/projects/mtm/vlm/youcookcap.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: YoucookVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: YoucookNLGMetaProcessor
5
+ train_path: data/youcook/train_list.txt
6
+ val_path: data/youcook/val_list.txt
7
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
8
+ vfeat_dir: data/feat/feat_youcook_s3d
9
+ text_processor: NLGTextProcessor
10
+ aligner: DSNLGAligner
11
+ max_video_len: 32
12
+ max_len: 96
13
+ fairseq:
14
+ common:
15
+ tensorboard_logdir: run
16
+ log_interval: 1000
17
+ fp16: true
18
+ dataset:
19
+ num_workers: 4
20
+ batch_size: 128
21
+ optimization:
22
+ lr:
23
+ - 5.0e-05
24
+ clip_norm: 2.0
25
+ optimizer: adam
26
+ adam_betas: (0.9, 0.98)
27
+ lr_scheduler: polynomial_decay
28
+ total_num_update: 1000000
29
+ warmup_updates: 122
30
+ weight_decay: 0.0
31
+ ddp_backend: no_c10d
32
+ max_epoch: 10
33
+ checkpoint:
34
+ restore_file: runs/mtm/vlm/checkpoint_best.pt
35
+ reset_optimizer: true
36
+ reset_dataloader: true
37
+ reset_meters: true
38
+ save_dir: runs/mtm/vlm/youcookcap
39
+ task_type: sweep_small
40
+ model:
41
+ model_cls: MMFusionNLG
42
+ mm_encoder_cls: MMBertForNLG
43
+ use_seg_emb: true
44
+ loss:
45
+ loss_cls: NLGLoss
data/fairseq/examples/MMPT/projects/retri/videoclip.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ includes: projects/retri/videoretri.yaml
2
+ project_dir: retri/videoclip
3
+ task_group:
4
+ pretrain:
5
+ model:
6
+ model_cls: MMFusionSeparate
7
+ mm_encoder_cls:
8
+ video_encoder_cls: MMBertForEncoder
9
+ text_encoder_cls: BertModel
10
+ num_hidden_video_layers: 6
data/fairseq/examples/MMPT/projects/retri/videoclip/coin_videoclip.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: COINActionSegmentationMetaProcessor
5
+ train_path: data/coin/COIN.json
6
+ val_path: data/coin/COIN.json
7
+ vfeat_dir: data/feat/feat_coin_s3d
8
+ text_processor: COINActionSegmentationTextProcessor
9
+ aligner: COINActionSegmentationAligner
10
+ num_iso_layer: 12
11
+ sliding_window: 8
12
+ sliding_window_size: 32
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 1
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 8
35
+ checkpoint:
36
+ restore_file: runs/retri/videoclip/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/retri/videoclip/coin
41
+ task_type: sweep_big
42
+ model:
43
+ model_cls: MMFusionSeparateActionSegmentation
44
+ mm_encoder_cls: null
45
+ video_encoder_cls: MMBertForTokenClassification
46
+ text_encoder_cls: BertModel
47
+ num_hidden_video_layers: 6
48
+ loss:
49
+ loss_cls: CrossEntropy
data/fairseq/examples/MMPT/projects/retri/videoclip/crosstask_videoclip.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: CrossTaskVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: CrossTaskMetaProcessor
5
+ train_path: data/crosstask/crosstask_release/videos.csv
6
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
7
+ val_path: data/crosstask/crosstask_release/videos_val.csv
8
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
9
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
10
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
11
+ vfeat_dir: data/feat/feat_crosstask_s3d
12
+ annotation_path: data/crosstask/crosstask_release/annotations
13
+ n_train: 30
14
+ text_processor: CrossTaskTextProcessor
15
+ aligner: CrossTaskAligner
16
+ num_iso_layer: 12
17
+ sliding_window: 16
18
+ sliding_window_size: 32
19
+ max_video_len: 32
20
+ max_len: 96
21
+ fairseq:
22
+ common:
23
+ tensorboard_logdir: run
24
+ log_interval: 1000
25
+ fp16: true
26
+ dataset:
27
+ num_workers: 4
28
+ batch_size: 1
29
+ optimization:
30
+ lr:
31
+ - 5.0e-05
32
+ clip_norm: 2.0
33
+ optimizer: adam
34
+ adam_betas: (0.9, 0.98)
35
+ lr_scheduler: polynomial_decay
36
+ total_num_update: 1000000
37
+ warmup_updates: 122
38
+ weight_decay: 0.0
39
+ ddp_backend: no_c10d
40
+ max_epoch: 5
41
+ checkpoint:
42
+ restore_file: runs/retri/videoclip/checkpoint_best.pt
43
+ reset_optimizer: true
44
+ reset_dataloader: true
45
+ reset_meters: true
46
+ save_dir: runs/retri/videoclip/crosstask
47
+ task_type: sweep_small
48
+ model:
49
+ model_cls: MMFusionSeparateActionLocalization
50
+ mm_encoder_cls: null
51
+ video_encoder_cls: MMBertForEncoder
52
+ text_encoder_cls: BertModel
53
+ num_hidden_video_layers: 6
54
+ loss:
55
+ loss_cls: BCE
data/fairseq/examples/MMPT/projects/retri/videoclip/how2.yaml ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: ShardedVideoRetriVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: ShardedHow2VideoRetriMetaProcessor
5
+ train_path: data/how2/how2_s3d_train.lst
6
+ val_path: data/how2/how2_s3d_val.lst
7
+ vfeat_dir: data/feat/feat_how2_s3d_shard_small
8
+ text_processor: ShardedVideoRetriTextProcessor
9
+ tfeat_dir: data/feat/feat_how2_s3d_shard_small/raw_caption_dedup.bert-base-uncased.
10
+ aligner: VideoRetriOverlappedAligner
11
+ subsampling: 1
12
+ sampled_min_len: 8
13
+ sampled_max_len: 64
14
+ max_video_len: 32
15
+ max_len: 96
16
+ lazy_vfeat_mask: true
17
+ mfm_probability: 0.15
18
+ mlm_probability: 0.15
19
+ mm_prob: 0.5
20
+ sampled_video_min_len: 3
21
+ sampled_video_max_len: 32
22
+ num_video_per_batch: 32
23
+ clip_per_video: 16
24
+ fairseq:
25
+ common:
26
+ tensorboard_logdir: run
27
+ log_interval: 1000
28
+ fp16: true
29
+ dataset:
30
+ num_workers: 4
31
+ batch_size: 1
32
+ optimization:
33
+ lr:
34
+ - 5.0e-05
35
+ clip_norm: 2.0
36
+ optimizer: adam
37
+ adam_betas: (0.9, 0.98)
38
+ lr_scheduler: polynomial_decay
39
+ total_num_update: 1000000
40
+ warmup_updates: 1000
41
+ weight_decay: 0.0
42
+ ddp_backend: no_c10d
43
+ max_epoch: 25
44
+ checkpoint:
45
+ save_dir: runs/retri/videoclip
46
+ save_interval_updates: 1024
47
+ keep_interval_updates: 2
48
+ keep_last_epochs: 30
49
+ task_type: sweep_big
50
+ slurm_config: big
51
+ eval:
52
+ save_path: runs/retri/videoclip
53
+ model:
54
+ model_cls: MMFusionSeparate
55
+ mm_encoder_cls: null
56
+ video_encoder_cls: MMBertForEncoder
57
+ text_encoder_cls: BertModel
58
+ num_hidden_video_layers: 6
59
+ loss:
60
+ loss_cls: MMContraLoss
61
+ task: VideoRetriTask
62
+ retri_epoch: 1
63
+ vectorpool_cls: VideoVectorPool
64
+ retriever_cls: VectorRetriever
65
+ num_cands: 64
data/fairseq/examples/MMPT/projects/retri/videoclip/test_coin_videoclip.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: COINActionSegmentationAligner
7
+ bert_name: bert-base-uncased
8
+ test_path: data/coin/COIN.json
9
+ meta_processor: COINActionSegmentationMetaProcessor
10
+ vfeat_dir: data/feat/feat_coin_s3d
11
+ text_processor: COINActionSegmentationTextProcessor
12
+ num_iso_layer: 12
13
+ sliding_window: 16
14
+ sliding_window_size: 32
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 1
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/retri/videoclip/coin/checkpoint_best.pt
24
+ model:
25
+ model_cls: MMFusionSeparateActionSegmentation
26
+ mm_encoder_cls: null
27
+ video_encoder_cls: MMBertForTokenClassification
28
+ text_encoder_cls: BertModel
29
+ num_hidden_video_layers: 6
30
+ eval:
31
+ save_path: runs/retri/videoclip/coin/eval
32
+ metric: COINActionSegmentationMetric
33
+ predictor: COINPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_coin_zs.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: COINActionSegmentationAligner
7
+ bert_name: bert-base-uncased
8
+ test_path: data/coin/COIN.json
9
+ meta_processor: COINActionSegmentationMetaProcessor
10
+ vfeat_dir: data/feat/feat_coin_s3d
11
+ text_processor: COINActionSegmentationTextProcessor
12
+ num_iso_layer: 12
13
+ sliding_window: 16
14
+ sliding_window_size: 32
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 1
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/retri/videoclip/checkpoint_best.pt
24
+ model:
25
+ model_cls: MMFusionSeparate
26
+ mm_encoder_cls: null
27
+ video_encoder_cls: MMBertForEncoder
28
+ text_encoder_cls: BertModel
29
+ num_hidden_video_layers: 6
30
+ eval:
31
+ save_path: runs/retri/videoclip/coin_zs/eval
32
+ metric: COINActionSegmentationMetric
33
+ predictor: COINZSPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_crosstask_videoclip.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: CrossTaskVideoProcessor
6
+ aligner: CrossTaskAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: CrossTaskMetaProcessor
9
+ test_path: data/crosstask/crosstask_release/videos_val.csv
10
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
11
+ val_path: data/crosstask/crosstask_release/videos_val.csv
12
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
13
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
14
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
15
+ vfeat_dir: data/feat/feat_crosstask_s3d
16
+ annotation_path: data/crosstask/crosstask_release/annotations
17
+ n_train: 30
18
+ text_processor: CrossTaskTextProcessor
19
+ num_iso_layer: 12
20
+ sliding_window: 16
21
+ sliding_window_size: 32
22
+ max_video_len: 32
23
+ max_len: 96
24
+ fairseq:
25
+ dataset:
26
+ batch_size: 1
27
+ valid_subset: test
28
+ num_workers: 2
29
+ common_eval:
30
+ path: runs/retri/videoclip/crosstask/checkpoint_best.pt
31
+ model:
32
+ model_cls: MMFusionSeparateActionLocalization
33
+ mm_encoder_cls: null
34
+ video_encoder_cls: MMBertForEncoder
35
+ text_encoder_cls: BertModel
36
+ num_hidden_video_layers: 6
37
+ eval:
38
+ save_path: runs/retri/videoclip/crosstask/eval
39
+ metric: CrossTaskMetric
40
+ predictor: CrossTaskPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_crosstask_zs_videoclip.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: CrossTaskVideoProcessor
6
+ aligner: CrossTaskAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: CrossTaskMetaProcessor
9
+ test_path: data/crosstask/crosstask_release/videos_val.csv
10
+ train_csv_path: data/crosstask/crosstask_release/videos.csv
11
+ val_path: data/crosstask/crosstask_release/videos_val.csv
12
+ val_csv_path: data/crosstask/crosstask_release/videos_val.csv
13
+ primary_path: data/crosstask/crosstask_release/tasks_primary.txt
14
+ related_path: data/crosstask/crosstask_release/tasks_related.txt
15
+ vfeat_dir: data/feat/feat_crosstask_s3d
16
+ annotation_path: data/crosstask/crosstask_release/annotations
17
+ n_train: 30
18
+ text_processor: CrossTaskTextProcessor
19
+ num_iso_layer: 12
20
+ sliding_window: 16
21
+ sliding_window_size: 32
22
+ max_video_len: 32
23
+ max_len: 96
24
+ fairseq:
25
+ dataset:
26
+ batch_size: 1
27
+ valid_subset: test
28
+ num_workers: 2
29
+ common_eval:
30
+ path: runs/retri/videoclip/checkpoint_best.pt
31
+ model:
32
+ model_cls: MMFusionSeparateActionLocalization
33
+ mm_encoder_cls: null
34
+ video_encoder_cls: MMBertForEncoder
35
+ text_encoder_cls: BertModel
36
+ num_hidden_video_layers: 6
37
+ eval:
38
+ save_path: runs/retri/videoclip/crosstask_zs/eval
39
+ metric: CrossTaskMetric
40
+ predictor: CrossTaskPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_didemo_zs.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: DiDeMoAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: DiDeMoMetaProcessor
9
+ test_path: data/didemo/test_data.json
10
+ vfeat_dir: data/feat/feat_didemo_s3d
11
+ text_processor: DiDeMoTextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/retri/videoclip/checkpoint_best.pt
22
+ model:
23
+ model_cls: MMFusionSeparate
24
+ mm_encoder_cls: null
25
+ video_encoder_cls: MMBertForEncoder
26
+ text_encoder_cls: BertModel
27
+ num_hidden_video_layers: 6
28
+ eval:
29
+ save_path: runs/retri/videoclip/didemo_zs/eval
30
+ metric: DiDeMoMetric
31
+ predictor: DiDeMoPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_vtt_videoclip.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTMetaProcessor
9
+ test_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTTextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/retri/videoclip/vtt/checkpoint_last.pt
22
+ model:
23
+ model_cls: MMFusionSeparate
24
+ mm_encoder_cls: null
25
+ video_encoder_cls: MMBertForEncoder
26
+ text_encoder_cls: BertModel
27
+ num_hidden_video_layers: 6
28
+ eval:
29
+ save_path: runs/retri/videoclip/vtt/eval
30
+ metric: RetrievalMetric
31
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_vtt_zs.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTMetaProcessor
9
+ test_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTTextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/retri/videoclip/checkpoint_best.pt
22
+ model:
23
+ model_cls: MMFusionSeparate
24
+ mm_encoder_cls: null
25
+ video_encoder_cls: MMBertForEncoder
26
+ text_encoder_cls: BertModel
27
+ num_hidden_video_layers: 6
28
+ eval:
29
+ save_path: runs/retri/videoclip/vtt_zs/eval
30
+ metric: RetrievalMetric
31
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_vttqa_videoclip.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: MSRVTTQAAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTQAMetaProcessor
9
+ test_path: data/msrvtt-qa/MSR_MC_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTQATextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/retri/videoclip/vttqa/checkpoint_last.pt
22
+ model:
23
+ model_cls: MMFusionSeparate
24
+ mm_encoder_cls: null
25
+ video_encoder_cls: MMBertForEncoder
26
+ text_encoder_cls: BertModel
27
+ num_hidden_video_layers: 6
28
+ eval:
29
+ save_path: runs/retri/videoclip/vttqa/eval
30
+ metric: QAMetric
31
+ predictor: QAPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_vttqa_zs.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: VideoProcessor
6
+ aligner: MSRVTTQAAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: MSRVTTQAMetaProcessor
9
+ test_path: data/msrvtt-qa/MSR_MC_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTQATextProcessor
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ dataset:
17
+ batch_size: 256
18
+ valid_subset: test
19
+ num_workers: 2
20
+ common_eval:
21
+ path: runs/retri/videoclip/checkpoint_best.pt
22
+ model:
23
+ model_cls: MMFusionSeparate
24
+ mm_encoder_cls: null
25
+ video_encoder_cls: MMBertForEncoder
26
+ text_encoder_cls: BertModel
27
+ num_hidden_video_layers: 6
28
+ eval:
29
+ save_path: runs/retri/videoclip/vttqa_zs/eval
30
+ metric: QAMetric
31
+ predictor: QAPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_youcook_videoclip.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: YoucookVideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: YoucookMetaProcessor
9
+ test_path: data/youcook/youcook_val.pkl
10
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
11
+ use_annotation_text: true
12
+ vfeat_dir: data/feat/feat_youcook_s3d
13
+ text_processor: TextProcessor
14
+ num_iso_layer: 12
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 256
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/retri/videoclip/youcook/checkpoint_last.pt
24
+ model:
25
+ model_cls: MMFusionSeparate
26
+ mm_encoder_cls: null
27
+ video_encoder_cls: MMBertForEncoder
28
+ text_encoder_cls: BertModel
29
+ num_hidden_video_layers: 6
30
+ eval:
31
+ save_path: runs/retri/videoclip/youcook/eval
32
+ metric: RetrievalMetric
33
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/test_youcook_zs.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ slurm_config: big
2
+ task_type: local_predict
3
+ dataset:
4
+ split: test
5
+ video_processor: YoucookVideoProcessor
6
+ aligner: DSAligner
7
+ bert_name: bert-base-uncased
8
+ meta_processor: YoucookMetaProcessor
9
+ test_path: data/youcook/youcook_val.pkl
10
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
11
+ use_annotation_text: true
12
+ vfeat_dir: data/feat/feat_youcook_s3d
13
+ text_processor: TextProcessor
14
+ num_iso_layer: 12
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ dataset:
19
+ batch_size: 256
20
+ valid_subset: test
21
+ num_workers: 2
22
+ common_eval:
23
+ path: runs/retri/videoclip/checkpoint_best.pt
24
+ model:
25
+ model_cls: MMFusionSeparate
26
+ mm_encoder_cls: null
27
+ video_encoder_cls: MMBertForEncoder
28
+ text_encoder_cls: BertModel
29
+ num_hidden_video_layers: 6
30
+ eval:
31
+ save_path: runs/retri/videoclip/youcook_zs/eval
32
+ metric: RetrievalMetric
33
+ predictor: RetrievalPredictor
data/fairseq/examples/MMPT/projects/retri/videoclip/vtt_videoclip.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: MSRVTTMetaProcessor
5
+ train_path: data/msrvtt/MSRVTT_train.csv
6
+ jsfusion_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
7
+ full_test_path: data/msrvtt/MSRVTT_FULL_test.csv
8
+ dup: 20
9
+ val_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
10
+ vfeat_dir: data/feat/feat_vtt_s3d
11
+ text_processor: MSRVTTTextProcessor
12
+ json_path: data/msrvtt/MSRVTT_data.json
13
+ aligner: DSAligner
14
+ num_iso_layer: 12
15
+ max_video_len: 32
16
+ max_len: 96
17
+ fairseq:
18
+ common:
19
+ tensorboard_logdir: run
20
+ log_interval: 1000
21
+ fp16: true
22
+ dataset:
23
+ num_workers: 4
24
+ batch_size: 224
25
+ optimization:
26
+ lr:
27
+ - 5.0e-05
28
+ clip_norm: 2.0
29
+ optimizer: adam
30
+ adam_betas: (0.9, 0.98)
31
+ lr_scheduler: polynomial_decay
32
+ total_num_update: 1000000
33
+ warmup_updates: 122
34
+ weight_decay: 0.0
35
+ ddp_backend: no_c10d
36
+ max_epoch: 10
37
+ checkpoint:
38
+ restore_file: runs/retri/videoclip/checkpoint_best.pt
39
+ reset_optimizer: true
40
+ reset_dataloader: true
41
+ reset_meters: true
42
+ save_dir: runs/retri/videoclip/vtt
43
+ task_type: sweep_small
44
+ model:
45
+ model_cls: MMFusionSeparate
46
+ mm_encoder_cls: null
47
+ video_encoder_cls: MMBertForEncoder
48
+ text_encoder_cls: BertModel
49
+ num_hidden_video_layers: 6
50
+ loss:
51
+ loss_cls: T2VContraLoss
data/fairseq/examples/MMPT/projects/retri/videoclip/vttqa_videoclip.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: VideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: MSRVTTMetaProcessor
5
+ train_path: data/msrvtt/MSRVTT_train.csv
6
+ dup: 20
7
+ val_path: data/msrvtt/MSRVTT_JSFUSION_test.csv
8
+ vfeat_dir: data/feat/feat_vtt_s3d
9
+ text_processor: MSRVTTTextProcessor
10
+ json_path: data/msrvtt/MSRVTT_data.json
11
+ aligner: DSAligner
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 128
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 5
35
+ checkpoint:
36
+ restore_file: runs/retri/videoclip/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/retri/videoclip/vttqa
41
+ task_type: sweep_small
42
+ model:
43
+ model_cls: MMFusionSeparate
44
+ mm_encoder_cls: null
45
+ video_encoder_cls: MMBertForEncoder
46
+ text_encoder_cls: BertModel
47
+ num_hidden_video_layers: 6
48
+ loss:
49
+ loss_cls: V2TContraLoss
data/fairseq/examples/MMPT/projects/retri/videoclip/youcook_videoclip.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ video_processor: YoucookVideoProcessor
3
+ bert_name: bert-base-uncased
4
+ meta_processor: YoucookMetaProcessor
5
+ train_path: data/youcook/youcook_train.pkl
6
+ val_path: data/youcook/youcook_val.pkl
7
+ trainval_annotation: data/youcook/youcookii_annotations_trainval.json
8
+ use_annotation_text: true
9
+ vfeat_dir: data/feat/feat_youcook_s3d
10
+ text_processor: TextProcessor
11
+ aligner: DSAligner
12
+ num_iso_layer: 12
13
+ max_video_len: 32
14
+ max_len: 96
15
+ fairseq:
16
+ common:
17
+ tensorboard_logdir: run
18
+ log_interval: 1000
19
+ fp16: true
20
+ dataset:
21
+ num_workers: 4
22
+ batch_size: 128
23
+ optimization:
24
+ lr:
25
+ - 5.0e-05
26
+ clip_norm: 2.0
27
+ optimizer: adam
28
+ adam_betas: (0.9, 0.98)
29
+ lr_scheduler: polynomial_decay
30
+ total_num_update: 1000000
31
+ warmup_updates: 122
32
+ weight_decay: 0.0
33
+ ddp_backend: no_c10d
34
+ max_epoch: 10
35
+ checkpoint:
36
+ restore_file: runs/retri/videoclip/checkpoint_best.pt
37
+ reset_optimizer: true
38
+ reset_dataloader: true
39
+ reset_meters: true
40
+ save_dir: runs/retri/videoclip/youcook
41
+ task_type: sweep_small
42
+ model:
43
+ model_cls: MMFusionSeparate
44
+ mm_encoder_cls: null
45
+ video_encoder_cls: MMBertForEncoder
46
+ text_encoder_cls: BertModel
47
+ num_hidden_video_layers: 6
48
+ loss:
49
+ loss_cls: T2VContraLoss
data/fairseq/examples/MMPT/projects/retri/videoretri.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ includes: projects/mfmmlm.yaml
2
+ project_dir: retri/videoretri
3
+ run_task:
4
+ - how2.yaml
5
+ task_group:
6
+ pretrain:
7
+ task: VideoRetriTask
8
+ retri_epoch: 1
9
+ vectorpool_cls: VideoVectorPool
10
+ retriever_cls: VectorRetriever
11
+ num_cands: 64
12
+ dataset:
13
+ train_path: data/how2/how2_s3d_train.lst
14
+ meta_processor: ShardedHow2VideoRetriMetaProcessor
15
+ video_processor: ShardedVideoRetriVideoProcessor
16
+ text_processor: ShardedVideoRetriTextProcessor
17
+ aligner: VideoRetriOverlappedAligner
18
+ sampled_video_min_len: 3
19
+ sampled_video_max_len: 32
20
+ sampled_min_len: 8
21
+ sampled_max_len: 64
22
+ num_video_per_batch: 32
23
+ # do not use subsampling as it changes fairseq batch_size.
24
+ subsampling: 1 # disable subsampling
25
+ clip_per_video: 16
26
+ fairseq:
27
+ dataset:
28
+ batch_size: 1
29
+ optimization:
30
+ max_epoch: 25
31
+ model:
32
+ model_cls: MMFusionShare
33
+ mm_encoder_cls: MMBertForEncoder
34
+ loss:
35
+ loss_cls: MMContraLoss
36
+ finetune:
37
+ task_list: [vtt_videoclip.yaml, youcook_videoclip.yaml, vttqa_videoclip.yaml, crosstask_videoclip.yaml, coin_videoclip.yaml]
38
+ test:
39
+ task_list:
40
+ - test_youcook_zs.yaml
41
+ - test_vtt_zs.yaml
42
+ - test_vttqa_zs.yaml
43
+ - test_crosstask_zs_videoclip.yaml
44
+ - test_coin_zs.yaml
45
+ - test_didemo_zs.yaml
46
+ - test_youcook_videoclip.yaml
47
+ - test_vtt_videoclip.yaml
48
+ - test_vttqa_videoclip.yaml
49
+ - test_crosstask_videoclip.yaml
50
+ - test_coin_videoclip.yaml
51
+
data/fairseq/examples/MMPT/projects/task/coin.yaml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ includes: projects/task/ft.yaml
2
+ task_type: sweep_big
3
+ dataset:
4
+ meta_processor: COINActionSegmentationMetaProcessor
5
+ train_path: data/coin/COIN.json
6
+ val_path: data/coin/COIN.json
7
+ vfeat_dir: data/feat/feat_coin_s3d
8
+ video_processor: VideoProcessor
9
+ text_processor: COINActionSegmentationTextProcessor
10
+ aligner: COINActionSegmentationAligner
11
+ num_iso_layer: 12
12
+ sliding_window: 8
13
+ sliding_window_size: 32
14
+ model:
15
+ model_cls: MMFusionActionSegmentation
16
+ mm_encoder_cls: MMBertForTokenClassification
17
+ loss:
18
+ loss_cls: CrossEntropy
19
+ fairseq:
20
+ dataset:
21
+ batch_size: 1
22
+ optimization:
23
+ max_epoch: 8
24
+ checkpoint:
25
+ save_dir: runs/task/coin