2021-08-15 03:17:51 +08:00
|
|
|
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
|
|
|
"""
|
|
|
|
Experimental modules
|
|
|
|
"""
|
2021-10-30 19:38:51 +08:00
|
|
|
import math
|
2021-11-05 00:24:25 +08:00
|
|
|
|
2020-08-03 06:47:36 +08:00
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
|
|
|
|
2021-08-15 03:17:51 +08:00
|
|
|
from models.common import Conv
|
2021-07-28 08:04:10 +08:00
|
|
|
from utils.downloads import attempt_download
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
|
2020-07-02 02:44:49 +08:00
|
|
|
class CrossConv(nn.Module):
|
2020-07-04 04:46:12 +08:00
|
|
|
# Cross Convolution Downsample
|
|
|
|
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
|
|
|
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-07-02 02:44:49 +08:00
|
|
|
c_ = int(c2 * e) # hidden channels
|
2020-07-04 04:46:12 +08:00
|
|
|
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
|
|
|
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
2020-07-02 02:44:49 +08:00
|
|
|
self.add = shortcut and c1 == c2
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
|
|
|
|
|
|
|
|
2020-05-30 08:04:54 +08:00
|
|
|
class Sum(nn.Module):
|
2020-06-11 10:11:11 +08:00
|
|
|
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
2020-05-30 08:04:54 +08:00
|
|
|
def __init__(self, n, weight=False): # n: number of inputs
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-05-30 08:04:54 +08:00
|
|
|
self.weight = weight # apply weights boolean
|
|
|
|
self.iter = range(n - 1) # iter object
|
|
|
|
if weight:
|
2021-11-04 06:36:53 +08:00
|
|
|
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
2020-05-30 08:04:54 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
y = x[0] # no weight
|
|
|
|
if self.weight:
|
|
|
|
w = torch.sigmoid(self.w) * 2
|
|
|
|
for i in self.iter:
|
|
|
|
y = y + x[i + 1] * w[i]
|
|
|
|
else:
|
|
|
|
for i in self.iter:
|
|
|
|
y = y + x[i + 1]
|
|
|
|
return y
|
|
|
|
|
|
|
|
|
2020-06-11 10:11:11 +08:00
|
|
|
class MixConv2d(nn.Module):
|
2021-08-02 21:36:30 +08:00
|
|
|
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
2021-10-30 19:38:51 +08:00
|
|
|
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2021-10-30 19:38:51 +08:00
|
|
|
n = len(k) # number of convolutions
|
2020-06-11 10:11:11 +08:00
|
|
|
if equal_ch: # equal c_ per group
|
2021-10-30 19:38:51 +08:00
|
|
|
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
|
|
|
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
2020-06-11 10:11:11 +08:00
|
|
|
else: # equal weight.numel() per group
|
2021-10-30 19:38:51 +08:00
|
|
|
b = [c2] + [0] * n
|
|
|
|
a = np.eye(n + 1, n, k=-1)
|
2020-06-11 10:11:11 +08:00
|
|
|
a -= np.roll(a, 1, axis=1)
|
|
|
|
a *= np.array(k) ** 2
|
|
|
|
a[0] = 1
|
|
|
|
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
|
|
|
|
2021-10-30 19:38:51 +08:00
|
|
|
self.m = nn.ModuleList(
|
|
|
|
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
2020-06-11 10:11:11 +08:00
|
|
|
self.bn = nn.BatchNorm2d(c2)
|
2021-10-30 19:38:51 +08:00
|
|
|
self.act = nn.SiLU()
|
2020-06-11 10:11:11 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
2021-10-30 19:38:51 +08:00
|
|
|
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
2020-07-06 06:02:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Ensemble(nn.ModuleList):
|
|
|
|
# Ensemble of models
|
|
|
|
def __init__(self):
|
2021-07-19 18:41:15 +08:00
|
|
|
super().__init__()
|
2020-07-06 06:02:56 +08:00
|
|
|
|
2021-07-12 01:47:08 +08:00
|
|
|
def forward(self, x, augment=False, profile=False, visualize=False):
|
2020-07-06 06:02:56 +08:00
|
|
|
y = []
|
|
|
|
for module in self:
|
2021-07-12 01:47:08 +08:00
|
|
|
y.append(module(x, augment, profile, visualize)[0])
|
2020-07-09 05:23:34 +08:00
|
|
|
# y = torch.stack(y).max(0)[0] # max ensemble
|
2021-01-05 11:54:09 +08:00
|
|
|
# y = torch.stack(y).mean(0) # mean ensemble
|
|
|
|
y = torch.cat(y, 1) # nms ensemble
|
2020-07-09 05:23:34 +08:00
|
|
|
return y, None # inference, train output
|
2020-07-08 06:40:50 +08:00
|
|
|
|
|
|
|
|
Add TensorFlow and TFLite export (#1127)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Add --agnostic-nms for TF class-agnostic NMS
* Cleanup after merge
* Cleanup2 after merge
* Cleanup3 after merge
* Add tf.py docstring with credit and usage
* pb saved_model and tflite use only one model in detect.py
* Add use cases in docstring of tf.py
* Remove redundant `stride` definition
* Remove keras direct import
* Fix `check_requirements(('tensorflow>=2.4.1',))`
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
2021-08-17 19:18:16 +08:00
|
|
|
def attempt_load(weights, map_location=None, inplace=True, fuse=True):
|
2021-04-30 18:54:48 +08:00
|
|
|
from models.yolo import Detect, Model
|
|
|
|
|
2020-07-08 06:40:50 +08:00
|
|
|
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
|
|
|
model = Ensemble()
|
|
|
|
for w in weights if isinstance(weights, list) else [weights]:
|
2021-06-08 16:22:10 +08:00
|
|
|
ckpt = torch.load(attempt_download(w), map_location=map_location) # load
|
Add TensorFlow and TFLite export (#1127)
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* Put representative dataset in tfl_int8 block
* detect.py TF inference
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* Add models/tf.py for TensorFlow and TFLite export
* Set auto=False for int8 calibration
* Update requirements.txt for TensorFlow and TFLite export
* Read anchors directly from PyTorch weights
* Add --tf-nms to append NMS in TensorFlow SavedModel and GraphDef export
* Remove check_anchor_order, check_file, set_logging from import
* Reformat code and optimize imports
* Autodownload model and check cfg
* update --source path, img-size to 320, single output
* Adjust representative_dataset
* detect.py TF inference
* Put representative dataset in tfl_int8 block
* weights to string
* weights to string
* cleanup tf.py
* Add --dynamic-batch-size
* Add xywh normalization to reduce calibration error
* Update requirements.txt
TensorFlow 2.3.1 -> 2.4.0 to avoid int8 quantization error
* Fix imports
Move C3 from models.experimental to models.common
* implement C3() and SiLU()
* Fix reshape dim to support dynamic batching
* Add epsilon argument in tf_BN, which is different between TF and PT
* Set stride to None if not using PyTorch, and do not warmup without PyTorch
* Add list support in check_img_size()
* Add list input support in detect.py
* sys.path.append('./') to run from yolov5/
* Add int8 quantization support for TensorFlow 2.5
* Add get_coco128.sh
* Remove --no-tfl-detect in models/tf.py (Use tf-android-tfl-detect branch for EdgeTPU)
* Update requirements.txt
* Replace torch.load() with attempt_load()
* Update requirements.txt
* Add --tf-raw-resize to set half_pixel_centers=False
* Add --agnostic-nms for TF class-agnostic NMS
* Cleanup after merge
* Cleanup2 after merge
* Cleanup3 after merge
* Add tf.py docstring with credit and usage
* pb saved_model and tflite use only one model in detect.py
* Add use cases in docstring of tf.py
* Remove redundant `stride` definition
* Remove keras direct import
* Fix `check_requirements(('tensorflow>=2.4.1',))`
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
2021-08-17 19:18:16 +08:00
|
|
|
if fuse:
|
|
|
|
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
|
|
|
|
else:
|
|
|
|
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
|
|
|
|
|
2020-10-28 22:03:50 +08:00
|
|
|
# Compatibility updates
|
|
|
|
for m in model.modules():
|
2021-04-30 18:54:48 +08:00
|
|
|
if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
|
|
|
|
m.inplace = inplace # pytorch 1.7.0 compatibility
|
2021-10-12 00:58:42 +08:00
|
|
|
if type(m) is Detect:
|
|
|
|
if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
|
|
|
|
delattr(m, 'anchor_grid')
|
|
|
|
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
2020-10-28 22:03:50 +08:00
|
|
|
elif type(m) is Conv:
|
|
|
|
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
|
|
|
|
|
2020-07-08 06:40:50 +08:00
|
|
|
if len(model) == 1:
|
|
|
|
return model[-1] # return model
|
|
|
|
else:
|
2021-05-09 01:06:12 +08:00
|
|
|
print(f'Ensemble created with {weights}\n')
|
|
|
|
for k in ['names']:
|
2020-07-08 06:40:50 +08:00
|
|
|
setattr(model, k, getattr(model[-1], k))
|
2021-05-09 01:06:12 +08:00
|
|
|
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
2020-07-08 06:40:50 +08:00
|
|
|
return model # return ensemble
|