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/yolo.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2YOLO-specific modules34Usage:5$ python path/to/models/yolo.py --cfg yolov5s.yaml6"""78import argparse9import sys10from copy import deepcopy11from pathlib import Path1213FILE = Path(__file__).resolve()14ROOT = FILE.parents[1] # YOLOv5 root directory15if str(ROOT) not in sys.path:16sys.path.append(str(ROOT)) # add ROOT to PATH17# ROOT = ROOT.relative_to(Path.cwd()) # relative1819from models.common import *20from models.experimental import *21from utils.autoanchor import check_anchor_order22from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args23from utils.plots import feature_visualization24from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, time_sync2526try:27import thop # for FLOPs computation28except ImportError:29thop = None303132class Detect(nn.Module):33stride = None # strides computed during build34onnx_dynamic = False # ONNX export parameter3536def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer37super().__init__()38self.nc = nc # number of classes39self.no = nc + 5 + 180 # number of outputs per anchor40self.nl = len(anchors) # number of detection layers41self.na = len(anchors[0]) // 2 # number of anchors42self.grid = [torch.zeros(1)] * self.nl # init grid43self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid44self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)45self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv46self.inplace = inplace # use in-place ops (e.g. slice assignment)4748def forward(self, x):49"""50Args:51x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)5253Return:54if train:55x (list[P3_out,...]): torch.Size(b, self.na, h_i, w_i, self.no), self.na means the number of anchors scales56else:57inference (tensor): (b, n_all_anchors, self.no)58x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)59"""60z = [] # inference output61for i in range(self.nl):62x[i] = self.m[i](x[i]) # conv63bs, _, ny, nx = x[i].shape # x[i](bs,self.no * self.na,20,20) to x[i](bs,self.na,20,20,self.no)64x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()6566if not self.training: # inference67if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:68self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)6970y = x[i].sigmoid() # (tensor): (b, self.na, h, w, self.no)71if self.inplace:72y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy73y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh74else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/295375xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy76wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh77y = torch.cat((xy, wh, y[..., 4:]), -1)78z.append(y.view(bs, -1, self.no)) # z (list[P3_pred]): Torch.Size(b, n_anchors, self.no)7980return x if self.training else (torch.cat(z, 1), x)8182def _make_grid(self, nx=20, ny=20, i=0):83d = self.anchors[i].device84if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility85yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij')86else:87yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)])88grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()89anchor_grid = (self.anchors[i].clone() * self.stride[i]) \90.view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()91return grid, anchor_grid929394class Model(nn.Module):95def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes96super().__init__()97if isinstance(cfg, dict):98self.yaml = cfg # model dict99else: # is *.yaml100import yaml # for torch hub101self.yaml_file = Path(cfg).name102with open(cfg, encoding='ascii', errors='ignore') as f:103self.yaml = yaml.safe_load(f) # model dict104105# Define model106ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels107if nc and nc != self.yaml['nc']:108LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")109self.yaml['nc'] = nc # override yaml value110if anchors:111LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')112self.yaml['anchors'] = round(anchors) # override yaml value113self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist114self.names = [str(i) for i in range(self.yaml['nc'])] # default names115self.inplace = self.yaml.get('inplace', True)116117# Build strides, anchors118m = self.model[-1] # Detect()119if isinstance(m, Detect):120s = 256 # 2x min stride121m.inplace = self.inplace122m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward123m.anchors /= m.stride.view(-1, 1, 1) # featuremap pixel124check_anchor_order(m)125self.stride = m.stride126self._initialize_biases() # only run once127128# Init weights, biases129initialize_weights(self)130self.info()131LOGGER.info('')132133def forward(self, x, augment=False, profile=False, visualize=False):134"""135Args:136x (tensor): (b, 3, height, width), RGB137138Return:139if not augment:140x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales141else:142143"""144if augment:145return self._forward_augment(x) # augmented inference, None146return self._forward_once(x, profile, visualize) # single-scale inference, train147148def _forward_augment(self, x):149img_size = x.shape[-2:] # height, width150s = [1, 0.83, 0.67] # scales151f = [None, 3, None] # flips (2-ud, 3-lr)152y = [] # outputs153for si, fi in zip(s, f):154xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))155yi = self._forward_once(xi)[0] # forward156# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save157yi = self._descale_pred(yi, fi, si, img_size)158y.append(yi)159y = self._clip_augmented(y) # clip augmented tails160return torch.cat(y, 1), None # augmented inference, train161162def _forward_once(self, x, profile=False, visualize=False):163"""164Args:165x (tensor): (b, 3, height, width), RGB166167Return:168x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales169"""170y, dt = [], [] # outputs171for m in self.model:172if m.f != -1: # if not from previous layer173x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers174if profile:175self._profile_one_layer(m, x, dt)176x = m(x) # run177y.append(x if m.i in self.save else None) # save output178if visualize:179feature_visualization(x, m.type, m.i, save_dir=visualize)180return x181182def _descale_pred(self, p, flips, scale, img_size):183# de-scale predictions following augmented inference (inverse operation)184if self.inplace:185p[..., :4] /= scale # de-scale186if flips == 2:187p[..., 1] = img_size[0] - p[..., 1] # de-flip ud188elif flips == 3:189p[..., 0] = img_size[1] - p[..., 0] # de-flip lr190else:191x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale192if flips == 2:193y = img_size[0] - y # de-flip ud194elif flips == 3:195x = img_size[1] - x # de-flip lr196p = torch.cat((x, y, wh, p[..., 4:]), -1)197return p198199def _clip_augmented(self, y):200# Clip YOLOv5 augmented inference tails201nl = self.model[-1].nl # number of detection layers (P3-P5)202g = sum(4 ** x for x in range(nl)) # grid points203e = 1 # exclude layer count204i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices205y[0] = y[0][:, :-i] # large206i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices207y[-1] = y[-1][:, i:] # small208return y209210def _profile_one_layer(self, m, x, dt):211c = isinstance(m, Detect) # is final layer, copy input as inplace fix212o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs213t = time_sync()214for _ in range(10):215m(x.copy() if c else x)216dt.append((time_sync() - t) * 100)217if m == self.model[0]:218LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")219LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')220if c:221LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")222223def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency224# https://arxiv.org/abs/1708.02002 section 3.3225# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.226m = self.model[-1] # Detect() module227for mi, s in zip(m.m, m.stride): # from228b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)229b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)230b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls231mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)232233def _print_biases(self):234m = self.model[-1] # Detect() module235for mi in m.m: # from236b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)237LOGGER.info(238('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))239240# def _print_weights(self):241# for m in self.model.modules():242# if type(m) is Bottleneck:243# LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights244245def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers246LOGGER.info('Fusing layers... ')247for m in self.model.modules():248if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):249m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv250delattr(m, 'bn') # remove batchnorm251m.forward = m.forward_fuse # update forward252self.info()253return self254255def info(self, verbose=False, img_size=640): # print model information256model_info(self, verbose, img_size)257258def _apply(self, fn):259# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers260self = super()._apply(fn)261m = self.model[-1] # Detect()262if isinstance(m, Detect):263m.stride = fn(m.stride)264m.grid = list(map(fn, m.grid))265if isinstance(m.anchor_grid, list):266m.anchor_grid = list(map(fn, m.anchor_grid))267return self268269270def parse_model(d, ch): # model_dict, input_channels(3)271LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")272anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']273na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors274# no = na * (nc + 5) # number of outputs = anchors * (classes + 5)275no = na * (nc + 185) # number of outputs = anchors * (classes + 185)276277layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out278for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args279m = eval(m) if isinstance(m, str) else m # eval strings280for j, a in enumerate(args):281try:282args[j] = eval(a) if isinstance(a, str) else a # eval strings283except NameError:284pass285286n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain287if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,288BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:289c1, c2 = ch[f], args[0]290if c2 != no: # if not output291c2 = make_divisible(c2 * gw, 8)292293args = [c1, c2, *args[1:]]294if m in [BottleneckCSP, C3, C3TR, C3Ghost]:295args.insert(2, n) # number of repeats296n = 1297elif m is nn.BatchNorm2d:298args = [ch[f]]299elif m is Concat:300c2 = sum(ch[x] for x in f)301elif m is Detect:302args.append([ch[x] for x in f])303if isinstance(args[1], int): # number of anchors304args[1] = [list(range(args[1] * 2))] * len(f)305elif m is Contract:306c2 = ch[f] * args[0] ** 2307elif m is Expand:308c2 = ch[f] // args[0] ** 2309else:310c2 = ch[f]311312m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module313t = str(m)[8:-2].replace('__main__.', '') # module type314np = sum(x.numel() for x in m_.parameters()) # number params315m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params316LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print317save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist318layers.append(m_)319if i == 0:320ch = []321ch.append(c2)322return nn.Sequential(*layers), sorted(save)323324325if __name__ == '__main__':326parser = argparse.ArgumentParser()327parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')328parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')329parser.add_argument('--profile', action='store_true', help='profile model speed')330parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')331opt = parser.parse_args()332opt.cfg = check_yaml(opt.cfg) # check YAML333print_args(FILE.stem, opt)334device = select_device(opt.device)335336# Create model337model = Model(opt.cfg).to(device)338model.train()339340# Profile341if opt.profile:342img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)343y = model(img, profile=True)344345# Test all models346if opt.test:347for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):348try:349_ = Model(cfg)350except Exception as e:351print(f'Error in {cfg}: {e}')352353# Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)354# from torch.utils.tensorboard import SummaryWriter355# tb_writer = SummaryWriter('.')356# LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")357# tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph358359360