Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/models/experimental.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Experimental modules3"""4import math56import numpy as np7import torch8import torch.nn as nn910from models.common import Conv11from utils.downloads import attempt_download121314class CrossConv(nn.Module):15# Cross Convolution Downsample16def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):17# ch_in, ch_out, kernel, stride, groups, expansion, shortcut18super().__init__()19c_ = int(c2 * e) # hidden channels20self.cv1 = Conv(c1, c_, (1, k), (1, s))21self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)22self.add = shortcut and c1 == c22324def forward(self, x):25return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))262728class Sum(nn.Module):29# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.0907030def __init__(self, n, weight=False): # n: number of inputs31super().__init__()32self.weight = weight # apply weights boolean33self.iter = range(n - 1) # iter object34if weight:35self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights3637def forward(self, x):38y = x[0] # no weight39if self.weight:40w = torch.sigmoid(self.w) * 241for i in self.iter:42y = y + x[i + 1] * w[i]43else:44for i in self.iter:45y = y + x[i + 1]46return y474849class MixConv2d(nn.Module):50# Mixed Depth-wise Conv https://arxiv.org/abs/1907.0959551def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy52super().__init__()53n = len(k) # number of convolutions54if equal_ch: # equal c_ per group55i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices56c_ = [(i == g).sum() for g in range(n)] # intermediate channels57else: # equal weight.numel() per group58b = [c2] + [0] * n59a = np.eye(n + 1, n, k=-1)60a -= np.roll(a, 1, axis=1)61a *= np.array(k) ** 262a[0] = 163c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b6465self.m = nn.ModuleList(66[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])67self.bn = nn.BatchNorm2d(c2)68self.act = nn.SiLU()6970def forward(self, x):71return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))727374class Ensemble(nn.ModuleList):75# Ensemble of models76def __init__(self):77super().__init__()7879def forward(self, x, augment=False, profile=False, visualize=False):80y = []81for module in self:82y.append(module(x, augment, profile, visualize)[0])83# y = torch.stack(y).max(0)[0] # max ensemble84# y = torch.stack(y).mean(0) # mean ensemble85y = torch.cat(y, 1) # nms ensemble86return y, None # inference, train output878889def attempt_load(weights, map_location=None, inplace=True, fuse=True):90from models.yolo import Detect, Model9192# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a93model = Ensemble()94for w in weights if isinstance(weights, list) else [weights]:95ckpt = torch.load(attempt_download(w), map_location=map_location) # load96if fuse:97model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model98else:99model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse100101# Compatibility updates102for m in model.modules():103if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:104m.inplace = inplace # pytorch 1.7.0 compatibility105if type(m) is Detect:106if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility107delattr(m, 'anchor_grid')108setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)109elif type(m) is Conv:110m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility111112if len(model) == 1:113return model[-1] # return model114else:115print(f'Ensemble created with {weights}\n')116for k in ['names']:117setattr(model, k, getattr(model[-1], k))118model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride119return model # return ensemble120121122