Add Gather-Excite and Global Context attn modules. Refactor existing SE-like attn for consistency and refactor byob/byoanet for less redundancy.
parent
9c78de8c02
commit
742c2d5247
@ -0,0 +1,90 @@
|
||||
""" Gather-Excite Attention Block
|
||||
|
||||
Paper: `Gather-Excite: Exploiting Feature Context in CNNs` - https://arxiv.org/abs/1810.12348
|
||||
|
||||
Official code here, but it's only partial impl in Caffe: https://github.com/hujie-frank/GENet
|
||||
|
||||
I've tried to support all of the extent both w/ and w/o params. I don't believe I've seen another
|
||||
impl that covers all of the cases.
|
||||
|
||||
NOTE: extent=0 + extra_params=False is equivalent to Squeeze-and-Excitation
|
||||
|
||||
Hacked together by / Copyright 2021 Ross Wightman
|
||||
"""
|
||||
import math
|
||||
|
||||
from torch import nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .create_act import create_act_layer, get_act_layer
|
||||
from .create_conv2d import create_conv2d
|
||||
from .helpers import make_divisible
|
||||
from .mlp import ConvMlp
|
||||
|
||||
|
||||
class GatherExcite(nn.Module):
|
||||
""" Gather-Excite Attention Module
|
||||
"""
|
||||
def __init__(
|
||||
self, channels, feat_size=None, extra_params=False, extent=0, use_mlp=True,
|
||||
rd_ratio=1./16, rd_channels=None, rd_divisor=1, add_maxpool=False,
|
||||
act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, gate_layer='sigmoid'):
|
||||
super(GatherExcite, self).__init__()
|
||||
self.add_maxpool = add_maxpool
|
||||
act_layer = get_act_layer(act_layer)
|
||||
self.extent = extent
|
||||
if extra_params:
|
||||
self.gather = nn.Sequential()
|
||||
if extent == 0:
|
||||
assert feat_size is not None, 'spatial feature size must be specified for global extent w/ params'
|
||||
self.gather.add_module(
|
||||
'conv1', create_conv2d(channels, channels, kernel_size=feat_size, stride=1, depthwise=True))
|
||||
if norm_layer:
|
||||
self.gather.add_module(f'norm1', nn.BatchNorm2d(channels))
|
||||
else:
|
||||
assert extent % 2 == 0
|
||||
num_conv = int(math.log2(extent))
|
||||
for i in range(num_conv):
|
||||
self.gather.add_module(
|
||||
f'conv{i + 1}',
|
||||
create_conv2d(channels, channels, kernel_size=3, stride=2, depthwise=True))
|
||||
if norm_layer:
|
||||
self.gather.add_module(f'norm{i + 1}', nn.BatchNorm2d(channels))
|
||||
if i != num_conv - 1:
|
||||
self.gather.add_module(f'act{i + 1}', act_layer(inplace=True))
|
||||
else:
|
||||
self.gather = None
|
||||
if self.extent == 0:
|
||||
self.gk = 0
|
||||
self.gs = 0
|
||||
else:
|
||||
assert extent % 2 == 0
|
||||
self.gk = self.extent * 2 - 1
|
||||
self.gs = self.extent
|
||||
|
||||
if not rd_channels:
|
||||
rd_channels = make_divisible(channels * rd_ratio, rd_divisor, round_limit=0.)
|
||||
self.mlp = ConvMlp(channels, rd_channels, act_layer=act_layer) if use_mlp else nn.Identity()
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
|
||||
def forward(self, x):
|
||||
size = x.shape[-2:]
|
||||
if self.gather is not None:
|
||||
x_ge = self.gather(x)
|
||||
else:
|
||||
if self.extent == 0:
|
||||
# global extent
|
||||
x_ge = x.mean(dim=(2, 3), keepdims=True)
|
||||
if self.add_maxpool:
|
||||
# experimental codepath, may remove or change
|
||||
x_ge = 0.5 * x_ge + 0.5 * x.amax((2, 3), keepdim=True)
|
||||
else:
|
||||
x_ge = F.avg_pool2d(
|
||||
x, kernel_size=self.gk, stride=self.gs, padding=self.gk // 2, count_include_pad=False)
|
||||
if self.add_maxpool:
|
||||
# experimental codepath, may remove or change
|
||||
x_ge = 0.5 * x_ge + 0.5 * F.max_pool2d(x, kernel_size=self.gk, stride=self.gs, padding=self.gk // 2)
|
||||
x_ge = self.mlp(x_ge)
|
||||
if x_ge.shape[-1] != 1 or x_ge.shape[-2] != 1:
|
||||
x_ge = F.interpolate(x_ge, size=size)
|
||||
return x * self.gate(x_ge)
|
@ -0,0 +1,67 @@
|
||||
""" Global Context Attention Block
|
||||
|
||||
Paper: `GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond`
|
||||
- https://arxiv.org/abs/1904.11492
|
||||
|
||||
Official code consulted as reference: https://github.com/xvjiarui/GCNet
|
||||
|
||||
Hacked together by / Copyright 2021 Ross Wightman
|
||||
"""
|
||||
from torch import nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .create_act import create_act_layer, get_act_layer
|
||||
from .helpers import make_divisible
|
||||
from .mlp import ConvMlp
|
||||
from .norm import LayerNorm2d
|
||||
|
||||
|
||||
class GlobalContext(nn.Module):
|
||||
|
||||
def __init__(self, channels, use_attn=True, fuse_add=True, fuse_scale=False, init_last_zero=False,
|
||||
rd_ratio=1./8, rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid'):
|
||||
super(GlobalContext, self).__init__()
|
||||
act_layer = get_act_layer(act_layer)
|
||||
|
||||
self.conv_attn = nn.Conv2d(channels, 1, kernel_size=1, bias=True) if use_attn else None
|
||||
|
||||
if rd_channels is None:
|
||||
rd_channels = make_divisible(channels * rd_ratio, rd_divisor, round_limit=0.)
|
||||
if fuse_add:
|
||||
self.mlp_add = ConvMlp(channels, rd_channels, act_layer=act_layer, norm_layer=LayerNorm2d)
|
||||
else:
|
||||
self.mlp_add = None
|
||||
if fuse_scale:
|
||||
self.mlp_scale = ConvMlp(channels, rd_channels, act_layer=act_layer, norm_layer=LayerNorm2d)
|
||||
else:
|
||||
self.mlp_scale = None
|
||||
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
self.init_last_zero = init_last_zero
|
||||
self.reset_parameters()
|
||||
|
||||
def reset_parameters(self):
|
||||
if self.conv_attn is not None:
|
||||
nn.init.kaiming_normal_(self.conv_attn.weight, mode='fan_in', nonlinearity='relu')
|
||||
if self.mlp_add is not None:
|
||||
nn.init.zeros_(self.mlp_add.fc2.weight)
|
||||
|
||||
def forward(self, x):
|
||||
B, C, H, W = x.shape
|
||||
|
||||
if self.conv_attn is not None:
|
||||
attn = self.conv_attn(x).reshape(B, 1, H * W) # (B, 1, H * W)
|
||||
attn = F.softmax(attn, dim=-1).unsqueeze(3) # (B, 1, H * W, 1)
|
||||
context = x.reshape(B, C, H * W).unsqueeze(1) @ attn
|
||||
context = context.view(B, C, 1, 1)
|
||||
else:
|
||||
context = x.mean(dim=(2, 3), keepdim=True)
|
||||
|
||||
if self.mlp_scale is not None:
|
||||
mlp_x = self.mlp_scale(context)
|
||||
x = x * self.gate(mlp_x)
|
||||
if self.mlp_add is not None:
|
||||
mlp_x = self.mlp_add(context)
|
||||
x = x + mlp_x
|
||||
|
||||
return x
|
@ -1,50 +0,0 @@
|
||||
from torch import nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .create_act import create_act_layer
|
||||
from .helpers import make_divisible
|
||||
|
||||
|
||||
class SEModule(nn.Module):
|
||||
""" SE Module as defined in original SE-Nets with a few additions
|
||||
Additions include:
|
||||
* min_channels can be specified to keep reduced channel count at a minimum (default: 8)
|
||||
* divisor can be specified to keep channels rounded to specified values (default: 1)
|
||||
* reduction channels can be specified directly by arg (if reduction_channels is set)
|
||||
* reduction channels can be specified by float ratio (if reduction_ratio is set)
|
||||
"""
|
||||
def __init__(self, channels, reduction=16, act_layer=nn.ReLU, gate_layer='sigmoid',
|
||||
reduction_ratio=None, reduction_channels=None, min_channels=8, divisor=1):
|
||||
super(SEModule, self).__init__()
|
||||
if reduction_channels is not None:
|
||||
reduction_channels = reduction_channels # direct specification highest priority, no rounding/min done
|
||||
elif reduction_ratio is not None:
|
||||
reduction_channels = make_divisible(channels * reduction_ratio, divisor, min_channels)
|
||||
else:
|
||||
reduction_channels = make_divisible(channels // reduction, divisor, min_channels)
|
||||
self.fc1 = nn.Conv2d(channels, reduction_channels, kernel_size=1, bias=True)
|
||||
self.act = act_layer(inplace=True)
|
||||
self.fc2 = nn.Conv2d(reduction_channels, channels, kernel_size=1, bias=True)
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
|
||||
def forward(self, x):
|
||||
x_se = x.mean((2, 3), keepdim=True)
|
||||
x_se = self.fc1(x_se)
|
||||
x_se = self.act(x_se)
|
||||
x_se = self.fc2(x_se)
|
||||
return x * self.gate(x_se)
|
||||
|
||||
|
||||
class EffectiveSEModule(nn.Module):
|
||||
""" 'Effective Squeeze-Excitation
|
||||
From `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667
|
||||
"""
|
||||
def __init__(self, channels, gate_layer='hard_sigmoid'):
|
||||
super(EffectiveSEModule, self).__init__()
|
||||
self.fc = nn.Conv2d(channels, channels, kernel_size=1, padding=0)
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
|
||||
def forward(self, x):
|
||||
x_se = x.mean((2, 3), keepdim=True)
|
||||
x_se = self.fc(x_se)
|
||||
return x * self.gate(x_se)
|
@ -0,0 +1,74 @@
|
||||
""" Squeeze-and-Excitation Channel Attention
|
||||
|
||||
An SE implementation originally based on PyTorch SE-Net impl.
|
||||
Has since evolved with additional functionality / configuration.
|
||||
|
||||
Paper: `Squeeze-and-Excitation Networks` - https://arxiv.org/abs/1709.01507
|
||||
|
||||
Also included is Effective Squeeze-Excitation (ESE).
|
||||
Paper: `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667
|
||||
|
||||
Hacked together by / Copyright 2021 Ross Wightman
|
||||
"""
|
||||
from torch import nn as nn
|
||||
|
||||
from .create_act import create_act_layer
|
||||
from .helpers import make_divisible
|
||||
|
||||
|
||||
class SEModule(nn.Module):
|
||||
""" SE Module as defined in original SE-Nets with a few additions
|
||||
Additions include:
|
||||
* divisor can be specified to keep channels % div == 0 (default: 8)
|
||||
* reduction channels can be specified directly by arg (if rd_channels is set)
|
||||
* reduction channels can be specified by float rd_ratio (default: 1/16)
|
||||
* global max pooling can be added to the squeeze aggregation
|
||||
* customizable activation, normalization, and gate layer
|
||||
"""
|
||||
def __init__(
|
||||
self, channels, rd_ratio=1. / 16, rd_channels=None, rd_divisor=8, add_maxpool=False,
|
||||
act_layer=nn.ReLU, norm_layer=None, gate_layer='sigmoid'):
|
||||
super(SEModule, self).__init__()
|
||||
self.add_maxpool = add_maxpool
|
||||
if not rd_channels:
|
||||
rd_channels = make_divisible(channels * rd_ratio, rd_divisor, round_limit=0.)
|
||||
self.fc1 = nn.Conv2d(channels, rd_channels, kernel_size=1, bias=True)
|
||||
self.bn = norm_layer(rd_channels) if norm_layer else nn.Identity()
|
||||
self.act = create_act_layer(act_layer, inplace=True)
|
||||
self.fc2 = nn.Conv2d(rd_channels, channels, kernel_size=1, bias=True)
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
|
||||
def forward(self, x):
|
||||
x_se = x.mean((2, 3), keepdim=True)
|
||||
if self.add_maxpool:
|
||||
# experimental codepath, may remove or change
|
||||
x_se = 0.5 * x_se + 0.5 * x.amax((2, 3), keepdim=True)
|
||||
x_se = self.fc1(x_se)
|
||||
x_se = self.act(self.bn(x_se))
|
||||
x_se = self.fc2(x_se)
|
||||
return x * self.gate(x_se)
|
||||
|
||||
|
||||
SqueezeExcite = SEModule # alias
|
||||
|
||||
|
||||
class EffectiveSEModule(nn.Module):
|
||||
""" 'Effective Squeeze-Excitation
|
||||
From `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667
|
||||
"""
|
||||
def __init__(self, channels, add_maxpool=False, gate_layer='hard_sigmoid'):
|
||||
super(EffectiveSEModule, self).__init__()
|
||||
self.add_maxpool = add_maxpool
|
||||
self.fc = nn.Conv2d(channels, channels, kernel_size=1, padding=0)
|
||||
self.gate = create_act_layer(gate_layer)
|
||||
|
||||
def forward(self, x):
|
||||
x_se = x.mean((2, 3), keepdim=True)
|
||||
if self.add_maxpool:
|
||||
# experimental codepath, may remove or change
|
||||
x_se = 0.5 * x_se + 0.5 * x.amax((2, 3), keepdim=True)
|
||||
x_se = self.fc(x_se)
|
||||
return x * self.gate(x_se)
|
||||
|
||||
|
||||
EffectiveSqueezeExcite = EffectiveSEModule # alias
|
Loading…
Reference in new issue