WAMA M⚙️dules
A PyTorch Computer Vision (CV) module library for building n-D networks flexibly ~
(Simple-to-use & Function-rich!)
Highlights
- Simple code and detailed annotation
- Easy and flexible to integrate with other codes
- Support 1D / 2D / 3D networks (for 1D signal, 2D image, 3D video, 3D medical image...)
- Abundant structure: CNN, GNN, Transformer
- Friendly demo codes
- 🚀 Abundant Pretrained weights: including 80000+
2D weights and 80+ 3D weights
Pretrained weights:
[Google Drive]
[Baidu Netdisk psw: wama ]
Quick start with demo codes of 6 different novel multi-label network structures
all model codes are re-constructed in a very simple way
| Network |
Publication |
Demo code |
Paper link |
Support multi-class per label |
| CNNRNN |
CVPR2016 |
code |
link |
× |
| ML-GCN |
CVPR2019 |
code |
link |
× |
| SSGRL |
ICCV2019 |
code |
link |
√ |
| C-tran |
CVPR2021 |
code |
link |
√ |
| ML-decoder |
arxiv2021 |
code |
link |
√ |
| Q2L |
arxiv2021 |
code |
link |
√ |
1. Installation
🔥 wama_modules
Basic 1D/2D/3D
Install wama_modules with command ↓
pip install git+https://github.com/WAMAWAMA/wama_modules.git
Other ways to install (or use) wama_modules
- Way1: Download code and run
python setup.py install
- Way2: Directly copy the folder
wama_modules into your project path
💧 segmentation_models_pytorch
Optional 2D 100+ pretrained weights
Introduction and installation command
segmentation_models_pytorch (called smp)
is a 2D CNN lib including many backbones and decoders, which is highly recommended to install for cooperating with this library.
*Our codes have already contained smp, but you can still install the latest version with the code below.
Install with pip ↓
pip install segmentation-models-pytorch
Install the latest version ↓
pip install git+https://github.com/rwightman/pytorch-image-models.git
💧 transformers
Optional 2D 80000+ pretrained weights
Introduction and installation command
transformer (powered by Huggingface) is a lib including super abundant CNN and Transformer structures, which is highly recommended to install for cooperating with this library.
Install transformer with pip ↓
pip install transformers
💧 timm
Optional 2D 400+ pretrained weights
Introduction and installation command
timm is a lib includes abundant CNN and Transformer structures, which is highly recommended to install for cooperating with this library.
Install with pip ↓
pip install timm
Install the latest version ↓
pip install git+https://github.com/rwightman/pytorch-image-models.git
2. Update list
- 2022/11/11: The birthday of this code, version
v0.0.1
- 2023/01/23: Add demo code of 6 multi-label network structures (Happy Chinese New Year 🎇)
- ...
3. Main modules and network architectures
An overview of this repo (let's call wama_modules as wm)
| File |
Description |
Main class or function |
wm.utils |
Some operations on tensors and pre-training weights |
resizeTensor() tensor2array() load_weights() |
wm.thirdparty_lib |
2D/3D network structures (CNN/GNN/Transformer) from other repositories, and all are with pre-trained weights 🚀 |
MedicalNet C3D 3D_DenseNet 3D_shufflenet transformers.ConvNextModel transformers.SwinModel Radimagenet |
wm.Attention |
Some attention-based plugins |
SCSEModule NonLocal |
wm.BaseModule |
Basic modules(layers). For example, BottleNeck block (ResBlock) in ResNet, and DenseBlock in DenseNet, etc. |
MakeNorm() MakeConv() MakeActive() VGGBlock ResBlock DenseBlock |
wm.Encoder |
Some encoders such like ResNet or DenseNet, but with more flexibility for building the network modularly, and 1D/2D/3D are all supported |
VGGEncoder ResNetEncoder DenseNetEncoder |
wm.Decoder |
Some encoders with more flexibility for building the network modularly, and 1D/2D/3D are all supported |
UNet_decoder |
wm.Neck |
Modules for making the multi-scale features (from encoder) interact with each other to generate stronger features |
FPN |
wm.Transformer |
Some self-attention or cross-attention modules, which can be used to build ViT, DETR or TransUnet |
TransformerEncoderLayer TransformerDecoderLayer |
wm.PositionEmbedding |
Some position embedding modules, such as the learnable embedding, or 1/2/3D sincos embedding in MAE or Vit |
PositionalEncoding_1D_sincos PositionalEncoding_2D_sincos PositionalEncoding_3D_sincos |
4. Guideline 1: Build networks modularly
How to build a network modularly? Here's a paradigm ↓
'Design architecture according to tasks, pick modules according to architecture'
So, network architectures for different tasks can be viewed modularly such as:
- VGG for classification
= VGG_encoder + classification_head
- ResNet for classification
=ResNet_encoder+classification_head
- Unet for segmentation
=encoder+decoder+segmentation_head
- A multi-task net for classification and segmentation
=encoder+decoder+cls_head+seg_head
For example, build a 3D resnet50 encoder to output multi-scale feature maps ↓
from wama_modules.Encoder import ResNetEncoder
import torch
dim = 3 # input is 3D volume
in_channels = 3
input = torch.ones([2, in_channels, 64, 64, 64])
encoder = ResNetEncoder(
in_channels,
stage_output_channels=[64, 128, 256],
blocks=[6, 12, 24],
downsample_ration=[0.5, 0.5, 0.5], # set your downsampling speed
dim=dim
)
multi_scale_f = encoder(input)
_ = [print(i.shape) for i in multi_scale_f]
# --------------------------------
# output 👇
# torch.Size([2, 64, 15, 15, 15])
# torch.Size([2, 128, 7, 7, 7])
# torch.Size([2, 256, 3, 3, 3])
# --------------------------------
Here are more demos shown below ↓ (Click to view codes, or visit the demo folder)
Demo0: Build a 3D VGG for Single Label Classification
import torch
import torch.nn as nn
from wama_modules.Encoder import VGGEncoder
from wama_modules.Head import ClassificationHead
from wama_modules.BaseModule import GlobalMaxPool
class Model(nn.Module):
def __init__(self, in_channel, label_category_dict, dim=2):
super().__init__()
# encoder
f_channel_list = [64, 128, 256, 512]
self.encoder = VGGEncoder(
in_channel,
stage_output_channels=f_channel_list,
blocks=[1, 2, 3, 4],
downsample_ration=[0.5, 0.5, 0.5, 0.5],
dim=dim)
# cls head
self.cls_head = ClassificationHead(label_category_dict, f_channel_list[-1])
self.pooling = GlobalMaxPool()
def forward(self, x):
f = self.encoder(x)
logits = self.cls_head(self.pooling(f[-1]))
return logits
if __name__ == '__main__':
x = torch.ones([2, 1, 64, 64, 64])
label_category_dict = dict(is_malignant=4)
model = Model(in_channel=1, label_category_dict=label_category_dict, dim=3)
logits = model(x)
print('single-label predicted logits')
_ = [print('logits of ', key, ':', logits[key].shape) for key in logits.keys()]
# output 👇
# single-label predicted logits
# logits of is_malignant : torch.Size([2, 4])
Demo1: Build a 3D ResNet for Single Label Classification
import torch
import torch.nn as nn
from wama_modules.Encoder import ResNetEncoder
from wama_modules.Head import ClassificationHead
from wama_modules.BaseModule import GlobalMaxPool
class Model(nn.Module):
def __init__(self, in_channel, label_category_dict, dim=2):
super().__init__()
# encoder
f_channel_list = [64, 128, 256, 512]
self.encoder = ResNetEncoder(
in_channel,
stage_output_channels=f_channel_list,
stage_middle_channels=f_channel_list,
blocks=[1, 2, 3, 4],
type='131',
downsample_ration=[0.5, 0.5, 0.5, 0.5],
dim=dim)
# cls head
self.cls_head = ClassificationHead(label_category_dict, f_channel_list[-1])
self.pooling = GlobalMaxPool()
def forward(self, x):
f = self.encoder(x)
logits = self.cls_head(self.pooling(f[-1]))
return logits
if __name__ == '__main__':
x = torch.ones([2, 1, 64, 64, 64])
label_category_dict = dict(is_malignant=4)
model = Model(in_channel=1, label_category_dict=label_category_dict, dim=3)
logits = model(x)
print('single-label predicted logits')
_ = [print('logits of ', key, ':', logits[key].shape) for key in logits.keys()]
# output 👇
# single-label predicted logits
# logits of is_malignant : torch.Size([2, 4])
Demo2: Build a ResNet for Multi-Label Classification