|
|
|
@ -25,15 +25,18 @@ class Conv(nn.Module):
|
|
|
|
|
default_act = nn.SiLU() # default activation
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
|
|
|
|
|
"""Initialize Conv layer with given arguments including activation."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
|
|
|
|
|
self.bn = nn.BatchNorm2d(c2)
|
|
|
|
|
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Apply convolution, batch normalization and activation to input tensor."""
|
|
|
|
|
return self.act(self.bn(self.conv(x)))
|
|
|
|
|
|
|
|
|
|
def forward_fuse(self, x):
|
|
|
|
|
"""Perform transposed convolution of 2D data."""
|
|
|
|
|
return self.act(self.conv(x))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -56,15 +59,18 @@ class ConvTranspose(nn.Module):
|
|
|
|
|
default_act = nn.SiLU() # default activation
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):
|
|
|
|
|
"""Initialize ConvTranspose2d layer with batch normalization and activation function."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)
|
|
|
|
|
self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()
|
|
|
|
|
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies transposed convolutions, batch normalization and activation to input."""
|
|
|
|
|
return self.act(self.bn(self.conv_transpose(x)))
|
|
|
|
|
|
|
|
|
|
def forward_fuse(self, x):
|
|
|
|
|
"""Applies activation and convolution transpose operation to input."""
|
|
|
|
|
return self.act(self.conv_transpose(x))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -75,6 +81,7 @@ class DFL(nn.Module):
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1=16):
|
|
|
|
|
"""Initialize a convolutional layer with a given number of input channels."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)
|
|
|
|
|
x = torch.arange(c1, dtype=torch.float)
|
|
|
|
@ -82,6 +89,7 @@ class DFL(nn.Module):
|
|
|
|
|
self.c1 = c1
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies a transformer layer on input tensor 'x' and returns a tensor."""
|
|
|
|
|
b, c, a = x.shape # batch, channels, anchors
|
|
|
|
|
return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)
|
|
|
|
|
# return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)
|
|
|
|
@ -91,6 +99,7 @@ class TransformerLayer(nn.Module):
|
|
|
|
|
"""Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c, num_heads):
|
|
|
|
|
"""Initializes a self-attention mechanism using linear transformations and multi-head attention."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.q = nn.Linear(c, c, bias=False)
|
|
|
|
|
self.k = nn.Linear(c, c, bias=False)
|
|
|
|
@ -100,6 +109,7 @@ class TransformerLayer(nn.Module):
|
|
|
|
|
self.fc2 = nn.Linear(c, c, bias=False)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Apply a transformer block to the input x and return the output."""
|
|
|
|
|
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
|
|
|
|
|
x = self.fc2(self.fc1(x)) + x
|
|
|
|
|
return x
|
|
|
|
@ -109,6 +119,7 @@ class TransformerBlock(nn.Module):
|
|
|
|
|
"""Vision Transformer https://arxiv.org/abs/2010.11929."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, num_heads, num_layers):
|
|
|
|
|
"""Initialize a Transformer module with position embedding and specified number of heads and layers."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.conv = None
|
|
|
|
|
if c1 != c2:
|
|
|
|
@ -118,6 +129,7 @@ class TransformerBlock(nn.Module):
|
|
|
|
|
self.c2 = c2
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward propagates the input through the bottleneck module."""
|
|
|
|
|
if self.conv is not None:
|
|
|
|
|
x = self.conv(x)
|
|
|
|
|
b, _, w, h = x.shape
|
|
|
|
@ -136,6 +148,7 @@ class Bottleneck(nn.Module):
|
|
|
|
|
self.add = shortcut and c1 == c2
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""'forward()' applies the YOLOv5 FPN to input data."""
|
|
|
|
|
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -154,6 +167,7 @@ class BottleneckCSP(nn.Module):
|
|
|
|
|
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies a CSP bottleneck with 3 convolutions."""
|
|
|
|
|
y1 = self.cv3(self.m(self.cv1(x)))
|
|
|
|
|
y2 = self.cv2(x)
|
|
|
|
|
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
|
|
|
|
@ -171,6 +185,7 @@ class C3(nn.Module):
|
|
|
|
|
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass through the CSP bottleneck with 2 convolutions."""
|
|
|
|
|
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -186,6 +201,7 @@ class C2(nn.Module):
|
|
|
|
|
self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)))
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass through the CSP bottleneck with 2 convolutions."""
|
|
|
|
|
a, b = self.cv1(x).chunk(2, 1)
|
|
|
|
|
return self.cv2(torch.cat((self.m(a), b), 1))
|
|
|
|
|
|
|
|
|
@ -201,11 +217,13 @@ class C2f(nn.Module):
|
|
|
|
|
self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass of a YOLOv5 CSPDarknet backbone layer."""
|
|
|
|
|
y = list(self.cv1(x).chunk(2, 1))
|
|
|
|
|
y.extend(m(y[-1]) for m in self.m)
|
|
|
|
|
return self.cv2(torch.cat(y, 1))
|
|
|
|
|
|
|
|
|
|
def forward_split(self, x):
|
|
|
|
|
"""Applies spatial attention to module's input."""
|
|
|
|
|
y = list(self.cv1(x).split((self.c, self.c), 1))
|
|
|
|
|
y.extend(m(y[-1]) for m in self.m)
|
|
|
|
|
return self.cv2(torch.cat(y, 1))
|
|
|
|
@ -228,6 +246,7 @@ class SpatialAttention(nn.Module):
|
|
|
|
|
"""Spatial-attention module."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, kernel_size=7):
|
|
|
|
|
"""Initialize Spatial-attention module with kernel size argument."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
|
|
|
|
|
padding = 3 if kernel_size == 7 else 1
|
|
|
|
@ -235,6 +254,7 @@ class SpatialAttention(nn.Module):
|
|
|
|
|
self.act = nn.Sigmoid()
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Apply channel and spatial attention on input for feature recalibration."""
|
|
|
|
|
return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -247,6 +267,7 @@ class CBAM(nn.Module):
|
|
|
|
|
self.spatial_attention = SpatialAttention(kernel_size)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies the forward pass through C1 module."""
|
|
|
|
|
return self.spatial_attention(self.channel_attention(x))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -259,6 +280,7 @@ class C1(nn.Module):
|
|
|
|
|
self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies cross-convolutions to input in the C3 module."""
|
|
|
|
|
y = self.cv1(x)
|
|
|
|
|
return self.m(y) + y
|
|
|
|
|
|
|
|
|
@ -267,6 +289,7 @@ class C3x(C3):
|
|
|
|
|
"""C3 module with cross-convolutions."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
|
|
|
|
"""Initialize C3TR instance and set default parameters."""
|
|
|
|
|
super().__init__(c1, c2, n, shortcut, g, e)
|
|
|
|
|
self.c_ = int(c2 * e)
|
|
|
|
|
self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n)))
|
|
|
|
@ -276,6 +299,7 @@ class C3TR(C3):
|
|
|
|
|
"""C3 module with TransformerBlock()."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
|
|
|
|
"""Initialize C3Ghost module with GhostBottleneck()."""
|
|
|
|
|
super().__init__(c1, c2, n, shortcut, g, e)
|
|
|
|
|
c_ = int(c2 * e)
|
|
|
|
|
self.m = TransformerBlock(c_, c_, 4, n)
|
|
|
|
@ -285,6 +309,7 @@ class C3Ghost(C3):
|
|
|
|
|
"""C3 module with GhostBottleneck()."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
|
|
|
|
|
"""Initialize 'SPP' module with various pooling sizes for spatial pyramid pooling."""
|
|
|
|
|
super().__init__(c1, c2, n, shortcut, g, e)
|
|
|
|
|
c_ = int(c2 * e) # hidden channels
|
|
|
|
|
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
|
|
|
|
@ -294,6 +319,7 @@ class SPP(nn.Module):
|
|
|
|
|
"""Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, c1, c2, k=(5, 9, 13)):
|
|
|
|
|
"""Initialize the SPP layer with input/output channels and pooling kernel sizes."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
c_ = c1 // 2 # hidden channels
|
|
|
|
|
self.cv1 = Conv(c1, c_, 1, 1)
|
|
|
|
@ -301,6 +327,7 @@ class SPP(nn.Module):
|
|
|
|
|
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass of the SPP layer, performing spatial pyramid pooling."""
|
|
|
|
|
x = self.cv1(x)
|
|
|
|
|
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
|
|
|
|
|
|
|
|
@ -316,6 +343,7 @@ class SPPF(nn.Module):
|
|
|
|
|
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass through Ghost Convolution block."""
|
|
|
|
|
x = self.cv1(x)
|
|
|
|
|
y1 = self.m(x)
|
|
|
|
|
y2 = self.m(y1)
|
|
|
|
@ -345,6 +373,7 @@ class GhostConv(nn.Module):
|
|
|
|
|
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward propagation through a Ghost Bottleneck layer with skip connection."""
|
|
|
|
|
y = self.cv1(x)
|
|
|
|
|
return torch.cat((y, self.cv2(y)), 1)
|
|
|
|
|
|
|
|
|
@ -363,6 +392,7 @@ class GhostBottleneck(nn.Module):
|
|
|
|
|
act=False)) if s == 2 else nn.Identity()
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Applies skip connection and concatenation to input tensor."""
|
|
|
|
|
return self.conv(x) + self.shortcut(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -370,10 +400,12 @@ class Concat(nn.Module):
|
|
|
|
|
"""Concatenate a list of tensors along dimension."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, dimension=1):
|
|
|
|
|
"""Concatenates a list of tensors along a specified dimension."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.d = dimension
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Forward pass for the YOLOv8 mask Proto module."""
|
|
|
|
|
return torch.cat(x, self.d)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -388,6 +420,7 @@ class Proto(nn.Module):
|
|
|
|
|
self.cv3 = Conv(c_, c2)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Performs a forward pass through layers using an upsampled input image."""
|
|
|
|
|
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@ -395,9 +428,11 @@ class Ensemble(nn.ModuleList):
|
|
|
|
|
"""Ensemble of models."""
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
"""Initialize an ensemble of models."""
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
|
|
def forward(self, x, augment=False, profile=False, visualize=False):
|
|
|
|
|
"""Function generates the YOLOv5 network's final layer."""
|
|
|
|
|
y = [module(x, augment, profile, visualize)[0] for module in self]
|
|
|
|
|
# y = torch.stack(y).max(0)[0] # max ensemble
|
|
|
|
|
# y = torch.stack(y).mean(0) # mean ensemble
|
|
|
|
@ -430,6 +465,7 @@ class Detect(nn.Module):
|
|
|
|
|
self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Concatenates and returns predicted bounding boxes and class probabilities."""
|
|
|
|
|
shape = x[0].shape # BCHW
|
|
|
|
|
for i in range(self.nl):
|
|
|
|
|
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
|
|
|
|
@ -463,6 +499,7 @@ class Segment(Detect):
|
|
|
|
|
"""YOLOv8 Segment head for segmentation models."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, nc=80, nm=32, npr=256, ch=()):
|
|
|
|
|
"""Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers."""
|
|
|
|
|
super().__init__(nc, ch)
|
|
|
|
|
self.nm = nm # number of masks
|
|
|
|
|
self.npr = npr # number of protos
|
|
|
|
@ -473,6 +510,7 @@ class Segment(Detect):
|
|
|
|
|
self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients."""
|
|
|
|
|
p = self.proto(x[0]) # mask protos
|
|
|
|
|
bs = p.shape[0] # batch size
|
|
|
|
|
|
|
|
|
@ -487,6 +525,7 @@ class Pose(Detect):
|
|
|
|
|
"""YOLOv8 Pose head for keypoints models."""
|
|
|
|
|
|
|
|
|
|
def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):
|
|
|
|
|
"""Initialize YOLO network with default parameters and Convolutional Layers."""
|
|
|
|
|
super().__init__(nc, ch)
|
|
|
|
|
self.kpt_shape = kpt_shape # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)
|
|
|
|
|
self.nk = kpt_shape[0] * kpt_shape[1] # number of keypoints total
|
|
|
|
@ -496,6 +535,7 @@ class Pose(Detect):
|
|
|
|
|
self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Perform forward pass through YOLO model and return predictions."""
|
|
|
|
|
bs = x[0].shape[0] # batch size
|
|
|
|
|
kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1) # (bs, 17*3, h*w)
|
|
|
|
|
x = self.detect(self, x)
|
|
|
|
@ -505,6 +545,7 @@ class Pose(Detect):
|
|
|
|
|
return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))
|
|
|
|
|
|
|
|
|
|
def kpts_decode(self, kpts):
|
|
|
|
|
"""Decodes keypoints."""
|
|
|
|
|
ndim = self.kpt_shape[1]
|
|
|
|
|
y = kpts.clone()
|
|
|
|
|
if ndim == 3:
|
|
|
|
@ -526,6 +567,7 @@ class Classify(nn.Module):
|
|
|
|
|
self.linear = nn.Linear(c_, c2) # to x(b,c2)
|
|
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""Performs a forward pass of the YOLO model on input image data."""
|
|
|
|
|
if isinstance(x, list):
|
|
|
|
|
x = torch.cat(x, 1)
|
|
|
|
|
x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
|
|
|
|
|