mirror of
https://github.com/open-mmlab/mmsegmentation.git
synced 2025-06-03 22:03:48 +08:00
## Motivation Support SAN for Open-Vocabulary Semantic Segmentation Paper: [Side Adapter Network for Open-Vocabulary Semantic Segmentation](https://arxiv.org/abs/2302.12242) official Code: [SAN](https://github.com/MendelXu/SAN) ## Modification - Added the parameters of backbone vit for implementing the image encoder of CLIP. - Added text encoder code. - Added segmentor multimodel encoder-decoder code for open-vocabulary semantic segmentation. - Added SideAdapterNetwork decode head code. - Added config files for train and inference. - Added tools for converting pretrained models. - Added loss implementation for mask classification model, such as SAN, Maskformer and remove dependency on mmdetection. - Added test units for text encoder, multimodel encoder-decoder, san decode head and hungarian_assigner. ## Use cases ### Convert Models **pretrained SAN model** The official pretrained model can be downloaded from [san_clip_vit_b_16.pth](https://huggingface.co/Mendel192/san/blob/main/san_vit_b_16.pth) and [san_clip_vit_large_14.pth](https://huggingface.co/Mendel192/san/blob/main/san_vit_large_14.pth). Use tools/model_converters/san2mmseg.py to convert offcial model into mmseg style. `python tools/model_converters/san2mmseg.py <MODEL_PATH> <OUTPUT_PATH>` **pretrained CLIP model** Use the CLIP model provided by openai to train SAN. The CLIP model can be download from [ViT-B-16.pt](https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt) and [ViT-L-14-336px.pt](https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt). Use tools/model_converters/clip2mmseg.py to convert model into mmseg style. `python tools/model_converters/clip2mmseg.py <MODEL_PATH> <OUTPUT_PATH>` ### Inference test san_vit-base-16 model on coco-stuff164k dataset `python tools/test.py ./configs/san/san-vit-b16_coco-stuff164k-640x640.py <TRAINED_MODEL_PATH>` ### Train test san_vit-base-16 model on coco-stuff164k dataset `python tools/train.py ./configs/san/san-vit-b16_coco-stuff164k-640x640.py --cfg-options model.pretrained=<PRETRAINED_MODEL_PATH>` ## Comparision Results ### Train on COCO-Stuff164k | | | mIoU | mAcc | pAcc | | --------------- | ----- | ----- | ----- | ----- | | san-vit-base16 | official | 41.93 | 56.73 | 67.69 | | | mmseg | 41.93 | 56.84 | 67.84 | | san-vit-large14 | official | 45.57 | 59.52 | 69.76 | | | mmseg | 45.78 | 59.61 | 69.21 | ### Evaluate on Pascal Context | | | mIoU | mAcc | pAcc | | --------------- | ----- | ----- | ----- | ----- | | san-vit-base16 | official | 54.05 | 72.96 | 77.77 | | | mmseg | 54.04 | 73.74 | 77.71 | | san-vit-large14 | official | 57.53 | 77.56 | 78.89 | | | mmseg | 56.89 | 76.96 | 78.74 | ### Evaluate on Voc12Aug | | | mIoU | mAcc | pAcc | | --------------- | ----- | ----- | ----- | ----- | | san-vit-base16 | official | 93.86 | 96.61 | 97.11 | | | mmseg | 94.58 | 97.01 | 97.38 | | san-vit-large14 | official | 95.17 | 97.61 | 97.63 | | | mmseg | 95.58 | 97.75 | 97.79 | --------- Co-authored-by: CastleDream <35064479+CastleDream@users.noreply.github.com> Co-authored-by: yeedrag <46050186+yeedrag@users.noreply.github.com> Co-authored-by: Yang-ChangHui <71805205+Yang-Changhui@users.noreply.github.com> Co-authored-by: Xu CAO <49406546+SheffieldCao@users.noreply.github.com> Co-authored-by: xiexinch <xiexinch@outlook.com> Co-authored-by: 小飞猪 <106524776+ooooo-create@users.noreply.github.com>
89 lines
3.8 KiB
Python
89 lines
3.8 KiB
Python
# Copyright (c) OpenMMLab. All rights reserved.
|
|
import torch
|
|
from mmcv.ops import point_sample
|
|
from torch import Tensor
|
|
|
|
|
|
def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor:
|
|
"""Estimate uncertainty based on pred logits.
|
|
|
|
We estimate uncertainty as L1 distance between 0.0 and the logits
|
|
prediction in 'mask_preds' for the foreground class in `classes`.
|
|
|
|
Args:
|
|
mask_preds (Tensor): mask predication logits, shape (num_rois,
|
|
num_classes, mask_height, mask_width).
|
|
|
|
labels (Tensor): Either predicted or ground truth label for
|
|
each predicted mask, of length num_rois.
|
|
|
|
Returns:
|
|
scores (Tensor): Uncertainty scores with the most uncertain
|
|
locations having the highest uncertainty score,
|
|
shape (num_rois, 1, mask_height, mask_width)
|
|
"""
|
|
if mask_preds.shape[1] == 1:
|
|
gt_class_logits = mask_preds.clone()
|
|
else:
|
|
inds = torch.arange(mask_preds.shape[0], device=mask_preds.device)
|
|
gt_class_logits = mask_preds[inds, labels].unsqueeze(1)
|
|
return -torch.abs(gt_class_logits)
|
|
|
|
|
|
def get_uncertain_point_coords_with_randomness(
|
|
mask_preds: Tensor, labels: Tensor, num_points: int,
|
|
oversample_ratio: float, importance_sample_ratio: float) -> Tensor:
|
|
"""Get ``num_points`` most uncertain points with random points during
|
|
train.
|
|
|
|
Sample points in [0, 1] x [0, 1] coordinate space based on their
|
|
uncertainty. The uncertainties are calculated for each point using
|
|
'get_uncertainty()' function that takes point's logit prediction as
|
|
input.
|
|
|
|
Args:
|
|
mask_preds (Tensor): A tensor of shape (num_rois, num_classes,
|
|
mask_height, mask_width) for class-specific or class-agnostic
|
|
prediction.
|
|
labels (Tensor): The ground truth class for each instance.
|
|
num_points (int): The number of points to sample.
|
|
oversample_ratio (float): Oversampling parameter.
|
|
importance_sample_ratio (float): Ratio of points that are sampled
|
|
via importnace sampling.
|
|
|
|
Returns:
|
|
point_coords (Tensor): A tensor of shape (num_rois, num_points, 2)
|
|
that contains the coordinates sampled points.
|
|
"""
|
|
assert oversample_ratio >= 1
|
|
assert 0 <= importance_sample_ratio <= 1
|
|
batch_size = mask_preds.shape[0]
|
|
num_sampled = int(num_points * oversample_ratio)
|
|
point_coords = torch.rand(
|
|
batch_size, num_sampled, 2, device=mask_preds.device)
|
|
point_logits = point_sample(mask_preds, point_coords)
|
|
# It is crucial to calculate uncertainty based on the sampled
|
|
# prediction value for the points. Calculating uncertainties of the
|
|
# coarse predictions first and sampling them for points leads to
|
|
# incorrect results. To illustrate this: assume uncertainty func(
|
|
# logits)=-abs(logits), a sampled point between two coarse
|
|
# predictions with -1 and 1 logits has 0 logits, and therefore 0
|
|
# uncertainty value. However, if we calculate uncertainties for the
|
|
# coarse predictions first, both will have -1 uncertainty,
|
|
# and sampled point will get -1 uncertainty.
|
|
point_uncertainties = get_uncertainty(point_logits, labels)
|
|
num_uncertain_points = int(importance_sample_ratio * num_points)
|
|
num_random_points = num_points - num_uncertain_points
|
|
idx = torch.topk(
|
|
point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
|
|
shift = num_sampled * torch.arange(
|
|
batch_size, dtype=torch.long, device=mask_preds.device)
|
|
idx += shift[:, None]
|
|
point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view(
|
|
batch_size, num_uncertain_points, 2)
|
|
if num_random_points > 0:
|
|
rand_roi_coords = torch.rand(
|
|
batch_size, num_random_points, 2, device=mask_preds.device)
|
|
point_coords = torch.cat((point_coords, rand_roi_coords), dim=1)
|
|
return point_coords
|