Torchreid Documentation

repository·master·Indexed 26 days ago

https://github.com/kaiyangzhou/deep-person-reid

A PyTorch-based library for deep-learning person re-identification (re-ID). It supports image- and video-based re-ID, multi-GPU training, and provides tools for end-to-end training, evaluation, and dataset preparation. The library includes a model zoo with OSNet variants, support for numerous datasets like Market1501 and MSMT17, and specialized projects for Person Attribute Recognition, Deep Mutual Learning (DML), and Differentiable NAS for OSNet-AIN.

Tokens
10.7K
Snippets
29
Records
88
Agent score
89%

What's inside Torchreid

  1. Quickstart: Train a model with Torchreid

    master

    This example demonstrates the standard workflow for training a person re-identification model: importing the library, initializing an ImageDataManager, building a model, optimizer, and scheduler, and finally running the training loop using ImageSoftmaxEngine.

    import torchreid
    
    # 1. Load data manager
    datamanager = torchreid.data.ImageDataManager(
        root="reid-data",
        sources="market1501",
        targets="market1501",
        height=256,
        width=128,
        batch_size_train=32,
        batch_size_test=100,
        transforms=["random_flip", "random_crop"]
    )
    
    # 2. Build model, optimizer and lr_scheduler
    model = torchreid.models.build_model(
        name="resnet50",
        num_classes=datamanager.num_train_pids,
        loss="softmax",
        pretrained=True
    )
    
    model = model.cuda()
    
    optimizer = torchreid.optim.build_optimizer(
        model,
        optim="adam",
        lr=0.0003
    )
    
    scheduler = torchreid.optim.build_lr_scheduler(
        optimizer,
        lr_scheduler="single_step",
        stepsize=20
    )
    
    # 3. Build engine
    engine = torchreid.engine.ImageSoftmaxEngine(
        datamanager,
        model,
        optimizer=optimizer,
        scheduler=scheduler,
        label_smooth=True
    )
    
    # 4. Run training and test
    engine.run(
        save_dir="log/resnet50",
        max_epoch=60,
        eval_freq=10,
        print_freq=10,
        test_only=False
    )
  2. Train and test models using scripts/main.py

    master

    Torchreid provides a unified interface via scripts/main.py to train and test models. You can use predefined configurations located in the configs/ directory as starting points.

    To train a model (e.g., OSNet) on a specific dataset like Market1501, use the --config-file flag to specify a config, --transforms to define augmentations, and --root to point to your dataset directory.

    python scripts/main.py \
        --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \
        --transforms random_flip random_erase \
        --root $PATH_TO_DATA
  3. Train the Differentiable NAS for OSNet-AIN

    master

    To perform the neural architecture search (NAS) to find the optimal OSNet+IN design, run the main.py script using the nas.yaml configuration file. Ensure your re-ID data is stored in a directory and provided via the --root flag.

    Important Notes:

    • Hardware: The default configuration is optimized for 8 Tesla V100 32GB GPUs. You may need to adjust the batch size in the config file to match your available device memory.
    • Evaluation: Do not use the test results obtained at the end of the architecture search to judge model performance. The results are not meaningful due to stochastic sampling layers used during the search process.
    • Final Model: To evaluate the discovered architecture, you must manually construct the found architecture in osnet_child.py, then perform a standard re-train and evaluation on your re-ID datasets.
    python main.py --config-file nas.yaml --root $DATA
  4. Use Same-domain ReID models

    master

    For ReID tasks within the same domain, several models are available with varying complexity. Results are reported as Rank-1 (mAP).

    Common configurations include:

    • resnet50: 23.5M params, 2.7 GFLOPs, uses softmax loss and euclidean distance.
    • osnet_x1_0: 2.2M params, 0.98 GFLOPs, uses softmax loss and euclidean distance.
    • osnet_x0_25: 0.2M params, 0.08 GFLOPs, optimized for low complexity.

    Standard input size for most models is (256, 128) with random_flip and random_crop transforms.

  5. Use your own custom dataset

    master

    To use a custom dataset in Torchreid, follow these three steps:

    1. Create a dataset class: Inherit from torchreid.data.ImageDataset (for images) or torchreid.data.VideoDataset (for video). You must generate three lists: train, query, and gallery. Each list must contain tuples of (img_path, pid, camid):
      • img_path (str): Absolute path to the image.
      • pid (int): 0-based person ID.
      • camid (int): 0-based camera ID.
      • Note: query and gallery must share the same pid scope. train, query, and gallery must share the same camid scope.
    2. Register the dataset: Use torchreid.data.register_image_dataset to make your class available via a string name.
    3. Initialize an ImageDataManager: Use the registered name in the sources argument.
    from torchreid.data import ImageDataset
    import os.path as osp
    
    class NewDataset(ImageDataset):
        dataset_dir = 'new_dataset'
    
        def __init__(self, root='', **kwargs):
            self.root = osp.abspath(osp.expanduser(root))
            self.dataset_dir = osp.join(self.root, self.dataset_dir)
    
            # Lists must contain (img_path, pid, camid)
            train = [('/path/to/img1.jpg', 0, 0), ...]
            query = [('/path/to/img2.jpg', 0, 1), ...]
            gallery = [('/path/to/img3.jpg', 0, 1), ...]
    
            super(NewDataset, self).__init__(train, query, gallery, **kwargs)
    
    import torchreid
    torchreid.data.register_image_dataset('new_dataset', NewDataset)
    
    # Initialize Data Manager
    datamanager = torchreid.data.ImageDataManager(
        root='reid-data',
        sources='new_dataset'
    )
  6. Visualize training curves with TensorBoard

    master

    Torchreid automatically saves TensorBoard files in the training log directory. To visualize learning curves, run the following command in your terminal and visit http://localhost:6006/ in your browser:

    tensorboard --logdir=log/osnet_x1_0_market1501_softmax_cosinelr
  7. Manual setup for MARS video dataset

    master

    To manually set up the MARS video dataset:

    1. Create mars/ under $REID.
    2. Place the downloaded dataset in mars/.
    3. Extract bbox_train.zip and bbox_test.zip into mars/.
    4. Download split metadata and place the info/ folder in mars/.

    Expected structure:

    mars/
        bbox_test/
        bbox_train/
        info/
  8. Use Cross-domain ReID models

    master

    Cross-domain ReID models are trained to generalize across different datasets.

    Market1501 $\rightarrow$ DukeMTMC-reID

    • osnet_ibn_x1_0: Uses euclidean distance.
    • osnet_ain_x1_0: Uses cosine distance.

    DukeMTMC-reID $\rightarrow$ Market1501

    • osnet_ibn_x1_0: Uses euclidean distance.
    • osnet_ain_x1_0: Uses cosine distance.

    MSMT17 $\rightarrow$ Market1501 & DukeMTMC-reID

    Models trained with combineall=True on MSMT17 can be used for cross-domain tasks.

    • osnet_ain_x1_0 (using cosine distance) generally provides higher performance for these transfers.