import argparse
import math
import logging
from copy import deepcopy
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from easydict import EasyDict as edict
from utils.general_helper import make_divisible, time_synchronized
from utils.read_file import check_file
from utils.log_helper import set_logging
from utils.model_helper import model_info, initialize_weights, select_device
from utils.tracking_helper import scale_img
class Model(nn.Module):
def init(self, cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes
super(Model, self).init()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
else: # is *.yaml
import yaml # for torch hub
self.yaml_file = Path(cfg).name
with open(cfg) as f:
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
code
self.yaml = edict(self.yaml)
# Define model
if nc and nc != self.yaml.MODEL.nc:
print('Overriding %s nc=%g with nc=%g' % (cfg, self.yaml['nc'], nc))
self.yaml.MODEL.nc = nc
self.model, self.save, self.out = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist, ch_out
# Build strides, anchors
m = self.model[-1] # Detect()
if isinstance(m, Detect):
s = 128 # 2x min stride
x = self.forward(torch.zeros(2, ch, s, s))
m.stride = torch.tensor([s / x.shape[-2] for x in x[-1][0]]) # forward
m.anchors /= m.stride.view(-1, 1, 1)
check_anchor_order(m)
self.stride = m.stride
self._initialize_biases() # only run once
# print('Strides: %s' % m.stride.tolist())
# Init weights, biases
initialize_weights(self)
self.info()
print('')
def forward(self, x, augment=False, profile=False):
if augment:
img_size = x.shape[-2:] # height, width
s = [1, 0.83, 0.67] # scales
f = [None, 3, None] # flips (2-ud, 3-lr)
y = [] # outputs
for si, fi in zip(s, f):
xi = scale_img(x.flip(fi) if fi else x, si)
yi = self.forward_once(xi)[0] # forward
yi[..., :4] /= si # de-scale
if fi == 2:
yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
elif fi == 3:
yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
y.append(yi)
return torch.cat(y, 1), None # augmented inference, train
else:
return self.forward_once(x, profile) # single-scale inference, train
def forward_once(self, x, profile=False):
y, dt = [], [] # outputs
output = []
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
try:
import thop
o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS
except:
o = 0
t = time_synchronized()
for _ in range(10):
_ = m(x)
dt.append((time_synchronized() - t) * 100)
print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
x = m(x) # run
if m.i in self.out:
output.append(x)
y.append(x if m.i in self.save else None) # save output
if profile:
print('%.1fms total' % sum(dt))
return output
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
def _print_biases(self):
m = self.model[-1] # Detect() module
for mi in m.m: # from
b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
# def _print_weights(self):
# for m in self.model.modules():
# if type(m) is Bottleneck:
# print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
print('Fusing layers... ')
for m in self.model.modules():
if type(m) is Conv:
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatability
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
m.bn = None # remove batchnorm
m.forward = m.fuseforward # update forward
self.info()
return self
def info(self): # print model information
model_info(self)
anchors, nc, gd, gw, id_embedding = detector_cfg.anchors, d.MODEL.nc, detector_cfg.depth_multiple, \
detector_cfg.width_multiple, d.MODEL.id_embedding
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
out_list = []
for i, (f, n, m, args) in enumerate(detector_cfg.backbone + detector_cfg.head): # from, number, module, args
m = eval(m) if isinstance(m, str) else m # eval strings
for j, a in enumerate(args):
try:
args[j] = eval(a) if isinstance(a, str) else a # eval strings
except:
pass
n = max(round(n * gd), 1) if n > 1 else n # depth gain
if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
c1, c2 = ch[f], args[0]
c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
if i == 24:
args = [c2, c1, *args[1:]]
else:
args = [c1, c2, *args[1:]]
if m in [BottleneckCSP, C3]:
args.insert(2, n)
n = 1
elif m is nn.BatchNorm2d:
args = [ch[f]]
elif m is Concat:
c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])
elif m is Detect:
args.append([ch[x + 1] for x in f])
if isinstance(args[1], int): # number of anchors
args[1] = [list(range(args[1] * 2))] * len(f)
out_list += [i]
elif m is SAAN:
out_list += [i]
args.append([ch[x + 1] for x in f])
elif m is DenseMask:
out_list += [i]
args.append([ch[x + 1] for x in f])
else:
c2 = ch[f]
m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
t = str(m)[8:-2].replace('__main__.', '') # module type
np = sum([x.numel() for x in m_.parameters()]) # number params
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
layers.append(m_)
ch.append(c2)
return nn.Sequential(*layers), sorted(save), sorted(out_list)
class DenseMask(nn.Module):
"""
predict pedestrian density, used for NMS
"""
TRAIN:
RESUME: False # False or 'last' or ckpt path
BATCH_SIZE: 8 # [total] batch size for all gpus / default: 10
UPDATE_BATCH: 64 # how many images corresponds to once loss backward
START_EPOCH: 0
END_EPOCH: 30
IMG_SIZE: !!python/tuple [1088, 608] # input image size
PRETRAIN: 'yolov5l.pt' # in 'pretrain' dir
# if resume, directly set PRETRAIN to corresponding weights
ADAM: False # bool: use adam optimizer
SYNCBN: False # use sync-bn
LR_G0: 0.005 # (lr0) lr for group 0 parameters (SGD=1E-2, Adam=1E-3)
MOMENTUM: 0.95 # SGD momentum/Adam beta1
WEIGHT_DECAY: 0.0005 # optimizer weight decay 5e-4
SYNC_BN: False # sync bn
PLOT_LR: False # plot learning rate curves
CLS_WEIGHT: 0.5 # (cls) cls loss gain (default: 80 cls, each is 0.5/80)
CLS_P_WEIGHT: 1.0 # cls BCELoss positive_weight
OBJ_WEIGHT: 1.0 # (obj) obj loss gain (scale with pixels)
OBJ_P_WEIGHT: 1.0 # obj BCELoss positive_weight
GIOU_WEIGHT: 0.05 # GIoU loss gain
IOU_THRESH: 0.20 # (iou_t) IoU training threshold
ANCHOR_THRESH: 4.0 # (anchor_t) anchor-multiple threshold, for anchor assign
FL_GAMMA: 0.0 # (fl_gamma) focal loss gamma (efficientDet default gamma=1.5)
FINETUNE: False # finetuning on MOT benchamrks
RECT_TRAIN: False # bool: rectangular training
FIX_LAYERS: []
UNFIX_EPOCH: None
WANDB_ONLINE: True
DATASET:
ROOT_DIR: '/datassd/tracking/MOT/LCFORMAT'
WHICH_MODE: 'Default' # (see CONFIG)
TEST: # TEST model is same as TRAIN.MODEL
COMMON_HYPER: # common hyper-parameters
nms_thres: 0.6 # threshold for detector nms process
conf_thres: 0.5 # objectness threshold
track_buffer: 30 # max saving frames for tracklets
min_box_area: 100 # min box area
img_size: !!python/tuple [1088, 608] # input image size
mean: [0.408, 0.447, 0.470] # mean and std to normalize image
std: [0.289, 0.274, 0.278]
KITTI:
分析,
Assistant
The provided Python script is a significant module for building multiple object tracking (MOT) models, specifically using the YOLOv5 architecture as a detector within a multi-part neural network model. Here's a breakdown and analysis of the components present in the script:
Key Components
Imports and Dependencies:
The script relies heavily on PyTorch for creating neural networks, and it utilizes specific utility functions imported from other modules. Tools like argparse are used for command-line argument parsing, while logging and loguru handle logging.
Model Class:
The core class Model(nn.Module) is built on PyTorch's nn.Module. Its primary function is to construct the network architecture from a configuration, which can be provided in the form of a YAML file or a dictionary.
The class is initialized with key parameters like the input channels (ch) and the number of classes (nc).
The model allows for overriding specific parameters and handles the parsing of model architectures through the function parse_model.
Functions and Utilities:
forward: Defines the forward pass of the model with options for data augmentation and profiling. It's designed to handle both single-scale and multi-scale inference.
forward_once: Executes a single forward pass through the model, calculating outputs and optionally profiling performance.
_initialize_biases: Initializes model biases, specifically targeting the Detect layer's biases.
fuse: Optimizes the model by fusing Conv2d and BatchNorm2d layers for faster inference.
Architectural Elements:
The architecture includes various neural network layers and blocks from YOLOv5, such as Conv, BottleneckCSP, SPP (Spatial Pyramid Pooling), and Detect. These are critical for feature extraction and detection operations.
Custom modules like SAAN (Self-Attention Aggregation Network) and DenseMask are introduced. SAAN helps in identity association for tracking, while DenseMask predicts pedestrian density, aiding non-maximum suppression (NMS).
The script includes an extensive configuration for both model and training parameters, typically loaded from a YAML file.
Model configurations specify details like the number of classes, detection type, and specific network architecture settings.
Training configurations in TRAIN include batch sizes, learning rates, data augmentation strategies, dataset details, and more.
Testing configurations (TEST) define parameters for running inference, such as NMS thresholds and input image sizes.
Multi-Object Tracking and Association:
The script establishes a tracking framework, implementing both detection and association types, with DeepSort specified as the association method.
Additional parameters like track_buffer and min_box_area contribute to the tracking logic by controlling how long detections are kept and the minimum size for bounding boxes, respectively.
Analysis
Flexibility and Extendibility: The script is designed to be highly configurable, with a focus on flexibility in adapting to different configurations for model architecture, training, and testing setups. The use of configuration files provides ease in hyperparameter tuning and allows rapid experimentation.
Usage of Advanced Neural Blocks: By incorporating advanced architecture modules like the SAAN_Attention block, the script builds directly on state-of-the-art methods for feature learning and attention, indispensable for enhancing multi-object tracking accuracy.
Focus on Performance Optimization: The inclusion of model fusion capabilities and profiling options exhibits a focus on optimizing model performance, critical for deploying models in real-time applications.
Comprehensive Tracking Framework: The integration of both detection (via YOLOv5) and tracking modules (via DeepSort) within a unified framework highlights a complete solution addressing complex tasks in the computer vision domain.
In summary, this script constructs a sophisticated multi-object tracking model using a combination of well-known neural network components and novel architectural features, making it suitable for fast and accurate tracking in diverse environments.