Diff of /docs/getting_started.md [000000] .. [6d389a]

Switch to unified view

a b/docs/getting_started.md
1
# Getting Started
2
3
This page provides basic tutorials about the usage of MMAction2.
4
For installation instructions, please see [install.md](install.md).
5
6
<!-- TOC -->
7
8
- [Getting Started](#getting-started)
9
  - [Datasets](#datasets)
10
  - [Inference with Pre-Trained Models](#inference-with-pre-trained-models)
11
    - [Test a dataset](#test-a-dataset)
12
    - [High-level APIs for testing a video and rawframes](#high-level-apis-for-testing-a-video-and-rawframes)
13
  - [Build a Model](#build-a-model)
14
    - [Build a model with basic components](#build-a-model-with-basic-components)
15
    - [Write a new model](#write-a-new-model)
16
  - [Train a Model](#train-a-model)
17
    - [Iteration pipeline](#iteration-pipeline)
18
    - [Training setting](#training-setting)
19
    - [Train with a single GPU](#train-with-a-single-gpu)
20
    - [Train with multiple GPUs](#train-with-multiple-gpus)
21
    - [Train with multiple machines](#train-with-multiple-machines)
22
    - [Launch multiple jobs on a single machine](#launch-multiple-jobs-on-a-single-machine)
23
  - [Tutorials](#tutorials)
24
25
<!-- TOC -->
26
27
## Datasets
28
29
It is recommended to symlink the dataset root to `$MMACTION2/data`.
30
If your folder structure is different, you may need to change the corresponding paths in config files.
31
32
```
33
mmaction2
34
├── mmaction
35
├── tools
36
├── configs
37
├── data
38
│   ├── kinetics400
39
│   │   ├── rawframes_train
40
│   │   ├── rawframes_val
41
│   │   ├── kinetics_train_list.txt
42
│   │   ├── kinetics_val_list.txt
43
│   ├── ucf101
44
│   │   ├── rawframes_train
45
│   │   ├── rawframes_val
46
│   │   ├── ucf101_train_list.txt
47
│   │   ├── ucf101_val_list.txt
48
│   ├── ...
49
```
50
51
For more information on data preparation, please see [data_preparation.md](data_preparation.md)
52
53
For using custom datasets, please refer to [Tutorial 3: Adding New Dataset](tutorials/3_new_dataset.md)
54
55
## Inference with Pre-Trained Models
56
57
We provide testing scripts to evaluate a whole dataset (Kinetics-400, Something-Something V1&V2, (Multi-)Moments in Time, etc.),
58
and provide some high-level apis for easier integration to other projects.
59
60
### Test a dataset
61
62
- [x] single GPU
63
- [x] single node multiple GPUs
64
- [x] multiple node
65
66
You can use the following commands to test a dataset.
67
68
```shell
69
# single-gpu testing
70
python tools/test.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] \
71
    [--gpu-collect] [--tmpdir ${TMPDIR}] [--options ${OPTIONS}] [--average-clips ${AVG_TYPE}] \
72
    [--launcher ${JOB_LAUNCHER}] [--local_rank ${LOCAL_RANK}] [--onnx] [--tensorrt]
73
74
# multi-gpu testing
75
./tools/dist_test.sh ${CONFIG_FILE} ${CHECKPOINT_FILE} ${GPU_NUM} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] \
76
    [--gpu-collect] [--tmpdir ${TMPDIR}] [--options ${OPTIONS}] [--average-clips ${AVG_TYPE}] \
77
    [--launcher ${JOB_LAUNCHER}] [--local_rank ${LOCAL_RANK}]
78
```
79
80
Optional arguments:
81
82
- `RESULT_FILE`: Filename of the output results. If not specified, the results will not be saved to a file.
83
- `EVAL_METRICS`: Items to be evaluated on the results. Allowed values depend on the dataset, e.g., `top_k_accuracy`, `mean_class_accuracy` are available for all datasets in recognition, `mmit_mean_average_precision` for Multi-Moments in Time, `mean_average_precision` for Multi-Moments in Time and HVU single category. `AR@AN` for ActivityNet, etc.
84
- `--gpu-collect`: If specified, recognition results will be collected using gpu communication. Otherwise, it will save the results on different gpus to `TMPDIR` and collect them by the rank 0 worker.
85
- `TMPDIR`: Temporary directory used for collecting results from multiple workers, available when `--gpu-collect` is not specified.
86
- `OPTIONS`: Custom options used for evaluation. Allowed values depend on the arguments of the `evaluate` function in dataset.
87
- `AVG_TYPE`: Items to average the test clips. If set to `prob`, it will apply softmax before averaging the clip scores. Otherwise, it will directly average the clip scores.
88
- `JOB_LAUNCHER`: Items for distributed job initialization launcher. Allowed choices are `none`, `pytorch`, `slurm`, `mpi`. Especially, if set to none, it will test in a non-distributed mode.
89
- `LOCAL_RANK`: ID for local rank. If not specified, it will be set to 0.
90
- `--onnx`: If specified, recognition results will be generated by onnx model and `CHECKPOINT_FILE` should be onnx model file path. Onnx model files are generated by `/tools/deployment/pytorch2onnx.py`. For now, multi-gpu mode and dynamic input shape mode are not supported. Please note that the output tensors of dataset and the input tensors of onnx model should share the same shape. And it is recommended to remove all test-time augmentation methods in `test_pipeline`(`ThreeCrop`, `TenCrop`, `twice_sample`, etc.)
91
- `--tensorrt`: If specified, recognition results will be generated by TensorRT engine and `CHECKPOINT_FILE` should be TensorRT engine file path. TensorRT engines are generated by exported onnx models and TensorRT official conversion tools. For now, multi-gpu mode and dynamic input shape mode are not supported. Please note that the output tensors of dataset and the input tensors of TensorRT engine should share the same shape. And it is recommended to remove all test-time augmentation methods in `test_pipeline`(`ThreeCrop`, `TenCrop`, `twice_sample`, etc.)
92
93
Examples:
94
95
Assume that you have already downloaded the checkpoints to the directory `checkpoints/`.
96
97
1. Test TSN on Kinetics-400 (without saving the test results) and evaluate the top-k accuracy and mean class accuracy.
98
99
    ```shell
100
    python tools/test.py configs/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py \
101
        checkpoints/SOME_CHECKPOINT.pth \
102
        --eval top_k_accuracy mean_class_accuracy
103
    ```
104
105
2. Test TSN on Something-Something V1 with 8 GPUS, and evaluate the top-k accuracy.
106
107
    ```shell
108
    ./tools/dist_test.sh configs/recognition/tsn/tsn_r50_1x1x8_50e_sthv1_rgb.py \
109
        checkpoints/SOME_CHECKPOINT.pth \
110
        8 --out results.pkl --eval top_k_accuracy
111
    ```
112
113
3. Test TSN on Kinetics-400 in slurm environment and evaluate the top-k accuracy
114
115
    ```shell
116
    python tools/test.py configs/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py \
117
        checkpoints/SOME_CHECKPOINT.pth \
118
        --launcher slurm --eval top_k_accuracy
119
    ```
120
121
4. Test TSN on Something-Something V1 with onnx model and evaluate the top-k accuracy
122
123
    ```shell
124
    python tools/test.py configs/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py \
125
        checkpoints/SOME_CHECKPOINT.onnx \
126
        --eval top_k_accuracy --onnx
127
    ```
128
129
### High-level APIs for testing a video and rawframes
130
131
Here is an example of building the model and testing a given video.
132
133
```python
134
import torch
135
136
from mmaction.apis import init_recognizer, inference_recognizer
137
138
config_file = 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py'
139
# download the checkpoint from model zoo and put it in `checkpoints/`
140
checkpoint_file = 'checkpoints/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth'
141
142
# assign the desired device.
143
device = 'cuda:0' # or 'cpu'
144
device = torch.device(device)
145
146
 # build the model from a config file and a checkpoint file
147
model = init_recognizer(config_file, checkpoint_file, device=device)
148
149
# test a single video and show the result:
150
video = 'demo/demo.mp4'
151
labels = 'tools/data/kinetics/label_map_k400.txt'
152
results = inference_recognizer(model, video, labels)
153
154
# show the results
155
labels = open('tools/data/kinetics/label_map_k400.txt').readlines()
156
labels = [x.strip() for x in labels]
157
results = [(labels[k[0]], k[1]) for k in results]
158
159
print(f'The top-5 labels with corresponding scores are:')
160
for result in results:
161
    print(f'{result[0]}: ', result[1])
162
```
163
164
Here is an example of building the model and testing with a given rawframes directory.
165
166
```python
167
import torch
168
169
from mmaction.apis import init_recognizer, inference_recognizer
170
171
config_file = 'configs/recognition/tsn/tsn_r50_inference_1x1x3_100e_kinetics400_rgb.py'
172
# download the checkpoint from model zoo and put it in `checkpoints/`
173
checkpoint_file = 'checkpoints/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth'
174
175
# assign the desired device.
176
device = 'cuda:0' # or 'cpu'
177
device = torch.device(device)
178
179
 # build the model from a config file and a checkpoint file
180
model = init_recognizer(config_file, checkpoint_file, device=device, use_frames=True)
181
182
# test rawframe directory of a single video and show the result:
183
video = 'SOME_DIR_PATH/'
184
labels = 'tools/data/kinetics/label_map_k400.txt'
185
results = inference_recognizer(model, video, labels, use_frames=True)
186
187
# show the results
188
labels = open('tools/data/kinetics/label_map_k400.txt').readlines()
189
labels = [x.strip() for x in labels]
190
results = [(labels[k[0]], k[1]) for k in results]
191
192
print(f'The top-5 labels with corresponding scores are:')
193
for result in results:
194
    print(f'{result[0]}: ', result[1])
195
```
196
197
Here is an example of building the model and testing with a given video url.
198
199
```python
200
import torch
201
202
from mmaction.apis import init_recognizer, inference_recognizer
203
204
config_file = 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py'
205
# download the checkpoint from model zoo and put it in `checkpoints/`
206
checkpoint_file = 'checkpoints/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth'
207
208
# assign the desired device.
209
device = 'cuda:0' # or 'cpu'
210
device = torch.device(device)
211
212
 # build the model from a config file and a checkpoint file
213
model = init_recognizer(config_file, checkpoint_file, device=device)
214
215
# test url of a single video and show the result:
216
video = 'https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4'
217
labels = 'tools/data/kinetics/label_map_k400.txt'
218
results = inference_recognizer(model, video, labels)
219
220
# show the results
221
labels = open('tools/data/kinetics/label_map_k400.txt').readlines()
222
labels = [x.strip() for x in labels]
223
results = [(labels[k[0]], k[1]) for k in results]
224
225
print(f'The top-5 labels with corresponding scores are:')
226
for result in results:
227
    print(f'{result[0]}: ', result[1])
228
```
229
230
:::{note}
231
We define `data_prefix` in config files and set it None as default for our provided inference configs.
232
If the `data_prefix` is not None, the path for the video file (or rawframe directory) to get will be `data_prefix/video`.
233
Here, the `video` is the param in the demo scripts above.
234
This detail can be found in `rawframe_dataset.py` and `video_dataset.py`. For example,
235
236
- When video (rawframes) path is `SOME_DIR_PATH/VIDEO.mp4` (`SOME_DIR_PATH/VIDEO_NAME/img_xxxxx.jpg`), and `data_prefix` is None in the config file,
237
  the param `video` should be `SOME_DIR_PATH/VIDEO.mp4` (`SOME_DIR_PATH/VIDEO_NAME`).
238
- When video (rawframes) path is `SOME_DIR_PATH/VIDEO.mp4` (`SOME_DIR_PATH/VIDEO_NAME/img_xxxxx.jpg`), and `data_prefix` is `SOME_DIR_PATH` in the config file,
239
  the param `video` should be `VIDEO.mp4` (`VIDEO_NAME`).
240
- When rawframes path is `VIDEO_NAME/img_xxxxx.jpg`, and `data_prefix` is None in the config file, the param `video` should be `VIDEO_NAME`.
241
- When passing a url instead of a local video file, you need to use OpenCV as the video decoding backend.
242
243
:::
244
245
A notebook demo can be found in [demo/demo.ipynb](/demo/demo.ipynb)
246
247
## Build a Model
248
249
### Build a model with basic components
250
251
In MMAction2, model components are basically categorized as 4 types.
252
253
- recognizer: the whole recognizer model pipeline, usually contains a backbone and cls_head.
254
- backbone: usually an FCN network to extract feature maps, e.g., ResNet, BNInception.
255
- cls_head: the component for classification task, usually contains an FC layer with some pooling layers.
256
- localizer: the model for localization task, currently available: BSN, BMN.
257
258
Following some basic pipelines (e.g., `Recognizer2D`), the model structure
259
can be customized through config files with no pains.
260
261
If we want to implement some new components, e.g., the temporal shift backbone structure as
262
in [TSM: Temporal Shift Module for Efficient Video Understanding](https://arxiv.org/abs/1811.08383), there are several things to do.
263
264
1. create a new file in `mmaction/models/backbones/resnet_tsm.py`.
265
266
    ```python
267
    from ..builder import BACKBONES
268
    from .resnet import ResNet
269
270
    @BACKBONES.register_module()
271
    class ResNetTSM(ResNet):
272
273
      def __init__(self,
274
                   depth,
275
                   num_segments=8,
276
                   is_shift=True,
277
                   shift_div=8,
278
                   shift_place='blockres',
279
                   temporal_pool=False,
280
                   **kwargs):
281
          pass
282
283
      def forward(self, x):
284
          # implementation is ignored
285
          pass
286
    ```
287
288
2. Import the module in `mmaction/models/backbones/__init__.py`
289
290
    ```python
291
    from .resnet_tsm import ResNetTSM
292
    ```
293
294
3. modify the config file from
295
296
    ```python
297
    backbone=dict(
298
      type='ResNet',
299
      pretrained='torchvision://resnet50',
300
      depth=50,
301
      norm_eval=False)
302
    ```
303
304
   to
305
306
    ```python
307
    backbone=dict(
308
        type='ResNetTSM',
309
        pretrained='torchvision://resnet50',
310
        depth=50,
311
        norm_eval=False,
312
        shift_div=8)
313
    ```
314
315
### Write a new model
316
317
To write a new recognition pipeline, you need to inherit from `BaseRecognizer`,
318
which defines the following abstract methods.
319
320
- `forward_train()`: forward method of the training mode.
321
- `forward_test()`: forward method of the testing mode.
322
323
[Recognizer2D](/mmaction/models/recognizers/recognizer2d.py) and [Recognizer3D](/mmaction/models/recognizers/recognizer3d.py)
324
are good examples which show how to do that.
325
326
## Train a Model
327
328
### Iteration pipeline
329
330
MMAction2 implements distributed training and non-distributed training,
331
which uses `MMDistributedDataParallel` and `MMDataParallel` respectively.
332
333
We adopt distributed training for both single machine and multiple machines.
334
Supposing that the server has 8 GPUs, 8 processes will be started and each process runs on a single GPU.
335
336
Each process keeps an isolated model, data loader, and optimizer.
337
Model parameters are only synchronized once at the beginning.
338
After a forward and backward pass, gradients will be allreduced among all GPUs,
339
and the optimizer will update model parameters.
340
Since the gradients are allreduced, the model parameter stays the same for all processes after the iteration.
341
342
### Training setting
343
344
All outputs (log files and checkpoints) will be saved to the working directory,
345
which is specified by `work_dir` in the config file.
346
347
By default we evaluate the model on the validation set after each epoch, you can change the evaluation interval by modifying the interval argument in the training config
348
349
```python
350
evaluation = dict(interval=5)  # This evaluate the model per 5 epoch.
351
```
352
353
According to the [Linear Scaling Rule](https://arxiv.org/abs/1706.02677), you need to set the learning rate proportional to the batch size if you use different GPUs or videos per GPU, e.g., lr=0.01 for 4 GPUs x 2 video/gpu and lr=0.08 for 16 GPUs x 4 video/gpu.
354
355
### Train with a single GPU
356
357
```shell
358
python tools/train.py ${CONFIG_FILE} [optional arguments]
359
```
360
361
If you want to specify the working directory in the command, you can add an argument `--work-dir ${YOUR_WORK_DIR}`.
362
363
### Train with multiple GPUs
364
365
```shell
366
./tools/dist_train.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments]
367
```
368
369
Optional arguments are:
370
371
- `--validate` (**strongly recommended**): Perform evaluation at every k (default value is 5, which can be modified by changing the `interval` value in `evaluation` dict in each config file) epochs during the training.
372
- `--test-last`: Test the final checkpoint when training is over, save the prediction to `${WORK_DIR}/last_pred.pkl`.
373
- `--test-best`: Test the best checkpoint when training is over, save the prediction to `${WORK_DIR}/best_pred.pkl`.
374
- `--work-dir ${WORK_DIR}`: Override the working directory specified in the config file.
375
- `--resume-from ${CHECKPOINT_FILE}`: Resume from a previous checkpoint file.
376
- `--gpus ${GPU_NUM}`: Number of gpus to use, which is only applicable to non-distributed training.
377
- `--gpu-ids ${GPU_IDS}`: IDs of gpus to use, which is only applicable to non-distributed training.
378
- `--seed ${SEED}`: Seed id for random state in python, numpy and pytorch to generate random numbers.
379
- `--deterministic`: If specified, it will set deterministic options for CUDNN backend.
380
- `JOB_LAUNCHER`: Items for distributed job initialization launcher. Allowed choices are `none`, `pytorch`, `slurm`, `mpi`. Especially, if set to none, it will test in a non-distributed mode.
381
- `LOCAL_RANK`: ID for local rank. If not specified, it will be set to 0.
382
383
Difference between `resume-from` and `load-from`:
384
`resume-from` loads both the model weights and optimizer status, and the epoch is also inherited from the specified checkpoint. It is usually used for resuming the training process that is interrupted accidentally.
385
`load-from` only loads the model weights and the training epoch starts from 0. It is usually used for finetuning.
386
387
Here is an example of using 8 GPUs to load TSN checkpoint.
388
389
```shell
390
./tools/dist_train.sh configs/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py 8 --resume-from work_dirs/tsn_r50_1x1x3_100e_kinetics400_rgb/latest.pth
391
```
392
393
### Train with multiple machines
394
395
If you can run MMAction2 on a cluster managed with [slurm](https://slurm.schedmd.com/), you can use the script `slurm_train.sh`. (This script also supports single machine training.)
396
397
```shell
398
[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} [--work-dir ${WORK_DIR}]
399
```
400
401
Here is an example of using 16 GPUs to train TSN on the dev partition in a slurm cluster. (use `GPUS_PER_NODE=8` to specify a single slurm cluster node with 8 GPUs.)
402
403
```shell
404
GPUS=16 ./tools/slurm_train.sh dev tsn_r50_k400 configs/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb.py --work-dir work_dirs/tsn_r50_1x1x3_100e_kinetics400_rgb
405
```
406
407
You can check [slurm_train.sh](/tools/slurm_train.sh) for full arguments and environment variables.
408
409
If you have just multiple machines connected with ethernet, you can refer to
410
pytorch [launch utility](https://pytorch.org/docs/stable/distributed.html#launch-utility).
411
Usually it is slow if you do not have high speed networking like InfiniBand.
412
413
### Launch multiple jobs on a single machine
414
415
If you launch multiple jobs on a single machine, e.g., 2 jobs of 4-GPU training on a machine with 8 GPUs,
416
you need to specify different ports (29500 by default) for each job to avoid communication conflict.
417
418
If you use `dist_train.sh` to launch training jobs, you can set the port in commands.
419
420
```shell
421
CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4
422
CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4
423
```
424
425
If you use launch training jobs with slurm, you need to modify `dist_params` in the config files (usually the 6th line from the bottom in config files) to set different communication ports.
426
427
In `config1.py`,
428
429
```python
430
dist_params = dict(backend='nccl', port=29500)
431
```
432
433
In `config2.py`,
434
435
```python
436
dist_params = dict(backend='nccl', port=29501)
437
```
438
439
Then you can launch two jobs with `config1.py` ang `config2.py`.
440
441
```shell
442
CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py [--work-dir ${WORK_DIR}]
443
CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py [--work-dir ${WORK_DIR}]
444
```
445
446
## Tutorials
447
448
Currently, we provide some tutorials for users to [learn about configs](tutorials/1_config.md), [finetune model](tutorials/2_finetune.md),
449
[add new dataset](tutorials/3_new_dataset.md), [customize data pipelines](tutorials/4_data_pipeline.md),
450
[add new modules](tutorials/5_new_modules.md), [export a model to ONNX](tutorials/6_export_model.md) and [customize runtime settings](tutorials/7_customize_runtime.md).